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