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