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