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