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