JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
removed (visual) bell. '\a' sets the urgency flag if st is unfocused.
[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,
50        CURSOR_SAVE, CURSOR_LOAD };
51 enum { CURSOR_DEFAULT = 0, CURSOR_HIDE = 1, CURSOR_WRAPNEXT = 2 };
52 enum { GLYPH_SET=1, GLYPH_DIRTY=2 };
53 enum { MODE_WRAP=1, MODE_INSERT=2, MODE_APPKEYPAD=4 };
54 enum { ESC_START=1, ESC_CSI=2, ESC_OSC=4, ESC_TITLE=8, ESC_ALTCHARSET=16 };
55 enum { SCREEN_UPDATE, SCREEN_REDRAW };
56
57 typedef struct {
58         char c;     /* character code  */
59         char mode;  /* attribute flags */
60         int fg;     /* foreground      */
61         int bg;     /* background      */
62         char state; /* state flags     */
63 } Glyph;
64
65 typedef Glyph* Line;
66
67 typedef struct {
68         Glyph attr;      /* current char attributes */
69         int x;
70         int y;
71         char state;
72 } TCursor;
73
74 /* CSI Escape sequence structs */
75 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
76 typedef struct {
77         char buf[ESC_BUF_SIZ]; /* raw string */
78         int len;                           /* raw string length */
79         char priv;
80         int arg[ESC_ARG_SIZ];
81         int narg;                          /* nb of args */
82         char mode;
83 } CSIEscape;
84
85 /* Internal representation of the screen */
86 typedef struct {
87         int row;        /* nb row */  
88         int col;        /* nb col */
89         Line* line; /* screen */
90         TCursor c;      /* cursor */
91         int top;        /* top    scroll limit */
92         int bot;        /* bottom scroll limit */
93         int mode;       /* terminal mode flags */
94         int esc;        /* escape state flags */
95         char title[ESC_TITLE_SIZ];
96         int titlelen;
97 } Term;
98
99 /* Purely graphic info */
100 typedef struct {
101         Display* dis;
102         Window win;
103         Pixmap buf;
104         int scr;
105         int w;  /* window width  */
106         int h;  /* window height */
107         int bufw; /* pixmap width  */
108         int bufh; /* pixmap height */
109         int ch; /* char height */
110         int cw; /* char width  */
111         int hasfocus;
112 } XWindow; 
113
114 typedef struct {
115         KeySym k;
116         char s[ESC_BUF_SIZ];
117 } Key;
118
119 /* Drawing Context */
120 typedef struct {
121         unsigned long col[256];
122         XFontStruct* font;
123         XFontStruct* bfont;
124         GC gc;
125 } DC;
126
127 #include "config.h"
128
129 static void die(const char *errstr, ...);
130 static void draw(int);
131 static void execsh(void);
132 static void sigchld(int);
133 static void run(void);
134
135 static void csidump(void);
136 static void csihandle(void);
137 static void csiparse(void);
138 static void csireset(void);
139
140 static void tclearregion(int, int, int, int);
141 static void tcursor(int);
142 static void tdeletechar(int);
143 static void tdeleteline(int);
144 static void tinsertblank(int);
145 static void tinsertblankline(int);
146 static void tmoveto(int, int);
147 static void tnew(int, int);
148 static void tnewline(void);
149 static void tputtab(void);
150 static void tputc(char);
151 static void tputs(char*, int);
152 static void treset(void);
153 static void tresize(int, int);
154 static void tscrollup(int);
155 static void tscrolldown(int);
156 static void tsetattr(int*, int);
157 static void tsetchar(char);
158 static void tsetscroll(int, int);
159
160 static void ttynew(void);
161 static void ttyread(void);
162 static void ttyresize(int, int);
163 static void ttywrite(const char *, size_t);
164
165 static void xdraws(char *, Glyph, int, int, int);
166 static void xhints(void);
167 static void xclear(int, int, int, int);
168 static void xdrawcursor(void);
169 static void xinit(void);
170 static void xloadcols(void);
171 static void xseturgency(int);
172
173 static void expose(XEvent *);
174 static char* kmap(KeySym);
175 static void kpress(XEvent *);
176 static void resize(XEvent *);
177 static void focus(XEvent *);
178
179
180 static void (*handler[LASTEvent])(XEvent *) = {
181         [KeyPress] = kpress,
182         [Expose] = expose,
183         [ConfigureNotify] = resize,
184         [FocusIn] = focus,
185         [FocusOut] = focus,
186 };
187
188 /* Globals */
189 static DC dc;
190 static XWindow xw;
191 static Term term;
192 static CSIEscape escseq;
193 static int cmdfd;
194 static pid_t pid;
195
196 #ifdef DEBUG
197 void
198 tdump(void) {
199         int row, col;
200         Glyph c;
201
202         for(row = 0; row < term.row; row++) {
203                 for(col = 0; col < term.col; col++) {
204                         if(col == term.c.x && row == term.c.y)
205                                 putchar('#');
206                         else {
207                                 c = term.line[row][col];
208                                 putchar(c.state & GLYPH_SET ? c.c : '.');
209                         }
210                 }
211                 putchar('\n');
212         }
213 }
214 #endif
215
216 void
217 die(const char *errstr, ...) {
218         va_list ap;
219
220         va_start(ap, errstr);
221         vfprintf(stderr, errstr, ap);
222         va_end(ap);
223         exit(EXIT_FAILURE);
224 }
225
226 void
227 execsh(void) {
228         char *args[3] = {getenv("SHELL"), "-i", NULL};
229         DEFAULT(args[0], "/bin/sh"); /* if getenv() failed */
230         putenv("TERM=" TNAME);
231         execvp(args[0], args);
232 }
233
234 void 
235 sigchld(int a) {
236         int stat = 0;
237         if(waitpid(pid, &stat, 0) < 0)
238                 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
239         if(WIFEXITED(stat))
240                 exit(WEXITSTATUS(stat));
241         else
242                 exit(EXIT_FAILURE);
243 }
244
245 void
246 ttynew(void) {
247         int m, s;
248         
249         /* seems to work fine on linux, openbsd and freebsd */
250         struct winsize w = {term.row, term.col, 0, 0};
251         if(openpty(&m, &s, NULL, NULL, &w) < 0)
252                 die("openpty failed: %s\n", SERRNO);
253
254         switch(pid = fork()) {
255         case -1:
256                 die("fork failed\n");
257                 break;
258         case 0:
259                 setsid(); /* create a new process group */
260                 dup2(s, STDIN_FILENO);
261                 dup2(s, STDOUT_FILENO);
262                 dup2(s, STDERR_FILENO);
263                 if(ioctl(s, TIOCSCTTY, NULL) < 0)
264                         die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
265                 close(s);
266                 close(m);
267                 execsh();
268                 break;
269         default:
270                 close(s);
271                 cmdfd = m;
272                 signal(SIGCHLD, sigchld);
273         }
274 }
275
276 void
277 dump(char c) {
278         static int col;
279         fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
280         if(++col % 10 == 0)
281                 fprintf(stderr, "\n");
282 }
283
284 void
285 ttyread(void) {
286         char buf[BUFSIZ] = {0};
287         int ret;
288
289         if((ret = read(cmdfd, buf, BUFSIZ)) < 0)
290                 die("Couldn't read from shell: %s\n", SERRNO);
291         else
292                 tputs(buf, ret);
293 }
294
295 void
296 ttywrite(const char *s, size_t n) {
297         if(write(cmdfd, s, n) == -1)
298                 die("write error on tty: %s\n", SERRNO);
299 }
300
301 void
302 ttyresize(int x, int y) {
303         struct winsize w;
304
305         w.ws_row = term.row;
306         w.ws_col = term.col;
307         w.ws_xpixel = w.ws_ypixel = 0;
308         if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
309                 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
310 }
311
312 void
313 tcursor(int mode) {
314         static TCursor c;
315
316         if(mode == CURSOR_SAVE)
317                 c = term.c;
318         else if(mode == CURSOR_LOAD)
319                 term.c = c, tmoveto(c.x, c.y);
320 }
321
322 void
323 treset(void) {
324         term.c = (TCursor){{
325                 .mode = ATTR_NULL, 
326                 .fg = DefaultFG, 
327                 .bg = DefaultBG
328         }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
329         
330         term.top = 0, term.bot = term.row - 1;
331         term.mode = MODE_WRAP;
332         tclearregion(0, 0, term.col-1, term.row-1);
333 }
334
335 void
336 tnew(int col, int row) {
337         /* set screen size */
338         term.row = row, term.col = col;
339         term.line = malloc(term.row * sizeof(Line));
340         for(row = 0 ; row < term.row; row++)
341                 term.line[row] = malloc(term.col * sizeof(Glyph));
342         /* setup screen */
343         treset();
344 }
345
346 void
347 tscrolldown (int n) {
348         int i;
349         Line temp;
350         
351         LIMIT(n, 0, term.bot-term.top+1);
352
353         for(i = 0; i < n; i++)
354                 memset(term.line[term.bot-i], 0, term.col*sizeof(Glyph));
355         
356         for(i = term.bot; i >= term.top+n; i--) {
357                 temp = term.line[i];
358                 term.line[i] = term.line[i-n];
359                 term.line[i-n] = temp;
360         }
361 }
362
363 void
364 tscrollup (int n) {
365         int i;
366         Line temp;
367         LIMIT(n, 0, term.bot-term.top+1);
368         
369         for(i = 0; i < n; i++)
370                 memset(term.line[term.top+i], 0, term.col*sizeof(Glyph));
371         
372         for(i = term.top; i <= term.bot-n; i++) { 
373                  temp = term.line[i];
374                  term.line[i] = term.line[i+n]; 
375                  term.line[i+n] = temp;
376         }
377 }
378
379 void
380 tnewline(void) {
381         int y = term.c.y + 1;
382         if(y > term.bot)
383                 tscrollup(1), y = term.bot;
384         tmoveto(0, y);
385 }
386
387 void
388 csiparse(void) {
389         /* int noarg = 1; */
390         char *p = escseq.buf;
391
392         escseq.narg = 0;
393         if(*p == '?')
394                 escseq.priv = 1, p++;
395         
396         while(p < escseq.buf+escseq.len) {
397                 while(isdigit(*p)) {
398                         escseq.arg[escseq.narg] *= 10;
399                         escseq.arg[escseq.narg] += *p++ - '0'/*, noarg = 0 */;
400                 }
401                 if(*p == ';' && escseq.narg+1 < ESC_ARG_SIZ)
402                         escseq.narg++, p++;
403                 else {
404                         escseq.mode = *p;
405                         escseq.narg++;
406                         return;
407                 }
408         }
409 }
410
411 void
412 tmoveto(int x, int y) {
413         LIMIT(x, 0, term.col-1);
414         LIMIT(y, 0, term.row-1);
415         term.c.state &= ~CURSOR_WRAPNEXT;
416         term.c.x = x;
417         term.c.y = 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.state |= CURSOR_HIDE;
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.state &= ~CURSOR_HIDE;
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                         tmoveto(0, 0);
791                 }
792                 break;
793         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
794                 tcursor(CURSOR_SAVE);
795                 break;
796         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
797                 tcursor(CURSOR_LOAD);
798                 break;
799         }
800 }
801
802 void
803 csidump(void) { 
804         int i;
805         printf("ESC [ %s", escseq.priv ? "? " : "");
806         if(escseq.narg)
807                 for(i = 0; i < escseq.narg; i++)
808                         printf("%d ", escseq.arg[i]);
809         if(escseq.mode)
810                 putchar(escseq.mode);
811         putchar('\n');
812 }
813
814 void
815 csireset(void) {
816         memset(&escseq, 0, sizeof(escseq));
817 }
818
819 void
820 tputtab(void) {
821         int space = TAB - term.c.x % TAB;
822         tmoveto(term.c.x + space, term.c.y);
823 }
824
825 void
826 tputc(char c) {
827         if(term.esc & ESC_START) {
828                 if(term.esc & ESC_CSI) {
829                         escseq.buf[escseq.len++] = c;
830                         if(BETWEEN(c, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
831                                 term.esc = 0;
832                                 csiparse(), csihandle();
833                         }
834                 } else if(term.esc & ESC_OSC) {
835                         if(c == ';') {
836                                 term.titlelen = 0;
837                                 term.esc = ESC_START | ESC_TITLE;
838                         }
839                 } else if(term.esc & ESC_TITLE) {
840                         if(c == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
841                                 term.esc = 0;
842                                 term.title[term.titlelen] = '\0';
843                                 XStoreName(xw.dis, xw.win, term.title);
844                         } else {
845                                 term.title[term.titlelen++] = c;
846                         }
847                 } else if(term.esc & ESC_ALTCHARSET) {
848                         switch(c) {
849                         case '0': /* Line drawing crap */
850                                 term.c.attr.mode |= ATTR_GFX;
851                                 break;
852                         case 'B': /* Back to regular text */
853                                 term.c.attr.mode &= ~ATTR_GFX;
854                                 break;
855                         default:
856                                 printf("esc unhandled charset: ESC ( %c\n", c);
857                         }
858                         term.esc = 0;
859                 } else {
860                         switch(c) {
861                         case '[':
862                                 term.esc |= ESC_CSI;
863                                 break;
864                         case ']':
865                                 term.esc |= ESC_OSC;
866                                 break;
867                         case '(':
868                                 term.esc |= ESC_ALTCHARSET;
869                                 break;
870                         case 'D': /* IND -- Linefeed */
871                                 if(term.c.y == term.bot)
872                                         tscrollup(1);
873                                 else
874                                         tmoveto(term.c.x, term.c.y+1);
875                                 term.esc = 0;
876                                 break;
877                         case 'E': /* NEL -- Next line */
878                                 tnewline();
879                                 term.esc = 0;
880                                 break;
881                         case 'M': /* RI -- Reverse index */
882                                 if(term.c.y == term.top)
883                                         tscrolldown(1);
884                                 else
885                                         tmoveto(term.c.x, term.c.y-1);
886                                 term.esc = 0;
887                                 break;
888                         case 'c': /* RIS -- Reset to inital state */
889                                 treset();
890                                 term.esc = 0;
891                                 break;
892                         case '=': /* DECPAM */
893                                 term.mode |= MODE_APPKEYPAD;
894                                 term.esc = 0;
895                                 break;
896                         case '>': /* DECPNM */
897                                 term.mode &= ~MODE_APPKEYPAD;
898                                 term.esc = 0;
899                                 break;
900                         case '7':
901                                 tcursor(CURSOR_SAVE);
902                                 term.esc = 0;
903                                 break;
904                         case '8':
905                                 tcursor(CURSOR_LOAD);
906                                 term.esc = 0;
907                                 break;
908                         default:
909                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n", c, isprint(c)?c:'.');
910                                 term.esc = 0;
911                         }
912                 }
913         } else {
914                 switch(c) {
915                 case '\t':
916                         tputtab();
917                         break;
918                 case '\b':
919                         tmoveto(term.c.x-1, term.c.y);
920                         break;
921                 case '\r':
922                         tmoveto(0, term.c.y);
923                         break;
924                 case '\n':
925                         tnewline();
926                         break;
927                 case '\a':
928                         if(!xw.hasfocus)
929                                 xseturgency(1);
930                         break;
931                 case '\033':
932                         csireset();
933                         term.esc = ESC_START;
934                         break;
935                 default:
936                         if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
937                                 tnewline();
938                         tsetchar(c);
939                         if(term.c.x+1 < term.col)
940                                 tmoveto(term.c.x+1, term.c.y);
941                         else
942                                 term.c.state |= CURSOR_WRAPNEXT;
943                         break;
944                 }
945         }
946 }
947
948 void
949 tputs(char *s, int len) {
950         for(; len > 0; len--)
951                 tputc(*s++);
952 }
953
954 void
955 tresize(int col, int row) {
956         int i;
957         int minrow = MIN(row, term.row);
958         int mincol = MIN(col, term.col);
959
960         if(col < 1 || row < 1)
961                 return;
962
963         /* free uneeded rows */
964         for(i = row; i < term.row; i++)
965                 free(term.line[i]);
966
967         /* resize to new height */
968         term.line = realloc(term.line, row * sizeof(Line));
969
970         /* resize each row to new width, zero-pad if needed */
971         for(i = 0; i < minrow; i++) {
972                 term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
973                 memset(term.line[i] + mincol, 0, (col - mincol) * sizeof(Glyph));
974         }
975
976         /* allocate any new rows */
977         for(/* i == minrow */; i < row; i++)
978                 term.line[i] = calloc(col, sizeof(Glyph));
979         
980         /* update terminal size */
981         term.col = col, term.row = row;
982         /* make use of the LIMIT in tmoveto */
983         tmoveto(term.c.x, term.c.y);
984         /* reset scrolling region */
985         tsetscroll(0, row-1);
986 }
987
988 void
989 xloadcols(void) {
990         int i, r, g, b;
991         XColor color;
992         Colormap cmap = DefaultColormap(xw.dis, xw.scr);
993         unsigned long white = WhitePixel(xw.dis, xw.scr);
994
995         for(i = 0; i < 16; i++) {
996                 if (!XAllocNamedColor(xw.dis, cmap, colorname[i], &color, &color)) {
997                         dc.col[i] = white;
998                         fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
999                 } else
1000                         dc.col[i] = color.pixel;
1001         }
1002
1003         /* same colors as xterm */
1004         for(r = 0; r < 6; r++)
1005                 for(g = 0; g < 6; g++)
1006                         for(b = 0; b < 6; b++) {
1007                                 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1008                                 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1009                                 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1010                                 if (!XAllocColor(xw.dis, cmap, &color)) {
1011                                         dc.col[i] = white;
1012                                         fprintf(stderr, "Could not allocate color %d\n", i);
1013                                 } else
1014                                         dc.col[i] = color.pixel;
1015                                 i++;
1016                         }
1017
1018         for(r = 0; r < 24; r++, i++) {
1019                 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
1020                 if (!XAllocColor(xw.dis, cmap, &color)) {
1021                         dc.col[i] = white;
1022                         fprintf(stderr, "Could not allocate color %d\n", i);
1023                 } else
1024                         dc.col[i] = color.pixel;
1025         }
1026 }
1027
1028 void
1029 xclear(int x1, int y1, int x2, int y2) {
1030         XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
1031         XFillRectangle(xw.dis, xw.buf, dc.gc,
1032                        x1 * xw.cw, y1 * xw.ch,
1033                        (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
1034 }
1035
1036 void
1037 xhints(void)
1038 {
1039         XClassHint class = {TNAME, TNAME};
1040         XWMHints wm = {.flags = InputHint, .input = 1};
1041         XSizeHints size = {
1042                 .flags = PSize | PResizeInc | PBaseSize,
1043                 .height = xw.h,
1044                 .width = xw.w,
1045                 .height_inc = xw.ch,
1046                 .width_inc = xw.cw,
1047                 .base_height = 2*BORDER,
1048                 .base_width = 2*BORDER,
1049         };
1050         XSetWMProperties(xw.dis, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
1051 }
1052
1053 void
1054 xinit(void) {
1055         if(!(xw.dis = XOpenDisplay(NULL)))
1056                 die("Can't open display\n");
1057         xw.scr = XDefaultScreen(xw.dis);
1058         
1059         /* font */
1060         if(!(dc.font = XLoadQueryFont(xw.dis, FONT)) || !(dc.bfont = XLoadQueryFont(xw.dis, BOLDFONT)))
1061                 die("Can't load font %s\n", dc.font ? BOLDFONT : FONT);
1062
1063         /* XXX: Assuming same size for bold font */
1064         xw.cw = dc.font->max_bounds.rbearing - dc.font->min_bounds.lbearing;
1065         xw.ch = dc.font->ascent + dc.font->descent;
1066
1067         /* colors */
1068         xloadcols();
1069
1070         /* windows */
1071         xw.h = term.row * xw.ch + 2*BORDER;
1072         xw.w = term.col * xw.cw + 2*BORDER;
1073         xw.win = XCreateSimpleWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
1074                         xw.w, xw.h, 0,
1075                         dc.col[DefaultBG],
1076                         dc.col[DefaultBG]);
1077         xw.bufw = xw.w - 2*BORDER;
1078         xw.bufh = xw.h - 2*BORDER;
1079         xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1080         /* gc */
1081         dc.gc = XCreateGC(xw.dis, xw.win, 0, NULL);
1082         XMapWindow(xw.dis, xw.win);
1083         xhints();
1084         XStoreName(xw.dis, xw.win, "st");
1085         XSync(xw.dis, 0);
1086 }
1087
1088 void
1089 xdraws(char *s, Glyph base, int x, int y, int len) {
1090         unsigned long xfg, xbg;
1091         int winx = x*xw.cw, winy = y*xw.ch + dc.font->ascent, width = len*xw.cw;
1092         int i;
1093
1094         if(base.mode & ATTR_REVERSE)
1095                 xfg = dc.col[base.bg], xbg = dc.col[base.fg];
1096         else
1097                 xfg = dc.col[base.fg], xbg = dc.col[base.bg];
1098
1099         XSetBackground(xw.dis, dc.gc, xbg);
1100         XSetForeground(xw.dis, dc.gc, xfg);
1101         
1102         if(base.mode & ATTR_GFX)
1103                 for(i = 0; i < len; i++)
1104                         s[i] = gfx[(int)s[i]];
1105
1106         XSetFont(xw.dis, dc.gc, base.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
1107         XDrawImageString(xw.dis, xw.buf, dc.gc, winx, winy, s, len);
1108         
1109         if(base.mode & ATTR_UNDERLINE)
1110                 XDrawLine(xw.dis, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
1111 }
1112
1113 void
1114 xdrawcursor(void) {
1115         static int oldx = 0;
1116         static int oldy = 0;
1117         Glyph g = {' ', ATTR_NULL, DefaultBG, DefaultCS, 0};
1118         
1119         LIMIT(oldx, 0, term.col-1);
1120         LIMIT(oldy, 0, term.row-1);
1121         
1122         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
1123                 g.c = term.line[term.c.y][term.c.x].c;
1124         
1125         /* remove the old cursor */
1126         if(term.line[oldy][oldx].state & GLYPH_SET)
1127                 xdraws(&term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1);
1128         else
1129                 xclear(oldx, oldy, oldx, oldy);
1130         
1131         /* draw the new one */
1132         if(!(term.c.state & CURSOR_HIDE)) {
1133                 xdraws(&g.c, g, term.c.x, term.c.y, 1);
1134                 oldx = term.c.x, oldy = term.c.y;
1135         }
1136 }
1137
1138 #ifdef DEBUG
1139 /* basic drawing routines */
1140 void
1141 xdrawc(int x, int y, Glyph g) {
1142         XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
1143         XSetBackground(xw.dis, dc.gc, dc.col[g.bg]);
1144         XSetForeground(xw.dis, dc.gc, dc.col[g.fg]);
1145         XSetFont(xw.dis, dc.gc, g.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
1146         XDrawImageString(xw.dis, xw.buf, dc.gc, r.x, r.y+dc.font->ascent, &g.c, 1);
1147 }
1148
1149 void
1150 draw(int dummy) {
1151         int x, y;
1152
1153         xclear(0, 0, term.col-1, term.row-1);
1154         for(y = 0; y < term.row; y++)
1155                 for(x = 0; x < term.col; x++)
1156                         if(term.line[y][x].state & GLYPH_SET)
1157                                 xdrawc(x, y, term.line[y][x]);
1158
1159         xdrawcursor();
1160         XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1161         XFlush(xw.dis);
1162 }
1163
1164 #else
1165 /* optimized drawing routine */
1166 void
1167 draw(int redraw_all) {
1168         int i, x, y, ox;
1169         Glyph base, new;
1170         char buf[DRAW_BUF_SIZ];
1171         
1172         XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
1173         XFillRectangle(xw.dis, xw.buf, dc.gc, 0, 0, xw.bufw, xw.bufh);
1174         for(y = 0; y < term.row; y++) {
1175                 base = term.line[y][0];
1176                 i = ox = 0;
1177                 for(x = 0; x < term.col; x++) {
1178                         new = term.line[y][x];
1179                         if(i > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
1180                                                 i >= DRAW_BUF_SIZ)) {
1181                                 xdraws(buf, base, ox, y, i);
1182                                 i = 0;
1183                         }
1184                         if(new.state & GLYPH_SET) {
1185                                 if(i == 0) {
1186                                         ox = x;
1187                                         base = new;
1188                                 }
1189                                 buf[i++] = new.c;
1190                         }
1191                 }
1192                 if(i > 0)
1193                         xdraws(buf, base, ox, y, i);
1194         }
1195         xdrawcursor();
1196         XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1197         XFlush(xw.dis);
1198 }
1199
1200 #endif
1201
1202 void
1203 expose(XEvent *ev) {
1204         draw(SCREEN_REDRAW);
1205 }
1206
1207 void
1208 xseturgency(int add) {
1209         XWMHints *h = XGetWMHints(xw.dis, xw.win);
1210         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
1211         XSetWMHints(xw.dis, xw.win, h);
1212         XFree(h);
1213 }
1214
1215 void
1216 focus(XEvent *ev) {
1217         if((xw.hasfocus = ev->type == FocusIn))
1218                 xseturgency(0);
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         long mask = ExposureMask | KeyPressMask | StructureNotifyMask | FocusChangeMask;
1296
1297         XSelectInput(xw.dis, xw.win, mask);
1298         XResizeWindow(xw.dis, xw.win, xw.w, xw.h); /* XXX: fix resize bug in wmii (?) */
1299
1300         while(1) {
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) < 0) {
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 }