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