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