Xinqi Bao's Git

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