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