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