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