Xinqi Bao's Git

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