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