Xinqi Bao's Git

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