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