Xinqi Bao's Git

added LNM mode; re-organized kpress() to handle it.
[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/Xatom.h>
21 #include <X11/keysym.h>
22 #include <X11/Xutil.h>
23
24 #if defined(__linux)
25 #include <pty.h>
26 #elif defined(__OpenBSD__) || defined(__NetBSD__)
27 #include <util.h>
28 #elif defined(__FreeBSD__) || defined(__DragonFly__)
29 #include <libutil.h>
30 #endif
31
32 #define USAGE \
33 "st-" VERSION ", (c) 2010 st engineers\n" \
34 "usage: st [-t title] [-e cmd] [-v]\n"
35
36 /* Arbitrary sizes */
37 #define ESC_TITLE_SIZ 256
38 #define ESC_BUF_SIZ 256
39 #define ESC_ARG_SIZ 16
40 #define DRAW_BUF_SIZ 1024
41
42 #define SERRNO strerror(errno)
43 #define MIN(a, b) ((a) < (b) ? (a) : (b))
44 #define MAX(a, b) ((a) < (b) ? (b) : (a))
45 #define LEN(a) (sizeof(a) / sizeof(a[0]))
46 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
47 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
48 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
49 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
50 #define IS_SET(flag) (term.mode & (flag))
51
52 /* Attribute, Cursor, Character state, Terminal mode, Screen draw mode */
53 enum { ATTR_NULL=0 , ATTR_REVERSE=1 , ATTR_UNDERLINE=2, ATTR_BOLD=4, ATTR_GFX=8 };
54 enum { CURSOR_UP, CURSOR_DOWN, CURSOR_LEFT, CURSOR_RIGHT,
55 CURSOR_SAVE, CURSOR_LOAD };
56 enum { CURSOR_DEFAULT = 0, CURSOR_HIDE = 1, CURSOR_WRAPNEXT = 2 };
57 enum { GLYPH_SET=1, GLYPH_DIRTY=2 };
58 enum { MODE_WRAP=1, MODE_INSERT=2, MODE_APPKEYPAD=4, MODE_ALTSCREEN=8,
59 MODE_CRLF=16 };
60 enum { ESC_START=1, ESC_CSI=2, ESC_OSC=4, ESC_TITLE=8, ESC_ALTCHARSET=16 };
61 enum { SCREEN_UPDATE, SCREEN_REDRAW };
62 enum { WIN_VISIBLE=1, WIN_REDRAW=2, WIN_FOCUSED=4 };
63
64 typedef struct {
65 char c; /* character code */
66 char mode; /* attribute flags */
67 int fg; /* foreground */
68 int bg; /* background */
69 char state; /* state flags */
70 } Glyph;
71
72 typedef Glyph* Line;
73
74 typedef struct {
75 Glyph attr; /* current char attributes */
76 int x;
77 int y;
78 char state;
79 } TCursor;
80
81 /* CSI Escape sequence structs */
82 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
83 typedef struct {
84 char buf[ESC_BUF_SIZ]; /* raw string */
85 int len; /* raw string length */
86 char priv;
87 int arg[ESC_ARG_SIZ];
88 int narg; /* nb of args */
89 char mode;
90 } CSIEscape;
91
92 /* Internal representation of the screen */
93 typedef struct {
94 int row; /* nb row */
95 int col; /* nb col */
96 Line* line; /* screen */
97 Line* alt; /* alternate screen */
98 TCursor c; /* cursor */
99 int top; /* top scroll limit */
100 int bot; /* bottom scroll limit */
101 int mode; /* terminal mode flags */
102 int esc; /* escape state flags */
103 char title[ESC_TITLE_SIZ];
104 int titlelen;
105 } Term;
106
107 /* Purely graphic info */
108 typedef struct {
109 Display* dis;
110 Colormap cmap;
111 Window win;
112 Pixmap buf;
113 XIM xim;
114 XIC xic;
115 int scr;
116 int w; /* window width */
117 int h; /* window height */
118 int bufw; /* pixmap width */
119 int bufh; /* pixmap height */
120 int ch; /* char height */
121 int cw; /* char width */
122 char state; /* focus, redraw, visible */
123 } XWindow;
124
125 typedef struct {
126 KeySym k;
127 char s[ESC_BUF_SIZ];
128 } Key;
129
130 /* Drawing Context */
131 typedef struct {
132 unsigned long col[256];
133 XFontStruct* font;
134 XFontStruct* bfont;
135 GC gc;
136 } DC;
137
138 /* TODO: use better name for vars... */
139 typedef struct {
140 int mode;
141 int bx, by;
142 int ex, ey;
143 struct {int x, y;} b, e;
144 char *clip;
145 } Selection;
146
147 #include "config.h"
148
149 static void die(const char *errstr, ...);
150 static void draw(int);
151 static void execsh(void);
152 static void sigchld(int);
153 static void run(void);
154
155 static void csidump(void);
156 static void csihandle(void);
157 static void csiparse(void);
158 static void csireset(void);
159
160 static void tclearregion(int, int, int, int);
161 static void tcursor(int);
162 static void tdeletechar(int);
163 static void tdeleteline(int);
164 static void tinsertblank(int);
165 static void tinsertblankline(int);
166 static void tmoveto(int, int);
167 static void tnew(int, int);
168 static void tnewline(int);
169 static void tputtab(void);
170 static void tputc(char);
171 static void tputs(char*, int);
172 static void treset(void);
173 static void tresize(int, int);
174 static void tscrollup(int, int);
175 static void tscrolldown(int, int);
176 static void tsetattr(int*, int);
177 static void tsetchar(char);
178 static void tsetscroll(int, int);
179 static void tswapscreen(void);
180
181 static void ttynew(void);
182 static void ttyread(void);
183 static void ttyresize(int, int);
184 static void ttywrite(const char *, size_t);
185
186 static void xdraws(char *, Glyph, int, int, int);
187 static void xhints(void);
188 static void xclear(int, int, int, int);
189 static void xdrawcursor(void);
190 static void xinit(void);
191 static void xloadcols(void);
192 static void xseturgency(int);
193
194 static void expose(XEvent *);
195 static void visibility(XEvent *);
196 static void unmap(XEvent *);
197 static char* kmap(KeySym);
198 static void kpress(XEvent *);
199 static void resize(XEvent *);
200 static void focus(XEvent *);
201 static void brelease(XEvent *);
202 static void bpress(XEvent *);
203 static void bmotion(XEvent *);
204 static void selection_notify(XEvent *);
205 static void selection_request(XEvent *);
206
207 static void (*handler[LASTEvent])(XEvent *) = {
208 [KeyPress] = kpress,
209 [ConfigureNotify] = resize,
210 [VisibilityNotify] = visibility,
211 [UnmapNotify] = unmap,
212 [Expose] = expose,
213 [FocusIn] = focus,
214 [FocusOut] = focus,
215 [MotionNotify] = bmotion,
216 [ButtonPress] = bpress,
217 [ButtonRelease] = brelease,
218 [SelectionNotify] = selection_notify,
219 [SelectionRequest] = selection_request,
220 };
221
222 /* Globals */
223 static DC dc;
224 static XWindow xw;
225 static Term term;
226 static CSIEscape escseq;
227 static int cmdfd;
228 static pid_t pid;
229 static Selection sel;
230 static char *opt_cmd = NULL;
231 static char *opt_title = NULL;
232
233 void
234 selinit(void) {
235 sel.mode = 0;
236 sel.bx = -1;
237 sel.clip = NULL;
238 }
239
240 static inline int selected(int x, int y) {
241 if(sel.ey == y && sel.by == y) {
242 int bx = MIN(sel.bx, sel.ex);
243 int ex = MAX(sel.bx, sel.ex);
244 return BETWEEN(x, bx, ex);
245 }
246 return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
247 || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
248 }
249
250 static void getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
251 if(b)
252 *b = e->xbutton.button;
253
254 *x = e->xbutton.x/xw.cw;
255 *y = e->xbutton.y/xw.ch;
256 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
257 sel.b.y = MIN(sel.by, sel.ey);
258 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
259 sel.e.y = MAX(sel.by, sel.ey);
260 }
261
262 static void bpress(XEvent *e) {
263 sel.mode = 1;
264 sel.ex = sel.bx = e->xbutton.x/xw.cw;
265 sel.ey = sel.by = e->xbutton.y/xw.ch;
266 }
267
268 static char *getseltext() {
269 char *str, *ptr;
270 int ls, x, y, sz;
271 if(sel.bx == -1)
272 return NULL;
273 sz = (term.col+1) * (sel.e.y-sel.b.y+1);
274 ptr = str = malloc(sz);
275 for(y = 0; y < term.row; y++) {
276 for(x = 0; x < term.col; x++)
277 if(term.line[y][x].state & GLYPH_SET && (ls = selected(x, y)))
278 *ptr = term.line[y][x].c, ptr++;
279 if(ls)
280 *ptr = '\n', ptr++;
281 }
282 *ptr = 0;
283 return str;
284 }
285
286 static void selection_notify(XEvent *e) {
287 unsigned long nitems;
288 unsigned long length;
289 int format, res;
290 unsigned char *data;
291 Atom type;
292
293 res = XGetWindowProperty(xw.dis, xw.win, XA_PRIMARY, 0, 0, False,
294 AnyPropertyType, &type, &format, &nitems, &length, &data);
295 switch(res) {
296 case BadAtom:
297 case BadValue:
298 case BadWindow:
299 fprintf(stderr, "Invalid paste, XGetWindowProperty0");
300 return;
301 }
302
303 res = XGetWindowProperty(xw.dis, xw.win, XA_PRIMARY, 0, length, False,
304 AnyPropertyType, &type, &format, &nitems, &length, &data);
305 switch(res) {
306 case BadAtom:
307 case BadValue:
308 case BadWindow:
309 fprintf(stderr, "Invalid paste, XGetWindowProperty0");
310 return;
311 }
312
313 if(data) {
314 ttywrite((const char *) data, nitems * format / 8);
315 XFree(data);
316 }
317 }
318
319 static void selpaste() {
320 XConvertSelection(xw.dis, XA_PRIMARY, XA_STRING, XA_PRIMARY, xw.win, CurrentTime);
321 }
322
323 static void selection_request(XEvent *e)
324 {
325 XSelectionRequestEvent *xsre;
326 XSelectionEvent xev;
327 int res;
328 Atom xa_targets;
329
330 xsre = (XSelectionRequestEvent *) e;
331 xev.type = SelectionNotify;
332 xev.requestor = xsre->requestor;
333 xev.selection = xsre->selection;
334 xev.target = xsre->target;
335 xev.time = xsre->time;
336 /* reject */
337 xev.property = None;
338
339 xa_targets = XInternAtom(xw.dis, "TARGETS", 0);
340 if(xsre->target == xa_targets) {
341 /* respond with the supported type */
342 Atom string = XA_STRING;
343 res = XChangeProperty(xsre->display, xsre->requestor, xsre->property, XA_ATOM, 32,
344 PropModeReplace, (unsigned char *) &string, 1);
345 switch(res) {
346 case BadAlloc:
347 case BadAtom:
348 case BadMatch:
349 case BadValue:
350 case BadWindow:
351 fprintf(stderr, "Error in selection_request, TARGETS");
352 break;
353 default:
354 xev.property = xsre->property;
355 }
356 } else if(xsre->target == XA_STRING) {
357 res = XChangeProperty(xsre->display, xsre->requestor, xsre->property,
358 xsre->target, 8, PropModeReplace, (unsigned char *) sel.clip,
359 strlen(sel.clip));
360 switch(res) {
361 case BadAlloc:
362 case BadAtom:
363 case BadMatch:
364 case BadValue:
365 case BadWindow:
366 fprintf(stderr, "Error in selection_request, XA_STRING");
367 break;
368 default:
369 xev.property = xsre->property;
370 }
371 }
372
373 /* all done, send a notification to the listener */
374 res = XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev);
375 switch(res) {
376 case 0:
377 case BadValue:
378 case BadWindow:
379 fprintf(stderr, "Error in selection_requested, XSendEvent");
380 }
381 }
382
383 static void selcopy(char *str) {
384 /* register the selection for both the clipboard and the primary */
385 Atom clipboard;
386 int res;
387
388 free(sel.clip);
389 sel.clip = str;
390
391 res = XSetSelectionOwner(xw.dis, XA_PRIMARY, xw.win, CurrentTime);
392 switch(res) {
393 case BadAtom:
394 case BadWindow:
395 fprintf(stderr, "Invalid copy, XSetSelectionOwner");
396 return;
397 }
398
399 clipboard = XInternAtom(xw.dis, "CLIPBOARD", 0);
400 res = XSetSelectionOwner(xw.dis, clipboard, xw.win, CurrentTime);
401 switch(res) {
402 case BadAtom:
403 case BadWindow:
404 fprintf(stderr, "Invalid copy, XSetSelectionOwner");
405 return;
406 }
407
408 XFlush(xw.dis);
409 }
410
411 /* TODO: doubleclick to select word */
412 static void brelease(XEvent *e) {
413 int b;
414 sel.mode = 0;
415 getbuttoninfo(e, &b, &sel.ex, &sel.ey);
416 if(sel.bx==sel.ex && sel.by==sel.ey) {
417 sel.bx = -1;
418 if(b==2)
419 selpaste();
420 } else {
421 if(b==1)
422 selcopy(getseltext());
423 }
424 draw(1);
425 }
426
427 static void bmotion(XEvent *e) {
428 if (sel.mode) {
429 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
430 draw(1);
431 }
432 }
433
434 #ifdef DEBUG
435 void
436 tdump(void) {
437 int row, col;
438 Glyph c;
439
440 for(row = 0; row < term.row; row++) {
441 for(col = 0; col < term.col; col++) {
442 if(col == term.c.x && row == term.c.y)
443 putchar('#');
444 else {
445 c = term.line[row][col];
446 putchar(c.state & GLYPH_SET ? c.c : '.');
447 }
448 }
449 putchar('\n');
450 }
451 }
452 #endif
453
454 void
455 die(const char *errstr, ...) {
456 va_list ap;
457
458 va_start(ap, errstr);
459 vfprintf(stderr, errstr, ap);
460 va_end(ap);
461 exit(EXIT_FAILURE);
462 }
463
464 void
465 execsh(void) {
466 char *args[] = {getenv("SHELL"), "-i", NULL};
467 if(opt_cmd)
468 args[0] = opt_cmd, args[1] = NULL;
469 else
470 DEFAULT(args[0], SHELL);
471 putenv("TERM="TNAME);
472 execvp(args[0], args);
473 }
474
475 void
476 sigchld(int a) {
477 int stat = 0;
478 if(waitpid(pid, &stat, 0) < 0)
479 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
480 if(WIFEXITED(stat))
481 exit(WEXITSTATUS(stat));
482 else
483 exit(EXIT_FAILURE);
484 }
485
486 void
487 ttynew(void) {
488 int m, s;
489
490 /* seems to work fine on linux, openbsd and freebsd */
491 struct winsize w = {term.row, term.col, 0, 0};
492 if(openpty(&m, &s, NULL, NULL, &w) < 0)
493 die("openpty failed: %s\n", SERRNO);
494
495 switch(pid = fork()) {
496 case -1:
497 die("fork failed\n");
498 break;
499 case 0:
500 setsid(); /* create a new process group */
501 dup2(s, STDIN_FILENO);
502 dup2(s, STDOUT_FILENO);
503 dup2(s, STDERR_FILENO);
504 if(ioctl(s, TIOCSCTTY, NULL) < 0)
505 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
506 close(s);
507 close(m);
508 execsh();
509 break;
510 default:
511 close(s);
512 cmdfd = m;
513 signal(SIGCHLD, sigchld);
514 }
515 }
516
517 void
518 dump(char c) {
519 static int col;
520 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
521 if(++col % 10 == 0)
522 fprintf(stderr, "\n");
523 }
524
525 void
526 ttyread(void) {
527 char buf[BUFSIZ];
528 int ret;
529
530 if((ret = read(cmdfd, buf, LEN(buf))) < 0)
531 die("Couldn't read from shell: %s\n", SERRNO);
532 else
533 tputs(buf, ret);
534 }
535
536 void
537 ttywrite(const char *s, size_t n) {
538 if(write(cmdfd, s, n) == -1)
539 die("write error on tty: %s\n", SERRNO);
540 }
541
542 void
543 ttyresize(int x, int y) {
544 struct winsize w;
545
546 w.ws_row = term.row;
547 w.ws_col = term.col;
548 w.ws_xpixel = w.ws_ypixel = 0;
549 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
550 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
551 }
552
553 void
554 tcursor(int mode) {
555 static TCursor c;
556
557 if(mode == CURSOR_SAVE)
558 c = term.c;
559 else if(mode == CURSOR_LOAD)
560 term.c = c, tmoveto(c.x, c.y);
561 }
562
563 void
564 treset(void) {
565 term.c = (TCursor){{
566 .mode = ATTR_NULL,
567 .fg = DefaultFG,
568 .bg = DefaultBG
569 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
570
571 term.top = 0, term.bot = term.row - 1;
572 term.mode = MODE_WRAP;
573 tclearregion(0, 0, term.col-1, term.row-1);
574 }
575
576 void
577 tnew(int col, int row) {
578 /* set screen size */
579 term.row = row, term.col = col;
580 term.line = malloc(term.row * sizeof(Line));
581 term.alt = malloc(term.row * sizeof(Line));
582 for(row = 0 ; row < term.row; row++) {
583 term.line[row] = malloc(term.col * sizeof(Glyph));
584 term.alt [row] = malloc(term.col * sizeof(Glyph));
585 }
586 /* setup screen */
587 treset();
588 }
589
590 void
591 tswapscreen(void) {
592 Line* tmp = term.line;
593 term.line = term.alt;
594 term.alt = tmp;
595 term.mode ^= MODE_ALTSCREEN;
596 }
597
598 void
599 tscrolldown(int orig, int n) {
600 int i;
601 Line temp;
602
603 LIMIT(n, 0, term.bot-orig+1);
604
605 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
606
607 for(i = term.bot; i >= orig+n; i--) {
608 temp = term.line[i];
609 term.line[i] = term.line[i-n];
610 term.line[i-n] = temp;
611 }
612 }
613
614 void
615 tscrollup(int orig, int n) {
616 int i;
617 Line temp;
618 LIMIT(n, 0, term.bot-orig+1);
619
620 tclearregion(0, orig, term.col-1, orig+n-1);
621
622 for(i = orig; i <= term.bot-n; i++) {
623 temp = term.line[i];
624 term.line[i] = term.line[i+n];
625 term.line[i+n] = temp;
626 }
627 }
628
629 void
630 tnewline(int first_col) {
631 int y = term.c.y;
632 if(y == term.bot)
633 tscrollup(term.top, 1);
634 else
635 y++;
636 tmoveto(first_col ? 0 : term.c.x, y);
637 }
638
639 void
640 csiparse(void) {
641 /* int noarg = 1; */
642 char *p = escseq.buf;
643
644 escseq.narg = 0;
645 if(*p == '?')
646 escseq.priv = 1, p++;
647
648 while(p < escseq.buf+escseq.len) {
649 while(isdigit(*p)) {
650 escseq.arg[escseq.narg] *= 10;
651 escseq.arg[escseq.narg] += *p++ - '0'/*, noarg = 0 */;
652 }
653 if(*p == ';' && escseq.narg+1 < ESC_ARG_SIZ)
654 escseq.narg++, p++;
655 else {
656 escseq.mode = *p;
657 escseq.narg++;
658 return;
659 }
660 }
661 }
662
663 void
664 tmoveto(int x, int y) {
665 LIMIT(x, 0, term.col-1);
666 LIMIT(y, 0, term.row-1);
667 term.c.state &= ~CURSOR_WRAPNEXT;
668 term.c.x = x;
669 term.c.y = y;
670 }
671
672 void
673 tsetchar(char c) {
674 term.line[term.c.y][term.c.x] = term.c.attr;
675 term.line[term.c.y][term.c.x].c = c;
676 term.line[term.c.y][term.c.x].state |= GLYPH_SET;
677 }
678
679 void
680 tclearregion(int x1, int y1, int x2, int y2) {
681 int x, y, temp;
682
683 if(x1 > x2)
684 temp = x1, x1 = x2, x2 = temp;
685 if(y1 > y2)
686 temp = y1, y1 = y2, y2 = temp;
687
688 LIMIT(x1, 0, term.col-1);
689 LIMIT(x2, 0, term.col-1);
690 LIMIT(y1, 0, term.row-1);
691 LIMIT(y2, 0, term.row-1);
692
693 for(y = y1; y <= y2; y++)
694 for(x = x1; x <= x2; x++)
695 term.line[y][x].state = 0;
696 }
697
698 void
699 tdeletechar(int n) {
700 int src = term.c.x + n;
701 int dst = term.c.x;
702 int size = term.col - src;
703
704 if(src >= term.col) {
705 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
706 return;
707 }
708 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
709 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
710 }
711
712 void
713 tinsertblank(int n) {
714 int src = term.c.x;
715 int dst = src + n;
716 int size = term.col - dst;
717
718 if(dst >= term.col) {
719 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
720 return;
721 }
722 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
723 tclearregion(src, term.c.y, dst - 1, term.c.y);
724 }
725
726 void
727 tinsertblankline(int n) {
728 if(term.c.y < term.top || term.c.y > term.bot)
729 return;
730
731 tscrolldown(term.c.y, n);
732 }
733
734 void
735 tdeleteline(int n) {
736 if(term.c.y < term.top || term.c.y > term.bot)
737 return;
738
739 tscrollup(term.c.y, n);
740 }
741
742 void
743 tsetattr(int *attr, int l) {
744 int i;
745
746 for(i = 0; i < l; i++) {
747 switch(attr[i]) {
748 case 0:
749 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
750 term.c.attr.fg = DefaultFG;
751 term.c.attr.bg = DefaultBG;
752 break;
753 case 1:
754 term.c.attr.mode |= ATTR_BOLD;
755 break;
756 case 4:
757 term.c.attr.mode |= ATTR_UNDERLINE;
758 break;
759 case 7:
760 term.c.attr.mode |= ATTR_REVERSE;
761 break;
762 case 22:
763 term.c.attr.mode &= ~ATTR_BOLD;
764 break;
765 case 24:
766 term.c.attr.mode &= ~ATTR_UNDERLINE;
767 break;
768 case 27:
769 term.c.attr.mode &= ~ATTR_REVERSE;
770 break;
771 case 38:
772 if (i + 2 < l && attr[i + 1] == 5) {
773 i += 2;
774 if (BETWEEN(attr[i], 0, 255))
775 term.c.attr.fg = attr[i];
776 else
777 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
778 }
779 else
780 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
781 break;
782 case 39:
783 term.c.attr.fg = DefaultFG;
784 break;
785 case 48:
786 if (i + 2 < l && attr[i + 1] == 5) {
787 i += 2;
788 if (BETWEEN(attr[i], 0, 255))
789 term.c.attr.bg = attr[i];
790 else
791 fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
792 }
793 else
794 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]);
795 break;
796 case 49:
797 term.c.attr.bg = DefaultBG;
798 break;
799 default:
800 if(BETWEEN(attr[i], 30, 37))
801 term.c.attr.fg = attr[i] - 30;
802 else if(BETWEEN(attr[i], 40, 47))
803 term.c.attr.bg = attr[i] - 40;
804 else if(BETWEEN(attr[i], 90, 97))
805 term.c.attr.fg = attr[i] - 90 + 8;
806 else if(BETWEEN(attr[i], 100, 107))
807 term.c.attr.fg = attr[i] - 100 + 8;
808 else
809 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[i]), csidump();
810
811 break;
812 }
813 }
814 }
815
816 void
817 tsetscroll(int t, int b) {
818 int temp;
819
820 LIMIT(t, 0, term.row-1);
821 LIMIT(b, 0, term.row-1);
822 if(t > b) {
823 temp = t;
824 t = b;
825 b = temp;
826 }
827 term.top = t;
828 term.bot = b;
829 }
830
831 void
832 csihandle(void) {
833 switch(escseq.mode) {
834 default:
835 unknown:
836 printf("erresc: unknown csi ");
837 csidump();
838 /* die(""); */
839 break;
840 case '@': /* ICH -- Insert <n> blank char */
841 DEFAULT(escseq.arg[0], 1);
842 tinsertblank(escseq.arg[0]);
843 break;
844 case 'A': /* CUU -- Cursor <n> Up */
845 case 'e':
846 DEFAULT(escseq.arg[0], 1);
847 tmoveto(term.c.x, term.c.y-escseq.arg[0]);
848 break;
849 case 'B': /* CUD -- Cursor <n> Down */
850 DEFAULT(escseq.arg[0], 1);
851 tmoveto(term.c.x, term.c.y+escseq.arg[0]);
852 break;
853 case 'C': /* CUF -- Cursor <n> Forward */
854 case 'a':
855 DEFAULT(escseq.arg[0], 1);
856 tmoveto(term.c.x+escseq.arg[0], term.c.y);
857 break;
858 case 'D': /* CUB -- Cursor <n> Backward */
859 DEFAULT(escseq.arg[0], 1);
860 tmoveto(term.c.x-escseq.arg[0], term.c.y);
861 break;
862 case 'E': /* CNL -- Cursor <n> Down and first col */
863 DEFAULT(escseq.arg[0], 1);
864 tmoveto(0, term.c.y+escseq.arg[0]);
865 break;
866 case 'F': /* CPL -- Cursor <n> Up and first col */
867 DEFAULT(escseq.arg[0], 1);
868 tmoveto(0, term.c.y-escseq.arg[0]);
869 break;
870 case 'G': /* CHA -- Move to <col> */
871 case '`': /* XXX: HPA -- same? */
872 DEFAULT(escseq.arg[0], 1);
873 tmoveto(escseq.arg[0]-1, term.c.y);
874 break;
875 case 'H': /* CUP -- Move to <row> <col> */
876 case 'f': /* XXX: HVP -- same? */
877 DEFAULT(escseq.arg[0], 1);
878 DEFAULT(escseq.arg[1], 1);
879 tmoveto(escseq.arg[1]-1, escseq.arg[0]-1);
880 break;
881 /* XXX: (CSI n I) CHT -- Cursor Forward Tabulation <n> tab stops */
882 case 'J': /* ED -- Clear screen */
883 switch(escseq.arg[0]) {
884 case 0: /* below */
885 tclearregion(term.c.x, term.c.y, term.col-1, term.row-1);
886 break;
887 case 1: /* above */
888 tclearregion(0, 0, term.c.x, term.c.y);
889 break;
890 case 2: /* all */
891 tclearregion(0, 0, term.col-1, term.row-1);
892 break;
893 default:
894 goto unknown;
895 }
896 break;
897 case 'K': /* EL -- Clear line */
898 switch(escseq.arg[0]) {
899 case 0: /* right */
900 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
901 break;
902 case 1: /* left */
903 tclearregion(0, term.c.y, term.c.x, term.c.y);
904 break;
905 case 2: /* all */
906 tclearregion(0, term.c.y, term.col-1, term.c.y);
907 break;
908 }
909 break;
910 case 'S': /* SU -- Scroll <n> line up */
911 DEFAULT(escseq.arg[0], 1);
912 tscrollup(term.top, escseq.arg[0]);
913 break;
914 case 'T': /* SD -- Scroll <n> line down */
915 DEFAULT(escseq.arg[0], 1);
916 tscrolldown(term.top, escseq.arg[0]);
917 break;
918 case 'L': /* IL -- Insert <n> blank lines */
919 DEFAULT(escseq.arg[0], 1);
920 tinsertblankline(escseq.arg[0]);
921 break;
922 case 'l': /* RM -- Reset Mode */
923 if(escseq.priv) {
924 switch(escseq.arg[0]) {
925 case 1:
926 term.mode &= ~MODE_APPKEYPAD;
927 break;
928 case 5: /* TODO: DECSCNM -- Remove reverse video */
929 break;
930 case 7:
931 term.mode &= ~MODE_WRAP;
932 break;
933 case 12: /* att610 -- Stop blinking cursor (IGNORED) */
934 break;
935 case 20:
936 term.mode &= ~MODE_CRLF;
937 break;
938 case 25:
939 term.c.state |= CURSOR_HIDE;
940 break;
941 case 1049: /* = 1047 and 1048 */
942 case 1047:
943 if(IS_SET(MODE_ALTSCREEN)) {
944 tclearregion(0, 0, term.col-1, term.row-1);
945 tswapscreen();
946 }
947 if(escseq.arg[0] == 1047)
948 break;
949 case 1048:
950 tcursor(CURSOR_LOAD);
951 break;
952 default:
953 goto unknown;
954 }
955 } else {
956 switch(escseq.arg[0]) {
957 case 4:
958 term.mode &= ~MODE_INSERT;
959 break;
960 default:
961 goto unknown;
962 }
963 }
964 break;
965 case 'M': /* DL -- Delete <n> lines */
966 DEFAULT(escseq.arg[0], 1);
967 tdeleteline(escseq.arg[0]);
968 break;
969 case 'X': /* ECH -- Erase <n> char */
970 DEFAULT(escseq.arg[0], 1);
971 tclearregion(term.c.x, term.c.y, term.c.x + escseq.arg[0], term.c.y);
972 break;
973 case 'P': /* DCH -- Delete <n> char */
974 DEFAULT(escseq.arg[0], 1);
975 tdeletechar(escseq.arg[0]);
976 break;
977 /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
978 case 'd': /* VPA -- Move to <row> */
979 DEFAULT(escseq.arg[0], 1);
980 tmoveto(term.c.x, escseq.arg[0]-1);
981 break;
982 case 'h': /* SM -- Set terminal mode */
983 if(escseq.priv) {
984 switch(escseq.arg[0]) {
985 case 1:
986 term.mode |= MODE_APPKEYPAD;
987 break;
988 case 5: /* DECSCNM -- Reverve video */
989 /* TODO: set REVERSE on the whole screen (f) */
990 break;
991 case 7:
992 term.mode |= MODE_WRAP;
993 break;
994 case 20:
995 term.mode |= MODE_CRLF;
996 break;
997 case 12: /* att610 -- Start blinking cursor (IGNORED) */
998 /* fallthrough for xterm cvvis = CSI [ ? 12 ; 25 h */
999 if(escseq.narg > 1 && escseq.arg[1] != 25)
1000 break;
1001 case 25:
1002 term.c.state &= ~CURSOR_HIDE;
1003 break;
1004 case 1049: /* = 1047 and 1048 */
1005 case 1047:
1006 if(IS_SET(MODE_ALTSCREEN))
1007 tclearregion(0, 0, term.col-1, term.row-1);
1008 else
1009 tswapscreen();
1010 if(escseq.arg[0] == 1047)
1011 break;
1012 case 1048:
1013 tcursor(CURSOR_SAVE);
1014 break;
1015 default: goto unknown;
1016 }
1017 } else {
1018 switch(escseq.arg[0]) {
1019 case 4:
1020 term.mode |= MODE_INSERT;
1021 break;
1022 default: goto unknown;
1023 }
1024 };
1025 break;
1026 case 'm': /* SGR -- Terminal attribute (color) */
1027 tsetattr(escseq.arg, escseq.narg);
1028 break;
1029 case 'r': /* DECSTBM -- Set Scrolling Region */
1030 if(escseq.priv)
1031 goto unknown;
1032 else {
1033 DEFAULT(escseq.arg[0], 1);
1034 DEFAULT(escseq.arg[1], term.row);
1035 tsetscroll(escseq.arg[0]-1, escseq.arg[1]-1);
1036 tmoveto(0, 0);
1037 }
1038 break;
1039 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1040 tcursor(CURSOR_SAVE);
1041 break;
1042 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1043 tcursor(CURSOR_LOAD);
1044 break;
1045 }
1046 }
1047
1048 void
1049 csidump(void) {
1050 int i;
1051 printf("ESC [ %s", escseq.priv ? "? " : "");
1052 if(escseq.narg)
1053 for(i = 0; i < escseq.narg; i++)
1054 printf("%d ", escseq.arg[i]);
1055 if(escseq.mode)
1056 putchar(escseq.mode);
1057 putchar('\n');
1058 }
1059
1060 void
1061 csireset(void) {
1062 memset(&escseq, 0, sizeof(escseq));
1063 }
1064
1065 void
1066 tputtab(void) {
1067 int space = TAB - term.c.x % TAB;
1068 tmoveto(term.c.x + space, term.c.y);
1069 }
1070
1071 void
1072 tputc(char c) {
1073 if(term.esc & ESC_START) {
1074 if(term.esc & ESC_CSI) {
1075 escseq.buf[escseq.len++] = c;
1076 if(BETWEEN(c, 0x40, 0x7E) || escseq.len >= ESC_BUF_SIZ) {
1077 term.esc = 0;
1078 csiparse(), csihandle();
1079 }
1080 /* TODO: handle other OSC */
1081 } else if(term.esc & ESC_OSC) {
1082 if(c == ';') {
1083 term.titlelen = 0;
1084 term.esc = ESC_START | ESC_TITLE;
1085 }
1086 } else if(term.esc & ESC_TITLE) {
1087 if(c == '\a' || term.titlelen+1 >= ESC_TITLE_SIZ) {
1088 term.esc = 0;
1089 term.title[term.titlelen] = '\0';
1090 XStoreName(xw.dis, xw.win, term.title);
1091 } else {
1092 term.title[term.titlelen++] = c;
1093 }
1094 } else if(term.esc & ESC_ALTCHARSET) {
1095 switch(c) {
1096 case '0': /* Line drawing crap */
1097 term.c.attr.mode |= ATTR_GFX;
1098 break;
1099 case 'B': /* Back to regular text */
1100 term.c.attr.mode &= ~ATTR_GFX;
1101 break;
1102 default:
1103 printf("esc unhandled charset: ESC ( %c\n", c);
1104 }
1105 term.esc = 0;
1106 } else {
1107 switch(c) {
1108 case '[':
1109 term.esc |= ESC_CSI;
1110 break;
1111 case ']':
1112 term.esc |= ESC_OSC;
1113 break;
1114 case '(':
1115 term.esc |= ESC_ALTCHARSET;
1116 break;
1117 case 'D': /* IND -- Linefeed */
1118 if(term.c.y == term.bot)
1119 tscrollup(term.top, 1);
1120 else
1121 tmoveto(term.c.x, term.c.y+1);
1122 term.esc = 0;
1123 break;
1124 case 'E': /* NEL -- Next line */
1125 tnewline(1); /* always go to first col */
1126 term.esc = 0;
1127 break;
1128 case 'M': /* RI -- Reverse index */
1129 if(term.c.y == term.top)
1130 tscrolldown(term.top, 1);
1131 else
1132 tmoveto(term.c.x, term.c.y-1);
1133 term.esc = 0;
1134 break;
1135 case 'c': /* RIS -- Reset to inital state */
1136 treset();
1137 term.esc = 0;
1138 break;
1139 case '=': /* DECPAM -- Application keypad */
1140 term.mode |= MODE_APPKEYPAD;
1141 term.esc = 0;
1142 break;
1143 case '>': /* DECPNM -- Normal keypad */
1144 term.mode &= ~MODE_APPKEYPAD;
1145 term.esc = 0;
1146 break;
1147 case '7': /* DECSC -- Save Cursor */
1148 tcursor(CURSOR_SAVE);
1149 term.esc = 0;
1150 break;
1151 case '8': /* DECRC -- Restore Cursor */
1152 tcursor(CURSOR_LOAD);
1153 term.esc = 0;
1154 break;
1155 default:
1156 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n", c, isprint(c)?c:'.');
1157 term.esc = 0;
1158 }
1159 }
1160 } else {
1161 switch(c) {
1162 case '\t':
1163 tputtab();
1164 break;
1165 case '\b':
1166 tmoveto(term.c.x-1, term.c.y);
1167 break;
1168 case '\r':
1169 tmoveto(0, term.c.y);
1170 break;
1171 case '\n':
1172 /* go to first col if the mode is set */
1173 tnewline(IS_SET(MODE_CRLF));
1174 break;
1175 case '\a':
1176 if(!(xw.state & WIN_FOCUSED))
1177 xseturgency(1);
1178 break;
1179 case '\033':
1180 csireset();
1181 term.esc = ESC_START;
1182 break;
1183 default:
1184 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1185 tnewline(1); /* always go to first col */
1186 tsetchar(c);
1187 if(term.c.x+1 < term.col)
1188 tmoveto(term.c.x+1, term.c.y);
1189 else
1190 term.c.state |= CURSOR_WRAPNEXT;
1191 break;
1192 }
1193 }
1194 }
1195
1196 void
1197 tputs(char *s, int len) {
1198 for(; len > 0; len--)
1199 tputc(*s++);
1200 }
1201
1202 void
1203 tresize(int col, int row) {
1204 int i, x;
1205 int minrow = MIN(row, term.row);
1206 int mincol = MIN(col, term.col);
1207 int slide = term.c.y - row + 1;
1208
1209 if(col < 1 || row < 1)
1210 return;
1211
1212 /* free unneeded rows */
1213 i = 0;
1214 if(slide > 0) {
1215 /* slide screen to keep cursor where we expect it -
1216 * tscrollup would work here, but we can optimize to
1217 * memmove because we're freeing the earlier lines */
1218 for(/* i = 0 */; i < slide; i++) {
1219 free(term.line[i]);
1220 free(term.alt[i]);
1221 }
1222 memmove(term.line, term.line + slide, row * sizeof(Line));
1223 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1224 }
1225 for(i += row; i < term.row; i++) {
1226 free(term.line[i]);
1227 free(term.alt[i]);
1228 }
1229
1230 /* resize to new height */
1231 term.line = realloc(term.line, row * sizeof(Line));
1232 term.alt = realloc(term.alt, row * sizeof(Line));
1233
1234 /* resize each row to new width, zero-pad if needed */
1235 for(i = 0; i < minrow; i++) {
1236 term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
1237 term.alt[i] = realloc(term.alt[i], col * sizeof(Glyph));
1238 for(x = mincol; x < col; x++) {
1239 term.line[i][x].state = 0;
1240 term.alt[i][x].state = 0;
1241 }
1242 }
1243
1244 /* allocate any new rows */
1245 for(/* i == minrow */; i < row; i++) {
1246 term.line[i] = calloc(col, sizeof(Glyph));
1247 term.alt [i] = calloc(col, sizeof(Glyph));
1248 }
1249
1250 /* update terminal size */
1251 term.col = col, term.row = row;
1252 /* make use of the LIMIT in tmoveto */
1253 tmoveto(term.c.x, term.c.y);
1254 /* reset scrolling region */
1255 tsetscroll(0, row-1);
1256 }
1257
1258 void
1259 xloadcols(void) {
1260 int i, r, g, b;
1261 XColor color;
1262 unsigned long white = WhitePixel(xw.dis, xw.scr);
1263
1264 for(i = 0; i < 16; i++) {
1265 if (!XAllocNamedColor(xw.dis, xw.cmap, colorname[i], &color, &color)) {
1266 dc.col[i] = white;
1267 fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
1268 } else
1269 dc.col[i] = color.pixel;
1270 }
1271
1272 /* same colors as xterm */
1273 for(r = 0; r < 6; r++)
1274 for(g = 0; g < 6; g++)
1275 for(b = 0; b < 6; b++) {
1276 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1277 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1278 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1279 if (!XAllocColor(xw.dis, xw.cmap, &color)) {
1280 dc.col[i] = white;
1281 fprintf(stderr, "Could not allocate color %d\n", i);
1282 } else
1283 dc.col[i] = color.pixel;
1284 i++;
1285 }
1286
1287 for(r = 0; r < 24; r++, i++) {
1288 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
1289 if (!XAllocColor(xw.dis, xw.cmap, &color)) {
1290 dc.col[i] = white;
1291 fprintf(stderr, "Could not allocate color %d\n", i);
1292 } else
1293 dc.col[i] = color.pixel;
1294 }
1295 }
1296
1297 void
1298 xclear(int x1, int y1, int x2, int y2) {
1299 XSetForeground(xw.dis, dc.gc, dc.col[DefaultBG]);
1300 XFillRectangle(xw.dis, xw.buf, dc.gc,
1301 x1 * xw.cw, y1 * xw.ch,
1302 (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
1303 }
1304
1305 void
1306 xhints(void)
1307 {
1308 XClassHint class = {TNAME, TNAME};
1309 XWMHints wm = {.flags = InputHint, .input = 1};
1310 XSizeHints size = {
1311 .flags = PSize | PResizeInc | PBaseSize,
1312 .height = xw.h,
1313 .width = xw.w,
1314 .height_inc = xw.ch,
1315 .width_inc = xw.cw,
1316 .base_height = 2*BORDER,
1317 .base_width = 2*BORDER,
1318 };
1319 XSetWMProperties(xw.dis, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
1320 }
1321
1322 void
1323 xinit(void) {
1324 XSetWindowAttributes attrs;
1325
1326 if(!(xw.dis = XOpenDisplay(NULL)))
1327 die("Can't open display\n");
1328 xw.scr = XDefaultScreen(xw.dis);
1329
1330 /* font */
1331 if(!(dc.font = XLoadQueryFont(xw.dis, FONT)) || !(dc.bfont = XLoadQueryFont(xw.dis, BOLDFONT)))
1332 die("Can't load font %s\n", dc.font ? BOLDFONT : FONT);
1333
1334 /* XXX: Assuming same size for bold font */
1335 xw.cw = dc.font->max_bounds.rbearing - dc.font->min_bounds.lbearing;
1336 xw.ch = dc.font->ascent + dc.font->descent;
1337
1338 /* colors */
1339 xw.cmap = XDefaultColormap(xw.dis, xw.scr);
1340 xloadcols();
1341
1342 /* window - default size */
1343 xw.bufh = 24 * xw.ch;
1344 xw.bufw = 80 * xw.cw;
1345 xw.h = xw.bufh + 2*BORDER;
1346 xw.w = xw.bufw + 2*BORDER;
1347
1348 attrs.background_pixel = dc.col[DefaultBG];
1349 attrs.border_pixel = dc.col[DefaultBG];
1350 attrs.bit_gravity = NorthWestGravity;
1351 attrs.event_mask = FocusChangeMask | KeyPressMask
1352 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1353 | PointerMotionMask | ButtonPressMask | ButtonReleaseMask;
1354 attrs.colormap = xw.cmap;
1355
1356 xw.win = XCreateWindow(xw.dis, XRootWindow(xw.dis, xw.scr), 0, 0,
1357 xw.w, xw.h, 0, XDefaultDepth(xw.dis, xw.scr), InputOutput,
1358 XDefaultVisual(xw.dis, xw.scr),
1359 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
1360 | CWColormap,
1361 &attrs);
1362 xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1363
1364
1365 /* input methods */
1366 xw.xim = XOpenIM(xw.dis, NULL, NULL, NULL);
1367 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
1368 | XIMStatusNothing, XNClientWindow, xw.win,
1369 XNFocusWindow, xw.win, NULL);
1370 /* gc */
1371 dc.gc = XCreateGC(xw.dis, xw.win, 0, NULL);
1372
1373 XMapWindow(xw.dis, xw.win);
1374 xhints();
1375 XStoreName(xw.dis, xw.win, opt_title ? opt_title : "st");
1376 XSync(xw.dis, 0);
1377 }
1378
1379 void
1380 xdraws(char *s, Glyph base, int x, int y, int len) {
1381 unsigned long xfg, xbg;
1382 int winx = x*xw.cw, winy = y*xw.ch + dc.font->ascent, width = len*xw.cw;
1383 int i;
1384
1385 if(base.mode & ATTR_REVERSE)
1386 xfg = dc.col[base.bg], xbg = dc.col[base.fg];
1387 else
1388 xfg = dc.col[base.fg], xbg = dc.col[base.bg];
1389
1390 XSetBackground(xw.dis, dc.gc, xbg);
1391 XSetForeground(xw.dis, dc.gc, xfg);
1392
1393 if(base.mode & ATTR_GFX)
1394 for(i = 0; i < len; i++) {
1395 char c = gfx[(unsigned int)s[i] % 256];
1396 if(c)
1397 s[i] = c;
1398 else if(s[i] > 0x5f)
1399 s[i] -= 0x5f;
1400 }
1401
1402 XSetFont(xw.dis, dc.gc, base.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
1403 XDrawImageString(xw.dis, xw.buf, dc.gc, winx, winy, s, len);
1404
1405 if(base.mode & ATTR_UNDERLINE)
1406 XDrawLine(xw.dis, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
1407 }
1408
1409 void
1410 xdrawcursor(void) {
1411 static int oldx = 0;
1412 static int oldy = 0;
1413 Glyph g = {' ', ATTR_NULL, DefaultBG, DefaultCS, 0};
1414
1415 LIMIT(oldx, 0, term.col-1);
1416 LIMIT(oldy, 0, term.row-1);
1417
1418 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
1419 g.c = term.line[term.c.y][term.c.x].c;
1420
1421 /* remove the old cursor */
1422 if(term.line[oldy][oldx].state & GLYPH_SET)
1423 xdraws(&term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1);
1424 else
1425 xclear(oldx, oldy, oldx, oldy);
1426
1427 /* draw the new one */
1428 if(!(term.c.state & CURSOR_HIDE) && (xw.state & WIN_FOCUSED)) {
1429 xdraws(&g.c, g, term.c.x, term.c.y, 1);
1430 oldx = term.c.x, oldy = term.c.y;
1431 }
1432 }
1433
1434 #ifdef DEBUG
1435 /* basic drawing routines */
1436 void
1437 xdrawc(int x, int y, Glyph g) {
1438 XRectangle r = { x * xw.cw, y * xw.ch, xw.cw, xw.ch };
1439 XSetBackground(xw.dis, dc.gc, dc.col[g.bg]);
1440 XSetForeground(xw.dis, dc.gc, dc.col[g.fg]);
1441 XSetFont(xw.dis, dc.gc, g.mode & ATTR_BOLD ? dc.bfont->fid : dc.font->fid);
1442 XDrawImageString(xw.dis, xw.buf, dc.gc, r.x, r.y+dc.font->ascent, &g.c, 1);
1443 }
1444
1445 void
1446 draw(int dummy) {
1447 int x, y;
1448
1449 xclear(0, 0, term.col-1, term.row-1);
1450 for(y = 0; y < term.row; y++)
1451 for(x = 0; x < term.col; x++)
1452 if(term.line[y][x].state & GLYPH_SET)
1453 xdrawc(x, y, term.line[y][x]);
1454
1455 xdrawcursor();
1456 XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1457 XFlush(xw.dis);
1458 }
1459
1460 #else
1461 /* optimized drawing routine */
1462 void
1463 draw(int redraw_all) {
1464 int i, x, y, ox;
1465 Glyph base, new;
1466 char buf[DRAW_BUF_SIZ];
1467
1468 if(!(xw.state & WIN_VISIBLE))
1469 return;
1470
1471 xclear(0, 0, term.col-1, term.row-1);
1472 for(y = 0; y < term.row; y++) {
1473 base = term.line[y][0];
1474 i = ox = 0;
1475 for(x = 0; x < term.col; x++) {
1476 new = term.line[y][x];
1477 if(sel.bx!=-1 && new.c && selected(x, y))
1478 new.mode ^= ATTR_REVERSE;
1479 if(i > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
1480 i >= DRAW_BUF_SIZ)) {
1481 xdraws(buf, base, ox, y, i);
1482 i = 0;
1483 }
1484 if(new.state & GLYPH_SET) {
1485 if(i == 0) {
1486 ox = x;
1487 base = new;
1488 }
1489 buf[i++] = new.c;
1490 }
1491 }
1492 if(i > 0)
1493 xdraws(buf, base, ox, y, i);
1494 }
1495 xdrawcursor();
1496 XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, 0, 0, xw.bufw, xw.bufh, BORDER, BORDER);
1497 }
1498
1499 #endif
1500
1501 void
1502 expose(XEvent *ev) {
1503 XExposeEvent *e = &ev->xexpose;
1504 if(xw.state & WIN_REDRAW) {
1505 if(!e->count) {
1506 xw.state &= ~WIN_REDRAW;
1507 draw(SCREEN_REDRAW);
1508 }
1509 } else
1510 XCopyArea(xw.dis, xw.buf, xw.win, dc.gc, e->x-BORDER, e->y-BORDER,
1511 e->width, e->height, e->x, e->y);
1512 }
1513
1514 void
1515 visibility(XEvent *ev) {
1516 XVisibilityEvent *e = &ev->xvisibility;
1517 if(e->state == VisibilityFullyObscured)
1518 xw.state &= ~WIN_VISIBLE;
1519 else if(!(xw.state & WIN_VISIBLE))
1520 /* need a full redraw for next Expose, not just a buf copy */
1521 xw.state |= WIN_VISIBLE | WIN_REDRAW;
1522 }
1523
1524 void
1525 unmap(XEvent *ev) {
1526 xw.state &= ~WIN_VISIBLE;
1527 }
1528
1529 void
1530 xseturgency(int add) {
1531 XWMHints *h = XGetWMHints(xw.dis, xw.win);
1532 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
1533 XSetWMHints(xw.dis, xw.win, h);
1534 XFree(h);
1535 }
1536
1537 void
1538 focus(XEvent *ev) {
1539 if(ev->type == FocusIn) {
1540 xw.state |= WIN_FOCUSED;
1541 xseturgency(0);
1542 } else
1543 xw.state &= ~WIN_FOCUSED;
1544 draw(SCREEN_UPDATE);
1545 }
1546
1547 char*
1548 kmap(KeySym k) {
1549 int i;
1550 for(i = 0; i < LEN(key); i++)
1551 if(key[i].k == k)
1552 return (char*)key[i].s;
1553 return NULL;
1554 }
1555
1556 void
1557 kpress(XEvent *ev) {
1558 XKeyEvent *e = &ev->xkey;
1559 KeySym ksym;
1560 char buf[32];
1561 char *customkey;
1562 int len;
1563 int meta;
1564 int shift;
1565 Status status;
1566
1567 meta = e->state & Mod1Mask;
1568 shift = e->state & ShiftMask;
1569 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
1570
1571 /* 1. custom keys from config.h */
1572 if((customkey = kmap(ksym)))
1573 ttywrite(customkey, strlen(customkey));
1574 /* 2. hardcoded (overrides X lookup) */
1575 else
1576 switch(ksym) {
1577 case XK_Up:
1578 case XK_Down:
1579 case XK_Left:
1580 case XK_Right:
1581 sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', "DACB"[ksym - XK_Left]);
1582 ttywrite(buf, 3);
1583 break;
1584 case XK_Insert:
1585 if(shift)
1586 selpaste();
1587 break;
1588 case XK_Return:
1589 if(IS_SET(MODE_CRLF))
1590 ttywrite("\r\n", 2);
1591 else
1592 ttywrite("\r", 1);
1593 break;
1594 /* 3. X lookup */
1595 default:
1596 if(len > 0) {
1597 buf[sizeof(buf)-1] = '\0';
1598 if(meta && len == 1)
1599 ttywrite("\033", 1);
1600 ttywrite(buf, len);
1601 } else /* 4. nothing to send */
1602 fprintf(stderr, "errkey: %d\n", (int)ksym);
1603 break;
1604 }
1605 }
1606
1607 void
1608 resize(XEvent *e) {
1609 int col, row;
1610
1611 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
1612 return;
1613
1614 xw.w = e->xconfigure.width;
1615 xw.h = e->xconfigure.height;
1616 xw.bufw = xw.w - 2*BORDER;
1617 xw.bufh = xw.h - 2*BORDER;
1618 col = xw.bufw / xw.cw;
1619 row = xw.bufh / xw.ch;
1620 tresize(col, row);
1621 ttyresize(col, row);
1622 xw.bufh = MAX(1, xw.bufh);
1623 xw.bufw = MAX(1, xw.bufw);
1624 XFreePixmap(xw.dis, xw.buf);
1625 xw.buf = XCreatePixmap(xw.dis, xw.win, xw.bufw, xw.bufh, XDefaultDepth(xw.dis, xw.scr));
1626 }
1627
1628 void
1629 run(void) {
1630 XEvent ev;
1631 fd_set rfd;
1632 int xfd = XConnectionNumber(xw.dis);
1633
1634 for(;;) {
1635 FD_ZERO(&rfd);
1636 FD_SET(cmdfd, &rfd);
1637 FD_SET(xfd, &rfd);
1638 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, NULL) < 0) {
1639 if(errno == EINTR)
1640 continue;
1641 die("select failed: %s\n", SERRNO);
1642 }
1643 if(FD_ISSET(cmdfd, &rfd)) {
1644 ttyread();
1645 draw(SCREEN_UPDATE);
1646 }
1647 while(XPending(xw.dis)) {
1648 XNextEvent(xw.dis, &ev);
1649 if (XFilterEvent(&ev, xw.win))
1650 continue;
1651 if(handler[ev.type])
1652 (handler[ev.type])(&ev);
1653 }
1654 }
1655 }
1656
1657 int
1658 main(int argc, char *argv[]) {
1659 int i;
1660
1661 for(i = 1; i < argc; i++) {
1662 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
1663 case 't':
1664 if(++i < argc) opt_title = argv[i];
1665 break;
1666 case 'e':
1667 if(++i < argc) opt_cmd = argv[i];
1668 break;
1669 case 'v':
1670 default:
1671 die(USAGE);
1672 }
1673 }
1674 setlocale(LC_CTYPE, "");
1675 tnew(80, 24);
1676 ttynew();
1677 xinit();
1678 selinit();
1679 run();
1680 return 0;
1681 }