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