Xinqi Bao's Git

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