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