JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
a84f0e02f75349f971248bc09ff312f58e714652
[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 TITLESIZ 256
27 #define ESCSIZ 256
28 #define ESCARGSIZ 16
29 #define MAXDRAWBUF 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 { ATnone=0 , ATreverse=1 , ATunderline=2, ATbold=4 };
42 enum { CSup, CSdown, CSright, CSleft, CShide, CSdraw, CSwrap, CSsave, CSload };
43 enum { CRset=1, CRupdate=2 };
44 enum { TMwrap=1, TMinsert=2, TMtitle=4 };
45 enum { ESCin = 1, ESCcsi = 2, ESCosc = 4, ESCtitle = 8 };
46 enum { SCupdate, SCredraw };
47
48 typedef int Color;
49
50 typedef struct {
51         char c;     /* character code  */
52         char mode;  /* attribute flags */
53         Color fg;   /* foreground      */
54         Color bg;   /* background      */
55         char state; /* state flag      */
56 } Glyph;
57
58 typedef Glyph* Line;
59
60 typedef struct {
61         Glyph attr;  /* current char attributes */
62         char hidden;
63         int x;
64         int y;
65 } TCursor;
66
67 /* CSI Escape sequence structs */
68 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
69 typedef struct {
70         char buf[ESCSIZ]; /* raw string */
71         int len;            /* raw string length */
72         char priv;
73         int arg[ESCARGSIZ];
74         int narg;           /* nb of args */
75         char mode;
76 } CSIEscape;
77
78 /* Internal representation of the screen */
79 typedef struct {
80         int row;    /* nb row */  
81         int col;    /* nb col */
82         Line* line; /* screen */
83         TCursor c;  /* cursor */
84         int top;    /* top    scroll limit */
85         int bot;    /* bottom scroll limit */
86         int mode;   /* terminal mode */
87         int esc;
88         char title[TITLESIZ];
89         int titlelen;
90 } Term;
91
92 /* Purely graphic info */
93 typedef struct {
94         Display* dis;
95         Window win;
96         int scr;
97         int w;  /* window width  */
98         int h;  /* window height */
99         int ch; /* char height */
100         int cw; /* char width  */
101 } XWindow; 
102
103 typedef struct {
104         KeySym k;
105         char s[ESCSIZ];
106 } Key;
107
108 #include "config.h"
109
110 /* Drawing Context */
111 typedef struct {
112         unsigned long col[LEN(colorname)];
113         XFontStruct* font;
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 tcpos(int);
130 static void tcursor(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 tresize(int, int);
141 static void tscroll(void);
142 static void tsetattr(int*, int);
143 static void tsetchar(char);
144 static void tsetscroll(int, int);
145
146 static void ttynew(void);
147 static void ttyread(void);
148 static void ttyresize(int, int);
149 static void ttywrite(const char *, size_t);
150
151 static unsigned long xgetcol(const char *);
152 static void xclear(int, int, int, int);
153 static void xcursor(int);
154 static void xdrawc(int, int, Glyph);
155 static void xinit(void);
156 static void xscroll(void);
157
158 static void expose(XEvent *);
159 static char * kmap(KeySym);
160 static void kpress(XEvent *);
161 static void resize(XEvent *);
162
163 static void (*handler[LASTEvent])(XEvent *) = {
164         [KeyPress] = kpress,
165         [Expose] = expose,
166         [ConfigureNotify] = resize
167 };
168
169 /* Globals */
170 static DC dc;
171 static XWindow xw;
172 static Term term;
173 static CSIEscape escseq;
174 static int cmdfd;
175 static pid_t pid;
176 static int running;
177
178 #ifdef DEBUG
179 void
180 tdump(void) {
181         int row, col;
182         Glyph c;
183
184         for(row = 0; row < term.row; row++) {
185                 for(col = 0; col < term.col; col++) {
186                         if(col == term.c.x && row == term.c.y)
187                                 putchar('#');
188                         else {
189                                 c = term.line[row][col];
190                                 putchar(c.state & CRset ? c.c : '.');
191                         }
192                 }
193                 putchar('\n');
194         }
195 }
196 #endif
197
198 void
199 die(const char *errstr, ...) {
200         va_list ap;
201
202         va_start(ap, errstr);
203         vfprintf(stderr, errstr, ap);
204         va_end(ap);
205         exit(EXIT_FAILURE);
206 }
207
208 void
209 execsh(void) {
210         char *args[3] = {SHELL, "-i", NULL};
211         putenv("TERM=" TNAME);
212         execvp(SHELL, args);
213 }
214
215 void
216 xbell(void) { /* visual bell */
217         XRectangle r = { 0, 0, xw.w, xw.h };
218         XSetForeground(xw.dis, dc.gc, dc.col[BellCol]);
219         XFillRectangles(xw.dis, xw.win, dc.gc, &r, 1);
220         /* usleep(30000); */
221         draw(SCredraw);
222 }
223
224 void 
225 sigchld(int a) {
226         int stat = 0;
227         if(waitpid(pid, &stat, 0) < 0)
228                 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
229         if(WIFEXITED(stat))
230                 exit(WEXITSTATUS(stat));
231         else
232                 exit(EXIT_FAILURE);
233 }
234
235 void
236 ttynew(void) {
237         int m, s;
238         char *pts;
239
240         if((m = posix_openpt(O_RDWR | O_NOCTTY)) < 0)
241                 die("openpt failed: %s\n", SERRNO);
242         if(grantpt(m) < 0)
243                 die("grandpt failed: %s\n", SERRNO);
244         if(unlockpt(m) < 0)
245                 die("unlockpt failed: %s\n", SERRNO);
246         if(!(pts = ptsname(m)))
247                 die("ptsname failed: %s\n", SERRNO);
248         if((s = open(pts, O_RDWR | O_NOCTTY)) < 0)
249                 die("Couldn't open slave: %s\n", SERRNO);
250         fcntl(s, F_SETFL, O_NDELAY);
251         switch(pid = fork()) {
252         case -1:
253                 die("fork failed\n");
254                 break;
255         case 0:
256                 setsid(); /* create a new process group */
257                 dup2(s, STDIN_FILENO);
258                 dup2(s, STDOUT_FILENO);
259                 dup2(s, STDERR_FILENO);
260                 if(ioctl(s, TIOCSCTTY, NULL) < 0)
261                         die("ioctl TTIOCSTTY failed: %s\n", SERRNO);
262                 execsh();
263                 break;
264         default:
265                 close(s);
266                 cmdfd = m;
267                 signal(SIGCHLD, sigchld);
268         }
269 }
270
271 void
272 dump(char c) {
273         static int col;
274         fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
275         if(++col % 10 == 0)
276                 fprintf(stderr, "\n");
277 }
278
279 void
280 ttyread(void) {
281         char buf[BUFSIZ] = {0};
282         int ret;
283
284         switch(ret = read(cmdfd, buf, BUFSIZ)) {
285         case -1: 
286                 die("Couldn't read from shell: %s\n", SERRNO);
287                 break;
288         default:
289                 tputs(buf, ret);
290         }
291 }
292
293 void
294 ttywrite(const char *s, size_t n) {
295         if(write(cmdfd, s, n) == -1)
296                 die("write error on tty: %s\n", SERRNO);
297 }
298
299 void
300 ttyresize(int x, int y) {
301         struct winsize w;
302
303         w.ws_row = term.row;
304         w.ws_col = term.col;
305         w.ws_xpixel = w.ws_ypixel = 0;
306         if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
307                 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
308 }
309
310 void
311 tcpos(int mode) {
312         static int x = 0;
313         static int y = 0;
314
315         if(mode == CSsave)
316                 x = term.c.x, y = term.c.y;
317         else if(mode == CSload)
318                 tmoveto(x, y);
319 }
320
321 void
322 tnew(int col, int row) {   /* screen size */
323         term.row = row, term.col = col;
324         term.top = 0, term.bot = term.row - 1;
325         /* mode */
326         term.mode = TMwrap;
327         /* cursor */
328         term.c.attr.mode = ATnone;
329         term.c.attr.fg = DefaultFG;
330         term.c.attr.bg = DefaultBG;
331         term.c.x = term.c.y = 0;
332         term.c.hidden = 0;
333         /* allocate screen */
334         term.line = calloc(term.row, sizeof(Line));
335         for(row = 0 ; row < term.row; row++)
336                 term.line[row] = calloc(term.col, sizeof(Glyph));
337 }
338
339 void
340 tscroll(void) {
341         Line temp = term.line[term.top];
342         int i;
343         /* X stuff _before_ the line swapping (results in wrong line index) */
344         xscroll();
345         for(i = term.top; i < term.bot; i++)
346                 term.line[i] = term.line[i+1];
347         memset(temp, 0, sizeof(Glyph) * term.col);
348         term.line[term.bot] = temp;
349 }
350
351 void
352 tnewline(void) {
353         int y = term.c.y + 1;
354         if(y > term.bot)
355                 tscroll(), y = term.bot;
356         tmoveto(0, y);
357 }
358
359 void
360 csiparse(void) {
361         /* int noarg = 1; */
362         char *p = escseq.buf;
363
364         escseq.narg = 0;
365         if(*p == '?')
366                 escseq.priv = 1, p++;
367         
368         while(p < escseq.buf+escseq.len) {
369                 while(isdigit(*p)) {
370                         escseq.arg[escseq.narg] *= 10;
371                         escseq.arg[escseq.narg] += *p++ - '0'/*, noarg = 0 */;
372                 }
373                 if(*p == ';' && escseq.narg+1 < ESCARGSIZ)
374                         escseq.narg++, p++;
375                 else {
376                         escseq.mode = *p;
377                         escseq.narg++;
378                         return;
379                 }
380         }
381 }
382
383 void
384 tmoveto(int x, int y) {
385         term.c.x = x < 0 ? 0 : x >= term.col ? term.col-1 : x;
386         term.c.y = y < 0 ? 0 : y >= term.row ? term.row-1 : y;
387 }
388
389 void
390 tcursor(int dir) {
391         int xf = term.c.x, yf = term.c.y;
392
393         switch(dir) {
394         case CSup:
395                 yf--;
396                 break;
397         case CSdown:
398                 yf++;
399                 break;
400         case CSleft:
401                 xf--;
402                 if(xf < 0) {
403                         xf = term.col-1, yf--;
404                         if(yf < term.top)
405                                 yf = term.top, xf = 0;
406                 }
407                 break;
408         case CSright:
409                 xf++;
410                 if(xf >= term.col) {
411                         xf = 0, yf++;
412                         if(yf > term.bot)
413                                 yf = term.bot, tscroll();
414                 }
415                 break;
416         }
417         tmoveto(xf, yf);
418 }
419
420 void
421 tsetchar(char c) {
422         term.line[term.c.y][term.c.x] = term.c.attr;
423         term.line[term.c.y][term.c.x].c = c;
424         term.line[term.c.y][term.c.x].state |= CRset | CRupdate;
425 }
426
427 void
428 tclearregion(int x1, int y1, int x2, int y2) {
429         int x, y;
430
431         LIMIT(x1, 0, term.col-1);
432         LIMIT(x2, 0, term.col-1);
433         LIMIT(y1, 0, term.row-1);
434         LIMIT(y2, 0, term.row-1);
435
436         /* XXX: could be optimized */
437         for(x = x1; x <= x2; x++)
438                 for(y = y1; y <= y2; y++)
439                         memset(&term.line[y][x], 0, sizeof(Glyph));
440
441         xclear(x1, y1, x2, y2);
442 }
443
444 void
445 tdeletechar(int n) {
446         int src = term.c.x + n;
447         int dst = term.c.x;
448         int size = term.col - src;
449
450         if(src >= term.col) {
451                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
452                 return;
453         }
454         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
455         tclearregion(term.col-size, term.c.y, term.col-1, term.c.y);
456 }
457
458 void
459 tinsertblank(int n) {
460         int src = term.c.x;
461         int dst = src + n;
462         int size = term.col - n - src;
463
464         if(dst >= term.col) {
465                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
466                 return;
467         }
468         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
469         tclearregion(src, term.c.y, dst, term.c.y);
470 }
471
472 void
473 tsetlinestate(int n, int state) {
474         int i;
475         for(i = 0; i < term.col; i++)
476                 term.line[n][i].state |= state;
477 }
478
479 void
480 tinsertblankline (int n) {
481         int i;
482         Line blank;
483         int bot = term.bot;
484
485         if(term.c.y > term.bot)
486                 bot = term.row - 1;
487         else if(term.c.y < term.top)
488                 bot = term.top - 1;
489         if(term.c.y + n >= bot) {
490                 tclearregion(0, term.c.y, term.col-1, bot);
491                 return;
492         }
493         for(i = bot; i >= term.c.y+n; i--) {
494                 /* swap deleted line <-> blanked line */
495                 blank = term.line[i];
496                 term.line[i] = term.line[i-n];
497                 term.line[i-n] = blank;
498                 /* blank it */
499                 memset(blank, 0, term.col * sizeof(Glyph));
500                 tsetlinestate(i, CRupdate);
501                 tsetlinestate(i-n, CRupdate);
502         }
503 }
504
505 void
506 tdeleteline(int n) {
507         int i;
508         Line blank;
509         int bot = term.bot;
510
511         if(term.c.y > term.bot)
512                 bot = term.row - 1;
513         else if(term.c.y < term.top)
514                 bot = term.top - 1;
515         if(term.c.y + n >= bot) {
516                 tclearregion(0, term.c.y, term.col-1, bot);
517                 return;
518         }
519         for(i = term.c.y; i <= bot-n; i++) {
520                 /* swap deleted line <-> blanked line */
521                 blank = term.line[i];
522                 term.line[i] = term.line[i+n];
523                 term.line[i+n] = blank;
524                 /* blank it */
525                 memset(blank, 0, term.col * sizeof(Glyph));
526                 tsetlinestate(i, CRupdate);
527                 tsetlinestate(i-n, CRupdate);
528         }
529 }
530
531 void
532 tsetattr(int *attr, int l) {
533         int i;
534
535         for(i = 0; i < l; i++) {
536                 switch(attr[i]) {
537                 case 0:
538                         memset(&term.c.attr, 0, sizeof(term.c.attr));
539                         term.c.attr.fg = DefaultFG;
540                         term.c.attr.bg = DefaultBG;
541                         break;
542                 case 1:
543                         term.c.attr.mode |= ATbold;      
544                         break;
545                 case 4: 
546                         term.c.attr.mode |= ATunderline;
547                         break;
548                 case 7: 
549                         term.c.attr.mode |= ATreverse;  
550                         break;
551                 case 8:
552                         term.c.hidden = CShide;
553                         break;
554                 case 22: 
555                         term.c.attr.mode &= ~ATbold;  
556                         break;
557                 case 24: 
558                         term.c.attr.mode &= ~ATunderline;
559                         break;
560                 case 27: 
561                         term.c.attr.mode &= ~ATreverse;  
562                         break;
563                 case 39:
564                         term.c.attr.fg = DefaultFG;
565                         break;
566                 case 49:
567                         term.c.attr.fg = DefaultBG;
568                         break;
569                 default:
570                         if(BETWEEN(attr[i], 30, 37))
571                                 term.c.attr.fg = attr[i] - 30;
572                         else if(BETWEEN(attr[i], 40, 47))
573                                 term.c.attr.bg = attr[i] - 40;
574                         break;
575                 }
576         }
577 }
578
579 void
580 tsetscroll(int t, int b) {
581         int temp;
582
583         LIMIT(t, 0, term.row-1);
584         LIMIT(b, 0, term.row-1);
585         if(t > b) {
586                 temp = t;
587                 t = b;
588                 b = temp;
589         }
590         term.top = t;
591         term.bot = b;    
592 }
593
594 void
595 csihandle(void) {
596         switch(escseq.mode) {
597         default:
598                 fprintf(stderr, "erresc: unknown sequence\n");
599                 csidump();
600                 /* die(""); */
601                 break;
602         case '@': /* Insert <n> blank char */
603                 DEFAULT(escseq.arg[0], 1);
604                 tinsertblank(escseq.arg[0]);
605                 break;
606         case 'A': /* Cursor <n> Up */
607         case 'e':
608                 DEFAULT(escseq.arg[0], 1);
609                 tmoveto(term.c.x, term.c.y-escseq.arg[0]);
610                 break;
611         case 'B': /* Cursor <n> Down */
612                 DEFAULT(escseq.arg[0], 1);
613                 tmoveto(term.c.x, term.c.y+escseq.arg[0]);
614                 break;
615         case 'C': /* Cursor <n> Forward */
616         case 'a':
617                 DEFAULT(escseq.arg[0], 1);
618                 tmoveto(term.c.x+escseq.arg[0], term.c.y);
619                 break;
620         case 'D': /* Cursor <n> Backward */
621                 DEFAULT(escseq.arg[0], 1);
622                 tmoveto(term.c.x-escseq.arg[0], term.c.y);
623                 break;
624         case 'E': /* Cursor <n> Down and first col */
625                 DEFAULT(escseq.arg[0], 1);
626                 tmoveto(0, term.c.y+escseq.arg[0]);
627                 break;
628         case 'F': /* Cursor <n> Up and first col */
629                 DEFAULT(escseq.arg[0], 1);
630                 tmoveto(0, term.c.y-escseq.arg[0]);
631                 break;
632         case 'G': /* Move to <col> */
633         case '`':
634                 DEFAULT(escseq.arg[0], 1);
635         tmoveto(escseq.arg[0]-1, term.c.y);
636                 break;
637         case 'H': /* Move to <row> <col> */
638         case 'f':
639                 DEFAULT(escseq.arg[0], 1);
640                 DEFAULT(escseq.arg[1], 1);
641                 tmoveto(escseq.arg[1]-1, escseq.arg[0]-1);
642                 break;
643         case 'J': /* Clear screen */
644                 switch(escseq.arg[0]) {
645                 case 0: /* below */
646                         tclearregion(term.c.x, term.c.y, term.col-1, term.row-1);
647                         break;
648                 case 1: /* above */
649                         tclearregion(0, 0, term.c.x, term.c.y);
650                         break;
651                 case 2: /* all */
652                         tclearregion(0, 0, term.col-1, term.row-1);
653                         break;                            
654                 }
655                 break;
656         case 'K': /* Clear line */
657                 switch(escseq.arg[0]) {
658                 case 0: /* right */
659                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
660                         break;
661                 case 1: /* left */
662                         tclearregion(0, term.c.y, term.c.x, term.c.y);
663                         break;
664                 case 2: /* all */
665                         tclearregion(0, term.c.y, term.col-1, term.c.y);
666                         break;
667                 }
668                 break;
669         case 'S':
670         case 'L': /* Insert <n> blank lines */
671                 DEFAULT(escseq.arg[0], 1);
672                 tinsertblankline(escseq.arg[0]);
673                 break;
674         case 'l':
675                 if(escseq.priv && escseq.arg[0] == 25)
676                                 term.c.hidden = 1;
677                 break;
678         case 'M': /* Delete <n> lines */
679                 DEFAULT(escseq.arg[0], 1);
680                 tdeleteline(escseq.arg[0]);
681                 break;
682         case 'X':
683         case 'P': /* Delete <n> char */
684                 DEFAULT(escseq.arg[0], 1);
685                 tdeletechar(escseq.arg[0]);
686                 break;
687         case 'd': /* Move to <row> */
688                 DEFAULT(escseq.arg[0], 1);
689                 tmoveto(term.c.x, escseq.arg[0]-1);
690                 break;
691         case 'h': /* Set terminal mode */
692                 if(escseq.priv && escseq.arg[0] == 25)
693                         term.c.hidden = 0;
694                 break;
695         case 'm': /* Terminal attribute (color) */
696                 tsetattr(escseq.arg, escseq.narg);
697                 break;
698         case 'r':
699                 if(escseq.priv)
700                         ;
701                 else {
702                         DEFAULT(escseq.arg[0], 1);
703                         DEFAULT(escseq.arg[1], term.row);
704                         tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
705                 }
706                 break;
707         case 's': /* Save cursor position */
708                 tcpos(CSsave);
709                 break;
710         case 'u': /* Load cursor position */
711                 tcpos(CSload);
712                 break;
713         }
714 }
715
716 void
717 csidump(void) { 
718         int i;
719         printf("ESC [ %s", escseq.priv ? "? " : "");
720         if(escseq.narg)
721                 for(i = 0; i < escseq.narg; i++)
722                         printf("%d ", escseq.arg[i]);
723         if(escseq.mode)
724                 putchar(escseq.mode);
725         putchar('\n');
726 }
727
728 void
729 csireset(void) {
730         memset(&escseq, 0, sizeof(escseq));
731 }
732
733 void
734 tputtab(void) {
735         int space = TAB - term.c.x % TAB;
736         
737         if(term.c.x + space >= term.col)
738                 space--;
739         
740         for(; space > 0; space--)
741                 tcursor(CSright);
742 }
743
744 void
745 tputc(char c) {
746 #if 0
747         dump(c);
748 #endif  
749         if(term.esc & ESCin) {
750                 if(term.esc & ESCcsi) {
751                         escseq.buf[escseq.len++] = c;
752                         if(BETWEEN(c, 0x40, 0x7E) || escseq.len >= ESCSIZ) {
753                                 term.esc = 0;
754                                 csiparse(), csihandle();
755                         }
756                 } else if (term.esc & ESCosc) {
757                         if(c == ';') {
758                                 term.titlelen = 0;
759                                 term.esc = ESCin | ESCtitle;
760                         }
761                 } else if(term.esc & ESCtitle) {
762                         if(c == '\a' || term.titlelen+1 >= TITLESIZ) {
763                                 term.esc = 0;
764                                 term.title[term.titlelen] = '\0';
765                                 XStoreName(xw.dis, xw.win, term.title);
766                         } else {
767                                 term.title[term.titlelen++] = c;
768                         }
769                 } else {                
770                         switch(c) {
771                         case '[':
772                                 term.esc |= ESCcsi;
773                                 break;
774                         case ']':
775                                 term.esc |= ESCosc;
776                                 break;
777                         }
778                 }
779         } else {
780                 switch(c) {
781                 case '\t':
782                         tputtab();
783                         break;
784                 case '\b':
785                         tcursor(CSleft);
786                         break;
787                 case '\r':
788                         tmoveto(0, term.c.y);
789                         break;
790                 case '\n':
791                         tnewline();
792                         break;
793                 case '\a':
794                         xbell();
795                         break;
796                 case '\033':
797                         csireset();
798                         term.esc = ESCin;
799                         break;
800                 default:
801                         tsetchar(c);
802                         tcursor(CSright);
803                         break;
804                 }
805         }
806 }
807
808 void
809 tputs(char *s, int len) { 
810         for(; len > 0; len--)
811                 tputc(*s++);
812 }
813
814 void
815 tresize(int col, int row) {
816         int i;
817         Line *line;
818         int minrow = MIN(row, term.row);
819         int mincol = MIN(col, term.col);
820
821         if(col < 1 || row < 1)
822                 return;
823         /* alloc */
824         line = calloc(row, sizeof(Line));
825         for(i = 0 ; i < row; i++)
826                 line[i] = calloc(col, sizeof(Glyph));
827         /* copy */
828         for(i = 0 ; i < minrow; i++)
829                 memcpy(line[i], term.line[i], mincol * sizeof(Glyph));
830         /* free */
831         for(i = 0; i < term.row; i++)
832                 free(term.line[i]);
833         free(term.line);
834         
835         LIMIT(term.c.x, 0, col-1);
836         LIMIT(term.c.y, 0, row-1);
837         LIMIT(term.top, 0, row-1);
838         LIMIT(term.bot, 0, row-1);
839         
840         term.bot = row-1;
841         term.line = line;
842         term.col = col, term.row = row;
843 }
844
845 unsigned long
846 xgetcol(const char *s) {
847         XColor color;
848         Colormap cmap = DefaultColormap(xw.dis, xw.scr);
849
850         if(!XAllocNamedColor(xw.dis, cmap, s, &color, &color)) {
851                 color.pixel = WhitePixel(xw.dis, xw.scr);
852                 fprintf(stderr, "Could not allocate color '%s'\n", s);
853         }
854         return color.pixel;
855 }
856
857 void
858 xclear(int x1, int y1, int x2, int y2) {
859         XClearArea(xw.dis, xw.win, 
860                         x1 * xw.cw, y1 * xw.ch, 
861                         (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch, 
862                         False);
863 }
864
865 void
866 xscroll(void) {
867         int srcy = (term.top+1) * xw.ch;
868         int dsty = term.top * xw.ch;
869         int height = (term.bot-term.top) * xw.ch;
870
871         xcursor(CShide);
872         XCopyArea(xw.dis, xw.win, xw.win, dc.gc, 0, srcy, xw.w, height, 0, dsty);
873         xclear(0, term.bot, term.col-1, term.bot);
874 }
875
876 void
877 xinit(void) {
878         XGCValues values;
879         unsigned long valuemask;
880         XClassHint chint;
881         XWMHints wmhint;
882         XSizeHints shint;
883         char *args[] = {NULL};
884         int i;
885
886         xw.dis = XOpenDisplay(NULL);
887         xw.scr = XDefaultScreen(xw.dis);
888         if(!xw.dis)
889                 die("Can't open display\n");
890         
891         /* font */
892         if(!(dc.font = XLoadQueryFont(xw.dis, FONT)))
893                 die("Can't load font %s\n", FONT);
894
895         xw.cw = dc.font->max_bounds.rbearing - dc.font->min_bounds.lbearing;
896         xw.ch = dc.font->ascent + dc.font->descent + LINESPACE;
897
898         /* colors */
899         for(i = 0; i < LEN(colorname); i++)
900                 dc.col[i] = xgetcol(colorname[i]);
901
902         term.c.attr.fg = DefaultFG;
903         term.c.attr.bg = DefaultBG;
904         term.c.attr.mode = ATnone;
905         /* windows */
906         xw.h = term.row * xw.ch;
907         xw.w = term.col * xw.cw;
908         /* XXX: this BORDER is useless after the first resize, handle it in xdraws() */
909         xw.win = XCreateSimpleWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
910                         xw.w, xw.h, BORDER, 
911                         dc.col[DefaultBG],
912                         dc.col[DefaultBG]);
913         /* gc */
914         values.foreground = XWhitePixel(xw.dis, xw.scr);
915         values.font = dc.font->fid;
916         valuemask = GCForeground | GCFont;
917         dc.gc = XCreateGC(xw.dis, xw.win, valuemask, &values);
918         XMapWindow(xw.dis, xw.win);
919         /* wm stuff */
920         chint.res_name = TNAME, chint.res_class = TNAME;
921         wmhint.input = 1, wmhint.flags = InputHint;
922         shint.height_inc = xw.ch, shint.width_inc = xw.cw;
923         shint.height = xw.h, shint.width = xw.w;
924         shint.flags = PSize | PResizeInc;
925         XSetWMProperties(xw.dis, xw.win, NULL, NULL, &args[0], 0, &shint, &wmhint, &chint);
926         XStoreName(xw.dis, xw.win, TNAME);
927         XSync(xw.dis, 0);
928 }
929
930 void
931 xdraws (char *s, Glyph base, int x, int y, int len) {
932         unsigned long xfg, xbg;
933         int winx = x*xw.cw, winy = y*xw.ch + dc.font->ascent, width = len*xw.cw;
934         if(base.mode & ATreverse)
935                 xfg = dc.col[base.bg], xbg = dc.col[base.fg];
936         else
937                 xfg = dc.col[base.fg], xbg = dc.col[base.bg];
938
939         XSetBackground(xw.dis, dc.gc, xbg);
940         XSetForeground(xw.dis, dc.gc, xfg);
941         XDrawImageString(xw.dis, xw.win, dc.gc, winx, winy, s, len);
942         
943         if(base.mode & ATunderline)
944                 XDrawLine(xw.dis, xw.win, dc.gc, winx, winy+1, winx+width-1, winy+1);
945 }
946
947 void
948 xdrawc(int x, int y, Glyph g) {
949         XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
950         unsigned long xfg, xbg;
951
952         /* reverse video */
953         if(g.mode & ATreverse)
954                 xfg = dc.col[g.bg], xbg = dc.col[g.fg];
955         else
956                 xfg = dc.col[g.fg], xbg = dc.col[g.bg];
957         /* background */
958         XSetBackground(xw.dis, dc.gc, xbg);
959         XSetForeground(xw.dis, dc.gc, xfg);
960         XDrawImageString(xw.dis, xw.win, dc.gc, r.x, r.y+dc.font->ascent, &g.c, 1);
961 }
962
963 void
964 xcursor(int mode) {
965         static int oldx = 0;
966         static int oldy = 0;
967         Glyph g = {' ', ATnone, DefaultBG, DefaultCS, 0};
968         
969         LIMIT(oldx, 0, term.col-1);
970         LIMIT(oldy, 0, term.row-1);
971         
972         if(term.line[term.c.y][term.c.x].state & CRset)
973                 g.c = term.line[term.c.y][term.c.x].c;
974         /* remove the old cursor */
975         if(term.line[oldy][oldx].state & CRset)
976                 xdrawc(oldx, oldy, term.line[oldy][oldx]);
977         else 
978                 xclear(oldx, oldy, oldx, oldy);
979         /* draw the new one */
980         if(mode == CSdraw) {
981                 xdrawc(term.c.x, term.c.y, g);
982                 oldx = term.c.x, oldy = term.c.y;
983         }
984 }
985
986 void
987 draw(int redraw_all) {
988         int i, x, y, ox;
989         Glyph base, new;
990         char buf[MAXDRAWBUF];
991         
992         for(y = 0; y < term.row; y++) {
993                 base = term.line[y][0];
994                 i = ox = 0;
995                 for(x = 0; x < term.col; x++) {
996                         new = term.line[y][x];
997                         if(!ATTRCMP(base, new) && i < MAXDRAWBUF)
998                                 buf[i++] = new.c;
999                         else {
1000                                 xdraws(buf, base, ox, y, i);
1001                                 buf[0] = new.c;
1002                                 i = 1;
1003                                 ox = x;
1004                                 base = new;
1005                         }
1006                 }
1007                 xdraws(buf, base, ox, y, i);
1008         }
1009         xcursor(CSdraw);
1010 }
1011
1012 void
1013 expose(XEvent *ev) {
1014         draw(SCredraw);
1015 }
1016
1017 char *
1018 kmap(KeySym k) {
1019         int i;
1020         for(i = 0; i < LEN(key); i++)
1021                 if(key[i].k == k)
1022                         return (char*)key[i].s;
1023         return NULL;
1024 }
1025
1026 void
1027 kpress(XEvent *ev) {
1028         XKeyEvent *e = &ev->xkey;
1029         KeySym ksym;
1030         char buf[32];
1031         char *customkey;
1032         int len;
1033         int meta;
1034         int shift;
1035
1036         meta  = e->state & Mod1Mask;
1037         shift = e->state & ShiftMask;
1038         len = XLookupString(e, buf, sizeof(buf), &ksym, NULL);
1039
1040         if(customkey = kmap(ksym))
1041                 ttywrite(customkey, strlen(customkey));
1042         else if(len > 0) {
1043                 buf[sizeof(buf)-1] = '\0';
1044                 if(meta && len == 1)
1045                         ttywrite("\033", 1);
1046                 ttywrite(buf, len);
1047         } else
1048                 switch(ksym) {
1049                 case XK_Insert:
1050                         if(shift)
1051                                 /* XXX: paste X clipboard */;
1052                         break;
1053                 default:
1054                         fprintf(stderr, "errkey: %d\n", (int)ksym);
1055                         break;
1056                 }
1057 }
1058
1059 void
1060 resize(XEvent *e) {
1061         int col, row;
1062         col = e->xconfigure.width / xw.cw;
1063         row = e->xconfigure.height / xw.ch;
1064         
1065         if(term.col != col || term.row != row) {
1066                 tresize(col, row);
1067                 ttyresize(col, row);
1068                 xw.w = e->xconfigure.width;
1069                 xw.h = e->xconfigure.height;
1070                 draw(SCredraw);
1071         }
1072 }
1073
1074 void
1075 run(void) {
1076         XEvent ev;
1077         fd_set rfd;
1078         int xfd = XConnectionNumber(xw.dis);
1079
1080         running = 1;
1081         XSelectInput(xw.dis, xw.win, ExposureMask | KeyPressMask | StructureNotifyMask);
1082         XResizeWindow(xw.dis, xw.win, xw.w , xw.h); /* fix resize bug in wmii (?) */
1083
1084         while(running) {
1085                 FD_ZERO(&rfd);
1086                 FD_SET(cmdfd, &rfd);
1087                 FD_SET(xfd, &rfd);
1088                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) == -1) {
1089                         if(errno == EINTR)
1090                                 continue;
1091                         die("select failed: %s\n", SERRNO);
1092                 }
1093                 if(FD_ISSET(cmdfd, &rfd)) {
1094                         ttyread();
1095                         draw(SCupdate);
1096                 }
1097                 while(XPending(xw.dis)) {
1098                         XNextEvent(xw.dis, &ev);
1099                         if(handler[ev.type])
1100                                 (handler[ev.type])(&ev);
1101                 }
1102         }
1103 }
1104
1105 int
1106 main(int argc, char *argv[]) {
1107         if(argc == 2 && !strncmp("-v", argv[1], 3))
1108                 die("st-" VERSION ", © 2009 st engineers\n");
1109         else if(argc != 1)
1110                 die("usage: st [-v]\n");
1111         setlocale(LC_CTYPE, "");
1112         tnew(80, 24);
1113         ttynew();
1114         xinit();
1115         run();
1116         return 0;
1117 }