JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
fix warning
[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 <pty.h>
20 #include <X11/Xlib.h>
21 #include <X11/keysym.h>
22 #include <X11/Xutil.h>
23
24 #if   defined(LINUX)
25  #include <pty.h>
26 #elif defined(OPENBSD)
27  #include <util.h>
28 #elif defined(FREEBSD)
29  #include <libutil.h>
30 #endif
31
32 /* Arbitrary sizes */
33 #define ESC_TITLE_SIZ 256
34 #define ESC_BUF_SIZ   256
35 #define ESC_ARG_SIZ   16
36 #define DRAW_BUF_SIZ  1024
37
38 #define SERRNO strerror(errno)
39 #define MIN(a, b)  ((a) < (b) ? (a) : (b))
40 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
41 #define LEN(a)     (sizeof(a) / sizeof(a[0]))
42 #define DEFAULT(a, b)     (a) = (a) ? (a) : (b)    
43 #define BETWEEN(x, a, b)  ((a) <= (x) && (x) <= (b))
44 #define LIMIT(x, a, b)    (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
45 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
46 #define IS_SET(flag) (term.mode & (flag))
47
48 /* Attribute, Cursor, Character state, Terminal mode, Screen draw mode */
49 enum { ATTR_NULL=0 , ATTR_REVERSE=1 , ATTR_UNDERLINE=2, ATTR_BOLD=4, ATTR_GFX=8 };
50 enum { CURSOR_UP, CURSOR_DOWN, CURSOR_LEFT, CURSOR_RIGHT, CURSOR_HIDE = 1, 
51        CURSOR_DRAW = 0, CURSOR_SAVE, CURSOR_LOAD };
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 hide;
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 xcursor(int);
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, .hide = 0};
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         term.c.x = x < 0 ? 0 : x >= term.col ? term.col-1 : x;
419         term.c.y = y < 0 ? 0 : y >= term.row ? term.row-1 : y;
420 }
421
422 void
423 tsetchar(char c) {
424         term.line[term.c.y][term.c.x] = term.c.attr;
425         term.line[term.c.y][term.c.x].c = c;
426         term.line[term.c.y][term.c.x].state |= GLYPH_SET;
427 }
428
429 void
430 tclearregion(int x1, int y1, int x2, int y2) {
431         int y, temp;
432
433         if(x1 > x2)
434                 temp = x1, x1 = x2, x2 = temp;
435         if(y1 > y2)
436                 temp = y1, y1 = y2, y2 = temp;
437
438         LIMIT(x1, 0, term.col-1);
439         LIMIT(x2, 0, term.col-1);
440         LIMIT(y1, 0, term.row-1);
441         LIMIT(y2, 0, term.row-1);
442
443         for(y = y1; y <= y2; y++)
444                 memset(&term.line[y][x1], 0, sizeof(Glyph)*(x2-x1+1));
445 }
446
447 void
448 tdeletechar(int n) {
449         int src = term.c.x + n;
450         int dst = term.c.x;
451         int size = term.col - src;
452
453         if(src >= term.col) {
454                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
455                 return;
456         }
457         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
458         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
459 }
460
461 void
462 tinsertblank(int n) {
463         int src = term.c.x;
464         int dst = src + n;
465         int size = term.col - dst;
466
467         if(dst >= term.col) {
468                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
469                 return;
470         }
471         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
472         tclearregion(src, term.c.y, dst - 1, term.c.y);
473 }
474
475 void
476 tinsertblankline(int n) {
477         int i;
478         Line blank;
479         int bot = term.bot;
480
481         if(term.c.y > term.bot)
482                 bot = term.row - 1;
483         else if(term.c.y < term.top)
484                 bot = term.top - 1;
485         if(term.c.y + n >= bot) {
486                 tclearregion(0, term.c.y, term.col-1, bot);
487                 return;
488         }
489         for(i = bot; i >= term.c.y+n; i--) {
490                 /* swap deleted line <-> blanked line */
491                 blank = term.line[i];
492                 term.line[i] = term.line[i-n];
493                 term.line[i-n] = blank;
494                 /* blank it */
495                 memset(blank, 0, term.col * sizeof(Glyph));
496         }
497 }
498
499 void
500 tdeleteline(int n) {
501         int i;
502         Line blank;
503         int bot = term.bot;
504
505         if(term.c.y > term.bot)
506                 bot = term.row - 1;
507         else if(term.c.y < term.top)
508                 bot = term.top - 1;
509         if(term.c.y + n >= bot) {
510                 tclearregion(0, term.c.y, term.col-1, bot);
511                 return;
512         }
513         for(i = term.c.y; i <= bot-n; i++) {
514                 /* swap deleted line <-> blanked line */
515                 blank = term.line[i];
516                 term.line[i] = term.line[i+n];
517                 term.line[i+n] = blank;
518                 /* blank it */
519                 memset(blank, 0, term.col * sizeof(Glyph));
520         }
521 }
522
523 void
524 tsetattr(int *attr, int l) {
525         int i;
526
527         for(i = 0; i < l; i++) {
528                 switch(attr[i]) {
529                 case 0:
530                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
531                         term.c.attr.fg = DefaultFG;
532                         term.c.attr.bg = DefaultBG;
533                         break;
534                 case 1:
535                         term.c.attr.mode |= ATTR_BOLD;   
536                         break;
537                 case 4: 
538                         term.c.attr.mode |= ATTR_UNDERLINE;
539                         break;
540                 case 7: 
541                         term.c.attr.mode |= ATTR_REVERSE;       
542                         break;
543                 case 22: 
544                         term.c.attr.mode &= ~ATTR_BOLD;  
545                         break;
546                 case 24: 
547                         term.c.attr.mode &= ~ATTR_UNDERLINE;
548                         break;
549                 case 27: 
550                         term.c.attr.mode &= ~ATTR_REVERSE;       
551                         break;
552                 case 38:
553                         if (i + 2 < l && attr[i + 1] == 5) {
554                                 i += 2;
555                                 if (BETWEEN(attr[i], 0, 255))
556                                         term.c.attr.fg = attr[i];
557                                 else
558                                         fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
559                         }
560                         else
561                                 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]); 
562                         break;
563                 case 39:
564                         term.c.attr.fg = DefaultFG;
565                         break;
566                 case 48:
567                         if (i + 2 < l && attr[i + 1] == 5) {
568                                 i += 2;
569                                 if (BETWEEN(attr[i], 0, 255))
570                                         term.c.attr.bg = attr[i];
571                                 else
572                                         fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
573                         }
574                         else
575                                 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]); 
576                         break;
577                 case 49:
578                         term.c.attr.bg = DefaultBG;
579                         break;
580                 default:
581                         if(BETWEEN(attr[i], 30, 37))
582                                 term.c.attr.fg = attr[i] - 30;
583                         else if(BETWEEN(attr[i], 40, 47))
584                                 term.c.attr.bg = attr[i] - 40;
585                         else if(BETWEEN(attr[i], 90, 97))
586                                 term.c.attr.fg = attr[i] - 90 + 8;
587                         else if(BETWEEN(attr[i], 100, 107))
588                                 term.c.attr.fg = attr[i] - 100 + 8;
589                         else 
590                                 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]); 
591                         break;
592                 }
593         }
594 }
595
596 void
597 tsetscroll(int t, int b) {
598         int temp;
599
600         LIMIT(t, 0, term.row-1);
601         LIMIT(b, 0, term.row-1);
602         if(t > b) {
603                 temp = t;
604                 t = b;
605                 b = temp;
606         }
607         term.top = t;
608         term.bot = b;    
609 }
610
611 void
612 csihandle(void) {
613         switch(escseq.mode) {
614         default:
615         unknown:
616                 printf("erresc: unknown csi ");
617                 csidump();
618                 /* die(""); */
619                 break;
620         case '@': /* ICH -- Insert <n> blank char */
621                 DEFAULT(escseq.arg[0], 1);
622                 tinsertblank(escseq.arg[0]);
623                 break;
624         case 'A': /* CUU -- Cursor <n> Up */
625         case 'e':
626                 DEFAULT(escseq.arg[0], 1);
627                 tmoveto(term.c.x, term.c.y-escseq.arg[0]);
628                 break;
629         case 'B': /* CUD -- Cursor <n> Down */
630                 DEFAULT(escseq.arg[0], 1);
631                 tmoveto(term.c.x, term.c.y+escseq.arg[0]);
632                 break;
633         case 'C': /* CUF -- Cursor <n> Forward */
634         case 'a':
635                 DEFAULT(escseq.arg[0], 1);
636                 tmoveto(term.c.x+escseq.arg[0], term.c.y);
637                 break;
638         case 'D': /* CUB -- Cursor <n> Backward */
639                 DEFAULT(escseq.arg[0], 1);
640                 tmoveto(term.c.x-escseq.arg[0], term.c.y);
641                 break;
642         case 'E': /* CNL -- Cursor <n> Down and first col */
643                 DEFAULT(escseq.arg[0], 1);
644                 tmoveto(0, term.c.y+escseq.arg[0]);
645                 break;
646         case 'F': /* CPL -- Cursor <n> Up and first col */
647                 DEFAULT(escseq.arg[0], 1);
648                 tmoveto(0, term.c.y-escseq.arg[0]);
649                 break;
650         case 'G': /* CHA -- Move to <col> */
651         case '`': /* XXX: HPA -- same? */
652                 DEFAULT(escseq.arg[0], 1);
653                 tmoveto(escseq.arg[0]-1, term.c.y);
654                 break;
655         case 'H': /* CUP -- Move to <row> <col> */
656         case 'f': /* XXX: HVP -- same? */
657                 DEFAULT(escseq.arg[0], 1);
658                 DEFAULT(escseq.arg[1], 1);
659                 tmoveto(escseq.arg[1]-1, escseq.arg[0]-1);
660                 break;
661         /* XXX: (CSI n I) CHT -- Cursor Forward Tabulation <n> tab stops */
662         case 'J': /* ED -- Clear screen */
663                 switch(escseq.arg[0]) {
664                 case 0: /* below */
665                         tclearregion(term.c.x, term.c.y, term.col-1, term.row-1);
666                         break;
667                 case 1: /* above */
668                         tclearregion(0, 0, term.c.x, term.c.y);
669                         break;
670                 case 2: /* all */
671                         tclearregion(0, 0, term.col-1, term.row-1);
672                         break;
673                 case 3: /* XXX: erase saved lines (xterm) */
674                 default:
675                         goto unknown;
676                 }
677                 break;
678         case 'K': /* EL -- Clear line */
679                 switch(escseq.arg[0]) {
680                 case 0: /* right */
681                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
682                         break;
683                 case 1: /* left */
684                         tclearregion(0, term.c.y, term.c.x, term.c.y);
685                         break;
686                 case 2: /* all */
687                         tclearregion(0, term.c.y, term.col-1, term.c.y);
688                         break;
689                 }
690                 break;
691         case 'S': /* SU -- Scroll <n> line up */
692                 DEFAULT(escseq.arg[0], 1);
693                 tscrollup(escseq.arg[0]);
694                 break;
695         case 'T': /* SD -- Scroll <n> line down */
696                 DEFAULT(escseq.arg[0], 1);
697                 tscrolldown(escseq.arg[0]);
698                 break;
699         case 'L': /* IL -- Insert <n> blank lines */
700                 DEFAULT(escseq.arg[0], 1);
701                 tinsertblankline(escseq.arg[0]);
702                 break;
703         case 'l': /* RM -- Reset Mode */
704                 if(escseq.priv) {
705                         switch(escseq.arg[0]) {
706                         case 1:
707                                 term.mode &= ~MODE_APPKEYPAD;
708                                 break;
709                         case 7:
710                                 term.mode &= ~MODE_WRAP;
711                                 break;
712                         case 12: /* att610 -- Stop blinking cursor (IGNORED) */
713                                 break;
714                         case 25:
715                                 term.c.hide = CURSOR_HIDE;
716                                 break;
717                         case 1048: /* XXX: no alt. screen to erase/save */
718                         case 1049:
719                                 tcursor(CURSOR_LOAD);
720                                 tclearregion(0, 0, term.col-1, term.row-1);
721                                 break;
722                         default:
723                                 goto unknown;
724                         }
725                 } else {
726                         switch(escseq.arg[0]) {
727                         case 4:
728                                 term.mode &= ~MODE_INSERT;
729                                 break;
730                         default:
731                                 goto unknown;
732                         }
733                 }
734                 break;
735         case 'M': /* DL -- Delete <n> lines */
736                 DEFAULT(escseq.arg[0], 1);
737                 tdeleteline(escseq.arg[0]);
738                 break;
739         case 'X': /* ECH -- Erase <n> char */
740                 DEFAULT(escseq.arg[0], 1);
741                 tclearregion(term.c.x, term.c.y, term.c.x + escseq.arg[0], term.c.y);
742                 break;
743         case 'P': /* DCH -- Delete <n> char */
744                 DEFAULT(escseq.arg[0], 1);
745                 tdeletechar(escseq.arg[0]);
746                 break;
747         /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
748         case 'd': /* VPA -- Move to <row> */
749                 DEFAULT(escseq.arg[0], 1);
750                 tmoveto(term.c.x, escseq.arg[0]-1);
751                 break;
752         case 'h': /* SM -- Set terminal mode */
753                 if(escseq.priv) {
754                         switch(escseq.arg[0]) {
755                         case 1:
756                                 term.mode |= MODE_APPKEYPAD;
757                                 break;
758                         case 7:
759                                 term.mode |= MODE_WRAP;
760                                 break;
761                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
762                                 break;
763                         case 25:
764                                 term.c.hide = CURSOR_DRAW;
765                                 break;
766                         case 1048: 
767                         case 1049: /* XXX: no alt. screen to erase/save */
768                                 tcursor(CURSOR_SAVE);
769                                 tclearregion(0, 0, term.col-1, term.row-1);
770                                 break;
771                         default: goto unknown;
772                         }
773                 } else {
774                         switch(escseq.arg[0]) {
775                         case 4:
776                                 term.mode |= MODE_INSERT;
777                                 break;
778                         default: goto unknown;
779                         }
780                 };
781                 break;
782         case 'm': /* SGR -- Terminal attribute (color) */
783                 tsetattr(escseq.arg, escseq.narg);
784                 break;
785         case 'r': /* DECSTBM -- Set Scrolling Region */
786                 if(escseq.priv)
787                         goto unknown;
788                 else {
789                         DEFAULT(escseq.arg[0], 1);
790                         DEFAULT(escseq.arg[1], term.row);
791                         tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
792                 }
793                 break;
794         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
795                 tcursor(CURSOR_SAVE);
796                 break;
797         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
798                 tcursor(CURSOR_LOAD);
799                 break;
800         }
801 }
802
803 void
804 csidump(void) { 
805         int i;
806         printf("ESC [ %s", escseq.priv ? "? " : "");
807         if(escseq.narg)
808                 for(i = 0; i < escseq.narg; i++)
809                         printf("%d ", escseq.arg[i]);
810         if(escseq.mode)
811                 putchar(escseq.mode);
812         putchar('\n');
813 }
814
815 void
816 csireset(void) {
817         memset(&escseq, 0, sizeof(escseq));
818 }
819
820 void
821 tputtab(void) {
822         int space = TAB - term.c.x % TAB;
823         tmoveto(term.c.x + space, term.c.y);
824 }
825
826 void
827 tputc(char c) {
828         if(term.esc & ESC_START) {
829                 if(term.esc & ESC_CSI) {
830                         escseq.buf[escseq.len++] = c;
831                         if(BETWEEN(c, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
832                                 term.esc = 0;
833                                 csiparse(), csihandle();
834                         }
835                 } else if(term.esc & ESC_OSC) {
836                         if(c == ';') {
837                                 term.titlelen = 0;
838                                 term.esc = ESC_START | ESC_TITLE;
839                         }
840                 } else if(term.esc & ESC_TITLE) {
841                         if(c == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
842                                 term.esc = 0;
843                                 term.title[term.titlelen] = '\0';
844                                 XStoreName(xw.dis, xw.win, term.title);
845                         } else {
846                                 term.title[term.titlelen++] = c;
847                         }
848                 } else if(term.esc & ESC_ALTCHARSET) {
849                         switch(c) {
850                         case '0': /* Line drawing crap */
851                                 term.c.attr.mode |= ATTR_GFX;
852                                 break;
853                         case 'B': /* Back to regular text */
854                                 term.c.attr.mode &= ~ATTR_GFX;
855                                 break;
856                         default:
857                                 printf("esc unhandled charset: ESC ( %c\n", c);
858                         }
859                         term.esc = 0;
860                 } else {
861                         switch(c) {
862                         case '[':
863                                 term.esc |= ESC_CSI;
864                                 break;
865                         case ']':
866                                 term.esc |= ESC_OSC;
867                                 break;
868                         case '(':
869                                 term.esc |= ESC_ALTCHARSET;
870                                 break;
871                         case 'A':
872                                 tmoveto(term.c.x, term.c.y-1);
873                                 term.esc = 0;
874                                 break;
875                         case 'B':
876                                 tmoveto(term.c.x, term.c.y+1);
877                                 term.esc = 0;
878                                 break;
879                         case 'C':
880                                 tmoveto(term.c.x+1, term.c.y);
881                                 term.esc = 0;
882                                 break;
883                         case 'D': /* XXX: CUP (VT100) or IND (VT52) ... */
884                                 tmoveto(term.c.x-1, term.c.y);
885                                 term.esc = 0;
886                                 break;
887                         case 'E': /* NEL -- Next line */
888                                 tnewline();
889                                 term.esc = 0;
890                                 break;
891                         case 'M': /* RI -- Reverse index */
892                                 if(term.c.y == term.top)
893                                         tscrolldown(1);
894                                 else
895                                         tmoveto(term.c.x, term.c.y-1);
896                                 term.esc = 0;
897                                 break;
898                         case 'c': /* RIS -- Reset to inital state */
899                                 treset();
900                                 term.esc = 0;
901                                 break;
902                         case '=': /* DECPAM */
903                                 term.mode |= MODE_APPKEYPAD;
904                                 term.esc = 0;
905                                 break;
906                         case '>': /* DECPNM */
907                                 term.mode &= ~MODE_APPKEYPAD;
908                                 term.esc = 0;
909                                 break;
910                         case '7':
911                                 tcursor(CURSOR_SAVE);
912                                 term.esc = 0;
913                                 break;
914                         case '8':
915                                 tcursor(CURSOR_LOAD);
916                                 term.esc = 0;
917                                 break;
918                         default:
919                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n", c, isprint(c)?c:'.');
920                                 term.esc = 0;
921                         }
922                 }
923         } else {
924                 switch(c) {
925                 case '\t':
926                         tputtab();
927                         break;
928                 case '\b':
929                         tmoveto(term.c.x-1, term.c.y);
930                         break;
931                 case '\r':
932                         tmoveto(0, term.c.y);
933                         break;
934                 case '\n':
935                         tnewline();
936                         break;
937                 case '\a':
938                         xbell();
939                         break;
940                 case '\033':
941                         csireset();
942                         term.esc = ESC_START;
943                         break;
944                 default:
945                         tsetchar(c);
946                         if(term.c.x+1 < term.col) {
947                                 tmoveto(term.c.x+1, term.c.y);
948                         } else if(IS_SET(MODE_WRAP))
949                                 tnewline();
950                         break;
951                 }
952         }
953 }
954
955 void
956 tputs(char *s, int len) {
957         for(; len > 0; len--)
958                 tputc(*s++);
959 }
960
961 void
962 tresize(int col, int row) {
963         int i;
964         int minrow = MIN(row, term.row);
965         int mincol = MIN(col, term.col);
966
967         if(col < 1 || row < 1)
968                 return;
969
970         /* free uneeded rows */
971         for(i = row; i < term.row; i++)
972                 free(term.line[i]);
973
974         /* resize to new height */
975         term.line = realloc(term.line, row * sizeof(Line));
976
977         /* resize each row to new width, zero-pad if needed */
978         for(i = 0; i < minrow; i++) {
979                 term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
980                 memset(term.line[i] + mincol, 0, (col - mincol) * sizeof(Glyph));
981         }
982
983         /* allocate any new rows */
984         for(/* i == minrow */; i < row; i++)
985                 term.line[i] = calloc(col, sizeof(Glyph));
986         
987         LIMIT(term.c.x, 0, col-1);
988         LIMIT(term.c.y, 0, row-1);
989         LIMIT(term.top, 0, row-1);
990         LIMIT(term.bot, 0, row-1);
991         
992         term.bot = row-1;
993         term.col = col, term.row = row;
994 }
995
996 void
997 xloadcols(void) {
998         int i, r, g, b;
999         XColor color;
1000         Colormap cmap = DefaultColormap(xw.dis, xw.scr);
1001         unsigned long white = WhitePixel(xw.dis, xw.scr);
1002
1003         for(i = 0; i < 16; i++) {
1004                 if (!XAllocNamedColor(xw.dis, cmap, colorname[i], &color, &color)) {
1005                         dc.col[i] = white;
1006                         fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
1007                 } else
1008                         dc.col[i] = color.pixel;
1009         }
1010
1011         /* same colors as xterm */
1012         for(r = 0; r < 6; r++)
1013                 for(g = 0; g < 6; g++)
1014                         for(b = 0; b < 6; b++) {
1015                                 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1016                                 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1017                                 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1018                                 if (!XAllocColor(xw.dis, cmap, &color)) {
1019                                         dc.col[i] = white;
1020                                         fprintf(stderr, "Could not allocate color %d\n", i);
1021                                 } else
1022                                         dc.col[i] = color.pixel;
1023                                 i++;
1024                         }
1025
1026         for(r = 0; r < 24; r++, i++) {
1027                 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
1028                 if (!XAllocColor(xw.dis, cmap, &color)) {
1029                         dc.col[i] = white;
1030                         fprintf(stderr, "Could not allocate color %d\n", i);
1031                 } else
1032                         dc.col[i] = color.pixel;
1033         }
1034 }
1035
1036 void
1037 xclear(int x1, int y1, int x2, int y2) {
1038         XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
1039         XFillRectangle(xw.dis, xw.buf, dc.gc,
1040                        x1 * xw.cw, y1 * xw.ch,
1041                        (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
1042 }
1043
1044 void
1045 xhints(void)
1046 {
1047         XClassHint class = {TNAME, TNAME};
1048         XWMHints wm = {.flags = InputHint, .input = 1};
1049         XSizeHints size = {
1050                 .flags = PSize | PResizeInc | PBaseSize,
1051                 .height = xw.h,
1052                 .width = xw.w,
1053                 .height_inc = xw.ch,
1054                 .width_inc = xw.cw,
1055                 .base_height = 2*BORDER,
1056                 .base_width = 2*BORDER,
1057         };
1058         XSetWMProperties(xw.dis, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
1059 }
1060
1061 void
1062 xinit(void) {
1063         if(!(xw.dis = XOpenDisplay(NULL)))
1064                 die("Can't open display\n");
1065         xw.scr = XDefaultScreen(xw.dis);
1066         
1067         /* font */
1068         if(!(dc.font = XLoadQueryFont(xw.dis, FONT)) || !(dc.bfont = XLoadQueryFont(xw.dis, BOLDFONT)))
1069                 die("Can't load font %s\n", dc.font ? BOLDFONT : FONT);
1070
1071         /* XXX: Assuming same size for bold font */
1072         xw.cw = dc.font->max_bounds.rbearing - dc.font->min_bounds.lbearing;
1073         xw.ch = dc.font->ascent + dc.font->descent;
1074
1075         /* colors */
1076         xloadcols();
1077
1078         term.c.attr.fg = DefaultFG;
1079         term.c.attr.bg = DefaultBG;
1080         term.c.attr.mode = ATTR_NULL;
1081         /* windows */
1082         xw.h = term.row * xw.ch + 2*BORDER;
1083         xw.w = term.col * xw.cw + 2*BORDER;
1084         xw.win = XCreateSimpleWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
1085                         xw.w, xw.h, 0,
1086                         dc.col[DefaultBG],
1087                         dc.col[DefaultBG]);
1088         xw.bufw = xw.w - 2*BORDER;
1089         xw.bufh = xw.h - 2*BORDER;
1090         xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1091         /* gc */
1092         dc.gc = XCreateGC(xw.dis, xw.win, 0, NULL);
1093         XMapWindow(xw.dis, xw.win);
1094         xhints();
1095         XStoreName(xw.dis, xw.win, "st");
1096         XSync(xw.dis, 0);
1097 }
1098
1099 void
1100 xdraws(char *s, Glyph base, int x, int y, int len) {
1101         unsigned long xfg, xbg;
1102         int winx = x*xw.cw, winy = y*xw.ch + dc.font->ascent, width = len*xw.cw;
1103         int i;
1104
1105         if(base.mode & ATTR_REVERSE)
1106                 xfg = dc.col[base.bg], xbg = dc.col[base.fg];
1107         else
1108                 xfg = dc.col[base.fg], xbg = dc.col[base.bg];
1109
1110         XSetBackground(xw.dis, dc.gc, xbg);
1111         XSetForeground(xw.dis, dc.gc, xfg);
1112         
1113         if(base.mode & ATTR_GFX)
1114                 for(i = 0; i < len; i++)
1115                         s[i] = gfx[(int)s[i]];
1116
1117         XSetFont(xw.dis, dc.gc, base.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
1118         XDrawImageString(xw.dis, xw.buf, dc.gc, winx, winy, s, len);
1119         
1120         if(base.mode & ATTR_UNDERLINE)
1121                 XDrawLine(xw.dis, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
1122 }
1123
1124 void
1125 xcursor(int mode) {
1126         static int oldx = 0;
1127         static int oldy = 0;
1128         Glyph g = {' ', ATTR_NULL, DefaultBG, DefaultCS, 0};
1129         
1130         LIMIT(oldx, 0, term.col-1);
1131         LIMIT(oldy, 0, term.row-1);
1132         
1133         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
1134                 g.c = term.line[term.c.y][term.c.x].c;
1135         
1136         /* remove the old cursor */
1137         if(term.line[oldy][oldx].state & GLYPH_SET)
1138                 xdraws(&term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1);
1139         else
1140                 xclear(oldx, oldy, oldx, oldy);
1141         
1142         /* draw the new one */
1143         if(mode == CURSOR_DRAW) {
1144                 xdraws(&g.c, g, term.c.x, term.c.y, 1);
1145                 oldx = term.c.x, oldy = term.c.y;
1146         }
1147 }
1148
1149 #ifdef DEBUG
1150 /* basic drawing routines */
1151 void
1152 xdrawc(int x, int y, Glyph g) {
1153         XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
1154         XSetBackground(xw.dis, dc.gc, dc.col[g.bg]);
1155         XSetForeground(xw.dis, dc.gc, dc.col[g.fg]);
1156         XSetFont(xw.dis, dc.gc, g.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
1157         XDrawImageString(xw.dis, xw.buf, dc.gc, r.x, r.y+dc.font->ascent, &g.c, 1);
1158 }
1159
1160 void
1161 draw(int dummy) {
1162         int x, y;
1163
1164         xclear(0, 0, term.col-1, term.row-1);
1165         for(y = 0; y < term.row; y++)
1166                 for(x = 0; x < term.col; x++)
1167                         if(term.line[y][x].state & GLYPH_SET)
1168                                 xdrawc(x, y, term.line[y][x]);
1169
1170         xcursor(term.c.hide);
1171         XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1172         XFlush(xw.dis);
1173 }
1174
1175 #else
1176 /* optimized drawing routine */
1177 void
1178 draw(int redraw_all) {
1179         int i, x, y, ox;
1180         Glyph base, new;
1181         char buf[DRAW_BUF_SIZ];
1182         
1183         XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
1184         XFillRectangle(xw.dis, xw.buf, dc.gc, 0, 0, xw.bufw, xw.bufh);
1185         for(y = 0; y < term.row; y++) {
1186                 base = term.line[y][0];
1187                 i = ox = 0;
1188                 for(x = 0; x < term.col; x++) {
1189                         new = term.line[y][x];
1190                         if(i > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
1191                                                 i >= DRAW_BUF_SIZ)) {
1192                                 xdraws(buf, base, ox, y, i);
1193                                 i = 0;
1194                         }
1195                         if(new.state & GLYPH_SET) {
1196                                 if(i == 0) {
1197                                         ox = x;
1198                                         base = new;
1199                                 }
1200                                 buf[i++] = new.c;
1201                         }
1202                 }
1203                 if(i > 0)
1204                         xdraws(buf, base, ox, y, i);
1205         }
1206         xcursor(term.c.hide);
1207         XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1208         XFlush(xw.dis);
1209 }
1210
1211 #endif
1212
1213 void
1214 expose(XEvent *ev) {
1215         draw(SCREEN_REDRAW);
1216 }
1217
1218 char*
1219 kmap(KeySym k) {
1220         int i;
1221         for(i = 0; i < LEN(key); i++)
1222                 if(key[i].k == k)
1223                         return (char*)key[i].s;
1224         return NULL;
1225 }
1226
1227 void
1228 kpress(XEvent *ev) {
1229         XKeyEvent *e = &ev->xkey;
1230         KeySym ksym;
1231         char buf[32];
1232         char *customkey;
1233         int len;
1234         int meta;
1235         int shift;
1236
1237         meta = e->state & Mod1Mask;
1238         shift = e->state & ShiftMask;
1239         len = XLookupString(e, buf, sizeof(buf), &ksym, NULL);
1240
1241         if((customkey = kmap(ksym)))
1242                 ttywrite(customkey, strlen(customkey));
1243         else if(len > 0) {
1244                 buf[sizeof(buf)-1] = '\0';
1245                 if(meta && len == 1)
1246                         ttywrite("\033", 1);
1247                 ttywrite(buf, len);
1248         } else
1249                 switch(ksym) {
1250                 case XK_Up:
1251                 case XK_Down:
1252                 case XK_Left:
1253                 case XK_Right:
1254                         sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', "DACB"[ksym - XK_Left]);
1255                         ttywrite(buf, 3);
1256                         break;
1257                 case XK_Insert:
1258                         if(shift)
1259                                 draw(1), puts("draw!")/* XXX: paste X clipboard */;
1260                         break;
1261                 default:
1262                         fprintf(stderr, "errkey: %d\n", (int)ksym);
1263                         break;
1264                 }
1265 }
1266
1267 void
1268 resize(XEvent *e) {
1269         int col, row;
1270         
1271         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
1272                 return;
1273         
1274         xw.w = e->xconfigure.width;
1275         xw.h = e->xconfigure.height;
1276         xw.bufw = xw.w - 2*BORDER;
1277         xw.bufh = xw.h - 2*BORDER;
1278         col = xw.bufw / xw.cw;
1279         row = xw.bufh / xw.ch;
1280         tresize(col, row);
1281         ttyresize(col, row);
1282         XFreePixmap(xw.dis, xw.buf);
1283         xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1284         draw(SCREEN_REDRAW);
1285 }
1286
1287 void
1288 run(void) {
1289         XEvent ev;
1290         fd_set rfd;
1291         int xfd = XConnectionNumber(xw.dis);
1292
1293         running = 1;
1294         XSelectInput(xw.dis, xw.win, ExposureMask | KeyPressMask | StructureNotifyMask);
1295         XResizeWindow(xw.dis, xw.win, xw.w, xw.h); /* XXX: fix resize bug in wmii (?) */
1296
1297         while(running) {
1298                 FD_ZERO(&rfd);
1299                 FD_SET(cmdfd, &rfd);
1300                 FD_SET(xfd, &rfd);
1301                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) < 0) {
1302                         if(errno == EINTR)
1303                                 continue;
1304                         die("select failed: %s\n", SERRNO);
1305                 }
1306                 if(FD_ISSET(cmdfd, &rfd)) {
1307                         ttyread();
1308                         draw(SCREEN_UPDATE); 
1309                 }
1310                 while(XPending(xw.dis)) {
1311                         XNextEvent(xw.dis, &ev);
1312                         if(handler[ev.type])
1313                                 (handler[ev.type])(&ev);
1314                 }
1315         }
1316 }
1317
1318 int
1319 main(int argc, char *argv[]) {
1320         if(argc == 2 && !strncmp("-v", argv[1], 3))
1321                 die("st-" VERSION ", (c) 2010 st engineers\n");
1322         else if(argc != 1)
1323                 die("usage: st [-v]\n");
1324         setlocale(LC_CTYPE, "");
1325         tnew(80, 24);
1326         ttynew();
1327         xinit();
1328         run();
1329         return 0;
1330 }