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