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