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