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