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