Xinqi Bao's Git

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