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