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