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