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