Xinqi Bao's Git

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