Xinqi Bao's Git

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