JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Save cursor position in terminal reset
[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 <pwd.h>
9 #include <stdarg.h>
10 #include <stdbool.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <signal.h>
15 #include <sys/ioctl.h>
16 #include <sys/select.h>
17 #include <sys/stat.h>
18 #include <sys/time.h>
19 #include <sys/types.h>
20 #include <sys/wait.h>
21 #include <time.h>
22 #include <unistd.h>
23 #include <X11/Xatom.h>
24 #include <X11/Xlib.h>
25 #include <X11/Xutil.h>
26 #include <X11/cursorfont.h>
27 #include <X11/keysym.h>
28 #include <X11/extensions/Xdbe.h>
29 #include <X11/Xft/Xft.h>
30 #include <fontconfig/fontconfig.h>
31 #define Glyph Glyph_
32 #define Font Font_
33
34 #if   defined(__linux)
35  #include <pty.h>
36 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
37  #include <util.h>
38 #elif defined(__FreeBSD__) || defined(__DragonFly__)
39  #include <libutil.h>
40 #endif
41
42 #define USAGE \
43         "st " VERSION " (c) 2010-2012 st engineers\n" \
44         "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
45         " [-t title] [-w windowid] [-e command ...]\n"
46
47 /* XEMBED messages */
48 #define XEMBED_FOCUS_IN  4
49 #define XEMBED_FOCUS_OUT 5
50
51 /* Arbitrary sizes */
52 #define ESC_BUF_SIZ   256
53 #define ESC_ARG_SIZ   16
54 #define STR_BUF_SIZ   256
55 #define STR_ARG_SIZ   16
56 #define DRAW_BUF_SIZ  20*1024
57 #define UTF_SIZ       4
58 #define XK_NO_MOD     UINT_MAX
59 #define XK_ANY_MOD    0
60
61 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
62
63 /* macros */
64 #define CLEANMASK(mask) (mask & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
65 #define SERRNO strerror(errno)
66 #define MIN(a, b)  ((a) < (b) ? (a) : (b))
67 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
68 #define LEN(a)     (sizeof(a) / sizeof(a[0]))
69 #define DEFAULT(a, b)     (a) = (a) ? (a) : (b)
70 #define BETWEEN(x, a, b)  ((a) <= (x) && (x) <= (b))
71 #define LIMIT(x, a, b)    (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
72 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
73 #define IS_SET(flag) (term.mode & (flag))
74 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
75
76 #define VT102ID "\033[?6c"
77
78 enum glyph_attribute {
79         ATTR_NULL      = 0,
80         ATTR_REVERSE   = 1,
81         ATTR_UNDERLINE = 2,
82         ATTR_BOLD      = 4,
83         ATTR_GFX       = 8,
84         ATTR_ITALIC    = 16,
85         ATTR_BLINK     = 32,
86 };
87
88 enum cursor_movement {
89         CURSOR_UP,
90         CURSOR_DOWN,
91         CURSOR_LEFT,
92         CURSOR_RIGHT,
93         CURSOR_SAVE,
94         CURSOR_LOAD
95 };
96
97 enum cursor_state {
98         CURSOR_DEFAULT  = 0,
99         CURSOR_WRAPNEXT = 1,
100 };
101
102 enum glyph_state {
103         GLYPH_SET   = 1,
104         GLYPH_DIRTY = 2
105 };
106
107 enum term_mode {
108         MODE_WRAP       = 1,
109         MODE_INSERT      = 2,
110         MODE_APPKEYPAD   = 4,
111         MODE_ALTSCREEN   = 8,
112         MODE_CRLF       = 16,
113         MODE_MOUSEBTN    = 32,
114         MODE_MOUSEMOTION = 64,
115         MODE_MOUSE       = 32|64,
116         MODE_REVERSE     = 128,
117         MODE_KBDLOCK     = 256,
118         MODE_HIDE      = 512
119 };
120
121 enum escape_state {
122         ESC_START      = 1,
123         ESC_CSI = 2,
124         ESC_STR = 4, /* DSC, OSC, PM, APC */
125         ESC_ALTCHARSET = 8,
126         ESC_STR_END    = 16, /* a final string was encountered */
127         ESC_TEST       = 32, /* Enter in test mode */
128 };
129
130 enum window_state {
131         WIN_VISIBLE = 1,
132         WIN_REDRAW  = 2,
133         WIN_FOCUSED = 4
134 };
135
136 /* bit macro */
137 #undef B0
138 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
139
140 typedef unsigned char uchar;
141 typedef unsigned int uint;
142 typedef unsigned long ulong;
143 typedef unsigned short ushort;
144
145 typedef struct {
146         char c[UTF_SIZ];     /* character code */
147         uchar mode;  /* attribute flags */
148         ushort fg;   /* foreground  */
149         ushort bg;   /* background  */
150         uchar state; /* state flags    */
151 } Glyph;
152
153 typedef Glyph* Line;
154
155 typedef struct {
156         Glyph attr;      /* current char attributes */
157         int x;
158         int y;
159         char state;
160 } TCursor;
161
162 /* CSI Escape sequence structs */
163 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
164 typedef struct {
165         char buf[ESC_BUF_SIZ]; /* raw string */
166         int len;               /* raw string length */
167         char priv;
168         int arg[ESC_ARG_SIZ];
169         int narg;             /* nb of args */
170         char mode;
171 } CSIEscape;
172
173 /* STR Escape sequence structs */
174 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
175 typedef struct {
176         char type;           /* ESC type ... */
177         char buf[STR_BUF_SIZ]; /* raw string */
178         int len;               /* raw string length */
179         char *args[STR_ARG_SIZ];
180         int narg;             /* nb of args */
181 } STREscape;
182
183 /* Internal representation of the screen */
184 typedef struct {
185         int row;        /* nb row */
186         int col;        /* nb col */
187         Line *line;     /* screen */
188         Line *alt;      /* alternate screen */
189         bool *dirty;    /* dirtyness of lines */
190         TCursor c;      /* cursor */
191         int top;        /* top    scroll limit */
192         int bot;        /* bottom scroll limit */
193         int mode;       /* terminal mode flags */
194         int esc;        /* escape state flags */
195         bool *tabs;
196 } Term;
197
198 /* Purely graphic info */
199 typedef struct {
200         Display* dpy;
201         Colormap cmap;
202         Window win;
203         XdbeBackBuffer buf;
204         Atom xembed, wmdeletewin;
205         XIM xim;
206         XIC xic;
207         XftDraw *xft_draw;
208         Visual *vis;
209         int scr;
210         bool isfixed; /* is fixed geometry? */
211         int fx, fy, fw, fh; /* fixed geometry */
212         int tw, th; /* tty width and height */
213         int w;  /* window width */
214         int h;  /* window height */
215         int ch; /* char height */
216         int cw; /* char width  */
217         char state; /* focus, redraw, visible */
218 } XWindow;
219
220 typedef struct {
221         KeySym k;
222         uint mask;
223         char s[ESC_BUF_SIZ];
224 } Key;
225
226 /* TODO: use better name for vars... */
227 typedef struct {
228         int mode;
229         int bx, by;
230         int ex, ey;
231         struct {
232                 int x, y;
233         } b, e;
234         char *clip;
235         Atom xtarget;
236         bool alt;
237         struct timeval tclick1;
238         struct timeval tclick2;
239 } Selection;
240
241 typedef union {
242         int i;
243         unsigned int ui;
244         float f;
245         const void *v;
246 } Arg;
247
248 typedef struct {
249         unsigned int mod;
250         KeySym keysym;
251         void (*func)(const Arg *);
252         const Arg arg;
253 } Shortcut;
254
255 /* function definitions used in config.h */
256 static void xzoom(const Arg *);
257
258 /* Config.h for applying patches and the configuration. */
259 #include "config.h"
260
261 /* Font structure */
262 typedef struct {
263         int height;
264         int width;
265         int ascent;
266         int descent;
267         short lbearing;
268         short rbearing;
269         XftFont *xft_set;
270 } Font;
271
272 /* Drawing Context */
273 typedef struct {
274         XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
275         GC gc;
276         Font font, bfont, ifont, ibfont;
277 } DC;
278
279 static void die(const char *, ...);
280 static void draw(void);
281 static void redraw(void);
282 static void drawregion(int, int, int, int);
283 static void execsh(void);
284 static void sigchld(int);
285 static void run(void);
286
287 static void csidump(void);
288 static void csihandle(void);
289 static void csiparse(void);
290 static void csireset(void);
291 static void strdump(void);
292 static void strhandle(void);
293 static void strparse(void);
294 static void strreset(void);
295
296 static void tclearregion(int, int, int, int);
297 static void tcursor(int);
298 static void tdeletechar(int);
299 static void tdeleteline(int);
300 static void tinsertblank(int);
301 static void tinsertblankline(int);
302 static void tmoveto(int, int);
303 static void tnew(int, int);
304 static void tnewline(int);
305 static void tputtab(bool);
306 static void tputc(char *, int);
307 static void treset(void);
308 static int tresize(int, int);
309 static void tscrollup(int, int);
310 static void tscrolldown(int, int);
311 static void tsetattr(int*, int);
312 static void tsetchar(char *, Glyph *, int, int);
313 static void tsetscroll(int, int);
314 static void tswapscreen(void);
315 static void tsetdirt(int, int);
316 static void tsetmode(bool, bool, int *, int);
317 static void tfulldirt(void);
318
319 static void ttynew(void);
320 static void ttyread(void);
321 static void ttyresize(void);
322 static void ttywrite(const char *, size_t);
323
324 static void xdraws(char *, Glyph, int, int, int, int);
325 static void xhints(void);
326 static void xclear(int, int, int, int);
327 static void xdrawcursor(void);
328 static void xinit(void);
329 static void xloadcols(void);
330 static void xresettitle(void);
331 static void xseturgency(int);
332 static void xsetsel(char*);
333 static void xtermclear(int, int, int, int);
334 static void xresize(int, int);
335
336 static void expose(XEvent *);
337 static void visibility(XEvent *);
338 static void unmap(XEvent *);
339 static char *kmap(KeySym, uint);
340 static void kpress(XEvent *);
341 static void cmessage(XEvent *);
342 static void cresize(int width, int height);
343 static void resize(XEvent *);
344 static void focus(XEvent *);
345 static void brelease(XEvent *);
346 static void bpress(XEvent *);
347 static void bmotion(XEvent *);
348 static void selnotify(XEvent *);
349 static void selclear(XEvent *);
350 static void selrequest(XEvent *);
351
352 static void selinit(void);
353 static inline bool selected(int, int);
354 static void selcopy(void);
355 static void selpaste(void);
356 static void selscroll(int, int);
357
358 static int utf8decode(char *, long *);
359 static int utf8encode(long *, char *);
360 static int utf8size(char *);
361 static int isfullutf8(char *, int);
362
363 static ssize_t xwrite(int, char *, size_t);
364 static void *xmalloc(size_t);
365 static void *xrealloc(void *, size_t);
366 static void *xcalloc(size_t nmemb, size_t size);
367
368 static void (*handler[LASTEvent])(XEvent *) = {
369         [KeyPress] = kpress,
370         [ClientMessage] = cmessage,
371         [ConfigureNotify] = resize,
372         [VisibilityNotify] = visibility,
373         [UnmapNotify] = unmap,
374         [Expose] = expose,
375         [FocusIn] = focus,
376         [FocusOut] = focus,
377         [MotionNotify] = bmotion,
378         [ButtonPress] = bpress,
379         [ButtonRelease] = brelease,
380         [SelectionClear] = selclear,
381         [SelectionNotify] = selnotify,
382         [SelectionRequest] = selrequest,
383 };
384
385 /* Globals */
386 static DC dc;
387 static XWindow xw;
388 static Term term;
389 static CSIEscape csiescseq;
390 static STREscape strescseq;
391 static int cmdfd;
392 static pid_t pid;
393 static Selection sel;
394 static int iofd = -1;
395 static char **opt_cmd = NULL;
396 static char *opt_io = NULL;
397 static char *opt_title = NULL;
398 static char *opt_embed = NULL;
399 static char *opt_class = NULL;
400 static char *opt_font = NULL;
401
402 static char *usedfont = NULL;
403 static int usedfontsize = 0;
404
405 ssize_t
406 xwrite(int fd, char *s, size_t len) {
407         size_t aux = len;
408
409         while(len > 0) {
410                 ssize_t r = write(fd, s, len);
411                 if(r < 0)
412                         return r;
413                 len -= r;
414                 s += r;
415         }
416         return aux;
417 }
418
419 void *
420 xmalloc(size_t len) {
421         void *p = malloc(len);
422
423         if(!p)
424                 die("Out of memory\n");
425
426         return p;
427 }
428
429 void *
430 xrealloc(void *p, size_t len) {
431         if((p = realloc(p, len)) == NULL)
432                 die("Out of memory\n");
433
434         return p;
435 }
436
437 void *
438 xcalloc(size_t nmemb, size_t size) {
439         void *p = calloc(nmemb, size);
440
441         if(!p)
442                 die("Out of memory\n");
443
444         return p;
445 }
446
447 int
448 utf8decode(char *s, long *u) {
449         uchar c;
450         int i, n, rtn;
451
452         rtn = 1;
453         c = *s;
454         if(~c & B7) { /* 0xxxxxxx */
455                 *u = c;
456                 return rtn;
457         } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
458                 *u = c&(B4|B3|B2|B1|B0);
459                 n = 1;
460         } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
461                 *u = c&(B3|B2|B1|B0);
462                 n = 2;
463         } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
464                 *u = c & (B2|B1|B0);
465                 n = 3;
466         } else {
467                 goto invalid;
468         }
469
470         for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
471                 c = *s;
472                 if((c & (B7|B6)) != B7) /* 10xxxxxx */
473                         goto invalid;
474                 *u <<= 6;
475                 *u |= c & (B5|B4|B3|B2|B1|B0);
476         }
477
478         if((n == 1 && *u < 0x80) ||
479            (n == 2 && *u < 0x800) ||
480            (n == 3 && *u < 0x10000) ||
481            (*u >= 0xD800 && *u <= 0xDFFF)) {
482                 goto invalid;
483         }
484
485         return rtn;
486 invalid:
487         *u = 0xFFFD;
488
489         return rtn;
490 }
491
492 int
493 utf8encode(long *u, char *s) {
494         uchar *sp;
495         ulong uc;
496         int i, n;
497
498         sp = (uchar *)s;
499         uc = *u;
500         if(uc < 0x80) {
501                 *sp = uc; /* 0xxxxxxx */
502                 return 1;
503         } else if(*u < 0x800) {
504                 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
505                 n = 1;
506         } else if(uc < 0x10000) {
507                 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
508                 n = 2;
509         } else if(uc <= 0x10FFFF) {
510                 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
511                 n = 3;
512         } else {
513                 goto invalid;
514         }
515
516         for(i=n,++sp; i>0; --i,++sp)
517                 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
518
519         return n+1;
520 invalid:
521         /* U+FFFD */
522         *s++ = '\xEF';
523         *s++ = '\xBF';
524         *s = '\xBD';
525
526         return 3;
527 }
528
529 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
530    UTF-8 otherwise return 0 */
531 int
532 isfullutf8(char *s, int b) {
533         uchar *c1, *c2, *c3;
534
535         c1 = (uchar *)s;
536         c2 = (uchar *)++s;
537         c3 = (uchar *)++s;
538         if(b < 1) {
539                 return 0;
540         } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
541                 return 0;
542         } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
543             ((b == 1) ||
544             ((b == 2) && (*c2&(B7|B6)) == B7))) {
545                 return 0;
546         } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
547             ((b == 1) ||
548             ((b == 2) && (*c2&(B7|B6)) == B7) ||
549             ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
550                 return 0;
551         } else {
552                 return 1;
553         }
554 }
555
556 int
557 utf8size(char *s) {
558         uchar c = *s;
559
560         if(~c&B7) {
561                 return 1;
562         } else if((c&(B7|B6|B5)) == (B7|B6)) {
563                 return 2;
564         } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
565                 return 3;
566         } else {
567                 return 4;
568         }
569 }
570
571 void
572 selinit(void) {
573         memset(&sel.tclick1, 0, sizeof(sel.tclick1));
574         memset(&sel.tclick2, 0, sizeof(sel.tclick2));
575         sel.mode = 0;
576         sel.bx = -1;
577         sel.clip = NULL;
578         sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
579         if(sel.xtarget == None)
580                 sel.xtarget = XA_STRING;
581 }
582
583 static int
584 x2col(int x) {
585         x -= borderpx;
586         x /= xw.cw;
587
588         return LIMIT(x, 0, term.col-1);
589 }
590
591 static int
592 y2row(int y) {
593         y -= borderpx;
594         y /= xw.ch;
595
596         return LIMIT(y, 0, term.row-1);
597 }
598
599 static inline bool
600 selected(int x, int y) {
601         int bx, ex;
602
603         if(sel.ey == y && sel.by == y) {
604                 bx = MIN(sel.bx, sel.ex);
605                 ex = MAX(sel.bx, sel.ex);
606                 return BETWEEN(x, bx, ex);
607         }
608
609         return ((sel.b.y < y && y < sel.e.y)
610                         || (y == sel.e.y && x <= sel.e.x))
611                         || (y == sel.b.y && x >= sel.b.x
612                                 && (x <= sel.e.x || sel.b.y != sel.e.y));
613 }
614
615 void
616 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
617         if(b)
618                 *b = e->xbutton.button;
619
620         *x = x2col(e->xbutton.x);
621         *y = y2row(e->xbutton.y);
622
623         sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
624         sel.b.y = MIN(sel.by, sel.ey);
625         sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
626         sel.e.y = MAX(sel.by, sel.ey);
627 }
628
629 void
630 mousereport(XEvent *e) {
631         int x = x2col(e->xbutton.x);
632         int y = y2row(e->xbutton.y);
633         int button = e->xbutton.button;
634         int state = e->xbutton.state;
635         char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
636         static int ob, ox, oy;
637
638         /* from urxvt */
639         if(e->xbutton.type == MotionNotify) {
640                 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
641                         return;
642                 button = ob + 32;
643                 ox = x, oy = y;
644         } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
645                 button = 3;
646         } else {
647                 button -= Button1;
648                 if(button >= 3)
649                         button += 64 - 3;
650                 if(e->xbutton.type == ButtonPress) {
651                         ob = button;
652                         ox = x, oy = y;
653                 }
654         }
655
656         buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
657                 + (state & Mod4Mask    ? 8  : 0)
658                 + (state & ControlMask ? 16 : 0);
659
660         ttywrite(buf, sizeof(buf));
661 }
662
663 void
664 bpress(XEvent *e) {
665         if(IS_SET(MODE_MOUSE)) {
666                 mousereport(e);
667         } else if(e->xbutton.button == Button1) {
668                 if(sel.bx != -1) {
669                         sel.bx = -1;
670                         tsetdirt(sel.b.y, sel.e.y);
671                         draw();
672                 }
673                 sel.mode = 1;
674                 sel.ex = sel.bx = x2col(e->xbutton.x);
675                 sel.ey = sel.by = y2row(e->xbutton.y);
676         } else if(e->xbutton.button == Button4) {
677                 ttywrite("\031", 1);
678         } else if(e->xbutton.button == Button5) {
679                 ttywrite("\005", 1);
680         }
681 }
682
683 void
684 selcopy(void) {
685         char *str, *ptr, *p;
686         int x, y, bufsize, is_selected = 0, size;
687         Glyph *gp, *last;
688
689         if(sel.bx == -1) {
690                 str = NULL;
691         } else {
692                 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
693                 ptr = str = xmalloc(bufsize);
694
695                 /* append every set & selected glyph to the selection */
696                 for(y = 0; y < term.row; y++) {
697                         gp = &term.line[y][0];
698                         last = gp + term.col;
699
700                         while(--last >= gp && !(last->state & GLYPH_SET))
701                                 /* nothing */;
702
703                         for(x = 0; gp <= last; x++, ++gp) {
704                                 if(!(is_selected = selected(x, y)))
705                                         continue;
706
707                                 p = (gp->state & GLYPH_SET) ? gp->c : " ";
708                                 size = utf8size(p);
709                                 memcpy(ptr, p, size);
710                                 ptr += size;
711                         }
712                         /* \n at the end of every selected line except for the last one */
713                         if(is_selected && y < sel.e.y)
714                                 *ptr++ = '\n';
715                 }
716                 *ptr = 0;
717         }
718         sel.alt = IS_SET(MODE_ALTSCREEN);
719         xsetsel(str);
720 }
721
722 void
723 selnotify(XEvent *e) {
724         ulong nitems, ofs, rem;
725         int format;
726         uchar *data;
727         Atom type;
728
729         ofs = 0;
730         do {
731                 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
732                                         False, AnyPropertyType, &type, &format,
733                                         &nitems, &rem, &data)) {
734                         fprintf(stderr, "Clipboard allocation failed\n");
735                         return;
736                 }
737                 ttywrite((const char *) data, nitems * format / 8);
738                 XFree(data);
739                 /* number of 32-bit chunks returned */
740                 ofs += nitems * format / 32;
741         } while(rem > 0);
742 }
743
744 void
745 selpaste(void) {
746         XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
747                         xw.win, CurrentTime);
748 }
749
750 void selclear(XEvent *e) {
751         if(sel.bx == -1)
752                 return;
753         sel.bx = -1;
754         tsetdirt(sel.b.y, sel.e.y);
755 }
756
757 void
758 selrequest(XEvent *e) {
759         XSelectionRequestEvent *xsre;
760         XSelectionEvent xev;
761         Atom xa_targets, string;
762
763         xsre = (XSelectionRequestEvent *) e;
764         xev.type = SelectionNotify;
765         xev.requestor = xsre->requestor;
766         xev.selection = xsre->selection;
767         xev.target = xsre->target;
768         xev.time = xsre->time;
769         /* reject */
770         xev.property = None;
771
772         xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
773         if(xsre->target == xa_targets) {
774                 /* respond with the supported type */
775                 string = sel.xtarget;
776                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
777                                 XA_ATOM, 32, PropModeReplace,
778                                 (uchar *) &string, 1);
779                 xev.property = xsre->property;
780         } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
781                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
782                                 xsre->target, 8, PropModeReplace,
783                                 (uchar *) sel.clip, strlen(sel.clip));
784                 xev.property = xsre->property;
785         }
786
787         /* all done, send a notification to the listener */
788         if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
789                 fprintf(stderr, "Error sending SelectionNotify event\n");
790 }
791
792 void
793 xsetsel(char *str) {
794         /* register the selection for both the clipboard and the primary */
795         Atom clipboard;
796
797         free(sel.clip);
798         sel.clip = str;
799
800         XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
801
802         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
803         XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
804 }
805
806 void
807 brelease(XEvent *e) {
808         struct timeval now;
809
810         if(IS_SET(MODE_MOUSE)) {
811                 mousereport(e);
812                 return;
813         }
814
815         if(e->xbutton.button == Button2) {
816                 selpaste();
817         } else if(e->xbutton.button == Button1) {
818                 sel.mode = 0;
819                 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
820                 term.dirty[sel.ey] = 1;
821                 if(sel.bx == sel.ex && sel.by == sel.ey) {
822                         sel.bx = -1;
823                         gettimeofday(&now, NULL);
824
825                         if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
826                                 /* triple click on the line */
827                                 sel.b.x = sel.bx = 0;
828                                 sel.e.x = sel.ex = term.col;
829                                 sel.b.y = sel.e.y = sel.ey;
830                                 selcopy();
831                         } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
832                                 /* double click to select word */
833                                 sel.bx = sel.ex;
834                                 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
835                                                 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
836                                         sel.bx--;
837                                 }
838                                 sel.b.x = sel.bx;
839                                 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
840                                                 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
841                                         sel.ex++;
842                                 }
843                                 sel.e.x = sel.ex;
844                                 sel.b.y = sel.e.y = sel.ey;
845                                 selcopy();
846                         }
847                 } else {
848                         selcopy();
849                 }
850         }
851
852         memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
853         gettimeofday(&sel.tclick1, NULL);
854 }
855
856 void
857 bmotion(XEvent *e) {
858         int starty, endy, oldey, oldex;
859
860         if(IS_SET(MODE_MOUSE)) {
861                 mousereport(e);
862                 return;
863         }
864
865         if(sel.mode) {
866                 oldey = sel.ey;
867                 oldex = sel.ex;
868                 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
869
870                 if(oldey != sel.ey || oldex != sel.ex) {
871                         starty = MIN(oldey, sel.ey);
872                         endy = MAX(oldey, sel.ey);
873                         tsetdirt(starty, endy);
874                 }
875         }
876 }
877
878 void
879 die(const char *errstr, ...) {
880         va_list ap;
881
882         va_start(ap, errstr);
883         vfprintf(stderr, errstr, ap);
884         va_end(ap);
885         exit(EXIT_FAILURE);
886 }
887
888 void
889 execsh(void) {
890         char **args;
891         char *envshell = getenv("SHELL");
892         const struct passwd *pass = getpwuid(getuid());
893         char buf[sizeof(long) * 8 + 1];
894
895         unsetenv("COLUMNS");
896         unsetenv("LINES");
897         unsetenv("TERMCAP");
898
899         if(pass) {
900                 setenv("LOGNAME", pass->pw_name, 1);
901                 setenv("USER", pass->pw_name, 1);
902                 setenv("SHELL", pass->pw_shell, 0);
903                 setenv("HOME", pass->pw_dir, 0);
904         }
905
906         snprintf(buf, sizeof(buf), "%lu", xw.win);
907         setenv("WINDOWID", buf, 1);
908
909         signal(SIGCHLD, SIG_DFL);
910         signal(SIGHUP, SIG_DFL);
911         signal(SIGINT, SIG_DFL);
912         signal(SIGQUIT, SIG_DFL);
913         signal(SIGTERM, SIG_DFL);
914         signal(SIGALRM, SIG_DFL);
915
916         DEFAULT(envshell, shell);
917         setenv("TERM", termname, 1);
918         args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
919         execvp(args[0], args);
920         exit(EXIT_FAILURE);
921 }
922
923 void
924 sigchld(int a) {
925         int stat = 0;
926
927         if(waitpid(pid, &stat, 0) < 0)
928                 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
929
930         if(WIFEXITED(stat)) {
931                 exit(WEXITSTATUS(stat));
932         } else {
933                 exit(EXIT_FAILURE);
934         }
935 }
936
937 void
938 ttynew(void) {
939         int m, s;
940         struct winsize w = {term.row, term.col, 0, 0};
941
942         /* seems to work fine on linux, openbsd and freebsd */
943         if(openpty(&m, &s, NULL, NULL, &w) < 0)
944                 die("openpty failed: %s\n", SERRNO);
945
946         switch(pid = fork()) {
947         case -1:
948                 die("fork failed\n");
949                 break;
950         case 0:
951                 setsid(); /* create a new process group */
952                 dup2(s, STDIN_FILENO);
953                 dup2(s, STDOUT_FILENO);
954                 dup2(s, STDERR_FILENO);
955                 if(ioctl(s, TIOCSCTTY, NULL) < 0)
956                         die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
957                 close(s);
958                 close(m);
959                 execsh();
960                 break;
961         default:
962                 close(s);
963                 cmdfd = m;
964                 signal(SIGCHLD, sigchld);
965                 if(opt_io) {
966                         iofd = (!strcmp(opt_io, "-")) ?
967                                   STDOUT_FILENO :
968                                   open(opt_io, O_WRONLY | O_CREAT, 0666);
969                         if(iofd < 0) {
970                                 fprintf(stderr, "Error opening %s:%s\n",
971                                         opt_io, strerror(errno));
972                         }
973                 }
974         }
975 }
976
977 void
978 dump(char c) {
979         static int col;
980
981         fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
982         if(++col % 10 == 0)
983                 fprintf(stderr, "\n");
984 }
985
986 void
987 ttyread(void) {
988         static char buf[BUFSIZ];
989         static int buflen = 0;
990         char *ptr;
991         char s[UTF_SIZ];
992         int charsize; /* size of utf8 char in bytes */
993         long utf8c;
994         int ret;
995
996         /* append read bytes to unprocessed bytes */
997         if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
998                 die("Couldn't read from shell: %s\n", SERRNO);
999
1000         /* process every complete utf8 char */
1001         buflen += ret;
1002         ptr = buf;
1003         while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1004                 charsize = utf8decode(ptr, &utf8c);
1005                 utf8encode(&utf8c, s);
1006                 tputc(s, charsize);
1007                 ptr += charsize;
1008                 buflen -= charsize;
1009         }
1010
1011         /* keep any uncomplete utf8 char for the next call */
1012         memmove(buf, ptr, buflen);
1013 }
1014
1015 void
1016 ttywrite(const char *s, size_t n) {
1017         if(write(cmdfd, s, n) == -1)
1018                 die("write error on tty: %s\n", SERRNO);
1019 }
1020
1021 void
1022 ttyresize(void) {
1023         struct winsize w;
1024
1025         w.ws_row = term.row;
1026         w.ws_col = term.col;
1027         w.ws_xpixel = xw.tw;
1028         w.ws_ypixel = xw.th;
1029         if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1030                 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1031 }
1032
1033 void
1034 tsetdirt(int top, int bot) {
1035         int i;
1036
1037         LIMIT(top, 0, term.row-1);
1038         LIMIT(bot, 0, term.row-1);
1039
1040         for(i = top; i <= bot; i++)
1041                 term.dirty[i] = 1;
1042 }
1043
1044 void
1045 tfulldirt(void) {
1046         tsetdirt(0, term.row-1);
1047 }
1048
1049 void
1050 tcursor(int mode) {
1051         static TCursor c;
1052
1053         if(mode == CURSOR_SAVE) {
1054                 c = term.c;
1055         } else if(mode == CURSOR_LOAD) {
1056                 term.c = c;
1057                 tmoveto(c.x, c.y);
1058         }
1059 }
1060
1061 void
1062 treset(void) {
1063         uint i;
1064
1065         term.c = (TCursor){{
1066                 .mode = ATTR_NULL,
1067                 .fg = defaultfg,
1068                 .bg = defaultbg
1069         }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1070
1071         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1072         for(i = tabspaces; i < term.col; i += tabspaces)
1073                 term.tabs[i] = 1;
1074         term.top = 0;
1075         term.bot = term.row - 1;
1076         term.mode = MODE_WRAP;
1077
1078         tclearregion(0, 0, term.col-1, term.row-1);
1079         tmoveto(0, 0);
1080         tcursor(CURSOR_SAVE);
1081 }
1082
1083 void
1084 tnew(int col, int row) {
1085         /* set screen size */
1086         term.row = row;
1087         term.col = col;
1088         term.line = xmalloc(term.row * sizeof(Line));
1089         term.alt  = xmalloc(term.row * sizeof(Line));
1090         term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1091         term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1092
1093         for(row = 0; row < term.row; row++) {
1094                 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1095                 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1096                 term.dirty[row] = 0;
1097         }
1098         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1099         /* setup screen */
1100         treset();
1101 }
1102
1103 void
1104 tswapscreen(void) {
1105         Line *tmp = term.line;
1106
1107         term.line = term.alt;
1108         term.alt = tmp;
1109         term.mode ^= MODE_ALTSCREEN;
1110         tfulldirt();
1111 }
1112
1113 void
1114 tscrolldown(int orig, int n) {
1115         int i;
1116         Line temp;
1117
1118         LIMIT(n, 0, term.bot-orig+1);
1119
1120         tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1121
1122         for(i = term.bot; i >= orig+n; i--) {
1123                 temp = term.line[i];
1124                 term.line[i] = term.line[i-n];
1125                 term.line[i-n] = temp;
1126
1127                 term.dirty[i] = 1;
1128                 term.dirty[i-n] = 1;
1129         }
1130
1131         selscroll(orig, n);
1132 }
1133
1134 void
1135 tscrollup(int orig, int n) {
1136         int i;
1137         Line temp;
1138         LIMIT(n, 0, term.bot-orig+1);
1139
1140         tclearregion(0, orig, term.col-1, orig+n-1);
1141
1142         for(i = orig; i <= term.bot-n; i++) {
1143                  temp = term.line[i];
1144                  term.line[i] = term.line[i+n];
1145                  term.line[i+n] = temp;
1146
1147                  term.dirty[i] = 1;
1148                  term.dirty[i+n] = 1;
1149         }
1150
1151         selscroll(orig, -n);
1152 }
1153
1154 void
1155 selscroll(int orig, int n) {
1156         if(sel.bx == -1)
1157                 return;
1158
1159         if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1160                 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1161                         sel.bx = -1;
1162                         return;
1163                 }
1164                 if(sel.by < term.top) {
1165                         sel.by = term.top;
1166                         sel.bx = 0;
1167                 }
1168                 if(sel.ey > term.bot) {
1169                         sel.ey = term.bot;
1170                         sel.ex = term.col;
1171                 }
1172                 sel.b.y = sel.by, sel.b.x = sel.bx;
1173                 sel.e.y = sel.ey, sel.e.x = sel.ex;
1174         }
1175 }
1176
1177 void
1178 tnewline(int first_col) {
1179         int y = term.c.y;
1180
1181         if(y == term.bot) {
1182                 tscrollup(term.top, 1);
1183         } else {
1184                 y++;
1185         }
1186         tmoveto(first_col ? 0 : term.c.x, y);
1187 }
1188
1189 void
1190 csiparse(void) {
1191         /* int noarg = 1; */
1192         char *p = csiescseq.buf;
1193
1194         csiescseq.narg = 0;
1195         if(*p == '?')
1196                 csiescseq.priv = 1, p++;
1197
1198         while(p < csiescseq.buf+csiescseq.len) {
1199                 while(isdigit(*p)) {
1200                         csiescseq.arg[csiescseq.narg] *= 10;
1201                         csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1202                 }
1203                 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1204                         csiescseq.narg++, p++;
1205                 } else {
1206                         csiescseq.mode = *p;
1207                         csiescseq.narg++;
1208
1209                         return;
1210                 }
1211         }
1212 }
1213
1214 void
1215 tmoveto(int x, int y) {
1216         LIMIT(x, 0, term.col-1);
1217         LIMIT(y, 0, term.row-1);
1218         term.c.state &= ~CURSOR_WRAPNEXT;
1219         term.c.x = x;
1220         term.c.y = y;
1221 }
1222
1223 void
1224 tsetchar(char *c, Glyph *attr, int x, int y) {
1225         static char *vt100_0[62] = { /* 0x41 - 0x7e */
1226                 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1227                 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1228                 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1229                 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1230                 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1231                 "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1232                 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1233                 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1234         };
1235
1236         /*
1237          * The table is proudly stolen from rxvt.
1238          */
1239         if(attr->mode & ATTR_GFX) {
1240                 if(c[0] >= 0x41 && c[0] <= 0x7e
1241                                 && vt100_0[c[0] - 0x41]) {
1242                         c = vt100_0[c[0] - 0x41];
1243                 }
1244         }
1245
1246         term.dirty[y] = 1;
1247         term.line[y][x] = *attr;
1248         memcpy(term.line[y][x].c, c, UTF_SIZ);
1249         term.line[y][x].state |= GLYPH_SET;
1250 }
1251
1252 void
1253 tclearregion(int x1, int y1, int x2, int y2) {
1254         int x, y, temp;
1255
1256         if(x1 > x2)
1257                 temp = x1, x1 = x2, x2 = temp;
1258         if(y1 > y2)
1259                 temp = y1, y1 = y2, y2 = temp;
1260
1261         LIMIT(x1, 0, term.col-1);
1262         LIMIT(x2, 0, term.col-1);
1263         LIMIT(y1, 0, term.row-1);
1264         LIMIT(y2, 0, term.row-1);
1265
1266         for(y = y1; y <= y2; y++) {
1267                 term.dirty[y] = 1;
1268                 for(x = x1; x <= x2; x++)
1269                         term.line[y][x].state = 0;
1270         }
1271 }
1272
1273 void
1274 tdeletechar(int n) {
1275         int src = term.c.x + n;
1276         int dst = term.c.x;
1277         int size = term.col - src;
1278
1279         term.dirty[term.c.y] = 1;
1280
1281         if(src >= term.col) {
1282                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1283                 return;
1284         }
1285
1286         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1287                         size * sizeof(Glyph));
1288         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1289 }
1290
1291 void
1292 tinsertblank(int n) {
1293         int src = term.c.x;
1294         int dst = src + n;
1295         int size = term.col - dst;
1296
1297         term.dirty[term.c.y] = 1;
1298
1299         if(dst >= term.col) {
1300                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1301                 return;
1302         }
1303
1304         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1305                         size * sizeof(Glyph));
1306         tclearregion(src, term.c.y, dst - 1, term.c.y);
1307 }
1308
1309 void
1310 tinsertblankline(int n) {
1311         if(term.c.y < term.top || term.c.y > term.bot)
1312                 return;
1313
1314         tscrolldown(term.c.y, n);
1315 }
1316
1317 void
1318 tdeleteline(int n) {
1319         if(term.c.y < term.top || term.c.y > term.bot)
1320                 return;
1321
1322         tscrollup(term.c.y, n);
1323 }
1324
1325 void
1326 tsetattr(int *attr, int l) {
1327         int i;
1328
1329         for(i = 0; i < l; i++) {
1330                 switch(attr[i]) {
1331                 case 0:
1332                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1333                                         | ATTR_ITALIC | ATTR_BLINK);
1334                         term.c.attr.fg = defaultfg;
1335                         term.c.attr.bg = defaultbg;
1336                         break;
1337                 case 1:
1338                         term.c.attr.mode |= ATTR_BOLD;
1339                         break;
1340                 case 3: /* enter standout (highlight) */
1341                         term.c.attr.mode |= ATTR_ITALIC;
1342                         break;
1343                 case 4:
1344                         term.c.attr.mode |= ATTR_UNDERLINE;
1345                         break;
1346                 case 5:
1347                         term.c.attr.mode |= ATTR_BLINK;
1348                         break;
1349                 case 7:
1350                         term.c.attr.mode |= ATTR_REVERSE;
1351                         break;
1352                 case 21:
1353                 case 22:
1354                         term.c.attr.mode &= ~ATTR_BOLD;
1355                         break;
1356                 case 23: /* leave standout (highlight) mode */
1357                         term.c.attr.mode &= ~ATTR_ITALIC;
1358                         break;
1359                 case 24:
1360                         term.c.attr.mode &= ~ATTR_UNDERLINE;
1361                         break;
1362                 case 25:
1363                         term.c.attr.mode &= ~ATTR_BLINK;
1364                         break;
1365                 case 27:
1366                         term.c.attr.mode &= ~ATTR_REVERSE;
1367                         break;
1368                 case 38:
1369                         if(i + 2 < l && attr[i + 1] == 5) {
1370                                 i += 2;
1371                                 if(BETWEEN(attr[i], 0, 255)) {
1372                                         term.c.attr.fg = attr[i];
1373                                 } else {
1374                                         fprintf(stderr,
1375                                                 "erresc: bad fgcolor %d\n",
1376                                                 attr[i]);
1377                                 }
1378                         } else {
1379                                 fprintf(stderr,
1380                                         "erresc(38): gfx attr %d unknown\n",
1381                                         attr[i]);
1382                         }
1383                         break;
1384                 case 39:
1385                         term.c.attr.fg = defaultfg;
1386                         break;
1387                 case 48:
1388                         if(i + 2 < l && attr[i + 1] == 5) {
1389                                 i += 2;
1390                                 if(BETWEEN(attr[i], 0, 255)) {
1391                                         term.c.attr.bg = attr[i];
1392                                 } else {
1393                                         fprintf(stderr,
1394                                                 "erresc: bad bgcolor %d\n",
1395                                                 attr[i]);
1396                                 }
1397                         } else {
1398                                 fprintf(stderr,
1399                                         "erresc(48): gfx attr %d unknown\n",
1400                                         attr[i]);
1401                         }
1402                         break;
1403                 case 49:
1404                         term.c.attr.bg = defaultbg;
1405                         break;
1406                 default:
1407                         if(BETWEEN(attr[i], 30, 37)) {
1408                                 term.c.attr.fg = attr[i] - 30;
1409                         } else if(BETWEEN(attr[i], 40, 47)) {
1410                                 term.c.attr.bg = attr[i] - 40;
1411                         } else if(BETWEEN(attr[i], 90, 97)) {
1412                                 term.c.attr.fg = attr[i] - 90 + 8;
1413                         } else if(BETWEEN(attr[i], 100, 107)) {
1414                                 term.c.attr.bg = attr[i] - 100 + 8;
1415                         } else {
1416                                 fprintf(stderr,
1417                                         "erresc(default): gfx attr %d unknown\n",
1418                                         attr[i]), csidump();
1419                         }
1420                         break;
1421                 }
1422         }
1423 }
1424
1425 void
1426 tsetscroll(int t, int b) {
1427         int temp;
1428
1429         LIMIT(t, 0, term.row-1);
1430         LIMIT(b, 0, term.row-1);
1431         if(t > b) {
1432                 temp = t;
1433                 t = b;
1434                 b = temp;
1435         }
1436         term.top = t;
1437         term.bot = b;
1438 }
1439
1440 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1441
1442 void
1443 tsetmode(bool priv, bool set, int *args, int narg) {
1444         int *lim, mode;
1445
1446         for(lim = args + narg; args < lim; ++args) {
1447                 if(priv) {
1448                         switch(*args) {
1449                                 break;
1450                         case 1: /* DECCKM -- Cursor key */
1451                                 MODBIT(term.mode, set, MODE_APPKEYPAD);
1452                                 break;
1453                         case 5: /* DECSCNM -- Reverse video */
1454                                 mode = term.mode;
1455                                 MODBIT(term.mode, set, MODE_REVERSE);
1456                                 if(mode != term.mode)
1457                                         redraw();
1458                                 break;
1459                         case 6: /* XXX: DECOM -- Origin */
1460                                 break;
1461                         case 7: /* DECAWM -- Auto wrap */
1462                                 MODBIT(term.mode, set, MODE_WRAP);
1463                                 break;
1464                         case 8: /* XXX: DECARM -- Auto repeat */
1465                                 break;
1466                         case 0:  /* Error (IGNORED) */
1467                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1468                                 break;
1469                         case 25: /* DECTCEM -- Text Cursor Enable Mode */
1470                                 MODBIT(term.mode, !set, MODE_HIDE);
1471                                 break;
1472                         case 1000: /* 1000,1002: enable xterm mouse report */
1473                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
1474                                 break;
1475                         case 1002:
1476                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1477                                 break;
1478                         case 1049: /* = 1047 and 1048 */
1479                         case 47:
1480                         case 1047: {
1481                                 bool alt = IS_SET(MODE_ALTSCREEN) != 0;
1482                                 if(alt)
1483                                         tclearregion(0, 0, term.col-1, term.row-1);
1484                                 if(set ^ alt)           /* set is always 1 or 0 */
1485                                         tswapscreen();
1486                                 if(*args != 1049)
1487                                         break;
1488                         }
1489                                 /* pass through */
1490                         case 1048:
1491                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1492                                 break;
1493                         default:
1494                         /* case 2:  DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1495                         /* case 3:  DECCOLM -- Column  (NOT SUPPORTED) */
1496                         /* case 4:  DECSCLM -- Scroll (NOT SUPPORTED) */
1497                         /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1498                         /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1499                         /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1500                                 fprintf(stderr,
1501                                         "erresc: unknown private set/reset mode %d\n",
1502                                         *args);
1503                                 break;
1504                         }
1505                 } else {
1506                         switch(*args) {
1507                         case 0:  /* Error (IGNORED) */
1508                                 break;
1509                         case 2:  /* KAM -- keyboard action */
1510                                 MODBIT(term.mode, set, MODE_KBDLOCK);
1511                                 break;
1512                         case 4:  /* IRM -- Insertion-replacement */
1513                                 MODBIT(term.mode, set, MODE_INSERT);
1514                                 break;
1515                         case 12: /* XXX: SRM -- Send/Receive */
1516                                 break;
1517                         case 20: /* LNM -- Linefeed/new line */
1518                                 MODBIT(term.mode, set, MODE_CRLF);
1519                                 break;
1520                         default:
1521                                 fprintf(stderr,
1522                                         "erresc: unknown set/reset mode %d\n",
1523                                         *args);
1524                                 break;
1525                         }
1526                 }
1527         }
1528 }
1529 #undef MODBIT
1530
1531
1532 void
1533 csihandle(void) {
1534         switch(csiescseq.mode) {
1535         default:
1536         unknown:
1537                 fprintf(stderr, "erresc: unknown csi ");
1538                 csidump();
1539                 /* die(""); */
1540                 break;
1541         case '@': /* ICH -- Insert <n> blank char */
1542                 DEFAULT(csiescseq.arg[0], 1);
1543                 tinsertblank(csiescseq.arg[0]);
1544                 break;
1545         case 'A': /* CUU -- Cursor <n> Up */
1546         case 'e':
1547                 DEFAULT(csiescseq.arg[0], 1);
1548                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1549                 break;
1550         case 'B': /* CUD -- Cursor <n> Down */
1551                 DEFAULT(csiescseq.arg[0], 1);
1552                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1553                 break;
1554         case 'c': /* DA -- Device Attributes */
1555                 if(csiescseq.arg[0] == 0)
1556                         ttywrite(VT102ID, sizeof(VT102ID) - 1);
1557                 break;
1558         case 'C': /* CUF -- Cursor <n> Forward */
1559         case 'a':
1560                 DEFAULT(csiescseq.arg[0], 1);
1561                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1562                 break;
1563         case 'D': /* CUB -- Cursor <n> Backward */
1564                 DEFAULT(csiescseq.arg[0], 1);
1565                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1566                 break;
1567         case 'E': /* CNL -- Cursor <n> Down and first col */
1568                 DEFAULT(csiescseq.arg[0], 1);
1569                 tmoveto(0, term.c.y+csiescseq.arg[0]);
1570                 break;
1571         case 'F': /* CPL -- Cursor <n> Up and first col */
1572                 DEFAULT(csiescseq.arg[0], 1);
1573                 tmoveto(0, term.c.y-csiescseq.arg[0]);
1574                 break;
1575         case 'g': /* TBC -- Tabulation clear */
1576                 switch (csiescseq.arg[0]) {
1577                 case 0: /* clear current tab stop */
1578                         term.tabs[term.c.x] = 0;
1579                         break;
1580                 case 3: /* clear all the tabs */
1581                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1582                         break;
1583                 default:
1584                         goto unknown;
1585                 }
1586                 break;
1587         case 'G': /* CHA -- Move to <col> */
1588         case '`': /* HPA */
1589                 DEFAULT(csiescseq.arg[0], 1);
1590                 tmoveto(csiescseq.arg[0]-1, term.c.y);
1591                 break;
1592         case 'H': /* CUP -- Move to <row> <col> */
1593         case 'f': /* HVP */
1594                 DEFAULT(csiescseq.arg[0], 1);
1595                 DEFAULT(csiescseq.arg[1], 1);
1596                 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1597                 break;
1598         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1599                 DEFAULT(csiescseq.arg[0], 1);
1600                 while(csiescseq.arg[0]--)
1601                         tputtab(1);
1602                 break;
1603         case 'J': /* ED -- Clear screen */
1604                 sel.bx = -1;
1605                 switch(csiescseq.arg[0]) {
1606                 case 0: /* below */
1607                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1608                         if(term.c.y < term.row-1)
1609                                 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1610                         break;
1611                 case 1: /* above */
1612                         if(term.c.y > 1)
1613                                 tclearregion(0, 0, term.col-1, term.c.y-1);
1614                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1615                         break;
1616                 case 2: /* all */
1617                         tclearregion(0, 0, term.col-1, term.row-1);
1618                         break;
1619                 default:
1620                         goto unknown;
1621                 }
1622                 break;
1623         case 'K': /* EL -- Clear line */
1624                 switch(csiescseq.arg[0]) {
1625                 case 0: /* right */
1626                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1627                         break;
1628                 case 1: /* left */
1629                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1630                         break;
1631                 case 2: /* all */
1632                         tclearregion(0, term.c.y, term.col-1, term.c.y);
1633                         break;
1634                 }
1635                 break;
1636         case 'S': /* SU -- Scroll <n> line up */
1637                 DEFAULT(csiescseq.arg[0], 1);
1638                 tscrollup(term.top, csiescseq.arg[0]);
1639                 break;
1640         case 'T': /* SD -- Scroll <n> line down */
1641                 DEFAULT(csiescseq.arg[0], 1);
1642                 tscrolldown(term.top, csiescseq.arg[0]);
1643                 break;
1644         case 'L': /* IL -- Insert <n> blank lines */
1645                 DEFAULT(csiescseq.arg[0], 1);
1646                 tinsertblankline(csiescseq.arg[0]);
1647                 break;
1648         case 'l': /* RM -- Reset Mode */
1649                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1650                 break;
1651         case 'M': /* DL -- Delete <n> lines */
1652                 DEFAULT(csiescseq.arg[0], 1);
1653                 tdeleteline(csiescseq.arg[0]);
1654                 break;
1655         case 'X': /* ECH -- Erase <n> char */
1656                 DEFAULT(csiescseq.arg[0], 1);
1657                 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1658                 break;
1659         case 'P': /* DCH -- Delete <n> char */
1660                 DEFAULT(csiescseq.arg[0], 1);
1661                 tdeletechar(csiescseq.arg[0]);
1662                 break;
1663         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1664                 DEFAULT(csiescseq.arg[0], 1);
1665                 while(csiescseq.arg[0]--)
1666                         tputtab(0);
1667                 break;
1668         case 'd': /* VPA -- Move to <row> */
1669                 DEFAULT(csiescseq.arg[0], 1);
1670                 tmoveto(term.c.x, csiescseq.arg[0]-1);
1671                 break;
1672         case 'h': /* SM -- Set terminal mode */
1673                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1674                 break;
1675         case 'm': /* SGR -- Terminal attribute (color) */
1676                 tsetattr(csiescseq.arg, csiescseq.narg);
1677                 break;
1678         case 'r': /* DECSTBM -- Set Scrolling Region */
1679                 if(csiescseq.priv) {
1680                         goto unknown;
1681                 } else {
1682                         DEFAULT(csiescseq.arg[0], 1);
1683                         DEFAULT(csiescseq.arg[1], term.row);
1684                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1685                         tmoveto(0, 0);
1686                 }
1687                 break;
1688         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1689                 tcursor(CURSOR_SAVE);
1690                 break;
1691         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1692                 tcursor(CURSOR_LOAD);
1693                 break;
1694         }
1695 }
1696
1697 void
1698 csidump(void) {
1699         int i;
1700         uint c;
1701
1702         printf("ESC[");
1703         for(i = 0; i < csiescseq.len; i++) {
1704                 c = csiescseq.buf[i] & 0xff;
1705                 if(isprint(c)) {
1706                         putchar(c);
1707                 } else if(c == '\n') {
1708                         printf("(\\n)");
1709                 } else if(c == '\r') {
1710                         printf("(\\r)");
1711                 } else if(c == 0x1b) {
1712                         printf("(\\e)");
1713                 } else {
1714                         printf("(%02x)", c);
1715                 }
1716         }
1717         putchar('\n');
1718 }
1719
1720 void
1721 csireset(void) {
1722         memset(&csiescseq, 0, sizeof(csiescseq));
1723 }
1724
1725 void
1726 strhandle(void) {
1727         char *p;
1728
1729         /*
1730          * TODO: make this being useful in case of color palette change.
1731          */
1732         strparse();
1733
1734         p = strescseq.buf;
1735
1736         switch(strescseq.type) {
1737         case ']': /* OSC -- Operating System Command */
1738                 switch(p[0]) {
1739                 case '0':
1740                 case '1':
1741                 case '2':
1742                         /*
1743                          * TODO: Handle special chars in string, like umlauts.
1744                          */
1745                         if(p[1] == ';') {
1746                                 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1747                         }
1748                         break;
1749                 case ';':
1750                         XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1751                         break;
1752                 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1753                         break;
1754                 default:
1755                         fprintf(stderr, "erresc: unknown str ");
1756                         strdump();
1757                         break;
1758                 }
1759                 break;
1760         case 'k': /* old title set compatibility */
1761                 XStoreName(xw.dpy, xw.win, strescseq.buf);
1762                 break;
1763         case 'P': /* DSC -- Device Control String */
1764         case '_': /* APC -- Application Program Command */
1765         case '^': /* PM -- Privacy Message */
1766         default:
1767                 fprintf(stderr, "erresc: unknown str ");
1768                 strdump();
1769                 /* die(""); */
1770                 break;
1771         }
1772 }
1773
1774 void
1775 strparse(void) {
1776         /*
1777          * TODO: Implement parsing like for CSI when required.
1778          * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1779          */
1780         return;
1781 }
1782
1783 void
1784 strdump(void) {
1785         int i;
1786         uint c;
1787
1788         printf("ESC%c", strescseq.type);
1789         for(i = 0; i < strescseq.len; i++) {
1790                 c = strescseq.buf[i] & 0xff;
1791                 if(isprint(c)) {
1792                         putchar(c);
1793                 } else if(c == '\n') {
1794                         printf("(\\n)");
1795                 } else if(c == '\r') {
1796                         printf("(\\r)");
1797                 } else if(c == 0x1b) {
1798                         printf("(\\e)");
1799                 } else {
1800                         printf("(%02x)", c);
1801                 }
1802         }
1803         printf("ESC\\\n");
1804 }
1805
1806 void
1807 strreset(void) {
1808         memset(&strescseq, 0, sizeof(strescseq));
1809 }
1810
1811 void
1812 tputtab(bool forward) {
1813         uint x = term.c.x;
1814
1815         if(forward) {
1816                 if(x == term.col)
1817                         return;
1818                 for(++x; x < term.col && !term.tabs[x]; ++x)
1819                         /* nothing */ ;
1820         } else {
1821                 if(x == 0)
1822                         return;
1823                 for(--x; x > 0 && !term.tabs[x]; --x)
1824                         /* nothing */ ;
1825         }
1826         tmoveto(x, term.c.y);
1827 }
1828
1829 void
1830 tputc(char *c, int len) {
1831         uchar ascii = *c;
1832         bool control = ascii < '\x20' || ascii == 0177;
1833
1834         if(iofd != -1) {
1835                 if (xwrite(iofd, c, len) < 0) {
1836                         fprintf(stderr, "Error writting in %s:%s\n",
1837                                 opt_io, strerror(errno));
1838                         close(iofd);
1839                         iofd = -1;
1840                 }
1841         }
1842         /*
1843          * STR sequences must be checked before anything else
1844          * because it can use some control codes as part of the sequence.
1845          */
1846         if(term.esc & ESC_STR) {
1847                 switch(ascii) {
1848                 case '\033':
1849                         term.esc = ESC_START | ESC_STR_END;
1850                         break;
1851                 case '\a': /* backwards compatibility to xterm */
1852                         term.esc = 0;
1853                         strhandle();
1854                         break;
1855                 default:
1856                         strescseq.buf[strescseq.len++] = ascii;
1857                         if(strescseq.len+1 >= STR_BUF_SIZ) {
1858                                 term.esc = 0;
1859                                 strhandle();
1860                         }
1861                 }
1862                 return;
1863         }
1864
1865         /*
1866          * Actions of control codes must be performed as soon they arrive
1867          * because they can be embedded inside a control sequence, and
1868          * they must not cause conflicts with sequences.
1869          */
1870         if(control) {
1871                 switch(ascii) {
1872                 case '\t':      /* HT */
1873                         tputtab(1);
1874                         return;
1875                 case '\b':      /* BS */
1876                         tmoveto(term.c.x-1, term.c.y);
1877                         return;
1878                 case '\r':      /* CR */
1879                         tmoveto(0, term.c.y);
1880                         return;
1881                 case '\f':      /* LF */
1882                 case '\v':      /* VT */
1883                 case '\n':      /* LF */
1884                         /* go to first col if the mode is set */
1885                         tnewline(IS_SET(MODE_CRLF));
1886                         return;
1887                 case '\a':      /* BEL */
1888                         if(!(xw.state & WIN_FOCUSED))
1889                                 xseturgency(1);
1890                         return;
1891                 case '\033':    /* ESC */
1892                         csireset();
1893                         term.esc = ESC_START;
1894                         return;
1895                 case '\016':    /* SO */
1896                         term.c.attr.mode |= ATTR_GFX;
1897                         return;
1898                 case '\017':    /* SI */
1899                         term.c.attr.mode &= ~ATTR_GFX;
1900                         return;
1901                 case '\032':    /* SUB */
1902                 case '\030':    /* CAN */
1903                         csireset();
1904                         return;
1905                 case '\005':    /* ENQ (IGNORED) */
1906                 case '\000':    /* NUL (IGNORED) */
1907                 case '\021':    /* XON (IGNORED) */
1908                 case '\023':    /* XOFF (IGNORED) */
1909                 case 0177:      /* DEL (IGNORED) */
1910                         return;
1911                 }
1912         } else if(term.esc & ESC_START) {
1913                 if(term.esc & ESC_CSI) {
1914                         csiescseq.buf[csiescseq.len++] = ascii;
1915                         if(BETWEEN(ascii, 0x40, 0x7E)
1916                                         || csiescseq.len >= ESC_BUF_SIZ) {
1917                                 term.esc = 0;
1918                                 csiparse(), csihandle();
1919                         }
1920                 } else if(term.esc & ESC_STR_END) {
1921                         term.esc = 0;
1922                         if(ascii == '\\')
1923                                 strhandle();
1924                 } else if(term.esc & ESC_ALTCHARSET) {
1925                         switch(ascii) {
1926                         case '0': /* Line drawing set */
1927                                 term.c.attr.mode |= ATTR_GFX;
1928                                 break;
1929                         case 'B': /* USASCII */
1930                                 term.c.attr.mode &= ~ATTR_GFX;
1931                                 break;
1932                         case 'A': /* UK (IGNORED) */
1933                         case '<': /* multinational charset (IGNORED) */
1934                         case '5': /* Finnish (IGNORED) */
1935                         case 'C': /* Finnish (IGNORED) */
1936                         case 'K': /* German (IGNORED) */
1937                                 break;
1938                         default:
1939                                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1940                         }
1941                         term.esc = 0;
1942                 } else if(term.esc & ESC_TEST) {
1943                         if(ascii == '8') { /* DEC screen alignment test. */
1944                                 char E[UTF_SIZ] = "E";
1945                                 int x, y;
1946
1947                                 for(x = 0; x < term.col; ++x) {
1948                                         for(y = 0; y < term.row; ++y)
1949                                                 tsetchar(E, &term.c.attr, x, y);
1950                                 }
1951                         }
1952                         term.esc = 0;
1953                 } else {
1954                         switch(ascii) {
1955                         case '[':
1956                                 term.esc |= ESC_CSI;
1957                                 break;
1958                         case '#':
1959                                 term.esc |= ESC_TEST;
1960                                 break;
1961                         case 'P': /* DCS -- Device Control String */
1962                         case '_': /* APC -- Application Program Command */
1963                         case '^': /* PM -- Privacy Message */
1964                         case ']': /* OSC -- Operating System Command */
1965                         case 'k': /* old title set compatibility */
1966                                 strreset();
1967                                 strescseq.type = ascii;
1968                                 term.esc |= ESC_STR;
1969                                 break;
1970                         case '(': /* set primary charset G0 */
1971                                 term.esc |= ESC_ALTCHARSET;
1972                                 break;
1973                         case ')': /* set secondary charset G1 (IGNORED) */
1974                         case '*': /* set tertiary charset G2 (IGNORED) */
1975                         case '+': /* set quaternary charset G3 (IGNORED) */
1976                                 term.esc = 0;
1977                                 break;
1978                         case 'D': /* IND -- Linefeed */
1979                                 if(term.c.y == term.bot) {
1980                                         tscrollup(term.top, 1);
1981                                 } else {
1982                                         tmoveto(term.c.x, term.c.y+1);
1983                                 }
1984                                 term.esc = 0;
1985                                 break;
1986                         case 'E': /* NEL -- Next line */
1987                                 tnewline(1); /* always go to first col */
1988                                 term.esc = 0;
1989                                 break;
1990                         case 'H': /* HTS -- Horizontal tab stop */
1991                                 term.tabs[term.c.x] = 1;
1992                                 term.esc = 0;
1993                                 break;
1994                         case 'M': /* RI -- Reverse index */
1995                                 if(term.c.y == term.top) {
1996                                         tscrolldown(term.top, 1);
1997                                 } else {
1998                                         tmoveto(term.c.x, term.c.y-1);
1999                                 }
2000                                 term.esc = 0;
2001                                 break;
2002                         case 'Z': /* DECID -- Identify Terminal */
2003                                 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2004                                 term.esc = 0;
2005                                 break;
2006                         case 'c': /* RIS -- Reset to inital state */
2007                                 treset();
2008                                 term.esc = 0;
2009                                 xresettitle();
2010                                 break;
2011                         case '=': /* DECPAM -- Application keypad */
2012                                 term.mode |= MODE_APPKEYPAD;
2013                                 term.esc = 0;
2014                                 break;
2015                         case '>': /* DECPNM -- Normal keypad */
2016                                 term.mode &= ~MODE_APPKEYPAD;
2017                                 term.esc = 0;
2018                                 break;
2019                         case '7': /* DECSC -- Save Cursor */
2020                                 tcursor(CURSOR_SAVE);
2021                                 term.esc = 0;
2022                                 break;
2023                         case '8': /* DECRC -- Restore Cursor */
2024                                 tcursor(CURSOR_LOAD);
2025                                 term.esc = 0;
2026                                 break;
2027                         case '\\': /* ST -- Stop */
2028                                 term.esc = 0;
2029                                 break;
2030                         default:
2031                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2032                                         (uchar) ascii, isprint(ascii)? ascii:'.');
2033                                 term.esc = 0;
2034                         }
2035                 }
2036                 /*
2037                  * All characters which forms part of a sequence are not
2038                  * printed
2039                  */
2040                 return;
2041         }
2042         /*
2043          * Display control codes only if we are in graphic mode
2044          */
2045         if(control && !(term.c.attr.mode & ATTR_GFX))
2046                 return;
2047         if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
2048                 sel.bx = -1;
2049         if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
2050                 tnewline(1); /* always go to first col */
2051         tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2052         if(term.c.x+1 < term.col)
2053                 tmoveto(term.c.x+1, term.c.y);
2054         else
2055                 term.c.state |= CURSOR_WRAPNEXT;
2056 }
2057
2058 int
2059 tresize(int col, int row) {
2060         int i, x;
2061         int minrow = MIN(row, term.row);
2062         int mincol = MIN(col, term.col);
2063         int slide = term.c.y - row + 1;
2064         bool *bp;
2065
2066         if(col < 1 || row < 1)
2067                 return 0;
2068
2069         /* free unneeded rows */
2070         i = 0;
2071         if(slide > 0) {
2072                 /* slide screen to keep cursor where we expect it -
2073                  * tscrollup would work here, but we can optimize to
2074                  * memmove because we're freeing the earlier lines */
2075                 for(/* i = 0 */; i < slide; i++) {
2076                         free(term.line[i]);
2077                         free(term.alt[i]);
2078                 }
2079                 memmove(term.line, term.line + slide, row * sizeof(Line));
2080                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2081         }
2082         for(i += row; i < term.row; i++) {
2083                 free(term.line[i]);
2084                 free(term.alt[i]);
2085         }
2086
2087         /* resize to new height */
2088         term.line = xrealloc(term.line, row * sizeof(Line));
2089         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
2090         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2091         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2092
2093         /* resize each row to new width, zero-pad if needed */
2094         for(i = 0; i < minrow; i++) {
2095                 term.dirty[i] = 1;
2096                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2097                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
2098                 for(x = mincol; x < col; x++) {
2099                         term.line[i][x].state = 0;
2100                         term.alt[i][x].state = 0;
2101                 }
2102         }
2103
2104         /* allocate any new rows */
2105         for(/* i == minrow */; i < row; i++) {
2106                 term.dirty[i] = 1;
2107                 term.line[i] = xcalloc(col, sizeof(Glyph));
2108                 term.alt [i] = xcalloc(col, sizeof(Glyph));
2109         }
2110         if(col > term.col) {
2111                 bp = term.tabs + term.col;
2112
2113                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2114                 while(--bp > term.tabs && !*bp)
2115                         /* nothing */ ;
2116                 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2117                         *bp = 1;
2118         }
2119         /* update terminal size */
2120         term.col = col;
2121         term.row = row;
2122         /* make use of the LIMIT in tmoveto */
2123         tmoveto(term.c.x, term.c.y);
2124         /* reset scrolling region */
2125         tsetscroll(0, row-1);
2126
2127         return (slide > 0);
2128 }
2129
2130 void
2131 xresize(int col, int row) {
2132         xw.tw = MAX(1, 2*borderpx + col * xw.cw);
2133         xw.th = MAX(1, 2*borderpx + row * xw.ch);
2134
2135         XftDrawChange(xw.xft_draw, xw.buf);
2136 }
2137
2138 void
2139 xloadcols(void) {
2140         int i, r, g, b;
2141         XRenderColor xft_color = { .alpha = 0 };
2142
2143         /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2144         for(i = 0; i < LEN(colorname); i++) {
2145                 if(!colorname[i])
2146                         continue;
2147                 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
2148                         die("Could not allocate color '%s'\n", colorname[i]);
2149                 }
2150         }
2151
2152         /* load colors [16-255] ; same colors as xterm */
2153         for(i = 16, r = 0; r < 6; r++) {
2154                 for(g = 0; g < 6; g++) {
2155                         for(b = 0; b < 6; b++) {
2156                                 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2157                                 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2158                                 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2159                                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
2160                                         die("Could not allocate color %d\n", i);
2161                                 }
2162                                 i++;
2163                         }
2164                 }
2165         }
2166
2167         for(r = 0; r < 24; r++, i++) {
2168                 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
2169                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
2170                                         &dc.xft_col[i])) {
2171                         die("Could not allocate color %d\n", i);
2172                 }
2173         }
2174 }
2175
2176 void
2177 xtermclear(int col1, int row1, int col2, int row2) {
2178         XftDrawRect(xw.xft_draw,
2179                         &dc.xft_col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2180                         borderpx + col1 * xw.cw,
2181                         borderpx + row1 * xw.ch,
2182                         (col2-col1+1) * xw.cw,
2183                         (row2-row1+1) * xw.ch);
2184 }
2185
2186 /*
2187  * Absolute coordinates.
2188  */
2189 void
2190 xclear(int x1, int y1, int x2, int y2) {
2191         XftDrawRect(xw.xft_draw,
2192                         &dc.xft_col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2193                         x1, y1, x2-x1, y2-y1);
2194 }
2195
2196 void
2197 xhints(void) {
2198         XClassHint class = {opt_class ? opt_class : termname, termname};
2199         XWMHints wm = {.flags = InputHint, .input = 1};
2200         XSizeHints *sizeh = NULL;
2201
2202         sizeh = XAllocSizeHints();
2203         if(xw.isfixed == False) {
2204                 sizeh->flags = PSize | PResizeInc | PBaseSize;
2205                 sizeh->height = xw.h;
2206                 sizeh->width = xw.w;
2207                 sizeh->height_inc = xw.ch;
2208                 sizeh->width_inc = xw.cw;
2209                 sizeh->base_height = 2*borderpx;
2210                 sizeh->base_width = 2*borderpx;
2211         } else {
2212                 sizeh->flags = PMaxSize | PMinSize;
2213                 sizeh->min_width = sizeh->max_width = xw.fw;
2214                 sizeh->min_height = sizeh->max_height = xw.fh;
2215         }
2216
2217         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2218         XFree(sizeh);
2219 }
2220
2221 int
2222 xloadfont(Font *f, FcPattern *pattern) {
2223         FcPattern *match;
2224         FcResult result;
2225
2226         match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2227         if(!match)
2228                 return 1;
2229         if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2230                 FcPatternDestroy(match);
2231                 return 1;
2232         }
2233
2234         f->ascent = f->xft_set->ascent;
2235         f->descent = f->xft_set->descent;
2236         f->lbearing = 0;
2237         f->rbearing = f->xft_set->max_advance_width;
2238
2239         f->height = f->xft_set->height;
2240         f->width = f->lbearing + f->rbearing;
2241
2242         return 0;
2243 }
2244
2245 void
2246 xloadfonts(char *fontstr, int fontsize) {
2247         FcPattern *pattern;
2248         FcResult result;
2249         double fontval;
2250
2251         if(fontstr[0] == '-') {
2252                 pattern = XftXlfdParse(fontstr, False, False);
2253         } else {
2254                 pattern = FcNameParse((FcChar8 *)fontstr);
2255         }
2256
2257         if(!pattern)
2258                 die("st: can't open font %s\n", fontstr);
2259
2260         if(fontsize > 0) {
2261                 FcPatternDel(pattern, FC_PIXEL_SIZE);
2262                 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2263                 usedfontsize = fontsize;
2264         } else {
2265                 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2266                 if(result == FcResultMatch) {
2267                         usedfontsize = (int)fontval;
2268                 } else {
2269                         /*
2270                          * Default font size is 12, if none given. This is to
2271                          * have a known usedfontsize value.
2272                          */
2273                         FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2274                         usedfontsize = 12;
2275                 }
2276         }
2277
2278         if(xloadfont(&dc.font, pattern))
2279                 die("st: can't open font %s\n", fontstr);
2280
2281         /* Setting character width and height. */
2282         xw.cw = dc.font.width;
2283         xw.ch = dc.font.height;
2284
2285         FcPatternDel(pattern, FC_WEIGHT);
2286         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2287         if(xloadfont(&dc.bfont, pattern))
2288                 die("st: can't open font %s\n", fontstr);
2289
2290         FcPatternDel(pattern, FC_SLANT);
2291         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2292         if(xloadfont(&dc.ibfont, pattern))
2293                 die("st: can't open font %s\n", fontstr);
2294
2295         FcPatternDel(pattern, FC_WEIGHT);
2296         if(xloadfont(&dc.ifont, pattern))
2297                 die("st: can't open font %s\n", fontstr);
2298
2299         FcPatternDestroy(pattern);
2300 }
2301
2302 void
2303 xzoom(const Arg *arg)
2304 {
2305         xloadfonts(usedfont, usedfontsize + arg->i);
2306         cresize(0, 0);
2307         draw();
2308 }
2309
2310 void
2311 xinit(void) {
2312         XSetWindowAttributes attrs;
2313         Cursor cursor;
2314         Window parent;
2315         int sw, sh, major, minor;
2316
2317         if(!(xw.dpy = XOpenDisplay(NULL)))
2318                 die("Can't open display\n");
2319         xw.scr = XDefaultScreen(xw.dpy);
2320         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2321
2322         /* font */
2323         usedfont = (opt_font == NULL)? font : opt_font;
2324         xloadfonts(usedfont, 0);
2325
2326         /* colors */
2327         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2328         xloadcols();
2329
2330         /* adjust fixed window geometry */
2331         if(xw.isfixed) {
2332                 sw = DisplayWidth(xw.dpy, xw.scr);
2333                 sh = DisplayHeight(xw.dpy, xw.scr);
2334                 if(xw.fx < 0)
2335                         xw.fx = sw + xw.fx - xw.fw - 1;
2336                 if(xw.fy < 0)
2337                         xw.fy = sh + xw.fy - xw.fh - 1;
2338
2339                 xw.h = xw.fh;
2340                 xw.w = xw.fw;
2341         } else {
2342                 /* window - default size */
2343                 xw.h = 2*borderpx + term.row * xw.ch;
2344                 xw.w = 2*borderpx + term.col * xw.cw;
2345                 xw.fx = 0;
2346                 xw.fy = 0;
2347         }
2348
2349         attrs.background_pixel = dc.xft_col[defaultbg].pixel;
2350         attrs.border_pixel = dc.xft_col[defaultbg].pixel;
2351         attrs.bit_gravity = NorthWestGravity;
2352         attrs.event_mask = FocusChangeMask | KeyPressMask
2353                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2354                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2355         attrs.colormap = xw.cmap;
2356
2357         parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2358         xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2359                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2360                         xw.vis,
2361                         CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2362                         | CWColormap,
2363                         &attrs);
2364
2365         /* double buffering */
2366         if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2367                 die("Xdbe extension is not present\n");
2368         xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2369
2370         /* Xft rendering context */
2371         xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2372
2373         /* input methods */
2374         xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2375         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2376                                            | XIMStatusNothing, XNClientWindow, xw.win,
2377                                            XNFocusWindow, xw.win, NULL);
2378         /* gc */
2379         dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2380
2381         /* white cursor, black outline */
2382         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2383         XDefineCursor(xw.dpy, xw.win, cursor);
2384         XRecolorCursor(xw.dpy, cursor,
2385                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2386                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2387
2388         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2389         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2390         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2391
2392         xresettitle();
2393         XMapWindow(xw.dpy, xw.win);
2394         xhints();
2395         XSync(xw.dpy, 0);
2396 }
2397
2398 void
2399 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2400         int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2401             width = charlen * xw.cw;
2402         Font *font = &dc.font;
2403         XGlyphInfo extents;
2404         XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2405                  *temp, revfg, revbg;
2406         XRenderColor colfg, colbg;
2407
2408         if(base.mode & ATTR_BOLD) {
2409                 if(BETWEEN(base.fg, 0, 7)) {
2410                         /* basic system colors */
2411                         fg = &dc.xft_col[base.fg + 8];
2412                 } else if(BETWEEN(base.fg, 16, 195)) {
2413                         /* 256 colors */
2414                         fg = &dc.xft_col[base.fg + 36];
2415                 } else if(BETWEEN(base.fg, 232, 251)) {
2416                         /* greyscale */
2417                         fg = &dc.xft_col[base.fg + 4];
2418                 }
2419                 /*
2420                  * Those ranges will not be brightened:
2421                  *      8 - 15 – bright system colors
2422                  *      196 - 231 – highest 256 color cube
2423                  *      252 - 255 – brightest colors in greyscale
2424                  */
2425                 font = &dc.bfont;
2426         }
2427
2428         if(base.mode & ATTR_ITALIC)
2429                 font = &dc.ifont;
2430         if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
2431                 font = &dc.ibfont;
2432
2433         if(IS_SET(MODE_REVERSE)) {
2434                 if(fg == &dc.xft_col[defaultfg]) {
2435                         fg = &dc.xft_col[defaultbg];
2436                 } else {
2437                         colfg.red = ~fg->color.red;
2438                         colfg.green = ~fg->color.green;
2439                         colfg.blue = ~fg->color.blue;
2440                         colfg.alpha = fg->color.alpha;
2441                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2442                         fg = &revfg;
2443                 }
2444
2445                 if(bg == &dc.xft_col[defaultbg]) {
2446                         bg = &dc.xft_col[defaultfg];
2447                 } else {
2448                         colbg.red = ~bg->color.red;
2449                         colbg.green = ~bg->color.green;
2450                         colbg.blue = ~bg->color.blue;
2451                         colbg.alpha = bg->color.alpha;
2452                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2453                         bg = &revbg;
2454                 }
2455         }
2456
2457         if(base.mode & ATTR_REVERSE)
2458                 temp = fg, fg = bg, bg = temp;
2459
2460         XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2461                         &extents);
2462         width = extents.xOff;
2463
2464         /* Intelligent cleaning up of the borders. */
2465         if(x == 0) {
2466                 xclear(0, (y == 0)? 0 : winy, borderpx,
2467                         winy + xw.ch + (y == term.row-1)? xw.h : 0);
2468         }
2469         if(x + charlen >= term.col-1) {
2470                 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2471                         (y == term.row-1)? xw.h : (winy + xw.ch));
2472         }
2473         if(y == 0)
2474                 xclear(winx, 0, winx + width, borderpx);
2475         if(y == term.row-1)
2476                 xclear(winx, winy + xw.ch, winx + width, xw.h);
2477
2478         XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2479         XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2480                         winy + font->ascent, (FcChar8 *)s, bytelen);
2481
2482         if(base.mode & ATTR_UNDERLINE) {
2483                 XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
2484                                 width, 1);
2485         }
2486 }
2487
2488 void
2489 xdrawcursor(void) {
2490         static int oldx = 0, oldy = 0;
2491         int sl;
2492         Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs, 0};
2493
2494         LIMIT(oldx, 0, term.col-1);
2495         LIMIT(oldy, 0, term.row-1);
2496
2497         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2498                 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2499
2500         /* remove the old cursor */
2501         if(term.line[oldy][oldx].state & GLYPH_SET) {
2502                 sl = utf8size(term.line[oldy][oldx].c);
2503                 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2504                                 oldy, 1, sl);
2505         } else {
2506                 xtermclear(oldx, oldy, oldx, oldy);
2507         }
2508
2509         /* draw the new one */
2510         if(!(IS_SET(MODE_HIDE))) {
2511                 if(!(xw.state & WIN_FOCUSED))
2512                         g.bg = defaultucs;
2513
2514                 if(IS_SET(MODE_REVERSE))
2515                         g.mode |= ATTR_REVERSE, g.fg = defaultcs, g.bg = defaultfg;
2516
2517                 sl = utf8size(g.c);
2518                 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2519                 oldx = term.c.x, oldy = term.c.y;
2520         }
2521 }
2522
2523 void
2524 xresettitle(void) {
2525         XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2526 }
2527
2528 void
2529 redraw(void) {
2530         struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2531
2532         tfulldirt();
2533         draw();
2534         XSync(xw.dpy, False); /* necessary for a good tput flash */
2535         nanosleep(&tv, NULL);
2536 }
2537
2538 void
2539 draw(void) {
2540         XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2541
2542         drawregion(0, 0, term.col, term.row);
2543         XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2544 }
2545
2546 void
2547 drawregion(int x1, int y1, int x2, int y2) {
2548         int ic, ib, x, y, ox, sl;
2549         Glyph base, new;
2550         char buf[DRAW_BUF_SIZ];
2551         bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN) != 0;
2552
2553         if((sel.alt != 0) ^ alt)
2554                 ena_sel = 0;
2555         if(!(xw.state & WIN_VISIBLE))
2556                 return;
2557
2558         for(y = y1; y < y2; y++) {
2559                 if(!term.dirty[y])
2560                         continue;
2561
2562                 xtermclear(0, y, term.col, y);
2563                 term.dirty[y] = 0;
2564                 base = term.line[y][0];
2565                 ic = ib = ox = 0;
2566                 for(x = x1; x < x2; x++) {
2567                         new = term.line[y][x];
2568                         if(ena_sel && *(new.c) && selected(x, y))
2569                                 new.mode ^= ATTR_REVERSE;
2570                         if(ib > 0 && (!(new.state & GLYPH_SET)
2571                                         || ATTRCMP(base, new)
2572                                         || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2573                                 xdraws(buf, base, ox, y, ic, ib);
2574                                 ic = ib = 0;
2575                         }
2576                         if(new.state & GLYPH_SET) {
2577                                 if(ib == 0) {
2578                                         ox = x;
2579                                         base = new;
2580                                 }
2581                                 sl = utf8size(new.c);
2582                                 memcpy(buf+ib, new.c, sl);
2583                                 ib += sl;
2584                                 ++ic;
2585                         }
2586                 }
2587                 if(ib > 0)
2588                         xdraws(buf, base, ox, y, ic, ib);
2589         }
2590         xdrawcursor();
2591 }
2592
2593 void
2594 expose(XEvent *ev) {
2595         XExposeEvent *e = &ev->xexpose;
2596
2597         if(xw.state & WIN_REDRAW) {
2598                 if(!e->count)
2599                         xw.state &= ~WIN_REDRAW;
2600         }
2601 }
2602
2603 void
2604 visibility(XEvent *ev) {
2605         XVisibilityEvent *e = &ev->xvisibility;
2606
2607         if(e->state == VisibilityFullyObscured) {
2608                 xw.state &= ~WIN_VISIBLE;
2609         } else if(!(xw.state & WIN_VISIBLE)) {
2610                 /* need a full redraw for next Expose, not just a buf copy */
2611                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2612         }
2613 }
2614
2615 void
2616 unmap(XEvent *ev) {
2617         xw.state &= ~WIN_VISIBLE;
2618 }
2619
2620 void
2621 xseturgency(int add) {
2622         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2623
2624         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2625         XSetWMHints(xw.dpy, xw.win, h);
2626         XFree(h);
2627 }
2628
2629 void
2630 focus(XEvent *ev) {
2631         if(ev->type == FocusIn) {
2632                 XSetICFocus(xw.xic);
2633                 xw.state |= WIN_FOCUSED;
2634                 xseturgency(0);
2635         } else {
2636                 XUnsetICFocus(xw.xic);
2637                 xw.state &= ~WIN_FOCUSED;
2638         }
2639 }
2640
2641 char*
2642 kmap(KeySym k, uint state) {
2643         int i;
2644         uint mask;
2645
2646         state &= ~Mod2Mask;
2647         for(i = 0; i < LEN(key); i++) {
2648                 mask = key[i].mask;
2649
2650                 if(key[i].k == k && ((state & mask) == mask
2651                                 || (mask == XK_NO_MOD && !state))) {
2652                         return (char*)key[i].s;
2653                 }
2654         }
2655         return NULL;
2656 }
2657
2658 void
2659 kpress(XEvent *ev) {
2660         XKeyEvent *e = &ev->xkey;
2661         KeySym ksym;
2662         char buf[32], *customkey;
2663         int len, meta, shift, i;
2664         Status status;
2665
2666         if (IS_SET(MODE_KBDLOCK))
2667                 return;
2668
2669         meta = e->state & Mod1Mask;
2670         shift = e->state & ShiftMask;
2671         len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2672
2673         /* 1. shortcuts */
2674         for(i = 0; i < LEN(shortcuts); i++) {
2675                 if((ksym == shortcuts[i].keysym)
2676                                 && (CLEANMASK(shortcuts[i].mod) == \
2677                                         CLEANMASK(e->state))
2678                                 && shortcuts[i].func) {
2679                         shortcuts[i].func(&(shortcuts[i].arg));
2680                 }
2681         }
2682
2683         /* 2. custom keys from config.h */
2684         if((customkey = kmap(ksym, e->state))) {
2685                 ttywrite(customkey, strlen(customkey));
2686         /* 2. hardcoded (overrides X lookup) */
2687         } else {
2688                 switch(ksym) {
2689                 case XK_Up:
2690                 case XK_Down:
2691                 case XK_Left:
2692                 case XK_Right:
2693                         /* XXX: shift up/down doesn't work */
2694                         sprintf(buf, "\033%c%c",
2695                                 IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
2696                                 (shift ? "dacb":"DACB")[ksym - XK_Left]);
2697                         ttywrite(buf, 3);
2698                         break;
2699                 case XK_Insert:
2700                         if(shift)
2701                                 selpaste();
2702                         break;
2703                 case XK_Return:
2704                         if(meta)
2705                                 ttywrite("\033", 1);
2706
2707                         if(IS_SET(MODE_CRLF)) {
2708                                 ttywrite("\r\n", 2);
2709                         } else {
2710                                 ttywrite("\r", 1);
2711                         }
2712                         break;
2713                         /* 3. X lookup  */
2714                 default:
2715                         if(len > 0) {
2716                                 if(meta && len == 1)
2717                                         ttywrite("\033", 1);
2718                                 ttywrite(buf, len);
2719                         }
2720                         break;
2721                 }
2722         }
2723 }
2724
2725 void
2726 cmessage(XEvent *e) {
2727         /* See xembed specs
2728            http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2729         if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2730                 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2731                         xw.state |= WIN_FOCUSED;
2732                         xseturgency(0);
2733                 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2734                         xw.state &= ~WIN_FOCUSED;
2735                 }
2736         } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2737                 /* Send SIGHUP to shell */
2738                 kill(pid, SIGHUP);
2739                 exit(EXIT_SUCCESS);
2740         }
2741 }
2742
2743 void
2744 cresize(int width, int height)
2745 {
2746         int col, row;
2747
2748         if(width != 0)
2749                 xw.w = width;
2750         if(height != 0)
2751                 xw.h = height;
2752
2753         col = (xw.w - 2*borderpx) / xw.cw;
2754         row = (xw.h - 2*borderpx) / xw.ch;
2755
2756         tresize(col, row);
2757         xresize(col, row);
2758         ttyresize();
2759 }
2760
2761 void
2762 resize(XEvent *e) {
2763         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2764                 return;
2765
2766         cresize(e->xconfigure.width, e->xconfigure.height);
2767 }
2768
2769 void
2770 run(void) {
2771         XEvent ev;
2772         fd_set rfd;
2773         int xfd = XConnectionNumber(xw.dpy), i;
2774         struct timeval drawtimeout, *tv = NULL;
2775
2776         for(i = 0;; i++) {
2777                 FD_ZERO(&rfd);
2778                 FD_SET(cmdfd, &rfd);
2779                 FD_SET(xfd, &rfd);
2780                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2781                         if(errno == EINTR)
2782                                 continue;
2783                         die("select failed: %s\n", SERRNO);
2784                 }
2785
2786                 /*
2787                  * Stop after a certain number of reads so the user does not
2788                  * feel like the system is stuttering.
2789                  */
2790                 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2791                         ttyread();
2792
2793                         /*
2794                          * Just wait a bit so it isn't disturbing the
2795                          * user and the system is able to write something.
2796                          */
2797                         drawtimeout.tv_sec = 0;
2798                         drawtimeout.tv_usec = 5;
2799                         tv = &drawtimeout;
2800                         continue;
2801                 }
2802                 i = 0;
2803                 tv = NULL;
2804
2805                 while(XPending(xw.dpy)) {
2806                         XNextEvent(xw.dpy, &ev);
2807                         if(XFilterEvent(&ev, None))
2808                                 continue;
2809                         if(handler[ev.type])
2810                                 (handler[ev.type])(&ev);
2811                 }
2812
2813                 draw();
2814                 XFlush(xw.dpy);
2815         }
2816 }
2817
2818 int
2819 main(int argc, char *argv[]) {
2820         int i, bitm, xr, yr;
2821         uint wr, hr;
2822
2823         xw.fw = xw.fh = xw.fx = xw.fy = 0;
2824         xw.isfixed = False;
2825
2826         for(i = 1; i < argc; i++) {
2827                 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2828                 case 'c':
2829                         if(++i < argc)
2830                                 opt_class = argv[i];
2831                         break;
2832                 case 'e':
2833                         /* eat every remaining arguments */
2834                         if(++i < argc)
2835                                 opt_cmd = &argv[i];
2836                         goto run;
2837                 case 'f':
2838                         if(++i < argc)
2839                                 opt_font = argv[i];
2840                         break;
2841                 case 'g':
2842                         if(++i >= argc)
2843                                 break;
2844
2845                         bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2846                         if(bitm & XValue)
2847                                 xw.fx = xr;
2848                         if(bitm & YValue)
2849                                 xw.fy = yr;
2850                         if(bitm & WidthValue)
2851                                 xw.fw = (int)wr;
2852                         if(bitm & HeightValue)
2853                                 xw.fh = (int)hr;
2854                         if(bitm & XNegative && xw.fx == 0)
2855                                 xw.fx = -1;
2856                         if(bitm & XNegative && xw.fy == 0)
2857                                 xw.fy = -1;
2858
2859                         if(xw.fh != 0 && xw.fw != 0)
2860                                 xw.isfixed = True;
2861                         break;
2862                 case 'o':
2863                         if(++i < argc)
2864                                 opt_io = argv[i];
2865                         break;
2866                 case 't':
2867                         if(++i < argc)
2868                                 opt_title = argv[i];
2869                         break;
2870                 case 'v':
2871                 default:
2872                         die(USAGE);
2873                 case 'w':
2874                         if(++i < argc)
2875                                 opt_embed = argv[i];
2876                         break;
2877                 }
2878         }
2879
2880 run:
2881         setlocale(LC_CTYPE, "");
2882         XSetLocaleModifiers("");
2883         tnew(80, 24);
2884         xinit();
2885         ttynew();
2886         selinit();
2887         run();
2888         return 0;
2889 }
2890