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