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