JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
rearranged code, resize fixed.
[st.git] / st.c
1 /* See LICENSE for licence details. */
2 #define _XOPEN_SOURCE 600
3 #include <ctype.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <limits.h>
7 #include <locale.h>
8 #include <stdarg.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <signal.h>
13 #include <sys/ioctl.h>
14 #include <sys/select.h>
15 #include <sys/stat.h>
16 #include <sys/types.h>
17 #include <sys/wait.h>
18 #include <unistd.h>
19 #include <X11/Xlib.h>
20 #include <X11/keysym.h>
21 #include <X11/Xutil.h>
22
23 #define TNAME "xterm"
24
25 /* Arbitrary sizes */
26 #define ESC_TITLE_SIZ 256
27 #define ESC_BUF_SIZ   256
28 #define ESC_ARG_SIZ   16
29 #define DRAW_BUF_SIZ  1024
30
31 #define SERRNO strerror(errno)
32 #define MIN(a, b)  ((a) < (b) ? (a) : (b))
33 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
34 #define LEN(a)     (sizeof(a) / sizeof(a[0]))
35 #define DEFAULT(a, b)     (a) = (a) ? (a) : (b)    
36 #define BETWEEN(x, a, b)  ((a) <= (x) && (x) <= (b))
37 #define LIMIT(x, a, b)    (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
38 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
39
40 /* Attribute, Cursor, Character state, Terminal mode, Screen draw mode */
41 enum { ATTR_NULL=0 , ATTR_REVERSE=1 , ATTR_UNDERLINE=2, ATTR_BOLD=4, ATTR_GFX=8 };
42 enum { CURSOR_UP, CURSOR_DOWN, CURSOR_LEFT, CURSOR_RIGHT, CURSOR_HIDE, CURSOR_DRAW, CURSOR_SAVE, CURSOR_LOAD };
43 enum { GLYPH_SET=1, GLYPH_DIRTY=2 };
44 enum { MODE_WRAP=1, MODE_INSERT=2, MODE_APPKEYPAD=4 };
45 enum { ESC_START=1, ESC_CSI=2, ESC_OSC=4, ESC_TITLE=8, ESC_ALTCHARSET=16 };
46 enum { SCREEN_UPDATE, SCREEN_REDRAW };
47
48 typedef struct {
49         char c;     /* character code  */
50         char mode;  /* attribute flags */
51         int fg;     /* foreground      */
52         int bg;     /* background      */
53         char state; /* state flags     */
54 } Glyph;
55
56 typedef Glyph* Line;
57
58 typedef struct {
59         Glyph attr;      /* current char attributes */
60         int x;
61         int y;
62 } TCursor;
63
64 /* CSI Escape sequence structs */
65 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
66 typedef struct {
67         char buf[ESC_BUF_SIZ]; /* raw string */
68         int len;                           /* raw string length */
69         char priv;
70         int arg[ESC_ARG_SIZ];
71         int narg;                          /* nb of args */
72         char mode;
73 } CSIEscape;
74
75 /* Internal representation of the screen */
76 typedef struct {
77         int row;        /* nb row */  
78         int col;        /* nb col */
79         Line* line; /* screen */
80         TCursor c;      /* cursor */
81         char hidec;
82         int top;        /* top    scroll limit */
83         int bot;        /* bottom scroll limit */
84         int mode;       /* terminal mode flags */
85         int esc;        /* escape state flags */
86         char title[ESC_TITLE_SIZ];
87         int titlelen;
88 } Term;
89
90 /* Purely graphic info */
91 typedef struct {
92         Display* dis;
93         Window win;
94         Pixmap buf;
95         int scr;
96         int w;  /* window width  */
97         int h;  /* window height */
98         int bufw; /* pixmap width  */
99         int bufh; /* pixmap height */
100         int ch; /* char height */
101         int cw; /* char width  */
102 } XWindow; 
103
104 typedef struct {
105         KeySym k;
106         char s[ESC_BUF_SIZ];
107 } Key;
108
109 #include "config.h"
110
111 /* Drawing Context */
112 typedef struct {
113         unsigned long col[LEN(colorname)];
114         XFontStruct* font;
115         XFontStruct* bfont;
116         GC gc;
117 } DC;
118
119 static void die(const char *errstr, ...);
120 static void draw(int);
121 static void execsh(void);
122 static void sigchld(int);
123 static void run(void);
124
125 static void csidump(void);
126 static void csihandle(void);
127 static void csiparse(void);
128 static void csireset(void);
129
130 static void tclearregion(int, int, int, int);
131 static void tcursor(int);
132 static void tmovecursor(int);
133 static void tdeletechar(int);
134 static void tdeleteline(int);
135 static void tinsertblank(int);
136 static void tinsertblankline(int);
137 static void tmoveto(int, int);
138 static void tnew(int, int);
139 static void tnewline(void);
140 static void tputc(char);
141 static void tputs(char*, int);
142 static void treset(void);
143 static void tresize(int, int);
144 static void tscroll(void);
145 static void tscrollup(int);
146 static void tscrolldown(int);
147 static void tsetattr(int*, int);
148 static void tsetchar(char);
149 static void tsetscroll(int, int);
150
151 static void ttynew(void);
152 static void ttyread(void);
153 static void ttyresize(int, int);
154 static void ttywrite(const char *, size_t);
155
156 static unsigned long xgetcol(const char *);
157 static void xclear(int, int, int, int);
158 static void xcursor(int);
159 static void xinit(void);
160
161 static void expose(XEvent *);
162 static char* kmap(KeySym);
163 static void kpress(XEvent *);
164 static void resize(XEvent *);
165
166 static void (*handler[LASTEvent])(XEvent *) = {
167         [KeyPress] = kpress,
168         [Expose] = expose,
169         [ConfigureNotify] = resize
170 };
171
172 /* Globals */
173 static DC dc;
174 static XWindow xw;
175 static Term term;
176 static CSIEscape escseq;
177 static int cmdfd;
178 static pid_t pid;
179 static int running;
180
181 #ifdef DEBUG
182 void
183 tdump(void) {
184         int row, col;
185         Glyph c;
186
187         for(row = 0; row < term.row; row++) {
188                 for(col = 0; col < term.col; col++) {
189                         if(col == term.c.x && row == term.c.y)
190                                 putchar('#');
191                         else {
192                                 c = term.line[row][col];
193                                 putchar(c.state & GLYPH_SET ? c.c : '.');
194                         }
195                 }
196                 putchar('\n');
197         }
198 }
199 #endif
200
201 void
202 die(const char *errstr, ...) {
203         va_list ap;
204
205         va_start(ap, errstr);
206         vfprintf(stderr, errstr, ap);
207         va_end(ap);
208         exit(EXIT_FAILURE);
209 }
210
211 void
212 execsh(void) {
213         char *args[3] = {getenv("SHELL"), "-i", NULL};
214         DEFAULT(args[0], "/bin/sh"); /* default shell if getenv() failed */
215         putenv("TERM=" TNAME);
216         execvp(args[0], args);
217 }
218
219 void
220 xbell(void) { /* visual bell */
221         XRectangle r = { BORDER, BORDER, xw.bufw, xw.bufh };
222         XSetForeground(xw.dis, dc.gc, dc.col[BellCol]);
223         XFillRectangles(xw.dis, xw.win, dc.gc, &r, 1);
224         /* usleep(30000); */
225         draw(SCREEN_REDRAW);
226 }
227
228 void 
229 sigchld(int a) {
230         int stat = 0;
231         if(waitpid(pid, &stat, 0) < 0)
232                 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
233         if(WIFEXITED(stat))
234                 exit(WEXITSTATUS(stat));
235         else
236                 exit(EXIT_FAILURE);
237 }
238
239 void
240 ttynew(void) {
241         int m, s;
242         char *pts;
243
244         if((m = posix_openpt(O_RDWR | O_NOCTTY)) < 0)
245                 die("openpt failed: %s\n", SERRNO);
246         if(grantpt(m) < 0)
247                 die("grandpt failed: %s\n", SERRNO);
248         if(unlockpt(m) < 0)
249                 die("unlockpt failed: %s\n", SERRNO);
250         if(!(pts = ptsname(m)))
251                 die("ptsname failed: %s\n", SERRNO);
252         if((s = open(pts, O_RDWR | O_NOCTTY)) < 0)
253                 die("Couldn't open slave: %s\n", SERRNO);
254         fcntl(s, F_SETFL, O_NDELAY);
255         switch(pid = fork()) {
256         case -1:
257                 die("fork failed\n");
258                 break;
259         case 0:
260                 setsid(); /* create a new process group */
261                 dup2(s, STDIN_FILENO);
262                 dup2(s, STDOUT_FILENO);
263                 dup2(s, STDERR_FILENO);
264                 if(ioctl(s, TIOCSCTTY, NULL) < 0)
265                         die("ioctl TTIOCSTTY failed: %s\n", SERRNO);
266                 execsh();
267                 break;
268         default:
269                 close(s);
270                 cmdfd = m;
271                 signal(SIGCHLD, sigchld);
272         }
273 }
274
275 void
276 dump(char c) {
277         static int col;
278         fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
279         if(++col % 10 == 0)
280                 fprintf(stderr, "\n");
281 }
282
283 void
284 ttyread(void) {
285         char buf[BUFSIZ] = {0};
286         int ret;
287
288         if((ret = read(cmdfd, buf, BUFSIZ)) < 0)
289                 die("Couldn't read from shell: %s\n", SERRNO);
290         else
291                 tputs(buf, ret);
292 }
293
294 void
295 ttywrite(const char *s, size_t n) {
296         if(write(cmdfd, s, n) == -1)
297                 die("write error on tty: %s\n", SERRNO);
298 }
299
300 void
301 ttyresize(int x, int y) {
302         struct winsize w;
303
304         w.ws_row = term.row;
305         w.ws_col = term.col;
306         w.ws_xpixel = w.ws_ypixel = 0;
307         if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
308                 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
309 }
310
311 void
312 tcursor(int mode) {
313         static TCursor c;
314
315         if(mode == CURSOR_SAVE)
316                 c = term.c;
317         else if(mode == CURSOR_LOAD)
318                 term.c = c, tmoveto(c.x, c.y);
319 }
320
321 void
322 treset(void) {
323         term.c.attr.mode = ATTR_NULL;
324         term.c.attr.fg = DefaultFG;
325         term.c.attr.bg = DefaultBG;
326         term.c.x = term.c.y = 0;
327         term.hidec = 0;
328         term.top = 0, term.bot = term.row - 1;
329         term.mode = MODE_WRAP;
330         tclearregion(0, 0, term.col-1, term.row-1);
331 }
332
333 void
334 tnew(int col, int row) {   /* screen size */
335         term.row = row, term.col = col;
336         term.top = 0, term.bot = term.row - 1;
337         /* mode */
338         term.mode = MODE_WRAP;
339         /* cursor */
340         term.c.attr.mode = ATTR_NULL;
341         term.c.attr.fg = DefaultFG;
342         term.c.attr.bg = DefaultBG;
343         term.c.x = term.c.y = 0;
344         term.hidec = 0;
345         /* allocate screen */
346         term.line = calloc(term.row, sizeof(Line));
347         for(row = 0 ; row < term.row; row++)
348                 term.line[row] = calloc(term.col, sizeof(Glyph));
349 }
350
351 /* TODO: Replace with scrollup/scolldown */
352 void
353 tscroll(void) {
354         Line temp = term.line[term.top];
355         int i;
356
357         for(i = term.top; i < term.bot; i++)
358                 term.line[i] = term.line[i+1];
359         memset(temp, 0, sizeof(Glyph) * term.col);
360         term.line[term.bot] = temp;
361 }
362
363 void
364 tscrolldown (int n) {
365         int i;
366         Line temp;
367         
368         LIMIT(n, 0, term.bot-term.top+1);
369
370         for(i = 0; i < n; i++)
371                 memset(term.line[term.bot-i], 0, term.col*sizeof(Glyph));
372         
373         for(i = term.bot; i >= term.top+n; i--) {
374                 temp = term.line[i];
375                 term.line[i] = term.line[i-n];
376                 term.line[i-n] = temp;
377         }
378 }
379
380 void
381 tscrollup (int n) {
382         int i;
383         Line temp;
384         LIMIT(n, 0, term.bot-term.top+1);
385         
386         for(i = 0; i < n; i++)
387                 memset(term.line[term.top+i], 0, term.col*sizeof(Glyph));
388         
389          for(i = term.top; i <= term.bot-n; i++) { 
390                  temp = term.line[i];
391                  term.line[i] = term.line[i+n]; 
392                  term.line[i+n] = temp;
393          }
394 }
395
396 void
397 tnewline(void) {
398         int y = term.c.y + 1;
399         if(y > term.bot)
400                 tscroll(), y = term.bot;
401         tmoveto(0, y);
402 }
403
404 void
405 csiparse(void) {
406         /* int noarg = 1; */
407         char *p = escseq.buf;
408
409         escseq.narg = 0;
410         if(*p == '?')
411                 escseq.priv = 1, p++;
412         
413         while(p < escseq.buf+escseq.len) {
414                 while(isdigit(*p)) {
415                         escseq.arg[escseq.narg] *= 10;
416                         escseq.arg[escseq.narg] += *p++ - '0'/*, noarg = 0 */;
417                 }
418                 if(*p == ';' && escseq.narg+1 < ESC_ARG_SIZ)
419                         escseq.narg++, p++;
420                 else {
421                         escseq.mode = *p;
422                         escseq.narg++;
423                         return;
424                 }
425         }
426 }
427
428 void
429 tmoveto(int x, int y) {
430         term.c.x = x < 0 ? 0 : x >= term.col ? term.col-1 : x;
431         term.c.y = y < 0 ? 0 : y >= term.row ? term.row-1 : y;
432 }
433
434 void
435 tmovecursor(int dir) {
436         int xf = term.c.x, yf = term.c.y;
437         
438         switch(dir) {
439         case CURSOR_UP:
440                 yf--;
441                 break;
442         case CURSOR_DOWN:
443                 yf++;
444                 break;
445         case CURSOR_LEFT:
446                 xf--;
447                 if(term.mode & MODE_WRAP && xf < 0) {
448                         xf = term.col-1, yf--;
449                         if(yf < term.top)
450                                 yf = term.top, xf = 0;
451                 }
452                 break;
453         case CURSOR_RIGHT:
454                 xf++;
455                 if(term.mode & MODE_WRAP && xf >= term.col) {
456                         xf = 0, yf++;
457                         if(yf > term.bot)
458                                 yf = term.bot, tscroll();
459                 }
460                 break;
461         }
462         tmoveto(xf, yf);
463 }
464         
465 void
466 tsetchar(char c) {
467         term.line[term.c.y][term.c.x] = term.c.attr;
468         term.line[term.c.y][term.c.x].c = c;
469         term.line[term.c.y][term.c.x].state |= GLYPH_SET;
470 }
471
472 void
473 tclearregion(int x1, int y1, int x2, int y2) {
474         int y, temp;
475
476         if(x1 > x2)
477                 temp = x1, x1 = x2, x2 = temp;
478         if(y1 > y2)
479                 temp = y1, y1 = y2, y2 = temp;
480
481         LIMIT(x1, 0, term.col-1);
482         LIMIT(x2, 0, term.col-1);
483         LIMIT(y1, 0, term.row-1);
484         LIMIT(y2, 0, term.row-1);
485
486         for(y = y1; y <= y2; y++)
487                 memset(&term.line[y][x1], 0, sizeof(Glyph)*(x2-x1+1));
488 }
489
490 void
491 tdeletechar(int n) {
492         int src = term.c.x + n;
493         int dst = term.c.x;
494         int size = term.col - src;
495
496         if(src >= term.col) {
497                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
498                 return;
499         }
500         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
501         tclearregion(term.col-size, term.c.y, term.col-1, term.c.y);
502 }
503
504 void
505 tinsertblank(int n) {
506         int src = term.c.x;
507         int dst = src + n;
508         int size = term.col - n - src;
509
510         if(dst >= term.col) {
511                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
512                 return;
513         }
514         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
515         tclearregion(src, term.c.y, dst, term.c.y);
516 }
517
518 void
519 tinsertblankline(int n) {
520         int i;
521         Line blank;
522         int bot = term.bot;
523
524         if(term.c.y > term.bot)
525                 bot = term.row - 1;
526         else if(term.c.y < term.top)
527                 bot = term.top - 1;
528         if(term.c.y + n >= bot) {
529                 tclearregion(0, term.c.y, term.col-1, bot);
530                 return;
531         }
532         for(i = bot; i >= term.c.y+n; i--) {
533                 /* swap deleted line <-> blanked line */
534                 blank = term.line[i];
535                 term.line[i] = term.line[i-n];
536                 term.line[i-n] = blank;
537                 /* blank it */
538                 memset(blank, 0, term.col * sizeof(Glyph));
539         }
540 }
541
542 void
543 tdeleteline(int n) {
544         int i;
545         Line blank;
546         int bot = term.bot;
547
548         if(term.c.y > term.bot)
549                 bot = term.row - 1;
550         else if(term.c.y < term.top)
551                 bot = term.top - 1;
552         if(term.c.y + n >= bot) {
553                 tclearregion(0, term.c.y, term.col-1, bot);
554                 return;
555         }
556         for(i = term.c.y; i <= bot-n; i++) {
557                 /* swap deleted line <-> blanked line */
558                 blank = term.line[i];
559                 term.line[i] = term.line[i+n];
560                 term.line[i+n] = blank;
561                 /* blank it */
562                 memset(blank, 0, term.col * sizeof(Glyph));
563         }
564 }
565
566 void
567 tsetattr(int *attr, int l) {
568         int i;
569
570         for(i = 0; i < l; i++) {
571                 switch(attr[i]) {
572                 case 0:
573                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
574                         term.c.attr.fg = DefaultFG;
575                         term.c.attr.bg = DefaultBG;
576                         break;
577                 case 1:
578                         term.c.attr.mode |= ATTR_BOLD;   
579                         break;
580                 case 4: 
581                         term.c.attr.mode |= ATTR_UNDERLINE;
582                         break;
583                 case 7: 
584                         term.c.attr.mode |= ATTR_REVERSE;       
585                         break;
586                 case 22: 
587                         term.c.attr.mode &= ~ATTR_BOLD;  
588                         break;
589                 case 24: 
590                         term.c.attr.mode &= ~ATTR_UNDERLINE;
591                         break;
592                 case 27: 
593                         term.c.attr.mode &= ~ATTR_REVERSE;       
594                         break;
595                 case 39:
596                         term.c.attr.fg = DefaultFG;
597                         break;
598                 case 49:
599                         term.c.attr.fg = DefaultBG;
600                         break;
601                 default:
602                         if(BETWEEN(attr[i], 30, 37))
603                                 term.c.attr.fg = attr[i] - 30;
604                         else if(BETWEEN(attr[i], 40, 47))
605                                 term.c.attr.bg = attr[i] - 40;
606                         else 
607                                 fprintf(stderr, "erresc: gfx attr %d unkown\n", attr[i]); 
608                         break;
609                 }
610         }
611 }
612
613 void
614 tsetscroll(int t, int b) {
615         int temp;
616
617         LIMIT(t, 0, term.row-1);
618         LIMIT(b, 0, term.row-1);
619         if(t > b) {
620                 temp = t;
621                 t = b;
622                 b = temp;
623         }
624         term.top = t;
625         term.bot = b;    
626 }
627
628 void
629 csihandle(void) {
630         switch(escseq.mode) {
631         default:
632         unknown:
633                 printf("erresc: unknown csi ");
634                 csidump();
635                 /* die(""); */
636                 break;
637         case '@': /* ICH -- Insert <n> blank char */
638                 DEFAULT(escseq.arg[0], 1);
639                 tinsertblank(escseq.arg[0]);
640                 break;
641         case 'A': /* CUU -- Cursor <n> Up */
642         case 'e':
643                 DEFAULT(escseq.arg[0], 1);
644                 tmoveto(term.c.x, term.c.y-escseq.arg[0]);
645                 break;
646         case 'B': /* CUD -- Cursor <n> Down */
647                 DEFAULT(escseq.arg[0], 1);
648                 tmoveto(term.c.x, term.c.y+escseq.arg[0]);
649                 break;
650         case 'C': /* CUF -- Cursor <n> Forward */
651         case 'a':
652                 DEFAULT(escseq.arg[0], 1);
653                 tmoveto(term.c.x+escseq.arg[0], term.c.y);
654                 break;
655         case 'D': /* CUB -- Cursor <n> Backward */
656                 DEFAULT(escseq.arg[0], 1);
657                 tmoveto(term.c.x-escseq.arg[0], term.c.y);
658                 break;
659         case 'E': /* CNL -- Cursor <n> Down and first col */
660                 DEFAULT(escseq.arg[0], 1);
661                 tmoveto(0, term.c.y+escseq.arg[0]);
662                 break;
663         case 'F': /* CPL -- Cursor <n> Up and first col */
664                 DEFAULT(escseq.arg[0], 1);
665                 tmoveto(0, term.c.y-escseq.arg[0]);
666                 break;
667         case 'G': /* CHA -- Move to <col> */
668         case '`': /* XXX: HPA -- same? */
669                 DEFAULT(escseq.arg[0], 1);
670                 tmoveto(escseq.arg[0]-1, term.c.y);
671                 break;
672         case 'H': /* CUP -- Move to <row> <col> */
673         case 'f': /* XXX: HVP -- same? */
674                 DEFAULT(escseq.arg[0], 1);
675                 DEFAULT(escseq.arg[1], 1);
676                 tmoveto(escseq.arg[1]-1, escseq.arg[0]-1);
677                 break;
678         /* XXX: (CSI n I) CHT -- Cursor Forward Tabulation <n> tab stops */
679         case 'J': /* ED -- Clear screen */
680                 switch(escseq.arg[0]) {
681                 case 0: /* below */
682                         tclearregion(term.c.x, term.c.y, term.col-1, term.row-1);
683                         break;
684                 case 1: /* above */
685                         tclearregion(0, 0, term.c.x, term.c.y);
686                         break;
687                 case 2: /* all */
688                         tclearregion(0, 0, term.col-1, term.row-1);
689                         break;
690                 case 3: /* XXX: erase saved lines (xterm) */
691                 default:
692                         goto unknown;
693                 }
694                 break;
695         case 'K': /* EL -- Clear line */
696                 switch(escseq.arg[0]) {
697                 case 0: /* right */
698                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
699                         break;
700                 case 1: /* left */
701                         tclearregion(0, term.c.y, term.c.x, term.c.y);
702                         break;
703                 case 2: /* all */
704                         tclearregion(0, term.c.y, term.col-1, term.c.y);
705                         break;
706                 }
707                 break;
708         case 'S': /* SU -- Scroll <n> line up */
709                 DEFAULT(escseq.arg[0], 1);
710                 tscrollup(escseq.arg[0]);
711                 break;
712         case 'T': /* SD -- Scroll <n> line down */
713                 DEFAULT(escseq.arg[0], 1);
714                 tscrolldown(escseq.arg[0]);
715                 break;
716         case 'L': /* IL -- Insert <n> blank lines */
717                 DEFAULT(escseq.arg[0], 1);
718                 tinsertblankline(escseq.arg[0]);
719                 break;
720         case 'l': /* RM -- Reset Mode */
721                 if(escseq.priv) {
722                         switch(escseq.arg[0]) {
723                         case 1:
724                                 term.mode &= ~MODE_APPKEYPAD;
725                                 break;
726                         case 7:
727                                 term.mode &= ~MODE_WRAP;
728                                 break;
729                         case 12: /* att610 -- Stop blinking cursor (IGNORED) */
730                                 break;
731                         case 25:
732                                 term.hidec = 1;
733                                 break;
734                         case 1048: /* XXX: no alt. screen to erase/save */
735                         case 1049:
736                                 tcursor(CURSOR_LOAD);
737                                 tclearregion(0, 0, term.col-1, term.row-1);
738                                 break;
739                         default:
740                                 goto unknown;
741                         }
742                 } else {
743                         switch(escseq.arg[0]) {
744                         case 4:
745                                 term.mode &= ~MODE_INSERT;
746                                 break;
747                         default:
748                                 goto unknown;
749                         }
750                 }
751                 break;
752         case 'M': /* DL -- Delete <n> lines */
753                 DEFAULT(escseq.arg[0], 1);
754                 tdeleteline(escseq.arg[0]);
755                 break;
756         case 'X': /* ECH -- Erase <n> char */
757                 DEFAULT(escseq.arg[0], 1);
758                 tclearregion(term.c.x, term.c.y, term.c.x + escseq.arg[0], term.c.y);
759                 break;
760         case 'P': /* DCH -- Delete <n> char */
761                 DEFAULT(escseq.arg[0], 1);
762                 tdeletechar(escseq.arg[0]);
763                 break;
764         /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
765         case 'd': /* VPA -- Move to <row> */
766                 DEFAULT(escseq.arg[0], 1);
767                 tmoveto(term.c.x, escseq.arg[0]-1);
768                 break;
769         case 'h': /* SM -- Set terminal mode */
770                 if(escseq.priv) {
771                         switch(escseq.arg[0]) {
772                         case 1:
773                                 term.mode |= MODE_APPKEYPAD;
774                                 break;
775                         case 7:
776                                 term.mode |= MODE_WRAP;
777                                 break;
778                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
779                                 break;
780                         case 25:
781                                 term.hidec = 0;
782                                 break;
783                         case 1048: 
784                         case 1049: /* XXX: no alt. screen to erase/save */
785                                 tcursor(CURSOR_SAVE);
786                                 tclearregion(0, 0, term.col-1, term.row-1);
787                                 break;
788                         default: goto unknown;
789                         }
790                 } else {
791                         switch(escseq.arg[0]) {
792                         case 4:
793                                 term.mode |= MODE_INSERT;
794                                 break;
795                         default: goto unknown;
796                         }
797                 };
798                 break;
799         case 'm': /* SGR -- Terminal attribute (color) */
800                 tsetattr(escseq.arg, escseq.narg);
801                 break;
802         case 'r': /* DECSTBM -- Set Scrolling Region */
803                 if(escseq.priv)
804                         goto unknown;
805                 else {
806                         DEFAULT(escseq.arg[0], 1);
807                         DEFAULT(escseq.arg[1], term.row);
808                         tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
809                 }
810                 break;
811         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
812                 tcursor(CURSOR_SAVE);
813                 break;
814         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
815                 tcursor(CURSOR_LOAD);
816                 break;
817         }
818 }
819
820 void
821 csidump(void) { 
822         int i;
823         printf("ESC [ %s", escseq.priv ? "? " : "");
824         if(escseq.narg)
825                 for(i = 0; i < escseq.narg; i++)
826                         printf("%d ", escseq.arg[i]);
827         if(escseq.mode)
828                 putchar(escseq.mode);
829         putchar('\n');
830 }
831
832 void
833 csireset(void) {
834         memset(&escseq, 0, sizeof(escseq));
835 }
836
837 void
838 tputtab(void) {
839         int space = TAB - term.c.x % TAB;
840         
841         if(term.c.x + space >= term.col)
842                 space--;
843         
844         for(; space > 0; space--)
845                 tmovecursor(CURSOR_RIGHT);
846 }
847
848 void
849 tputc(char c) {
850         if(term.esc & ESC_START) {
851                 if(term.esc & ESC_CSI) {
852                         escseq.buf[escseq.len++] = c;
853                         if(BETWEEN(c, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
854                                 term.esc = 0;
855                                 csiparse(), csihandle();
856                         }
857                 } else if(term.esc & ESC_OSC) {
858                         if(c == ';') {
859                                 term.titlelen = 0;
860                                 term.esc = ESC_START | ESC_TITLE;
861                         }
862                 } else if(term.esc & ESC_TITLE) {
863                         if(c == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
864                                 term.esc = 0;
865                                 term.title[term.titlelen] = '\0';
866                                 XStoreName(xw.dis, xw.win, term.title);
867                         } else {
868                                 term.title[term.titlelen++] = c;
869                         }
870                 } else if(term.esc & ESC_ALTCHARSET) {
871                         switch(c) {
872                         case '0': /* Line drawing crap */
873                                 term.c.attr.mode |= ATTR_GFX;
874                                 break;
875                         case 'B': /* Back to regular text */
876                                 term.c.attr.mode &= ~ATTR_GFX;
877                                 break;
878                         default:
879                                 printf("esc unhandled charset: ESC ( %c\n", c);
880                         }
881                         term.esc = 0;
882                 } else {                
883                         switch(c) {
884                         case '[':
885                                 term.esc |= ESC_CSI;
886                                 break;
887                         case ']':
888                                 term.esc |= ESC_OSC;
889                                 break;
890                         case '(':
891                                 term.esc |= ESC_ALTCHARSET;
892                                 break;
893                         case 'A':
894                                 tmoveto(term.c.x, term.c.y-1);
895                                 term.esc = 0;
896                                 break;
897                         case 'B':
898                                 tmoveto(term.c.x, term.c.y+1);
899                                 term.esc = 0;
900                                 break;
901                         case 'C':
902                                 tmoveto(term.c.x+1, term.c.y);
903                                 term.esc = 0;
904                                 break;
905                         case 'D': /* XXX: CUP (VT100) or IND (VT52) ... */
906                                 tmoveto(term.c.x-1, term.c.y);
907                                 term.esc = 0;
908                                 break;
909                         case 'E': /* NEL -- Next line */
910                                 tnewline();
911                                 term.esc = 0;
912                                 break;
913                         case 'M': /* RI -- Reverse index */
914                                 if(term.c.y == term.top)
915                                         tscrolldown(1);
916                                 else
917                                         tmoveto(term.c.x, term.c.y-1);
918                                 term.esc = 0;
919                                 break;
920                         case 'c': /* RIS -- Reset to inital state */
921                                 treset();
922                                 term.esc = 0;
923                                 break;
924                         case '=': /* DECPAM */
925                                 term.mode |= MODE_APPKEYPAD;
926                                 term.esc = 0;
927                                 break;
928                         case '>': /* DECPNM */
929                                 term.mode &= ~MODE_APPKEYPAD;
930                                 term.esc = 0;
931                                 break;
932                         case '7':
933                                 tcursor(CURSOR_SAVE);
934                                 term.esc = 0;
935                                 break;
936                         case '8':
937                                 tcursor(CURSOR_LOAD);
938                                 term.esc = 0;
939                                 break;
940                         default:
941                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n", c, isprint(c)?c:'.');
942                                 term.esc = 0;
943                         }
944                 }
945         } else {
946                 switch(c) {
947                 case '\t':
948                         tputtab();
949                         break;
950                 case '\b':
951                         tmovecursor(CURSOR_LEFT);
952                         break;
953                 case '\r':
954                         tmoveto(0, term.c.y);
955                         break;
956                 case '\n':
957                         tnewline();
958                         break;
959                 case '\a':
960                         xbell();
961                         break;
962                 case '\033':
963                         csireset();
964                         term.esc = ESC_START;
965                         break;
966                 default:
967                         tsetchar(c);
968                         tmovecursor(CURSOR_RIGHT);
969                         break;
970                 }
971         }
972 }
973
974 void
975 tputs(char *s, int len) { 
976         for(; len > 0; len--)
977                 tputc(*s++);
978 }
979
980 void
981 tresize(int col, int row) {
982         int i;
983         Line *line;
984         int minrow = MIN(row, term.row);
985         int mincol = MIN(col, term.col);
986
987         if(col < 1 || row < 1)
988                 return;
989         /* alloc */
990         line = calloc(row, sizeof(Line));
991         for(i = 0 ; i < row; i++)
992                 line[i] = calloc(col, sizeof(Glyph));
993         /* copy */
994         for(i = 0 ; i < minrow; i++)
995                 memcpy(line[i], term.line[i], mincol * sizeof(Glyph));
996         /* free */
997         for(i = 0; i < term.row; i++)
998                 free(term.line[i]);
999         free(term.line);
1000         
1001         LIMIT(term.c.x, 0, col-1);
1002         LIMIT(term.c.y, 0, row-1);
1003         LIMIT(term.top, 0, row-1);
1004         LIMIT(term.bot, 0, row-1);
1005         
1006         term.bot = row-1;
1007         term.line = line;
1008         term.col = col, term.row = row;
1009 }
1010
1011 unsigned long
1012 xgetcol(const char *s) {
1013         XColor color;
1014         Colormap cmap = DefaultColormap(xw.dis, xw.scr);
1015
1016         if(!XAllocNamedColor(xw.dis, cmap, s, &color, &color)) {
1017                 color.pixel = WhitePixel(xw.dis, xw.scr);
1018                 fprintf(stderr, "Could not allocate color '%s'\n", s);
1019         }
1020         return color.pixel;
1021 }
1022
1023 void
1024 xclear(int x1, int y1, int x2, int y2) {
1025         XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
1026         XFillRectangle(xw.dis, xw.buf, dc.gc,
1027                                    x1 * xw.cw, y1 * xw.ch, 
1028                                    (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
1029 }
1030
1031 void
1032 xhints(void)
1033 {
1034         XClassHint chint = {TNAME, TNAME};
1035         XWMHints wmhint  = {.flags = InputHint, .input = 1};
1036         XSizeHints shint = { 
1037                 .flags = PSize | PResizeInc,
1038                 .height = xw.h, /* XXX: doesn't seem to work, see run() */
1039                 .width = xw.w,
1040                 .height_inc = xw.ch,
1041                 .width_inc = xw.cw,
1042         };
1043         XSetWMProperties(xw.dis, xw.win, NULL, NULL, NULL, 0, &shint, &wmhint, &chint);
1044 }
1045
1046 void
1047 xinit(void) {
1048         int i;
1049
1050         xw.dis = XOpenDisplay(NULL);
1051         xw.scr = XDefaultScreen(xw.dis);
1052         if(!xw.dis)
1053                 die("Can't open display\n");
1054         
1055         /* font */
1056         if(!(dc.font = XLoadQueryFont(xw.dis, FONT)) || !(dc.bfont = XLoadQueryFont(xw.dis, BOLDFONT)))
1057                 die("Can't load font %s\n", dc.font ? BOLDFONT : FONT);
1058
1059         /* XXX: Assuming same size for bold font */
1060         xw.cw = dc.font->max_bounds.rbearing - dc.font->min_bounds.lbearing;
1061         xw.ch = dc.font->ascent + dc.font->descent;
1062
1063         /* colors */
1064         for(i = 0; i < LEN(colorname); i++)
1065                 dc.col[i] = xgetcol(colorname[i]);
1066
1067         term.c.attr.fg = DefaultFG;
1068         term.c.attr.bg = DefaultBG;
1069         term.c.attr.mode = ATTR_NULL;
1070         /* windows */
1071         xw.h = term.row * xw.ch + 2*BORDER;
1072         xw.w = term.col * xw.cw + 2*BORDER;
1073         xw.win = XCreateSimpleWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
1074                         xw.w, xw.h, 0, 
1075                         dc.col[DefaultBG],
1076                         dc.col[DefaultBG]);
1077         xw.bufw = xw.w - 2*BORDER;
1078         xw.bufh = xw.h - 2*BORDER;
1079         xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1080         /* gc */
1081         dc.gc = XCreateGC(xw.dis, xw.win, 0, NULL);
1082         XMapWindow(xw.dis, xw.win);
1083         xhints();
1084         XStoreName(xw.dis, xw.win, TNAME);
1085         XSync(xw.dis, 0);
1086 }
1087
1088 void
1089 xdraws(char *s, Glyph base, int x, int y, int len) {
1090         unsigned long xfg, xbg;
1091         int winx = x*xw.cw, winy = y*xw.ch + dc.font->ascent, width = len*xw.cw;
1092         int i;
1093
1094         if(base.mode & ATTR_REVERSE)
1095                 xfg = dc.col[base.bg], xbg = dc.col[base.fg];
1096         else
1097                 xfg = dc.col[base.fg], xbg = dc.col[base.bg];
1098
1099         XSetBackground(xw.dis, dc.gc, xbg);
1100         XSetForeground(xw.dis, dc.gc, xfg);
1101         
1102         if(base.mode & ATTR_GFX)
1103                 for(i = 0; i < len; i++)
1104                         s[i] = gfx[s[i]];
1105
1106         XSetFont(xw.dis, dc.gc, base.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);  
1107         XDrawImageString(xw.dis, xw.buf, dc.gc, winx, winy, s, len);
1108         
1109         if(base.mode & ATTR_UNDERLINE)
1110                 XDrawLine(xw.dis, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
1111 }
1112
1113 void
1114 xcursor(int mode) {
1115         static int oldx = 0;
1116         static int oldy = 0;
1117         Glyph g = {' ', ATTR_NULL, DefaultBG, DefaultCS, 0};
1118         
1119         LIMIT(oldx, 0, term.col-1);
1120         LIMIT(oldy, 0, term.row-1);
1121         
1122         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
1123                 g.c = term.line[term.c.y][term.c.x].c;
1124
1125         /* remove the old cursor */
1126         if(term.line[oldy][oldx].state & GLYPH_SET)
1127                 xdraws(&term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1);
1128         else
1129                 xclear(oldx, oldy, oldx, oldy);
1130         
1131         /* draw the new one */
1132         if(mode == CURSOR_DRAW) {
1133                 xdraws(&g.c, g, term.c.x, term.c.y, 1);
1134                 oldx = term.c.x, oldy = term.c.y;
1135         }
1136 }
1137
1138
1139 #ifdef DEBUG
1140 /* basic drawing routines */
1141 void
1142 xdrawc(int x, int y, Glyph g) {
1143         XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
1144         XSetBackground(xw.dis, dc.gc, dc.col[g.bg]);
1145         XSetForeground(xw.dis, dc.gc, dc.col[g.fg]);
1146         XSetFont(xw.dis, dc.gc, g.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
1147         XDrawImageString(xw.dis, xw.buf, dc.gc, r.x, r.y+dc.font->ascent, &g.c, 1);
1148 }
1149
1150 void
1151 draw_(int dummy) {
1152         int x, y;
1153
1154         xclear(0, 0, term.col-1, term.row-1);
1155         for(y = 0; y < term.row; y++)
1156                 for(x = 0; x < term.col; x++)
1157                         if(term.line[y][x].state & GLYPH_SET)
1158                                 xdrawc(x, y, term.line[y][x]);
1159
1160         if(!term.hidec)
1161                 xcursor(CURSOR_DRAW);
1162         XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1163         XFlush(xw.dis);
1164 }
1165 #endif
1166
1167 void
1168 draw(int redraw_all) {
1169         int i, x, y, ox;
1170         Glyph base, new;
1171         char buf[DRAW_BUF_SIZ];
1172         
1173         for(y = 0; y < term.row; y++) {
1174                 base = term.line[y][0];
1175                 i = ox = 0;
1176                 for(x = 0; x < term.col; x++) {
1177                         new = term.line[y][x];
1178                         if(!ATTRCMP(base, new) && i < DRAW_BUF_SIZ)
1179                                 buf[i++] = new.c;
1180                         else {
1181                                 xdraws(buf, base, ox, y, i);
1182                                 buf[0] = new.c;
1183                                 i = 1;
1184                                 ox = x;
1185                                 base = new;
1186                         }
1187                 }
1188                 xdraws(buf, base, ox, y, i);
1189         }
1190         xcursor(term.hidec ? CURSOR_HIDE : CURSOR_DRAW);
1191         XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1192         XFlush(xw.dis);
1193 }
1194
1195 void
1196 expose(XEvent *ev) {
1197         draw(SCREEN_REDRAW);
1198 }
1199
1200 char*
1201 kmap(KeySym k) {
1202         int i;
1203         for(i = 0; i < LEN(key); i++)
1204                 if(key[i].k == k)
1205                         return (char*)key[i].s;
1206         return NULL;
1207 }
1208
1209 void
1210 kpress(XEvent *ev) {
1211         XKeyEvent *e = &ev->xkey;
1212         KeySym ksym;
1213         char buf[32];
1214         char *customkey;
1215         int len;
1216         int meta;
1217         int shift;
1218
1219         meta = e->state & Mod1Mask;
1220         shift = e->state & ShiftMask;
1221         len = XLookupString(e, buf, sizeof(buf), &ksym, NULL);
1222
1223         if(customkey = kmap(ksym))
1224                 ttywrite(customkey, strlen(customkey));
1225         else if(len > 0) {
1226                 buf[sizeof(buf)-1] = '\0';
1227                 if(meta && len == 1)
1228                         ttywrite("\033", 1);
1229                 ttywrite(buf, len);
1230         } else
1231                 switch(ksym) {
1232                 case XK_Up:
1233                 case XK_Down:
1234                 case XK_Left:
1235                 case XK_Right:
1236                         sprintf(buf, "\033%c%c", term.mode & MODE_APPKEYPAD ? 'O' : '[', "DACB"[ksym - XK_Left]);
1237                         ttywrite(buf, 3);
1238                         break;
1239                 case XK_Insert:
1240                         if(shift)
1241                                 draw(1), puts("draw!")/* XXX: paste X clipboard */;
1242                         break;
1243                 default:
1244                         fprintf(stderr, "errkey: %d\n", (int)ksym);
1245                         break;
1246                 }
1247 }
1248
1249 void
1250 resize(XEvent *e) {
1251         int col, row;
1252         
1253         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
1254                 return;
1255         
1256         xw.w = e->xconfigure.width;
1257         xw.h = e->xconfigure.height;
1258         xw.bufw = xw.w - 2*BORDER;
1259         xw.bufh = xw.h - 2*BORDER;
1260         col = xw.bufw / xw.cw;
1261         row = xw.bufh / xw.ch;
1262         tresize(col, row);
1263         ttyresize(col, row);
1264         XFreePixmap(xw.dis, xw.buf);
1265         xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1266         draw(SCREEN_REDRAW);
1267 }
1268
1269 void
1270 run(void) {
1271         XEvent ev;
1272         fd_set rfd;
1273         int xfd = XConnectionNumber(xw.dis);
1274
1275         running = 1;
1276         XSelectInput(xw.dis, xw.win, ExposureMask | KeyPressMask | StructureNotifyMask);
1277         XResizeWindow(xw.dis, xw.win, xw.w, xw.h); /* XXX: fix resize bug in wmii (?) */
1278
1279         while(running) {
1280                 FD_ZERO(&rfd);
1281                 FD_SET(cmdfd, &rfd);
1282                 FD_SET(xfd, &rfd);
1283                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) == -1) {
1284                         if(errno == EINTR)
1285                                 continue;
1286                         die("select failed: %s\n", SERRNO);
1287                 }
1288                 if(FD_ISSET(cmdfd, &rfd)) {
1289                         ttyread();
1290                         draw(SCREEN_UPDATE); 
1291                 }
1292                 while(XPending(xw.dis)) {
1293                         XNextEvent(xw.dis, &ev);
1294                         if(handler[ev.type])
1295                                 (handler[ev.type])(&ev);
1296                 }
1297         }
1298 }
1299
1300 int
1301 main(int argc, char *argv[]) {
1302         if(argc == 2 && !strncmp("-v", argv[1], 3))
1303                 die("st-" VERSION ", © 2009 st engineers\n");
1304         else if(argc != 1)
1305                 die("usage: st [-v]\n");
1306         setlocale(LC_CTYPE, "");
1307         tnew(80, 24);
1308         ttynew();
1309         xinit();
1310         run();
1311         return 0;
1312 }