JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Adding true mouse motion support.
[st.git] / st.c
1 /* See LICENSE for licence details. */
2 #include <ctype.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <limits.h>
6 #include <locale.h>
7 #include <pwd.h>
8 #include <stdarg.h>
9 #include <stdbool.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <signal.h>
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
16 #include <sys/stat.h>
17 #include <sys/time.h>
18 #include <sys/types.h>
19 #include <sys/wait.h>
20 #include <time.h>
21 #include <unistd.h>
22 #include <X11/Xatom.h>
23 #include <X11/Xlib.h>
24 #include <X11/Xutil.h>
25 #include <X11/cursorfont.h>
26 #include <X11/keysym.h>
27 #include <X11/Xft/Xft.h>
28 #include <fontconfig/fontconfig.h>
29
30 #include "arg.h"
31
32 char *argv0;
33
34 #define Glyph Glyph_
35 #define Font Font_
36 #define Draw XftDraw *
37 #define Colour XftColor
38 #define Colourmap Colormap
39 #define Rectangle XRectangle
40
41 #if   defined(__linux)
42  #include <pty.h>
43 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
44  #include <util.h>
45 #elif defined(__FreeBSD__) || defined(__DragonFly__)
46  #include <libutil.h>
47 #endif
48
49
50 /* XEMBED messages */
51 #define XEMBED_FOCUS_IN  4
52 #define XEMBED_FOCUS_OUT 5
53
54 /* Arbitrary sizes */
55 #define UTF_SIZ       4
56 #define ESC_BUF_SIZ   (128*UTF_SIZ)
57 #define ESC_ARG_SIZ   16
58 #define STR_BUF_SIZ   ESC_BUF_SIZ
59 #define STR_ARG_SIZ   ESC_ARG_SIZ
60 #define DRAW_BUF_SIZ  20*1024
61 #define XK_ANY_MOD    UINT_MAX
62 #define XK_NO_MOD     0
63 #define XK_SWITCH_MOD (1<<13)
64
65 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
66
67 /* macros */
68 #define SERRNO strerror(errno)
69 #define MIN(a, b)  ((a) < (b) ? (a) : (b))
70 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
71 #define LEN(a)     (sizeof(a) / sizeof(a[0]))
72 #define DEFAULT(a, b)     (a) = (a) ? (a) : (b)
73 #define BETWEEN(x, a, b)  ((a) <= (x) && (x) <= (b))
74 #define LIMIT(x, a, b)    (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
75 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
76 #define IS_SET(flag) ((term.mode & (flag)) != 0)
77 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
78
79 #define VT102ID "\033[?6c"
80
81 enum glyph_attribute {
82         ATTR_NULL      = 0,
83         ATTR_REVERSE   = 1,
84         ATTR_UNDERLINE = 2,
85         ATTR_BOLD      = 4,
86         ATTR_GFX       = 8,
87         ATTR_ITALIC    = 16,
88         ATTR_BLINK     = 32,
89         ATTR_WRAP      = 64,
90 };
91
92 enum cursor_movement {
93         CURSOR_SAVE,
94         CURSOR_LOAD
95 };
96
97 enum cursor_state {
98         CURSOR_DEFAULT  = 0,
99         CURSOR_WRAPNEXT = 1,
100         CURSOR_ORIGIN   = 2
101 };
102
103 enum term_mode {
104         MODE_WRAP        = 1,
105         MODE_INSERT      = 2,
106         MODE_APPKEYPAD   = 4,
107         MODE_ALTSCREEN   = 8,
108         MODE_CRLF        = 16,
109         MODE_MOUSEBTN    = 32,
110         MODE_MOUSEMOTION = 64,
111         MODE_REVERSE     = 128,
112         MODE_KBDLOCK     = 256,
113         MODE_HIDE        = 512,
114         MODE_ECHO        = 1024,
115         MODE_APPCURSOR   = 2048,
116         MODE_MOUSESGR    = 4096,
117         MODE_8BIT        = 8192,
118         MODE_BLINK       = 16384,
119         MODE_FBLINK      = 32768,
120         MODE_FOCUS       = 65536,
121         MODE_MOUSEX10    = 131072,
122         MODE_MOUSEMANY   = 262144,
123         MODE_MOUSE       = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
124                            |MODE_MOUSEMANY,
125 };
126
127 enum escape_state {
128         ESC_START      = 1,
129         ESC_CSI = 2,
130         ESC_STR = 4, /* DSC, OSC, PM, APC */
131         ESC_ALTCHARSET = 8,
132         ESC_STR_END    = 16, /* a final string was encountered */
133         ESC_TEST       = 32, /* Enter in test mode */
134 };
135
136 enum window_state {
137         WIN_VISIBLE = 1,
138         WIN_REDRAW  = 2,
139         WIN_FOCUSED = 4
140 };
141
142 enum selection_type {
143         SEL_REGULAR = 1,
144         SEL_RECTANGULAR = 2
145 };
146
147 enum selection_snap {
148         SNAP_WORD = 1,
149         SNAP_LINE = 2
150 };
151
152 /* bit macro */
153 #undef B0
154 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
155
156 typedef unsigned char uchar;
157 typedef unsigned int uint;
158 typedef unsigned long ulong;
159 typedef unsigned short ushort;
160
161 typedef struct {
162         char c[UTF_SIZ];     /* character code */
163         uchar mode;  /* attribute flags */
164         ushort fg;   /* foreground  */
165         ushort bg;   /* background  */
166 } Glyph;
167
168 typedef Glyph *Line;
169
170 typedef struct {
171         Glyph attr;      /* current char attributes */
172         int x;
173         int y;
174         char state;
175 } TCursor;
176
177 /* CSI Escape sequence structs */
178 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
179 typedef struct {
180         char buf[ESC_BUF_SIZ]; /* raw string */
181         int len;               /* raw string length */
182         char priv;
183         int arg[ESC_ARG_SIZ];
184         int narg;              /* nb of args */
185         char mode;
186 } CSIEscape;
187
188 /* STR Escape sequence structs */
189 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
190 typedef struct {
191         char type;           /* ESC type ... */
192         char buf[STR_BUF_SIZ]; /* raw string */
193         int len;               /* raw string length */
194         char *args[STR_ARG_SIZ];
195         int narg;             /* nb of args */
196 } STREscape;
197
198 /* Internal representation of the screen */
199 typedef struct {
200         int row;        /* nb row */
201         int col;        /* nb col */
202         Line *line;     /* screen */
203         Line *alt;      /* alternate screen */
204         bool *dirty;    /* dirtyness of lines */
205         TCursor c;      /* cursor */
206         int top;        /* top    scroll limit */
207         int bot;        /* bottom scroll limit */
208         int mode;       /* terminal mode flags */
209         int esc;        /* escape state flags */
210         bool numlock;   /* lock numbers in keyboard */
211         bool *tabs;
212 } Term;
213
214 /* Purely graphic info */
215 typedef struct {
216         Display *dpy;
217         Colourmap cmap;
218         Window win;
219         Drawable buf;
220         Atom xembed, wmdeletewin;
221         XIM xim;
222         XIC xic;
223         Draw draw;
224         Visual *vis;
225         XSetWindowAttributes attrs;
226         int scr;
227         bool isfixed; /* is fixed geometry? */
228         int fx, fy, fw, fh; /* fixed geometry */
229         int tw, th; /* tty width and height */
230         int w, h; /* window width and height */
231         int ch; /* char height */
232         int cw; /* char width  */
233         char state; /* focus, redraw, visible */
234 } XWindow;
235
236 typedef struct {
237         int b;
238         uint mask;
239         char s[ESC_BUF_SIZ];
240 } Mousekey;
241
242 typedef struct {
243         KeySym k;
244         uint mask;
245         char s[ESC_BUF_SIZ];
246         /* three valued logic variables: 0 indifferent, 1 on, -1 off */
247         signed char appkey;             /* application keypad */
248         signed char appcursor;          /* application cursor */
249         signed char crlf;               /* crlf mode          */
250 } Key;
251
252 typedef struct {
253         int mode;
254         int type;
255         int snap;
256         /*
257          * Selection variables:
258          * nb – normalized coordinates of the beginning of the selection
259          * ne – normalized coordinates of the end of the selection
260          * ob – original coordinates of the beginning of the selection
261          * oe – original coordinates of the end of the selection
262          */
263         struct {
264                 int x, y;
265         } nb, ne, ob, oe;
266
267         char *clip;
268         Atom xtarget;
269         bool alt;
270         struct timeval tclick1;
271         struct timeval tclick2;
272 } Selection;
273
274 typedef union {
275         int i;
276         unsigned int ui;
277         float f;
278         const void *v;
279 } Arg;
280
281 typedef struct {
282         unsigned int mod;
283         KeySym keysym;
284         void (*func)(const Arg *);
285         const Arg arg;
286 } Shortcut;
287
288 /* function definitions used in config.h */
289 static void clippaste(const Arg *);
290 static void numlock(const Arg *);
291 static void selpaste(const Arg *);
292 static void xzoom(const Arg *);
293
294 /* Config.h for applying patches and the configuration. */
295 #include "config.h"
296
297 /* Font structure */
298 typedef struct {
299         int height;
300         int width;
301         int ascent;
302         int descent;
303         short lbearing;
304         short rbearing;
305         XftFont *match;
306         FcFontSet *set;
307         FcPattern *pattern;
308 } Font;
309
310 /* Drawing Context */
311 typedef struct {
312         Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
313         Font font, bfont, ifont, ibfont;
314         GC gc;
315 } DC;
316
317 static void die(const char *, ...);
318 static void draw(void);
319 static void redraw(int);
320 static void drawregion(int, int, int, int);
321 static void execsh(void);
322 static void sigchld(int);
323 static void run(void);
324
325 static void csidump(void);
326 static void csihandle(void);
327 static void csiparse(void);
328 static void csireset(void);
329 static void strdump(void);
330 static void strhandle(void);
331 static void strparse(void);
332 static void strreset(void);
333
334 static int tattrset(int);
335 static void tclearregion(int, int, int, int);
336 static void tcursor(int);
337 static void tdeletechar(int);
338 static void tdeleteline(int);
339 static void tinsertblank(int);
340 static void tinsertblankline(int);
341 static void tmoveto(int, int);
342 static void tmoveato(int x, int y);
343 static void tnew(int, int);
344 static void tnewline(int);
345 static void tputtab(bool);
346 static void tputc(char *, int);
347 static void treset(void);
348 static int tresize(int, int);
349 static void tscrollup(int, int);
350 static void tscrolldown(int, int);
351 static void tsetattr(int*, int);
352 static void tsetchar(char *, Glyph *, int, int);
353 static void tsetscroll(int, int);
354 static void tswapscreen(void);
355 static void tsetdirt(int, int);
356 static void tsetdirtattr(int);
357 static void tsetmode(bool, bool, int *, int);
358 static void tfulldirt(void);
359 static void techo(char *, int);
360
361 static inline bool match(uint, uint);
362 static void ttynew(void);
363 static void ttyread(void);
364 static void ttyresize(void);
365 static void ttywrite(const char *, size_t);
366
367 static void xdraws(char *, Glyph, int, int, int, int);
368 static void xhints(void);
369 static void xclear(int, int, int, int);
370 static void xdrawcursor(void);
371 static void xinit(void);
372 static void xloadcols(void);
373 static int xsetcolorname(int, const char *);
374 static int xloadfont(Font *, FcPattern *);
375 static void xloadfonts(char *, int);
376 static int xloadfontset(Font *);
377 static void xsettitle(char *);
378 static void xresettitle(void);
379 static void xsetpointermotion(int);
380 static void xseturgency(int);
381 static void xsetsel(char*);
382 static void xtermclear(int, int, int, int);
383 static void xunloadfont(Font *f);
384 static void xunloadfonts(void);
385 static void xresize(int, int);
386
387 static void expose(XEvent *);
388 static void visibility(XEvent *);
389 static void unmap(XEvent *);
390 static char *kmap(KeySym, uint);
391 static void kpress(XEvent *);
392 static void cmessage(XEvent *);
393 static void cresize(int, int);
394 static void resize(XEvent *);
395 static void focus(XEvent *);
396 static void brelease(XEvent *);
397 static void bpress(XEvent *);
398 static void bmotion(XEvent *);
399 static void selnotify(XEvent *);
400 static void selclear(XEvent *);
401 static void selrequest(XEvent *);
402
403 static void selinit(void);
404 static void selsort(void);
405 static inline bool selected(int, int);
406 static void selcopy(void);
407 static void selscroll(int, int);
408 static void selsnap(int, int *, int *, int);
409
410 static int utf8decode(char *, long *);
411 static int utf8encode(long *, char *);
412 static int utf8size(char *);
413 static int isfullutf8(char *, int);
414
415 static ssize_t xwrite(int, char *, size_t);
416 static void *xmalloc(size_t);
417 static void *xrealloc(void *, size_t);
418 static void *xcalloc(size_t, size_t);
419
420 static void (*handler[LASTEvent])(XEvent *) = {
421         [KeyPress] = kpress,
422         [ClientMessage] = cmessage,
423         [ConfigureNotify] = resize,
424         [VisibilityNotify] = visibility,
425         [UnmapNotify] = unmap,
426         [Expose] = expose,
427         [FocusIn] = focus,
428         [FocusOut] = focus,
429         [MotionNotify] = bmotion,
430         [ButtonPress] = bpress,
431         [ButtonRelease] = brelease,
432         [SelectionClear] = selclear,
433         [SelectionNotify] = selnotify,
434         [SelectionRequest] = selrequest,
435 };
436
437 /* Globals */
438 static DC dc;
439 static XWindow xw;
440 static Term term;
441 static CSIEscape csiescseq;
442 static STREscape strescseq;
443 static int cmdfd;
444 static pid_t pid;
445 static Selection sel;
446 static int iofd = -1;
447 static char **opt_cmd = NULL;
448 static char *opt_io = NULL;
449 static char *opt_title = NULL;
450 static char *opt_embed = NULL;
451 static char *opt_class = NULL;
452 static char *opt_font = NULL;
453 static int oldbutton = 3; /* button event on startup: 3 = release */
454
455 static char *usedfont = NULL;
456 static int usedfontsize = 0;
457
458 /* Font Ring Cache */
459 enum {
460         FRC_NORMAL,
461         FRC_ITALIC,
462         FRC_BOLD,
463         FRC_ITALICBOLD
464 };
465
466 typedef struct {
467         XftFont *font;
468         long c;
469         int flags;
470 } Fontcache;
471
472 /*
473  * Fontcache is a ring buffer, with frccur as current position and frclen as
474  * the current length of used elements.
475  */
476
477 static Fontcache frc[1024];
478 static int frccur = -1, frclen = 0;
479
480 ssize_t
481 xwrite(int fd, char *s, size_t len) {
482         size_t aux = len;
483
484         while(len > 0) {
485                 ssize_t r = write(fd, s, len);
486                 if(r < 0)
487                         return r;
488                 len -= r;
489                 s += r;
490         }
491         return aux;
492 }
493
494 void *
495 xmalloc(size_t len) {
496         void *p = malloc(len);
497
498         if(!p)
499                 die("Out of memory\n");
500
501         return p;
502 }
503
504 void *
505 xrealloc(void *p, size_t len) {
506         if((p = realloc(p, len)) == NULL)
507                 die("Out of memory\n");
508
509         return p;
510 }
511
512 void *
513 xcalloc(size_t nmemb, size_t size) {
514         void *p = calloc(nmemb, size);
515
516         if(!p)
517                 die("Out of memory\n");
518
519         return p;
520 }
521
522 int
523 utf8decode(char *s, long *u) {
524         uchar c;
525         int i, n, rtn;
526
527         rtn = 1;
528         c = *s;
529         if(~c & B7) { /* 0xxxxxxx */
530                 *u = c;
531                 return rtn;
532         } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
533                 *u = c&(B4|B3|B2|B1|B0);
534                 n = 1;
535         } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
536                 *u = c&(B3|B2|B1|B0);
537                 n = 2;
538         } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
539                 *u = c & (B2|B1|B0);
540                 n = 3;
541         } else {
542                 goto invalid;
543         }
544
545         for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
546                 c = *s;
547                 if((c & (B7|B6)) != B7) /* 10xxxxxx */
548                         goto invalid;
549                 *u <<= 6;
550                 *u |= c & (B5|B4|B3|B2|B1|B0);
551         }
552
553         if((n == 1 && *u < 0x80) ||
554            (n == 2 && *u < 0x800) ||
555            (n == 3 && *u < 0x10000) ||
556            (*u >= 0xD800 && *u <= 0xDFFF)) {
557                 goto invalid;
558         }
559
560         return rtn;
561 invalid:
562         *u = 0xFFFD;
563
564         return rtn;
565 }
566
567 int
568 utf8encode(long *u, char *s) {
569         uchar *sp;
570         ulong uc;
571         int i, n;
572
573         sp = (uchar *)s;
574         uc = *u;
575         if(uc < 0x80) {
576                 *sp = uc; /* 0xxxxxxx */
577                 return 1;
578         } else if(*u < 0x800) {
579                 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
580                 n = 1;
581         } else if(uc < 0x10000) {
582                 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
583                 n = 2;
584         } else if(uc <= 0x10FFFF) {
585                 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
586                 n = 3;
587         } else {
588                 goto invalid;
589         }
590
591         for(i=n,++sp; i>0; --i,++sp)
592                 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
593
594         return n+1;
595 invalid:
596         /* U+FFFD */
597         *s++ = '\xEF';
598         *s++ = '\xBF';
599         *s = '\xBD';
600
601         return 3;
602 }
603
604 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
605    UTF-8 otherwise return 0 */
606 int
607 isfullutf8(char *s, int b) {
608         uchar *c1, *c2, *c3;
609
610         c1 = (uchar *)s;
611         c2 = (uchar *)++s;
612         c3 = (uchar *)++s;
613         if(b < 1) {
614                 return 0;
615         } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
616                 return 0;
617         } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
618             ((b == 1) ||
619             ((b == 2) && (*c2&(B7|B6)) == B7))) {
620                 return 0;
621         } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
622             ((b == 1) ||
623             ((b == 2) && (*c2&(B7|B6)) == B7) ||
624             ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
625                 return 0;
626         } else {
627                 return 1;
628         }
629 }
630
631 int
632 utf8size(char *s) {
633         uchar c = *s;
634
635         if(~c&B7) {
636                 return 1;
637         } else if((c&(B7|B6|B5)) == (B7|B6)) {
638                 return 2;
639         } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
640                 return 3;
641         } else {
642                 return 4;
643         }
644 }
645
646 static void
647 selinit(void) {
648         memset(&sel.tclick1, 0, sizeof(sel.tclick1));
649         memset(&sel.tclick2, 0, sizeof(sel.tclick2));
650         sel.mode = 0;
651         sel.ob.x = -1;
652         sel.clip = NULL;
653         sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
654         if(sel.xtarget == None)
655                 sel.xtarget = XA_STRING;
656 }
657
658 static int
659 x2col(int x) {
660         x -= borderpx;
661         x /= xw.cw;
662
663         return LIMIT(x, 0, term.col-1);
664 }
665
666 static int
667 y2row(int y) {
668         y -= borderpx;
669         y /= xw.ch;
670
671         return LIMIT(y, 0, term.row-1);
672 }
673
674 static void
675 selsort(void) {
676         if(sel.ob.y == sel.oe.y) {
677                 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
678                 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
679         } else {
680                 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
681                 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
682         }
683         sel.nb.y = MIN(sel.ob.y, sel.oe.y);
684         sel.ne.y = MAX(sel.ob.y, sel.oe.y);
685 }
686
687 static inline bool
688 selected(int x, int y) {
689         if(sel.ne.y == y && sel.nb.y == y)
690                 return BETWEEN(x, sel.nb.x, sel.ne.x);
691
692         if(sel.type == SEL_RECTANGULAR) {
693                 return ((sel.nb.y <= y && y <= sel.ne.y)
694                         && (sel.nb.x <= x && x <= sel.ne.x));
695         }
696
697         return ((sel.nb.y < y && y < sel.ne.y)
698                 || (y == sel.ne.y && x <= sel.ne.x))
699                 || (y == sel.nb.y && x >= sel.nb.x
700                         && (x <= sel.ne.x || sel.nb.y != sel.ne.y));
701 }
702
703 void
704 selsnap(int mode, int *x, int *y, int direction) {
705         int i;
706
707         switch(mode) {
708         case SNAP_WORD:
709                 /*
710                  * Snap around if the word wraps around at the end or
711                  * beginning of a line.
712                  */
713                 for(;;) {
714                         if(direction < 0 && *x <= 0) {
715                                 if(*y > 0 && term.line[*y - 1][term.col-1].mode
716                                                 & ATTR_WRAP) {
717                                         *y -= 1;
718                                         *x = term.col-1;
719                                 } else {
720                                         break;
721                                 }
722                         }
723                         if(direction > 0 && *x >= term.col-1) {
724                                 if(*y < term.row-1 && term.line[*y][*x].mode
725                                                 & ATTR_WRAP) {
726                                         *y += 1;
727                                         *x = 0;
728                                 } else {
729                                         break;
730                                 }
731                         }
732
733                         if(strchr(worddelimiters,
734                                         term.line[*y][*x + direction].c[0])) {
735                                 break;
736                         }
737
738                         *x += direction;
739                 }
740                 break;
741         case SNAP_LINE:
742                 /*
743                  * Snap around if the the previous line or the current one
744                  * has set ATTR_WRAP at its end. Then the whole next or
745                  * previous line will be selected.
746                  */
747                 *x = (direction < 0) ? 0 : term.col - 1;
748                 if(direction < 0 && *y > 0) {
749                         for(; *y > 0; *y += direction) {
750                                 if(!(term.line[*y-1][term.col-1].mode
751                                                 & ATTR_WRAP)) {
752                                         break;
753                                 }
754                         }
755                 } else if(direction > 0 && *y < term.row-1) {
756                         for(; *y < term.row; *y += direction) {
757                                 if(!(term.line[*y][term.col-1].mode
758                                                 & ATTR_WRAP)) {
759                                         break;
760                                 }
761                         }
762                 }
763                 break;
764         default:
765                 /*
766                  * Select the whole line when the end of line is reached.
767                  */
768                 if(direction > 0) {
769                         i = term.col;
770                         while(--i > 0 && term.line[*y][i].c[0] == ' ')
771                                 /* nothing */;
772                         if(i > 0 && i < *x)
773                                 *x = term.col - 1;
774                 }
775                 break;
776         }
777 }
778
779 void
780 getbuttoninfo(XEvent *e) {
781         int type;
782         uint state = e->xbutton.state &~Button1Mask;
783
784         sel.alt = IS_SET(MODE_ALTSCREEN);
785
786         sel.oe.x = x2col(e->xbutton.x);
787         sel.oe.y = y2row(e->xbutton.y);
788
789         if(sel.ob.y < sel.oe.y
790                         || (sel.ob.y == sel.oe.y && sel.ob.x < sel.oe.x)) {
791                 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
792                 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
793         } else {
794                 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, -1);
795                 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, +1);
796         }
797         selsort();
798
799         sel.type = SEL_REGULAR;
800         for(type = 1; type < LEN(selmasks); ++type) {
801                 if(match(selmasks[type], state)) {
802                         sel.type = type;
803                         break;
804                 }
805         }
806 }
807
808 void
809 mousereport(XEvent *e) {
810         int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
811             button = e->xbutton.button, state = e->xbutton.state,
812             len;
813         char buf[40];
814         static int ox, oy;
815
816         /* from urxvt */
817         if(e->xbutton.type == MotionNotify) {
818                 if(x == ox && y == oy)
819                         return;
820                 if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
821                         return;
822                 /* MOUSE_MOTION: no reporting if no button is pressed */
823                 if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
824                         return;
825
826                 button = oldbutton + 32;
827                 ox = x;
828                 oy = y;
829         } else if(!IS_SET(MODE_MOUSESGR)
830                         && (e->xbutton.type == ButtonRelease
831                                 || button == AnyButton)) {
832                 button = 3;
833         } else {
834                 button -= Button1;
835                 if(button >= 3)
836                         button += 64 - 3;
837                 if(e->xbutton.type == ButtonPress) {
838                         oldbutton = button;
839                         ox = x;
840                         oy = y;
841                 }
842         }
843
844         if(!IS_SET(MODE_MOUSEX10)) {
845                 button += (state & ShiftMask   ? 4  : 0)
846                         + (state & Mod4Mask    ? 8  : 0)
847                         + (state & ControlMask ? 16 : 0);
848         }
849
850         len = 0;
851         if(IS_SET(MODE_MOUSESGR)) {
852                 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
853                                 button, x+1, y+1,
854                                 e->xbutton.type == ButtonRelease ? 'm' : 'M');
855         } else if(x < 223 && y < 223) {
856                 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
857                                 IS_SET(MODE_MOUSEX10)? button-1 : 32+button,
858                                 32+x+1, 32+y+1);
859         } else {
860                 return;
861         }
862
863         ttywrite(buf, len);
864 }
865
866 void
867 bpress(XEvent *e) {
868         struct timeval now;
869         Mousekey *mk;
870
871         if(IS_SET(MODE_MOUSE)) {
872                 mousereport(e);
873                 return;
874         }
875
876         for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
877                 if(e->xbutton.button == mk->b
878                                 && match(mk->mask, e->xbutton.state)) {
879                         ttywrite(mk->s, strlen(mk->s));
880                         if(IS_SET(MODE_ECHO))
881                                 techo(mk->s, strlen(mk->s));
882                         return;
883                 }
884         }
885
886         if(e->xbutton.button == Button1) {
887                 gettimeofday(&now, NULL);
888
889                 /* Clear previous selection, logically and visually. */
890                 if(sel.ob.x != -1) {
891                         sel.ob.x = -1;
892                         tsetdirt(sel.nb.y, sel.ne.y);
893                         draw();
894                 }
895                 sel.mode = 1;
896                 sel.type = SEL_REGULAR;
897                 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
898                 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
899
900                 /*
901                  * If the user clicks below predefined timeouts specific
902                  * snapping behaviour is exposed.
903                  */
904                 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
905                         sel.snap = SNAP_LINE;
906                 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
907                         sel.snap = SNAP_WORD;
908                 } else {
909                         sel.snap = 0;
910                 }
911                 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
912                 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
913                 selsort();
914
915                 /*
916                  * Draw selection, unless it's regular and we don't want to
917                  * make clicks visible
918                  */
919                 if(sel.snap != 0) {
920                         sel.mode++;
921                         tsetdirt(sel.nb.y, sel.ne.y);
922                         draw();
923                 }
924                 sel.tclick2 = sel.tclick1;
925                 sel.tclick1 = now;
926         }
927 }
928
929 void
930 selcopy(void) {
931         char *str, *ptr;
932         int x, y, bufsize, size, i, ex;
933         Glyph *gp, *last;
934
935         if(sel.ob.x == -1) {
936                 str = NULL;
937         } else {
938                 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
939                 ptr = str = xmalloc(bufsize);
940
941                 /* append every set & selected glyph to the selection */
942                 for(y = sel.nb.y; y < sel.ne.y + 1; y++) {
943                         gp = &term.line[y][0];
944                         last = gp + term.col;
945
946                         while(--last >= gp && !(selected(last - gp, y) && \
947                                                 strcmp(last->c, " ") != 0))
948                                 /* nothing */;
949
950                         for(x = 0; gp <= last; x++, ++gp) {
951                                 if(!selected(x, y))
952                                         continue;
953
954                                 size = utf8size(gp->c);
955                                 memcpy(ptr, gp->c, size);
956                                 ptr += size;
957                         }
958
959                         /*
960                          * Copy and pasting of line endings is inconsistent
961                          * in the inconsistent terminal and GUI world.
962                          * The best solution seems like to produce '\n' when
963                          * something is copied from st and convert '\n' to
964                          * '\r', when something to be pasted is received by
965                          * st.
966                          * FIXME: Fix the computer world.
967                          */
968                         if(y < sel.ne.y && !((gp-1)->mode & ATTR_WRAP))
969                                 *ptr++ = '\n';
970
971                         /*
972                          * If the last selected line expands in the selection
973                          * after the visible text '\n' is appended.
974                          */
975                         if(y == sel.ne.y) {
976                                 i = term.col;
977                                 while(--i > 0 && term.line[y][i].c[0] == ' ')
978                                         /* nothing */;
979                                 ex = sel.ne.x;
980                                 if(sel.nb.y == sel.ne.y && sel.ne.x < sel.nb.x)
981                                         ex = sel.nb.x;
982                                 if(i < ex)
983                                         *ptr++ = '\n';
984                         }
985                 }
986                 *ptr = 0;
987         }
988         xsetsel(str);
989 }
990
991 void
992 selnotify(XEvent *e) {
993         ulong nitems, ofs, rem;
994         int format;
995         uchar *data, *last, *repl;
996         Atom type;
997
998         ofs = 0;
999         do {
1000                 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
1001                                         False, AnyPropertyType, &type, &format,
1002                                         &nitems, &rem, &data)) {
1003                         fprintf(stderr, "Clipboard allocation failed\n");
1004                         return;
1005                 }
1006
1007                 /*
1008                  * As seen in selcopy:
1009                  * Line endings are inconsistent in the terminal and GUI world
1010                  * copy and pasting. When receiving some selection data,
1011                  * replace all '\n' with '\r'.
1012                  * FIXME: Fix the computer world.
1013                  */
1014                 repl = data;
1015                 last = data + nitems * format / 8;
1016                 while((repl = memchr(repl, '\n', last - repl))) {
1017                         *repl++ = '\r';
1018                 }
1019
1020                 ttywrite((const char *)data, nitems * format / 8);
1021                 XFree(data);
1022                 /* number of 32-bit chunks returned */
1023                 ofs += nitems * format / 32;
1024         } while(rem > 0);
1025 }
1026
1027 void
1028 selpaste(const Arg *dummy) {
1029         XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1030                         xw.win, CurrentTime);
1031 }
1032
1033 void
1034 clippaste(const Arg *dummy) {
1035         Atom clipboard;
1036
1037         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1038         XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
1039                         xw.win, CurrentTime);
1040 }
1041
1042 void
1043 selclear(XEvent *e) {
1044         if(sel.ob.x == -1)
1045                 return;
1046         sel.ob.x = -1;
1047         tsetdirt(sel.nb.y, sel.ne.y);
1048 }
1049
1050 void
1051 selrequest(XEvent *e) {
1052         XSelectionRequestEvent *xsre;
1053         XSelectionEvent xev;
1054         Atom xa_targets, string;
1055
1056         xsre = (XSelectionRequestEvent *) e;
1057         xev.type = SelectionNotify;
1058         xev.requestor = xsre->requestor;
1059         xev.selection = xsre->selection;
1060         xev.target = xsre->target;
1061         xev.time = xsre->time;
1062         /* reject */
1063         xev.property = None;
1064
1065         xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1066         if(xsre->target == xa_targets) {
1067                 /* respond with the supported type */
1068                 string = sel.xtarget;
1069                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1070                                 XA_ATOM, 32, PropModeReplace,
1071                                 (uchar *) &string, 1);
1072                 xev.property = xsre->property;
1073         } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
1074                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1075                                 xsre->target, 8, PropModeReplace,
1076                                 (uchar *) sel.clip, strlen(sel.clip));
1077                 xev.property = xsre->property;
1078         }
1079
1080         /* all done, send a notification to the listener */
1081         if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1082                 fprintf(stderr, "Error sending SelectionNotify event\n");
1083 }
1084
1085 void
1086 xsetsel(char *str) {
1087         /* register the selection for both the clipboard and the primary */
1088         Atom clipboard;
1089
1090         free(sel.clip);
1091         sel.clip = str;
1092
1093         XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1094
1095         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1096         XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1097 }
1098
1099 void
1100 brelease(XEvent *e) {
1101         if(IS_SET(MODE_MOUSE)) {
1102                 mousereport(e);
1103                 return;
1104         }
1105
1106         if(e->xbutton.button == Button2) {
1107                 selpaste(NULL);
1108         } else if(e->xbutton.button == Button1) {
1109                 if(sel.mode < 2) {
1110                         sel.ob.x = -1;
1111                 } else {
1112                         getbuttoninfo(e);
1113                         selcopy();
1114                 }
1115                 sel.mode = 0;
1116                 tsetdirt(sel.nb.y, sel.ne.y);
1117         }
1118 }
1119
1120 void
1121 bmotion(XEvent *e) {
1122         int oldey, oldex, oldsby, oldsey;
1123
1124         if(IS_SET(MODE_MOUSE)) {
1125                 mousereport(e);
1126                 return;
1127         }
1128
1129         if(!sel.mode)
1130                 return;
1131
1132         sel.mode++;
1133         oldey = sel.oe.y;
1134         oldex = sel.oe.x;
1135         oldsby = sel.nb.y;
1136         oldsey = sel.ne.y;
1137         getbuttoninfo(e);
1138
1139         if(oldey != sel.oe.y || oldex != sel.oe.x)
1140                 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1141 }
1142
1143 void
1144 die(const char *errstr, ...) {
1145         va_list ap;
1146
1147         va_start(ap, errstr);
1148         vfprintf(stderr, errstr, ap);
1149         va_end(ap);
1150         exit(EXIT_FAILURE);
1151 }
1152
1153 void
1154 execsh(void) {
1155         char **args;
1156         char *envshell = getenv("SHELL");
1157         const struct passwd *pass = getpwuid(getuid());
1158         char buf[sizeof(long) * 8 + 1];
1159
1160         unsetenv("COLUMNS");
1161         unsetenv("LINES");
1162         unsetenv("TERMCAP");
1163
1164         if(pass) {
1165                 setenv("LOGNAME", pass->pw_name, 1);
1166                 setenv("USER", pass->pw_name, 1);
1167                 setenv("SHELL", pass->pw_shell, 0);
1168                 setenv("HOME", pass->pw_dir, 0);
1169         }
1170
1171         snprintf(buf, sizeof(buf), "%lu", xw.win);
1172         setenv("WINDOWID", buf, 1);
1173
1174         signal(SIGCHLD, SIG_DFL);
1175         signal(SIGHUP, SIG_DFL);
1176         signal(SIGINT, SIG_DFL);
1177         signal(SIGQUIT, SIG_DFL);
1178         signal(SIGTERM, SIG_DFL);
1179         signal(SIGALRM, SIG_DFL);
1180
1181         DEFAULT(envshell, shell);
1182         setenv("TERM", termname, 1);
1183         args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1184         execvp(args[0], args);
1185         exit(EXIT_FAILURE);
1186 }
1187
1188 void
1189 sigchld(int a) {
1190         int stat = 0;
1191
1192         if(waitpid(pid, &stat, 0) < 0)
1193                 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1194
1195         if(WIFEXITED(stat)) {
1196                 exit(WEXITSTATUS(stat));
1197         } else {
1198                 exit(EXIT_FAILURE);
1199         }
1200 }
1201
1202 void
1203 ttynew(void) {
1204         int m, s;
1205         struct winsize w = {term.row, term.col, 0, 0};
1206
1207         /* seems to work fine on linux, openbsd and freebsd */
1208         if(openpty(&m, &s, NULL, NULL, &w) < 0)
1209                 die("openpty failed: %s\n", SERRNO);
1210
1211         switch(pid = fork()) {
1212         case -1:
1213                 die("fork failed\n");
1214                 break;
1215         case 0:
1216                 setsid(); /* create a new process group */
1217                 dup2(s, STDIN_FILENO);
1218                 dup2(s, STDOUT_FILENO);
1219                 dup2(s, STDERR_FILENO);
1220                 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1221                         die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1222                 close(s);
1223                 close(m);
1224                 execsh();
1225                 break;
1226         default:
1227                 close(s);
1228                 cmdfd = m;
1229                 signal(SIGCHLD, sigchld);
1230                 if(opt_io) {
1231                         iofd = (!strcmp(opt_io, "-")) ?
1232                                   STDOUT_FILENO :
1233                                   open(opt_io, O_WRONLY | O_CREAT, 0666);
1234                         if(iofd < 0) {
1235                                 fprintf(stderr, "Error opening %s:%s\n",
1236                                         opt_io, strerror(errno));
1237                         }
1238                 }
1239         }
1240 }
1241
1242 void
1243 dump(char c) {
1244         static int col;
1245
1246         fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1247         if(++col % 10 == 0)
1248                 fprintf(stderr, "\n");
1249 }
1250
1251 void
1252 ttyread(void) {
1253         static char buf[BUFSIZ];
1254         static int buflen = 0;
1255         char *ptr;
1256         char s[UTF_SIZ];
1257         int charsize; /* size of utf8 char in bytes */
1258         long utf8c;
1259         int ret;
1260
1261         /* append read bytes to unprocessed bytes */
1262         if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1263                 die("Couldn't read from shell: %s\n", SERRNO);
1264
1265         /* process every complete utf8 char */
1266         buflen += ret;
1267         ptr = buf;
1268         while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1269                 charsize = utf8decode(ptr, &utf8c);
1270                 utf8encode(&utf8c, s);
1271                 tputc(s, charsize);
1272                 ptr += charsize;
1273                 buflen -= charsize;
1274         }
1275
1276         /* keep any uncomplete utf8 char for the next call */
1277         memmove(buf, ptr, buflen);
1278 }
1279
1280 void
1281 ttywrite(const char *s, size_t n) {
1282         if(write(cmdfd, s, n) == -1)
1283                 die("write error on tty: %s\n", SERRNO);
1284 }
1285
1286 void
1287 ttyresize(void) {
1288         struct winsize w;
1289
1290         w.ws_row = term.row;
1291         w.ws_col = term.col;
1292         w.ws_xpixel = xw.tw;
1293         w.ws_ypixel = xw.th;
1294         if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1295                 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1296 }
1297
1298 int
1299 tattrset(int attr) {
1300         int i, j;
1301
1302         for(i = 0; i < term.row-1; i++) {
1303                 for(j = 0; j < term.col-1; j++) {
1304                         if(term.line[i][j].mode & attr)
1305                                 return 1;
1306                 }
1307         }
1308
1309         return 0;
1310 }
1311
1312 void
1313 tsetdirt(int top, int bot) {
1314         int i;
1315
1316         LIMIT(top, 0, term.row-1);
1317         LIMIT(bot, 0, term.row-1);
1318
1319         for(i = top; i <= bot; i++)
1320                 term.dirty[i] = 1;
1321 }
1322
1323 void
1324 tsetdirtattr(int attr) {
1325         int i, j;
1326
1327         for(i = 0; i < term.row-1; i++) {
1328                 for(j = 0; j < term.col-1; j++) {
1329                         if(term.line[i][j].mode & attr) {
1330                                 tsetdirt(i, i);
1331                                 break;
1332                         }
1333                 }
1334         }
1335 }
1336
1337 void
1338 tfulldirt(void) {
1339         tsetdirt(0, term.row-1);
1340 }
1341
1342 void
1343 tcursor(int mode) {
1344         static TCursor c;
1345
1346         if(mode == CURSOR_SAVE) {
1347                 c = term.c;
1348         } else if(mode == CURSOR_LOAD) {
1349                 term.c = c;
1350                 tmoveto(c.x, c.y);
1351         }
1352 }
1353
1354 void
1355 treset(void) {
1356         uint i;
1357
1358         term.c = (TCursor){{
1359                 .mode = ATTR_NULL,
1360                 .fg = defaultfg,
1361                 .bg = defaultbg
1362         }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1363
1364         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1365         for(i = tabspaces; i < term.col; i += tabspaces)
1366                 term.tabs[i] = 1;
1367         term.top = 0;
1368         term.bot = term.row - 1;
1369         term.mode = MODE_WRAP;
1370
1371         tclearregion(0, 0, term.col-1, term.row-1);
1372         tmoveto(0, 0);
1373         tcursor(CURSOR_SAVE);
1374 }
1375
1376 void
1377 tnew(int col, int row) {
1378         memset(&term, 0, sizeof(Term));
1379         tresize(col, row);
1380         term.numlock = 1;
1381
1382         treset();
1383 }
1384
1385 void
1386 tswapscreen(void) {
1387         Line *tmp = term.line;
1388
1389         term.line = term.alt;
1390         term.alt = tmp;
1391         term.mode ^= MODE_ALTSCREEN;
1392         tfulldirt();
1393 }
1394
1395 void
1396 tscrolldown(int orig, int n) {
1397         int i;
1398         Line temp;
1399
1400         LIMIT(n, 0, term.bot-orig+1);
1401
1402         tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1403
1404         for(i = term.bot; i >= orig+n; i--) {
1405                 temp = term.line[i];
1406                 term.line[i] = term.line[i-n];
1407                 term.line[i-n] = temp;
1408
1409                 term.dirty[i] = 1;
1410                 term.dirty[i-n] = 1;
1411         }
1412
1413         selscroll(orig, n);
1414 }
1415
1416 void
1417 tscrollup(int orig, int n) {
1418         int i;
1419         Line temp;
1420         LIMIT(n, 0, term.bot-orig+1);
1421
1422         tclearregion(0, orig, term.col-1, orig+n-1);
1423
1424         for(i = orig; i <= term.bot-n; i++) {
1425                  temp = term.line[i];
1426                  term.line[i] = term.line[i+n];
1427                  term.line[i+n] = temp;
1428
1429                  term.dirty[i] = 1;
1430                  term.dirty[i+n] = 1;
1431         }
1432
1433         selscroll(orig, -n);
1434 }
1435
1436 void
1437 selscroll(int orig, int n) {
1438         if(sel.ob.x == -1)
1439                 return;
1440
1441         if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1442                 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1443                         sel.ob.x = -1;
1444                         return;
1445                 }
1446                 if(sel.type == SEL_RECTANGULAR) {
1447                         if(sel.ob.y < term.top)
1448                                 sel.ob.y = term.top;
1449                         if(sel.oe.y > term.bot)
1450                                 sel.oe.y = term.bot;
1451                 } else {
1452                         if(sel.ob.y < term.top) {
1453                                 sel.ob.y = term.top;
1454                                 sel.ob.x = 0;
1455                         }
1456                         if(sel.oe.y > term.bot) {
1457                                 sel.oe.y = term.bot;
1458                                 sel.oe.x = term.col;
1459                         }
1460                 }
1461                 selsort();
1462         }
1463 }
1464
1465 void
1466 tnewline(int first_col) {
1467         int y = term.c.y;
1468
1469         if(y == term.bot) {
1470                 tscrollup(term.top, 1);
1471         } else {
1472                 y++;
1473         }
1474         tmoveto(first_col ? 0 : term.c.x, y);
1475 }
1476
1477 void
1478 csiparse(void) {
1479         char *p = csiescseq.buf, *np;
1480         long int v;
1481
1482         csiescseq.narg = 0;
1483         if(*p == '?') {
1484                 csiescseq.priv = 1;
1485                 p++;
1486         }
1487
1488         csiescseq.buf[csiescseq.len] = '\0';
1489         while(p < csiescseq.buf+csiescseq.len) {
1490                 np = NULL;
1491                 v = strtol(p, &np, 10);
1492                 if(np == p)
1493                         v = 0;
1494                 if(v == LONG_MAX || v == LONG_MIN)
1495                         v = -1;
1496                 csiescseq.arg[csiescseq.narg++] = v;
1497                 p = np;
1498                 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1499                         break;
1500                 p++;
1501         }
1502         csiescseq.mode = *p;
1503 }
1504
1505 /* for absolute user moves, when decom is set */
1506 void
1507 tmoveato(int x, int y) {
1508         tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1509 }
1510
1511 void
1512 tmoveto(int x, int y) {
1513         int miny, maxy;
1514
1515         if(term.c.state & CURSOR_ORIGIN) {
1516                 miny = term.top;
1517                 maxy = term.bot;
1518         } else {
1519                 miny = 0;
1520                 maxy = term.row - 1;
1521         }
1522         LIMIT(x, 0, term.col-1);
1523         LIMIT(y, miny, maxy);
1524         term.c.state &= ~CURSOR_WRAPNEXT;
1525         term.c.x = x;
1526         term.c.y = y;
1527 }
1528
1529 void
1530 tsetchar(char *c, Glyph *attr, int x, int y) {
1531         static char *vt100_0[62] = { /* 0x41 - 0x7e */
1532                 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1533                 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1534                 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1535                 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1536                 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1537                 "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1538                 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1539                 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1540         };
1541
1542         /*
1543          * The table is proudly stolen from rxvt.
1544          */
1545         if(attr->mode & ATTR_GFX) {
1546                 if(c[0] >= 0x41 && c[0] <= 0x7e
1547                                 && vt100_0[c[0] - 0x41]) {
1548                         c = vt100_0[c[0] - 0x41];
1549                 }
1550         }
1551
1552         term.dirty[y] = 1;
1553         term.line[y][x] = *attr;
1554         memcpy(term.line[y][x].c, c, UTF_SIZ);
1555 }
1556
1557 void
1558 tclearregion(int x1, int y1, int x2, int y2) {
1559         int x, y, temp;
1560
1561         if(x1 > x2)
1562                 temp = x1, x1 = x2, x2 = temp;
1563         if(y1 > y2)
1564                 temp = y1, y1 = y2, y2 = temp;
1565
1566         LIMIT(x1, 0, term.col-1);
1567         LIMIT(x2, 0, term.col-1);
1568         LIMIT(y1, 0, term.row-1);
1569         LIMIT(y2, 0, term.row-1);
1570
1571         for(y = y1; y <= y2; y++) {
1572                 term.dirty[y] = 1;
1573                 for(x = x1; x <= x2; x++) {
1574                         if(selected(x, y))
1575                                 selclear(NULL);
1576                         term.line[y][x] = term.c.attr;
1577                         memcpy(term.line[y][x].c, " ", 2);
1578                 }
1579         }
1580 }
1581
1582 void
1583 tdeletechar(int n) {
1584         int src = term.c.x + n;
1585         int dst = term.c.x;
1586         int size = term.col - src;
1587
1588         term.dirty[term.c.y] = 1;
1589
1590         if(src >= term.col) {
1591                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1592                 return;
1593         }
1594
1595         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1596                         size * sizeof(Glyph));
1597         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1598 }
1599
1600 void
1601 tinsertblank(int n) {
1602         int src = term.c.x;
1603         int dst = src + n;
1604         int size = term.col - dst;
1605
1606         term.dirty[term.c.y] = 1;
1607
1608         if(dst >= term.col) {
1609                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1610                 return;
1611         }
1612
1613         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1614                         size * sizeof(Glyph));
1615         tclearregion(src, term.c.y, dst - 1, term.c.y);
1616 }
1617
1618 void
1619 tinsertblankline(int n) {
1620         if(term.c.y < term.top || term.c.y > term.bot)
1621                 return;
1622
1623         tscrolldown(term.c.y, n);
1624 }
1625
1626 void
1627 tdeleteline(int n) {
1628         if(term.c.y < term.top || term.c.y > term.bot)
1629                 return;
1630
1631         tscrollup(term.c.y, n);
1632 }
1633
1634 void
1635 tsetattr(int *attr, int l) {
1636         int i;
1637
1638         for(i = 0; i < l; i++) {
1639                 switch(attr[i]) {
1640                 case 0:
1641                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1642                                         | ATTR_BOLD | ATTR_ITALIC \
1643                                         | ATTR_BLINK);
1644                         term.c.attr.fg = defaultfg;
1645                         term.c.attr.bg = defaultbg;
1646                         break;
1647                 case 1:
1648                         term.c.attr.mode |= ATTR_BOLD;
1649                         break;
1650                 case 3:
1651                         term.c.attr.mode |= ATTR_ITALIC;
1652                         break;
1653                 case 4:
1654                         term.c.attr.mode |= ATTR_UNDERLINE;
1655                         break;
1656                 case 5: /* slow blink */
1657                 case 6: /* rapid blink */
1658                         term.c.attr.mode |= ATTR_BLINK;
1659                         break;
1660                 case 7:
1661                         term.c.attr.mode |= ATTR_REVERSE;
1662                         break;
1663                 case 21:
1664                 case 22:
1665                         term.c.attr.mode &= ~ATTR_BOLD;
1666                         break;
1667                 case 23:
1668                         term.c.attr.mode &= ~ATTR_ITALIC;
1669                         break;
1670                 case 24:
1671                         term.c.attr.mode &= ~ATTR_UNDERLINE;
1672                         break;
1673                 case 25:
1674                 case 26:
1675                         term.c.attr.mode &= ~ATTR_BLINK;
1676                         break;
1677                 case 27:
1678                         term.c.attr.mode &= ~ATTR_REVERSE;
1679                         break;
1680                 case 38:
1681                         if(i + 2 < l && attr[i + 1] == 5) {
1682                                 i += 2;
1683                                 if(BETWEEN(attr[i], 0, 255)) {
1684                                         term.c.attr.fg = attr[i];
1685                                 } else {
1686                                         fprintf(stderr,
1687                                                 "erresc: bad fgcolor %d\n",
1688                                                 attr[i]);
1689                                 }
1690                         } else {
1691                                 fprintf(stderr,
1692                                         "erresc(38): gfx attr %d unknown\n",
1693                                         attr[i]);
1694                         }
1695                         break;
1696                 case 39:
1697                         term.c.attr.fg = defaultfg;
1698                         break;
1699                 case 48:
1700                         if(i + 2 < l && attr[i + 1] == 5) {
1701                                 i += 2;
1702                                 if(BETWEEN(attr[i], 0, 255)) {
1703                                         term.c.attr.bg = attr[i];
1704                                 } else {
1705                                         fprintf(stderr,
1706                                                 "erresc: bad bgcolor %d\n",
1707                                                 attr[i]);
1708                                 }
1709                         } else {
1710                                 fprintf(stderr,
1711                                         "erresc(48): gfx attr %d unknown\n",
1712                                         attr[i]);
1713                         }
1714                         break;
1715                 case 49:
1716                         term.c.attr.bg = defaultbg;
1717                         break;
1718                 default:
1719                         if(BETWEEN(attr[i], 30, 37)) {
1720                                 term.c.attr.fg = attr[i] - 30;
1721                         } else if(BETWEEN(attr[i], 40, 47)) {
1722                                 term.c.attr.bg = attr[i] - 40;
1723                         } else if(BETWEEN(attr[i], 90, 97)) {
1724                                 term.c.attr.fg = attr[i] - 90 + 8;
1725                         } else if(BETWEEN(attr[i], 100, 107)) {
1726                                 term.c.attr.bg = attr[i] - 100 + 8;
1727                         } else {
1728                                 fprintf(stderr,
1729                                         "erresc(default): gfx attr %d unknown\n",
1730                                         attr[i]), csidump();
1731                         }
1732                         break;
1733                 }
1734         }
1735 }
1736
1737 void
1738 tsetscroll(int t, int b) {
1739         int temp;
1740
1741         LIMIT(t, 0, term.row-1);
1742         LIMIT(b, 0, term.row-1);
1743         if(t > b) {
1744                 temp = t;
1745                 t = b;
1746                 b = temp;
1747         }
1748         term.top = t;
1749         term.bot = b;
1750 }
1751
1752 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1753
1754 void
1755 tsetmode(bool priv, bool set, int *args, int narg) {
1756         int *lim, mode;
1757         bool alt;
1758
1759         for(lim = args + narg; args < lim; ++args) {
1760                 if(priv) {
1761                         switch(*args) {
1762                                 break;
1763                         case 1: /* DECCKM -- Cursor key */
1764                                 MODBIT(term.mode, set, MODE_APPCURSOR);
1765                                 break;
1766                         case 5: /* DECSCNM -- Reverse video */
1767                                 mode = term.mode;
1768                                 MODBIT(term.mode, set, MODE_REVERSE);
1769                                 if(mode != term.mode)
1770                                         redraw(REDRAW_TIMEOUT);
1771                                 break;
1772                         case 6: /* DECOM -- Origin */
1773                                 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1774                                 tmoveato(0, 0);
1775                                 break;
1776                         case 7: /* DECAWM -- Auto wrap */
1777                                 MODBIT(term.mode, set, MODE_WRAP);
1778                                 break;
1779                         case 0:  /* Error (IGNORED) */
1780                         case 2:  /* DECANM -- ANSI/VT52 (IGNORED) */
1781                         case 3:  /* DECCOLM -- Column  (IGNORED) */
1782                         case 4:  /* DECSCLM -- Scroll (IGNORED) */
1783                         case 8:  /* DECARM -- Auto repeat (IGNORED) */
1784                         case 18: /* DECPFF -- Printer feed (IGNORED) */
1785                         case 19: /* DECPEX -- Printer extent (IGNORED) */
1786                         case 42: /* DECNRCM -- National characters (IGNORED) */
1787                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1788                                 break;
1789                         case 25: /* DECTCEM -- Text Cursor Enable Mode */
1790                                 MODBIT(term.mode, !set, MODE_HIDE);
1791                                 break;
1792                         case 9:    /* X10 mouse compatibility mode */
1793                                 xsetpointermotion(0);
1794                                 MODBIT(term.mode, 0, MODE_MOUSE);
1795                                 MODBIT(term.mode, set, MODE_MOUSEX10);
1796                                 break;
1797                         case 1000: /* 1000: report button press */
1798                                 xsetpointermotion(0);
1799                                 MODBIT(term.mode, 0, MODE_MOUSE);
1800                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
1801                                 break;
1802                         case 1002: /* 1002: report motion on button press */
1803                                 xsetpointermotion(0);
1804                                 MODBIT(term.mode, 0, MODE_MOUSE);
1805                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1806                                 break;
1807                         case 1003: /* 1003: enable all mouse motions */
1808                                 xsetpointermotion(set);
1809                                 MODBIT(term.mode, 0, MODE_MOUSE);
1810                                 MODBIT(term.mode, set, MODE_MOUSEMANY);
1811                                 break;
1812                         case 1004: /* 1004: send focus events to tty */
1813                                 MODBIT(term.mode, set, MODE_FOCUS);
1814                                 break;
1815                         case 1006: /* 1006: extended reporting mode */
1816                                 MODBIT(term.mode, set, MODE_MOUSESGR);
1817                                 break;
1818                         case 1034:
1819                                 MODBIT(term.mode, set, MODE_8BIT);
1820                                 break;
1821                         case 1049: /* = 1047 and 1048 */
1822                         case 47:
1823                         case 1047:
1824                                 if (!allowaltscreen)
1825                                         break;
1826
1827                                 alt = IS_SET(MODE_ALTSCREEN);
1828                                 if(alt) {
1829                                         tclearregion(0, 0, term.col-1,
1830                                                         term.row-1);
1831                                 }
1832                                 if(set ^ alt)           /* set is always 1 or 0 */
1833                                         tswapscreen();
1834                                 if(*args != 1049)
1835                                         break;
1836                                 /* FALLTRU */
1837                         case 1048:
1838                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1839                                 break;
1840                         /* Not implemented mouse modes. See comments there. */
1841                         case 1001: /* mouse highlight mode; can hang the
1842                                       terminal by design when implemented. */
1843                         case 1005: /* UTF-8 mouse mode; will confuse
1844                                       applications not supporting UTF-8
1845                                       and luit. */
1846                         case 1015: /* urxvt mangled mouse mode; incompatible
1847                                       and can be mistaken for other control
1848                                       codes. */
1849                         default:
1850                                 fprintf(stderr,
1851                                         "erresc: unknown private set/reset mode %d\n",
1852                                         *args);
1853                                 break;
1854                         }
1855                 } else {
1856                         switch(*args) {
1857                         case 0:  /* Error (IGNORED) */
1858                                 break;
1859                         case 2:  /* KAM -- keyboard action */
1860                                 MODBIT(term.mode, set, MODE_KBDLOCK);
1861                                 break;
1862                         case 4:  /* IRM -- Insertion-replacement */
1863                                 MODBIT(term.mode, set, MODE_INSERT);
1864                                 break;
1865                         case 12: /* SRM -- Send/Receive */
1866                                 MODBIT(term.mode, !set, MODE_ECHO);
1867                                 break;
1868                         case 20: /* LNM -- Linefeed/new line */
1869                                 MODBIT(term.mode, set, MODE_CRLF);
1870                                 break;
1871                         default:
1872                                 fprintf(stderr,
1873                                         "erresc: unknown set/reset mode %d\n",
1874                                         *args);
1875                                 break;
1876                         }
1877                 }
1878         }
1879 }
1880
1881 void
1882 csihandle(void) {
1883         switch(csiescseq.mode) {
1884         default:
1885         unknown:
1886                 fprintf(stderr, "erresc: unknown csi ");
1887                 csidump();
1888                 /* die(""); */
1889                 break;
1890         case '@': /* ICH -- Insert <n> blank char */
1891                 DEFAULT(csiescseq.arg[0], 1);
1892                 tinsertblank(csiescseq.arg[0]);
1893                 break;
1894         case 'A': /* CUU -- Cursor <n> Up */
1895                 DEFAULT(csiescseq.arg[0], 1);
1896                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1897                 break;
1898         case 'B': /* CUD -- Cursor <n> Down */
1899         case 'e': /* VPR --Cursor <n> Down */
1900                 DEFAULT(csiescseq.arg[0], 1);
1901                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1902                 break;
1903         case 'c': /* DA -- Device Attributes */
1904                 if(csiescseq.arg[0] == 0)
1905                         ttywrite(VT102ID, sizeof(VT102ID) - 1);
1906                 break;
1907         case 'C': /* CUF -- Cursor <n> Forward */
1908         case 'a': /* HPR -- Cursor <n> Forward */
1909                 DEFAULT(csiescseq.arg[0], 1);
1910                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1911                 break;
1912         case 'D': /* CUB -- Cursor <n> Backward */
1913                 DEFAULT(csiescseq.arg[0], 1);
1914                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1915                 break;
1916         case 'E': /* CNL -- Cursor <n> Down and first col */
1917                 DEFAULT(csiescseq.arg[0], 1);
1918                 tmoveto(0, term.c.y+csiescseq.arg[0]);
1919                 break;
1920         case 'F': /* CPL -- Cursor <n> Up and first col */
1921                 DEFAULT(csiescseq.arg[0], 1);
1922                 tmoveto(0, term.c.y-csiescseq.arg[0]);
1923                 break;
1924         case 'g': /* TBC -- Tabulation clear */
1925                 switch(csiescseq.arg[0]) {
1926                 case 0: /* clear current tab stop */
1927                         term.tabs[term.c.x] = 0;
1928                         break;
1929                 case 3: /* clear all the tabs */
1930                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1931                         break;
1932                 default:
1933                         goto unknown;
1934                 }
1935                 break;
1936         case 'G': /* CHA -- Move to <col> */
1937         case '`': /* HPA */
1938                 DEFAULT(csiescseq.arg[0], 1);
1939                 tmoveto(csiescseq.arg[0]-1, term.c.y);
1940                 break;
1941         case 'H': /* CUP -- Move to <row> <col> */
1942         case 'f': /* HVP */
1943                 DEFAULT(csiescseq.arg[0], 1);
1944                 DEFAULT(csiescseq.arg[1], 1);
1945                 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1946                 break;
1947         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1948                 DEFAULT(csiescseq.arg[0], 1);
1949                 while(csiescseq.arg[0]--)
1950                         tputtab(1);
1951                 break;
1952         case 'J': /* ED -- Clear screen */
1953                 sel.ob.x = -1;
1954                 switch(csiescseq.arg[0]) {
1955                 case 0: /* below */
1956                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1957                         if(term.c.y < term.row-1) {
1958                                 tclearregion(0, term.c.y+1, term.col-1,
1959                                                 term.row-1);
1960                         }
1961                         break;
1962                 case 1: /* above */
1963                         if(term.c.y > 1)
1964                                 tclearregion(0, 0, term.col-1, term.c.y-1);
1965                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1966                         break;
1967                 case 2: /* all */
1968                         tclearregion(0, 0, term.col-1, term.row-1);
1969                         break;
1970                 default:
1971                         goto unknown;
1972                 }
1973                 break;
1974         case 'K': /* EL -- Clear line */
1975                 switch(csiescseq.arg[0]) {
1976                 case 0: /* right */
1977                         tclearregion(term.c.x, term.c.y, term.col-1,
1978                                         term.c.y);
1979                         break;
1980                 case 1: /* left */
1981                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1982                         break;
1983                 case 2: /* all */
1984                         tclearregion(0, term.c.y, term.col-1, term.c.y);
1985                         break;
1986                 }
1987                 break;
1988         case 'S': /* SU -- Scroll <n> line up */
1989                 DEFAULT(csiescseq.arg[0], 1);
1990                 tscrollup(term.top, csiescseq.arg[0]);
1991                 break;
1992         case 'T': /* SD -- Scroll <n> line down */
1993                 DEFAULT(csiescseq.arg[0], 1);
1994                 tscrolldown(term.top, csiescseq.arg[0]);
1995                 break;
1996         case 'L': /* IL -- Insert <n> blank lines */
1997                 DEFAULT(csiescseq.arg[0], 1);
1998                 tinsertblankline(csiescseq.arg[0]);
1999                 break;
2000         case 'l': /* RM -- Reset Mode */
2001                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2002                 break;
2003         case 'M': /* DL -- Delete <n> lines */
2004                 DEFAULT(csiescseq.arg[0], 1);
2005                 tdeleteline(csiescseq.arg[0]);
2006                 break;
2007         case 'X': /* ECH -- Erase <n> char */
2008                 DEFAULT(csiescseq.arg[0], 1);
2009                 tclearregion(term.c.x, term.c.y,
2010                                 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2011                 break;
2012         case 'P': /* DCH -- Delete <n> char */
2013                 DEFAULT(csiescseq.arg[0], 1);
2014                 tdeletechar(csiescseq.arg[0]);
2015                 break;
2016         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2017                 DEFAULT(csiescseq.arg[0], 1);
2018                 while(csiescseq.arg[0]--)
2019                         tputtab(0);
2020                 break;
2021         case 'd': /* VPA -- Move to <row> */
2022                 DEFAULT(csiescseq.arg[0], 1);
2023                 tmoveato(term.c.x, csiescseq.arg[0]-1);
2024                 break;
2025         case 'h': /* SM -- Set terminal mode */
2026                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2027                 break;
2028         case 'm': /* SGR -- Terminal attribute (color) */
2029                 tsetattr(csiescseq.arg, csiescseq.narg);
2030                 break;
2031         case 'r': /* DECSTBM -- Set Scrolling Region */
2032                 if(csiescseq.priv) {
2033                         goto unknown;
2034                 } else {
2035                         DEFAULT(csiescseq.arg[0], 1);
2036                         DEFAULT(csiescseq.arg[1], term.row);
2037                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2038                         tmoveato(0, 0);
2039                 }
2040                 break;
2041         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2042                 tcursor(CURSOR_SAVE);
2043                 break;
2044         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2045                 tcursor(CURSOR_LOAD);
2046                 break;
2047         }
2048 }
2049
2050 void
2051 csidump(void) {
2052         int i;
2053         uint c;
2054
2055         printf("ESC[");
2056         for(i = 0; i < csiescseq.len; i++) {
2057                 c = csiescseq.buf[i] & 0xff;
2058                 if(isprint(c)) {
2059                         putchar(c);
2060                 } else if(c == '\n') {
2061                         printf("(\\n)");
2062                 } else if(c == '\r') {
2063                         printf("(\\r)");
2064                 } else if(c == 0x1b) {
2065                         printf("(\\e)");
2066                 } else {
2067                         printf("(%02x)", c);
2068                 }
2069         }
2070         putchar('\n');
2071 }
2072
2073 void
2074 csireset(void) {
2075         memset(&csiescseq, 0, sizeof(csiescseq));
2076 }
2077
2078 void
2079 strhandle(void) {
2080         char *p = NULL;
2081         int i, j, narg;
2082
2083         strparse();
2084         narg = strescseq.narg;
2085
2086         switch(strescseq.type) {
2087         case ']': /* OSC -- Operating System Command */
2088                 switch(i = atoi(strescseq.args[0])) {
2089                 case 0:
2090                 case 1:
2091                 case 2:
2092                         if(narg > 1)
2093                                 xsettitle(strescseq.args[1]);
2094                         break;
2095                 case 4: /* color set */
2096                         if(narg < 3)
2097                                 break;
2098                         p = strescseq.args[2];
2099                         /* fall through */
2100                 case 104: /* color reset, here p = NULL */
2101                         j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2102                         if (!xsetcolorname(j, p)) {
2103                                 fprintf(stderr, "erresc: invalid color %s\n", p);
2104                         } else {
2105                                 /*
2106                                  * TODO if defaultbg color is changed, borders
2107                                  * are dirty
2108                                  */
2109                                 redraw(0);
2110                         }
2111                         break;
2112                 default:
2113                         fprintf(stderr, "erresc: unknown str ");
2114                         strdump();
2115                         break;
2116                 }
2117                 break;
2118         case 'k': /* old title set compatibility */
2119                 xsettitle(strescseq.args[0]);
2120                 break;
2121         case 'P': /* DSC -- Device Control String */
2122         case '_': /* APC -- Application Program Command */
2123         case '^': /* PM -- Privacy Message */
2124         default:
2125                 fprintf(stderr, "erresc: unknown str ");
2126                 strdump();
2127                 /* die(""); */
2128                 break;
2129         }
2130 }
2131
2132 void
2133 strparse(void) {
2134         char *p = strescseq.buf;
2135
2136         strescseq.narg = 0;
2137         strescseq.buf[strescseq.len] = '\0';
2138         while(p && strescseq.narg < STR_ARG_SIZ)
2139                 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2140 }
2141
2142 void
2143 strdump(void) {
2144         int i;
2145         uint c;
2146
2147         printf("ESC%c", strescseq.type);
2148         for(i = 0; i < strescseq.len; i++) {
2149                 c = strescseq.buf[i] & 0xff;
2150                 if(c == '\0') {
2151                         return;
2152                 } else if(isprint(c)) {
2153                         putchar(c);
2154                 } else if(c == '\n') {
2155                         printf("(\\n)");
2156                 } else if(c == '\r') {
2157                         printf("(\\r)");
2158                 } else if(c == 0x1b) {
2159                         printf("(\\e)");
2160                 } else {
2161                         printf("(%02x)", c);
2162                 }
2163         }
2164         printf("ESC\\\n");
2165 }
2166
2167 void
2168 strreset(void) {
2169         memset(&strescseq, 0, sizeof(strescseq));
2170 }
2171
2172 void
2173 tputtab(bool forward) {
2174         uint x = term.c.x;
2175
2176         if(forward) {
2177                 if(x == term.col)
2178                         return;
2179                 for(++x; x < term.col && !term.tabs[x]; ++x)
2180                         /* nothing */ ;
2181         } else {
2182                 if(x == 0)
2183                         return;
2184                 for(--x; x > 0 && !term.tabs[x]; --x)
2185                         /* nothing */ ;
2186         }
2187         tmoveto(x, term.c.y);
2188 }
2189
2190 void
2191 techo(char *buf, int len) {
2192         for(; len > 0; buf++, len--) {
2193                 char c = *buf;
2194
2195                 if(c == '\033') {               /* escape */
2196                         tputc("^", 1);
2197                         tputc("[", 1);
2198                 } else if(c < '\x20') { /* control code */
2199                         if(c != '\n' && c != '\r' && c != '\t') {
2200                                 c |= '\x40';
2201                                 tputc("^", 1);
2202                         }
2203                         tputc(&c, 1);
2204                 } else {
2205                         break;
2206                 }
2207         }
2208         if(len)
2209                 tputc(buf, len);
2210 }
2211
2212 void
2213 tputc(char *c, int len) {
2214         uchar ascii = *c;
2215         bool control = ascii < '\x20' || ascii == 0177;
2216
2217         if(iofd != -1) {
2218                 if(xwrite(iofd, c, len) < 0) {
2219                         fprintf(stderr, "Error writing in %s:%s\n",
2220                                 opt_io, strerror(errno));
2221                         close(iofd);
2222                         iofd = -1;
2223                 }
2224         }
2225
2226         /*
2227          * STR sequences must be checked before anything else
2228          * because it can use some control codes as part of the sequence.
2229          */
2230         if(term.esc & ESC_STR) {
2231                 switch(ascii) {
2232                 case '\033':
2233                         term.esc = ESC_START | ESC_STR_END;
2234                         break;
2235                 case '\a': /* backwards compatibility to xterm */
2236                         term.esc = 0;
2237                         strhandle();
2238                         break;
2239                 default:
2240                         if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2241                                 memmove(&strescseq.buf[strescseq.len], c, len);
2242                                 strescseq.len += len;
2243                         } else {
2244                         /*
2245                          * Here is a bug in terminals. If the user never sends
2246                          * some code to stop the str or esc command, then st
2247                          * will stop responding. But this is better than
2248                          * silently failing with unknown characters. At least
2249                          * then users will report back.
2250                          *
2251                          * In the case users ever get fixed, here is the code:
2252                          */
2253                         /*
2254                          * term.esc = 0;
2255                          * strhandle();
2256                          */
2257                         }
2258                 }
2259                 return;
2260         }
2261
2262         /*
2263          * Actions of control codes must be performed as soon they arrive
2264          * because they can be embedded inside a control sequence, and
2265          * they must not cause conflicts with sequences.
2266          */
2267         if(control) {
2268                 switch(ascii) {
2269                 case '\t':      /* HT */
2270                         tputtab(1);
2271                         return;
2272                 case '\b':      /* BS */
2273                         tmoveto(term.c.x-1, term.c.y);
2274                         return;
2275                 case '\r':      /* CR */
2276                         tmoveto(0, term.c.y);
2277                         return;
2278                 case '\f':      /* LF */
2279                 case '\v':      /* VT */
2280                 case '\n':      /* LF */
2281                         /* go to first col if the mode is set */
2282                         tnewline(IS_SET(MODE_CRLF));
2283                         return;
2284                 case '\a':      /* BEL */
2285                         if(!(xw.state & WIN_FOCUSED))
2286                                 xseturgency(1);
2287                         return;
2288                 case '\033':    /* ESC */
2289                         csireset();
2290                         term.esc = ESC_START;
2291                         return;
2292                 case '\016':    /* SO */
2293                 case '\017':    /* SI */
2294                         /*
2295                          * Different charsets are hard to handle. Applications
2296                          * should use the right alt charset escapes for the
2297                          * only reason they still exist: line drawing. The
2298                          * rest is incompatible history st should not support.
2299                          */
2300                         return;
2301                 case '\032':    /* SUB */
2302                 case '\030':    /* CAN */
2303                         csireset();
2304                         return;
2305                 case '\005':    /* ENQ (IGNORED) */
2306                 case '\000':    /* NUL (IGNORED) */
2307                 case '\021':    /* XON (IGNORED) */
2308                 case '\023':    /* XOFF (IGNORED) */
2309                 case 0177:      /* DEL (IGNORED) */
2310                         return;
2311                 }
2312         } else if(term.esc & ESC_START) {
2313                 if(term.esc & ESC_CSI) {
2314                         csiescseq.buf[csiescseq.len++] = ascii;
2315                         if(BETWEEN(ascii, 0x40, 0x7E)
2316                                         || csiescseq.len >= \
2317                                         sizeof(csiescseq.buf)-1) {
2318                                 term.esc = 0;
2319                                 csiparse();
2320                                 csihandle();
2321                         }
2322                 } else if(term.esc & ESC_STR_END) {
2323                         term.esc = 0;
2324                         if(ascii == '\\')
2325                                 strhandle();
2326                 } else if(term.esc & ESC_ALTCHARSET) {
2327                         switch(ascii) {
2328                         case '0': /* Line drawing set */
2329                                 term.c.attr.mode |= ATTR_GFX;
2330                                 break;
2331                         case 'B': /* USASCII */
2332                                 term.c.attr.mode &= ~ATTR_GFX;
2333                                 break;
2334                         case 'A': /* UK (IGNORED) */
2335                         case '<': /* multinational charset (IGNORED) */
2336                         case '5': /* Finnish (IGNORED) */
2337                         case 'C': /* Finnish (IGNORED) */
2338                         case 'K': /* German (IGNORED) */
2339                                 break;
2340                         default:
2341                                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2342                         }
2343                         term.esc = 0;
2344                 } else if(term.esc & ESC_TEST) {
2345                         if(ascii == '8') { /* DEC screen alignment test. */
2346                                 char E[UTF_SIZ] = "E";
2347                                 int x, y;
2348
2349                                 for(x = 0; x < term.col; ++x) {
2350                                         for(y = 0; y < term.row; ++y)
2351                                                 tsetchar(E, &term.c.attr, x, y);
2352                                 }
2353                         }
2354                         term.esc = 0;
2355                 } else {
2356                         switch(ascii) {
2357                         case '[':
2358                                 term.esc |= ESC_CSI;
2359                                 break;
2360                         case '#':
2361                                 term.esc |= ESC_TEST;
2362                                 break;
2363                         case 'P': /* DCS -- Device Control String */
2364                         case '_': /* APC -- Application Program Command */
2365                         case '^': /* PM -- Privacy Message */
2366                         case ']': /* OSC -- Operating System Command */
2367                         case 'k': /* old title set compatibility */
2368                                 strreset();
2369                                 strescseq.type = ascii;
2370                                 term.esc |= ESC_STR;
2371                                 break;
2372                         case '(': /* set primary charset G0 */
2373                                 term.esc |= ESC_ALTCHARSET;
2374                                 break;
2375                         case ')': /* set secondary charset G1 (IGNORED) */
2376                         case '*': /* set tertiary charset G2 (IGNORED) */
2377                         case '+': /* set quaternary charset G3 (IGNORED) */
2378                                 term.esc = 0;
2379                                 break;
2380                         case 'D': /* IND -- Linefeed */
2381                                 if(term.c.y == term.bot) {
2382                                         tscrollup(term.top, 1);
2383                                 } else {
2384                                         tmoveto(term.c.x, term.c.y+1);
2385                                 }
2386                                 term.esc = 0;
2387                                 break;
2388                         case 'E': /* NEL -- Next line */
2389                                 tnewline(1); /* always go to first col */
2390                                 term.esc = 0;
2391                                 break;
2392                         case 'H': /* HTS -- Horizontal tab stop */
2393                                 term.tabs[term.c.x] = 1;
2394                                 term.esc = 0;
2395                                 break;
2396                         case 'M': /* RI -- Reverse index */
2397                                 if(term.c.y == term.top) {
2398                                         tscrolldown(term.top, 1);
2399                                 } else {
2400                                         tmoveto(term.c.x, term.c.y-1);
2401                                 }
2402                                 term.esc = 0;
2403                                 break;
2404                         case 'Z': /* DECID -- Identify Terminal */
2405                                 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2406                                 term.esc = 0;
2407                                 break;
2408                         case 'c': /* RIS -- Reset to inital state */
2409                                 treset();
2410                                 term.esc = 0;
2411                                 xresettitle();
2412                                 break;
2413                         case '=': /* DECPAM -- Application keypad */
2414                                 term.mode |= MODE_APPKEYPAD;
2415                                 term.esc = 0;
2416                                 break;
2417                         case '>': /* DECPNM -- Normal keypad */
2418                                 term.mode &= ~MODE_APPKEYPAD;
2419                                 term.esc = 0;
2420                                 break;
2421                         case '7': /* DECSC -- Save Cursor */
2422                                 tcursor(CURSOR_SAVE);
2423                                 term.esc = 0;
2424                                 break;
2425                         case '8': /* DECRC -- Restore Cursor */
2426                                 tcursor(CURSOR_LOAD);
2427                                 term.esc = 0;
2428                                 break;
2429                         case '\\': /* ST -- Stop */
2430                                 term.esc = 0;
2431                                 break;
2432                         default:
2433                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2434                                         (uchar) ascii, isprint(ascii)? ascii:'.');
2435                                 term.esc = 0;
2436                         }
2437                 }
2438                 /*
2439                  * All characters which form part of a sequence are not
2440                  * printed
2441                  */
2442                 return;
2443         }
2444         /*
2445          * Display control codes only if we are in graphic mode
2446          */
2447         if(control && !(term.c.attr.mode & ATTR_GFX))
2448                 return;
2449         if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2450                 sel.ob.x = -1;
2451         if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2452                 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2453                 tnewline(1);
2454         }
2455
2456         if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2457                 memmove(&term.line[term.c.y][term.c.x+1],
2458                         &term.line[term.c.y][term.c.x],
2459                         (term.col - term.c.x - 1) * sizeof(Glyph));
2460         }
2461
2462         tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2463         if(term.c.x+1 < term.col) {
2464                 tmoveto(term.c.x+1, term.c.y);
2465         } else {
2466                 term.c.state |= CURSOR_WRAPNEXT;
2467         }
2468 }
2469
2470 int
2471 tresize(int col, int row) {
2472         int i;
2473         int minrow = MIN(row, term.row);
2474         int mincol = MIN(col, term.col);
2475         int slide = term.c.y - row + 1;
2476         bool *bp;
2477         Line *orig;
2478
2479         if(col < 1 || row < 1)
2480                 return 0;
2481
2482         /* free unneeded rows */
2483         i = 0;
2484         if(slide > 0) {
2485                 /*
2486                  * slide screen to keep cursor where we expect it -
2487                  * tscrollup would work here, but we can optimize to
2488                  * memmove because we're freeing the earlier lines
2489                  */
2490                 for(/* i = 0 */; i < slide; i++) {
2491                         free(term.line[i]);
2492                         free(term.alt[i]);
2493                 }
2494                 memmove(term.line, term.line + slide, row * sizeof(Line));
2495                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2496         }
2497         for(i += row; i < term.row; i++) {
2498                 free(term.line[i]);
2499                 free(term.alt[i]);
2500         }
2501
2502         /* resize to new height */
2503         term.line = xrealloc(term.line, row * sizeof(Line));
2504         term.alt  = xrealloc(term.alt,  row * sizeof(Line));
2505         term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2506         term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2507
2508         /* resize each row to new width, zero-pad if needed */
2509         for(i = 0; i < minrow; i++) {
2510                 term.dirty[i] = 1;
2511                 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2512                 term.alt[i]  = xrealloc(term.alt[i],  col * sizeof(Glyph));
2513         }
2514
2515         /* allocate any new rows */
2516         for(/* i == minrow */; i < row; i++) {
2517                 term.dirty[i] = 1;
2518                 term.line[i] = xcalloc(col, sizeof(Glyph));
2519                 term.alt [i] = xcalloc(col, sizeof(Glyph));
2520         }
2521         if(col > term.col) {
2522                 bp = term.tabs + term.col;
2523
2524                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2525                 while(--bp > term.tabs && !*bp)
2526                         /* nothing */ ;
2527                 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2528                         *bp = 1;
2529         }
2530         /* update terminal size */
2531         term.col = col;
2532         term.row = row;
2533         /* reset scrolling region */
2534         tsetscroll(0, row-1);
2535         /* make use of the LIMIT in tmoveto */
2536         tmoveto(term.c.x, term.c.y);
2537         /* Clearing both screens */
2538         orig = term.line;
2539         do {
2540                 if(mincol < col && 0 < minrow) {
2541                         tclearregion(mincol, 0, col - 1, minrow - 1);
2542                 }
2543                 if(0 < col && minrow < row) {
2544                         tclearregion(0, minrow, col - 1, row - 1);
2545                 }
2546                 tswapscreen();
2547         } while(orig != term.line);
2548
2549         return (slide > 0);
2550 }
2551
2552 void
2553 xresize(int col, int row) {
2554         xw.tw = MAX(1, col * xw.cw);
2555         xw.th = MAX(1, row * xw.ch);
2556
2557         XFreePixmap(xw.dpy, xw.buf);
2558         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2559                         DefaultDepth(xw.dpy, xw.scr));
2560         XftDrawChange(xw.draw, xw.buf);
2561         xclear(0, 0, xw.w, xw.h);
2562 }
2563
2564 static inline ushort
2565 sixd_to_16bit(int x) {
2566         return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2567 }
2568
2569 void
2570 xloadcols(void) {
2571         int i, r, g, b;
2572         XRenderColor color = { .alpha = 0xffff };
2573
2574         /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2575         for(i = 0; i < LEN(colorname); i++) {
2576                 if(!colorname[i])
2577                         continue;
2578                 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2579                         die("Could not allocate color '%s'\n", colorname[i]);
2580                 }
2581         }
2582
2583         /* load colors [16-255] ; same colors as xterm */
2584         for(i = 16, r = 0; r < 6; r++) {
2585                 for(g = 0; g < 6; g++) {
2586                         for(b = 0; b < 6; b++) {
2587                                 color.red = sixd_to_16bit(r);
2588                                 color.green = sixd_to_16bit(g);
2589                                 color.blue = sixd_to_16bit(b);
2590                                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2591                                         die("Could not allocate color %d\n", i);
2592                                 }
2593                                 i++;
2594                         }
2595                 }
2596         }
2597
2598         for(r = 0; r < 24; r++, i++) {
2599                 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2600                 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2601                                         &dc.col[i])) {
2602                         die("Could not allocate color %d\n", i);
2603                 }
2604         }
2605 }
2606
2607 int
2608 xsetcolorname(int x, const char *name) {
2609         XRenderColor color = { .alpha = 0xffff };
2610         Colour colour;
2611         if (x < 0 || x > LEN(colorname))
2612                 return -1;
2613         if(!name) {
2614                 if(16 <= x && x < 16 + 216) {
2615                         int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2616                         color.red = sixd_to_16bit(r);
2617                         color.green = sixd_to_16bit(g);
2618                         color.blue = sixd_to_16bit(b);
2619                         if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2620                                 return 0; /* something went wrong */
2621                         dc.col[x] = colour;
2622                         return 1;
2623                 } else if (16 + 216 <= x && x < 256) {
2624                         color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2625                         if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2626                                 return 0; /* something went wrong */
2627                         dc.col[x] = colour;
2628                         return 1;
2629                 } else {
2630                         name = colorname[x];
2631                 }
2632         }
2633         if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2634                 return 0;
2635         dc.col[x] = colour;
2636         return 1;
2637 }
2638
2639 void
2640 xtermclear(int col1, int row1, int col2, int row2) {
2641         XftDrawRect(xw.draw,
2642                         &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2643                         borderpx + col1 * xw.cw,
2644                         borderpx + row1 * xw.ch,
2645                         (col2-col1+1) * xw.cw,
2646                         (row2-row1+1) * xw.ch);
2647 }
2648
2649 /*
2650  * Absolute coordinates.
2651  */
2652 void
2653 xclear(int x1, int y1, int x2, int y2) {
2654         XftDrawRect(xw.draw,
2655                         &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2656                         x1, y1, x2-x1, y2-y1);
2657 }
2658
2659 void
2660 xhints(void) {
2661         XClassHint class = {opt_class ? opt_class : termname, termname};
2662         XWMHints wm = {.flags = InputHint, .input = 1};
2663         XSizeHints *sizeh = NULL;
2664
2665         sizeh = XAllocSizeHints();
2666         if(xw.isfixed == False) {
2667                 sizeh->flags = PSize | PResizeInc | PBaseSize;
2668                 sizeh->height = xw.h;
2669                 sizeh->width = xw.w;
2670                 sizeh->height_inc = xw.ch;
2671                 sizeh->width_inc = xw.cw;
2672                 sizeh->base_height = 2 * borderpx;
2673                 sizeh->base_width = 2 * borderpx;
2674         } else {
2675                 sizeh->flags = PMaxSize | PMinSize;
2676                 sizeh->min_width = sizeh->max_width = xw.fw;
2677                 sizeh->min_height = sizeh->max_height = xw.fh;
2678         }
2679
2680         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2681         XFree(sizeh);
2682 }
2683
2684 int
2685 xloadfont(Font *f, FcPattern *pattern) {
2686         FcPattern *match;
2687         FcResult result;
2688
2689         match = FcFontMatch(NULL, pattern, &result);
2690         if(!match)
2691                 return 1;
2692
2693         if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2694                 FcPatternDestroy(match);
2695                 return 1;
2696         }
2697
2698         f->set = NULL;
2699         f->pattern = FcPatternDuplicate(pattern);
2700
2701         f->ascent = f->match->ascent;
2702         f->descent = f->match->descent;
2703         f->lbearing = 0;
2704         f->rbearing = f->match->max_advance_width;
2705
2706         f->height = f->ascent + f->descent;
2707         f->width = f->lbearing + f->rbearing;
2708
2709         return 0;
2710 }
2711
2712 void
2713 xloadfonts(char *fontstr, int fontsize) {
2714         FcPattern *pattern;
2715         FcResult result;
2716         double fontval;
2717
2718         if(fontstr[0] == '-') {
2719                 pattern = XftXlfdParse(fontstr, False, False);
2720         } else {
2721                 pattern = FcNameParse((FcChar8 *)fontstr);
2722         }
2723
2724         if(!pattern)
2725                 die("st: can't open font %s\n", fontstr);
2726
2727         if(fontsize > 0) {
2728                 FcPatternDel(pattern, FC_PIXEL_SIZE);
2729                 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2730                 usedfontsize = fontsize;
2731         } else {
2732                 result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2733                 if(result == FcResultMatch) {
2734                         usedfontsize = (int)fontval;
2735                 } else {
2736                         /*
2737                          * Default font size is 12, if none given. This is to
2738                          * have a known usedfontsize value.
2739                          */
2740                         FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2741                         usedfontsize = 12;
2742                 }
2743         }
2744
2745         FcConfigSubstitute(0, pattern, FcMatchPattern);
2746         FcDefaultSubstitute(pattern);
2747
2748         if(xloadfont(&dc.font, pattern))
2749                 die("st: can't open font %s\n", fontstr);
2750
2751         /* Setting character width and height. */
2752         xw.cw = dc.font.width;
2753         xw.ch = dc.font.height;
2754
2755         FcPatternDel(pattern, FC_SLANT);
2756         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2757         if(xloadfont(&dc.ifont, pattern))
2758                 die("st: can't open font %s\n", fontstr);
2759
2760         FcPatternDel(pattern, FC_WEIGHT);
2761         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2762         if(xloadfont(&dc.ibfont, pattern))
2763                 die("st: can't open font %s\n", fontstr);
2764
2765         FcPatternDel(pattern, FC_SLANT);
2766         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2767         if(xloadfont(&dc.bfont, pattern))
2768                 die("st: can't open font %s\n", fontstr);
2769
2770         FcPatternDestroy(pattern);
2771 }
2772
2773 int
2774 xloadfontset(Font *f) {
2775         FcResult result;
2776
2777         if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
2778                 return 1;
2779         return 0;
2780 }
2781
2782 void
2783 xunloadfont(Font *f) {
2784         XftFontClose(xw.dpy, f->match);
2785         FcPatternDestroy(f->pattern);
2786         if(f->set)
2787                 FcFontSetDestroy(f->set);
2788 }
2789
2790 void
2791 xunloadfonts(void) {
2792         int i, ip;
2793
2794         /*
2795          * Free the loaded fonts in the font cache. This is done backwards
2796          * from the frccur.
2797          */
2798         for(i = 0, ip = frccur; i < frclen; i++, ip--) {
2799                 if(ip < 0)
2800                         ip = LEN(frc) - 1;
2801                 XftFontClose(xw.dpy, frc[ip].font);
2802         }
2803         frccur = -1;
2804         frclen = 0;
2805
2806         xunloadfont(&dc.font);
2807         xunloadfont(&dc.bfont);
2808         xunloadfont(&dc.ifont);
2809         xunloadfont(&dc.ibfont);
2810 }
2811
2812 void
2813 xzoom(const Arg *arg) {
2814         xunloadfonts();
2815         xloadfonts(usedfont, usedfontsize + arg->i);
2816         cresize(0, 0);
2817         redraw(0);
2818 }
2819
2820 void
2821 xinit(void) {
2822         XGCValues gcvalues;
2823         Cursor cursor;
2824         Window parent;
2825         int sw, sh;
2826
2827         if(!(xw.dpy = XOpenDisplay(NULL)))
2828                 die("Can't open display\n");
2829         xw.scr = XDefaultScreen(xw.dpy);
2830         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2831
2832         /* font */
2833         if(!FcInit())
2834                 die("Could not init fontconfig.\n");
2835
2836         usedfont = (opt_font == NULL)? font : opt_font;
2837         xloadfonts(usedfont, 0);
2838
2839         /* colors */
2840         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2841         xloadcols();
2842
2843         /* adjust fixed window geometry */
2844         if(xw.isfixed) {
2845                 sw = DisplayWidth(xw.dpy, xw.scr);
2846                 sh = DisplayHeight(xw.dpy, xw.scr);
2847                 if(xw.fx < 0)
2848                         xw.fx = sw + xw.fx - xw.fw - 1;
2849                 if(xw.fy < 0)
2850                         xw.fy = sh + xw.fy - xw.fh - 1;
2851
2852                 xw.h = xw.fh;
2853                 xw.w = xw.fw;
2854         } else {
2855                 /* window - default size */
2856                 xw.h = 2 * borderpx + term.row * xw.ch;
2857                 xw.w = 2 * borderpx + term.col * xw.cw;
2858                 xw.fx = 0;
2859                 xw.fy = 0;
2860         }
2861
2862         /* Events */
2863         xw.attrs.background_pixel = dc.col[defaultbg].pixel;
2864         xw.attrs.border_pixel = dc.col[defaultbg].pixel;
2865         xw.attrs.bit_gravity = NorthWestGravity;
2866         xw.attrs.event_mask = FocusChangeMask | KeyPressMask
2867                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2868                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2869         xw.attrs.colormap = xw.cmap;
2870
2871         parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2872                         XRootWindow(xw.dpy, xw.scr);
2873         xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2874                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2875                         xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
2876                         | CWEventMask | CWColormap, &xw.attrs);
2877
2878         memset(&gcvalues, 0, sizeof(gcvalues));
2879         gcvalues.graphics_exposures = False;
2880         dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2881                         &gcvalues);
2882         xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2883                         DefaultDepth(xw.dpy, xw.scr));
2884         XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
2885         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
2886
2887         /* Xft rendering context */
2888         xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2889
2890         /* input methods */
2891         if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2892                 XSetLocaleModifiers("@im=local");
2893                 if((xw.xim =  XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
2894                         XSetLocaleModifiers("@im=");
2895                         if((xw.xim = XOpenIM(xw.dpy,
2896                                         NULL, NULL, NULL)) == NULL) {
2897                                 die("XOpenIM failed. Could not open input"
2898                                         " device.\n");
2899                         }
2900                 }
2901         }
2902         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2903                                            | XIMStatusNothing, XNClientWindow, xw.win,
2904                                            XNFocusWindow, xw.win, NULL);
2905         if(xw.xic == NULL)
2906                 die("XCreateIC failed. Could not obtain input method.\n");
2907
2908         /* white cursor, black outline */
2909         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2910         XDefineCursor(xw.dpy, xw.win, cursor);
2911         XRecolorCursor(xw.dpy, cursor,
2912                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2913                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2914
2915         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2916         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2917         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2918
2919         xresettitle();
2920         XMapWindow(xw.dpy, xw.win);
2921         xhints();
2922         XSync(xw.dpy, 0);
2923 }
2924
2925 void
2926 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2927         int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
2928             width = charlen * xw.cw, xp, i;
2929         int frp, frcflags;
2930         int u8fl, u8fblen, u8cblen, doesexist;
2931         char *u8c, *u8fs;
2932         long u8char;
2933         Font *font = &dc.font;
2934         FcResult fcres;
2935         FcPattern *fcpattern, *fontpattern;
2936         FcFontSet *fcsets[] = { NULL };
2937         FcCharSet *fccharset;
2938         Colour *fg, *bg, *temp, revfg, revbg;
2939         XRenderColor colfg, colbg;
2940         Rectangle r;
2941
2942         frcflags = FRC_NORMAL;
2943
2944         if(base.mode & ATTR_ITALIC) {
2945                 if(base.fg == defaultfg)
2946                         base.fg = defaultitalic;
2947                 font = &dc.ifont;
2948                 frcflags = FRC_ITALIC;
2949         } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
2950                 if(base.fg == defaultfg)
2951                         base.fg = defaultitalic;
2952                 font = &dc.ibfont;
2953                 frcflags = FRC_ITALICBOLD;
2954         } else if(base.mode & ATTR_UNDERLINE) {
2955                 if(base.fg == defaultfg)
2956                         base.fg = defaultunderline;
2957         }
2958         fg = &dc.col[base.fg];
2959         bg = &dc.col[base.bg];
2960
2961         if(base.mode & ATTR_BOLD) {
2962                 if(BETWEEN(base.fg, 0, 7)) {
2963                         /* basic system colors */
2964                         fg = &dc.col[base.fg + 8];
2965                 } else if(BETWEEN(base.fg, 16, 195)) {
2966                         /* 256 colors */
2967                         fg = &dc.col[base.fg + 36];
2968                 } else if(BETWEEN(base.fg, 232, 251)) {
2969                         /* greyscale */
2970                         fg = &dc.col[base.fg + 4];
2971                 }
2972                 /*
2973                  * Those ranges will not be brightened:
2974                  *      8 - 15 – bright system colors
2975                  *      196 - 231 – highest 256 color cube
2976                  *      252 - 255 – brightest colors in greyscale
2977                  */
2978                 font = &dc.bfont;
2979                 frcflags = FRC_BOLD;
2980         }
2981
2982         if(IS_SET(MODE_REVERSE)) {
2983                 if(fg == &dc.col[defaultfg]) {
2984                         fg = &dc.col[defaultbg];
2985                 } else {
2986                         colfg.red = ~fg->color.red;
2987                         colfg.green = ~fg->color.green;
2988                         colfg.blue = ~fg->color.blue;
2989                         colfg.alpha = fg->color.alpha;
2990                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2991                         fg = &revfg;
2992                 }
2993
2994                 if(bg == &dc.col[defaultbg]) {
2995                         bg = &dc.col[defaultfg];
2996                 } else {
2997                         colbg.red = ~bg->color.red;
2998                         colbg.green = ~bg->color.green;
2999                         colbg.blue = ~bg->color.blue;
3000                         colbg.alpha = bg->color.alpha;
3001                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
3002                         bg = &revbg;
3003                 }
3004         }
3005
3006         if(base.mode & ATTR_REVERSE) {
3007                 temp = fg;
3008                 fg = bg;
3009                 bg = temp;
3010         }
3011
3012         if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3013                 fg = bg;
3014
3015         /* Intelligent cleaning up of the borders. */
3016         if(x == 0) {
3017                 xclear(0, (y == 0)? 0 : winy, borderpx,
3018                         winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3019         }
3020         if(x + charlen >= term.col) {
3021                 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3022                         ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3023         }
3024         if(y == 0)
3025                 xclear(winx, 0, winx + width, borderpx);
3026         if(y == term.row-1)
3027                 xclear(winx, winy + xw.ch, winx + width, xw.h);
3028
3029         /* Clean up the region we want to draw to. */
3030         XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3031
3032         /* Set the clip region because Xft is sometimes dirty. */
3033         r.x = 0;
3034         r.y = 0;
3035         r.height = xw.ch;
3036         r.width = width;
3037         XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3038
3039         for(xp = winx; bytelen > 0;) {
3040                 /*
3041                  * Search for the range in the to be printed string of glyphs
3042                  * that are in the main font. Then print that range. If
3043                  * some glyph is found that is not in the font, do the
3044                  * fallback dance.
3045                  */
3046                 u8fs = s;
3047                 u8fblen = 0;
3048                 u8fl = 0;
3049                 for(;;) {
3050                         u8c = s;
3051                         u8cblen = utf8decode(s, &u8char);
3052                         s += u8cblen;
3053                         bytelen -= u8cblen;
3054
3055                         doesexist = XftCharIndex(xw.dpy, font->match, u8char);
3056                         if(!doesexist || bytelen <= 0) {
3057                                 if(bytelen <= 0) {
3058                                         if(doesexist) {
3059                                                 u8fl++;
3060                                                 u8fblen += u8cblen;
3061                                         }
3062                                 }
3063
3064                                 if(u8fl > 0) {
3065                                         XftDrawStringUtf8(xw.draw, fg,
3066                                                         font->match, xp,
3067                                                         winy + font->ascent,
3068                                                         (FcChar8 *)u8fs,
3069                                                         u8fblen);
3070                                         xp += font->width * u8fl;
3071
3072                                 }
3073                                 break;
3074                         }
3075
3076                         u8fl++;
3077                         u8fblen += u8cblen;
3078                 }
3079                 if(doesexist)
3080                         break;
3081
3082                 frp = frccur;
3083                 /* Search the font cache. */
3084                 for(i = 0; i < frclen; i++, frp--) {
3085                         if(frp <= 0)
3086                                 frp = LEN(frc) - 1;
3087
3088                         if(frc[frp].c == u8char
3089                                         && frc[frp].flags == frcflags) {
3090                                 break;
3091                         }
3092                 }
3093
3094                 /* Nothing was found. */
3095                 if(i >= frclen) {
3096                         if(!font->set)
3097                                 xloadfontset(font);
3098                         fcsets[0] = font->set;
3099
3100                         /*
3101                          * Nothing was found in the cache. Now use
3102                          * some dozen of Fontconfig calls to get the
3103                          * font for one single character.
3104                          */
3105                         fcpattern = FcPatternDuplicate(font->pattern);
3106                         fccharset = FcCharSetCreate();
3107
3108                         FcCharSetAddChar(fccharset, u8char);
3109                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
3110                                         fccharset);
3111                         FcPatternAddBool(fcpattern, FC_SCALABLE,
3112                                         FcTrue);
3113
3114                         FcConfigSubstitute(0, fcpattern,
3115                                         FcMatchPattern);
3116                         FcDefaultSubstitute(fcpattern);
3117
3118                         fontpattern = FcFontSetMatch(0, fcsets,
3119                                         FcTrue, fcpattern, &fcres);
3120
3121                         /*
3122                          * Overwrite or create the new cache entry.
3123                          */
3124                         frccur++;
3125                         frclen++;
3126                         if(frccur >= LEN(frc))
3127                                 frccur = 0;
3128                         if(frclen > LEN(frc)) {
3129                                 frclen = LEN(frc);
3130                                 XftFontClose(xw.dpy, frc[frccur].font);
3131                         }
3132
3133                         frc[frccur].font = XftFontOpenPattern(xw.dpy,
3134                                         fontpattern);
3135                         frc[frccur].c = u8char;
3136                         frc[frccur].flags = frcflags;
3137
3138                         FcPatternDestroy(fcpattern);
3139                         FcCharSetDestroy(fccharset);
3140
3141                         frp = frccur;
3142                 }
3143
3144                 XftDrawStringUtf8(xw.draw, fg, frc[frp].font,
3145                                 xp, winy + frc[frp].font->ascent,
3146                                 (FcChar8 *)u8c, u8cblen);
3147
3148                 xp += font->width;
3149         }
3150
3151         /*
3152         XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3153                         winy + font->ascent, (FcChar8 *)s, bytelen);
3154         */
3155
3156         if(base.mode & ATTR_UNDERLINE) {
3157                 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3158                                 width, 1);
3159         }
3160
3161         /* Reset clip to none. */
3162         XftDrawSetClip(xw.draw, 0);
3163 }
3164
3165 void
3166 xdrawcursor(void) {
3167         static int oldx = 0, oldy = 0;
3168         int sl;
3169         Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3170
3171         LIMIT(oldx, 0, term.col-1);
3172         LIMIT(oldy, 0, term.row-1);
3173
3174         memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3175
3176         /* remove the old cursor */
3177         sl = utf8size(term.line[oldy][oldx].c);
3178         xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3179                         oldy, 1, sl);
3180
3181         /* draw the new one */
3182         if(!(IS_SET(MODE_HIDE))) {
3183                 if(xw.state & WIN_FOCUSED) {
3184                         if(IS_SET(MODE_REVERSE)) {
3185                                 g.mode |= ATTR_REVERSE;
3186                                 g.fg = defaultcs;
3187                                 g.bg = defaultfg;
3188                         }
3189
3190                         sl = utf8size(g.c);
3191                         xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
3192                 } else {
3193                         XftDrawRect(xw.draw, &dc.col[defaultcs],
3194                                         borderpx + term.c.x * xw.cw,
3195                                         borderpx + term.c.y * xw.ch,
3196                                         xw.cw - 1, 1);
3197                         XftDrawRect(xw.draw, &dc.col[defaultcs],
3198                                         borderpx + term.c.x * xw.cw,
3199                                         borderpx + term.c.y * xw.ch,
3200                                         1, xw.ch - 1);
3201                         XftDrawRect(xw.draw, &dc.col[defaultcs],
3202                                         borderpx + (term.c.x + 1) * xw.cw - 1,
3203                                         borderpx + term.c.y * xw.ch,
3204                                         1, xw.ch - 1);
3205                         XftDrawRect(xw.draw, &dc.col[defaultcs],
3206                                         borderpx + term.c.x * xw.cw,
3207                                         borderpx + (term.c.y + 1) * xw.ch - 1,
3208                                         xw.cw, 1);
3209                 }
3210                 oldx = term.c.x, oldy = term.c.y;
3211         }
3212 }
3213
3214
3215 void
3216 xsettitle(char *p) {
3217         XTextProperty prop;
3218
3219         Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3220                         &prop);
3221         XSetWMName(xw.dpy, xw.win, &prop);
3222 }
3223
3224 void
3225 xresettitle(void) {
3226         xsettitle(opt_title ? opt_title : "st");
3227 }
3228
3229 void
3230 redraw(int timeout) {
3231         struct timespec tv = {0, timeout * 1000};
3232
3233         tfulldirt();
3234         draw();
3235
3236         if(timeout > 0) {
3237                 nanosleep(&tv, NULL);
3238                 XSync(xw.dpy, False); /* necessary for a good tput flash */
3239         }
3240 }
3241
3242 void
3243 draw(void) {
3244         drawregion(0, 0, term.col, term.row);
3245         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3246                         xw.h, 0, 0);
3247         XSetForeground(xw.dpy, dc.gc,
3248                         dc.col[IS_SET(MODE_REVERSE)?
3249                                 defaultfg : defaultbg].pixel);
3250 }
3251
3252 void
3253 drawregion(int x1, int y1, int x2, int y2) {
3254         int ic, ib, x, y, ox, sl;
3255         Glyph base, new;
3256         char buf[DRAW_BUF_SIZ];
3257         bool ena_sel = sel.ob.x != -1;
3258
3259         if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3260                 ena_sel = 0;
3261
3262         if(!(xw.state & WIN_VISIBLE))
3263                 return;
3264
3265         for(y = y1; y < y2; y++) {
3266                 if(!term.dirty[y])
3267                         continue;
3268
3269                 xtermclear(0, y, term.col, y);
3270                 term.dirty[y] = 0;
3271                 base = term.line[y][0];
3272                 ic = ib = ox = 0;
3273                 for(x = x1; x < x2; x++) {
3274                         new = term.line[y][x];
3275                         if(ena_sel && selected(x, y))
3276                                 new.mode ^= ATTR_REVERSE;
3277                         if(ib > 0 && (ATTRCMP(base, new)
3278                                         || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3279                                 xdraws(buf, base, ox, y, ic, ib);
3280                                 ic = ib = 0;
3281                         }
3282                         if(ib == 0) {
3283                                 ox = x;
3284                                 base = new;
3285                         }
3286
3287                         sl = utf8size(new.c);
3288                         memcpy(buf+ib, new.c, sl);
3289                         ib += sl;
3290                         ++ic;
3291                 }
3292                 if(ib > 0)
3293                         xdraws(buf, base, ox, y, ic, ib);
3294         }
3295         xdrawcursor();
3296 }
3297
3298 void
3299 expose(XEvent *ev) {
3300         XExposeEvent *e = &ev->xexpose;
3301
3302         if(xw.state & WIN_REDRAW) {
3303                 if(!e->count)
3304                         xw.state &= ~WIN_REDRAW;
3305         }
3306         redraw(0);
3307 }
3308
3309 void
3310 visibility(XEvent *ev) {
3311         XVisibilityEvent *e = &ev->xvisibility;
3312
3313         if(e->state == VisibilityFullyObscured) {
3314                 xw.state &= ~WIN_VISIBLE;
3315         } else if(!(xw.state & WIN_VISIBLE)) {
3316                 /* need a full redraw for next Expose, not just a buf copy */
3317                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3318         }
3319 }
3320
3321 void
3322 unmap(XEvent *ev) {
3323         xw.state &= ~WIN_VISIBLE;
3324 }
3325
3326 void
3327 xsetpointermotion(int set) {
3328         MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3329         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3330 }
3331
3332 void
3333 xseturgency(int add) {
3334         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3335
3336         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3337         XSetWMHints(xw.dpy, xw.win, h);
3338         XFree(h);
3339 }
3340
3341 void
3342 focus(XEvent *ev) {
3343         XFocusChangeEvent *e = &ev->xfocus;
3344
3345         if(e->mode == NotifyGrab)
3346                 return;
3347
3348         if(ev->type == FocusIn) {
3349                 XSetICFocus(xw.xic);
3350                 xw.state |= WIN_FOCUSED;
3351                 xseturgency(0);
3352                 if(IS_SET(MODE_FOCUS))
3353                         ttywrite("\033[I", 3);
3354         } else {
3355                 XUnsetICFocus(xw.xic);
3356                 xw.state &= ~WIN_FOCUSED;
3357                 if(IS_SET(MODE_FOCUS))
3358                         ttywrite("\033[O", 3);
3359         }
3360 }
3361
3362 inline bool
3363 match(uint mask, uint state) {
3364         state &= ~(ignoremod);
3365
3366         if(mask == XK_NO_MOD && state)
3367                 return false;
3368         if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
3369                 return false;
3370         if((state & mask) != state)
3371                 return false;
3372         return true;
3373 }
3374
3375 void
3376 numlock(const Arg *dummy) {
3377         term.numlock ^= 1;
3378 }
3379
3380 char*
3381 kmap(KeySym k, uint state) {
3382         uint mask;
3383         Key *kp;
3384         int i;
3385
3386         /* Check for mapped keys out of X11 function keys. */
3387         for(i = 0; i < LEN(mappedkeys); i++) {
3388                 if(mappedkeys[i] == k)
3389                         break;
3390         }
3391         if(i == LEN(mappedkeys)) {
3392                 if((k & 0xFFFF) < 0xFD00)
3393                         return NULL;
3394         }
3395
3396         for(kp = key; kp < key + LEN(key); kp++) {
3397                 mask = kp->mask;
3398
3399                 if(kp->k != k)
3400                         continue;
3401
3402                 if(!match(mask, state))
3403                         continue;
3404
3405                 if(kp->appkey > 0) {
3406                         if(!IS_SET(MODE_APPKEYPAD))
3407                                 continue;
3408                         if(term.numlock && kp->appkey == 2)
3409                                 continue;
3410                 } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
3411                         continue;
3412                 }
3413
3414                 if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
3415                                 (kp->appcursor > 0
3416                                  && !IS_SET(MODE_APPCURSOR))) {
3417                         continue;
3418                 }
3419
3420                 if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
3421                                 (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
3422                         continue;
3423                 }
3424
3425                 return kp->s;
3426         }
3427
3428         return NULL;
3429 }
3430
3431 void
3432 kpress(XEvent *ev) {
3433         XKeyEvent *e = &ev->xkey;
3434         KeySym ksym;
3435         char xstr[31], buf[32], *customkey, *cp = buf;
3436         int len, ret;
3437         long c;
3438         Status status;
3439         Shortcut *bp;
3440
3441         if(IS_SET(MODE_KBDLOCK))
3442                 return;
3443
3444         len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
3445         e->state &= ~Mod2Mask;
3446         /* 1. shortcuts */
3447         for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3448                 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3449                         bp->func(&(bp->arg));
3450                         return;
3451                 }
3452         }
3453
3454         /* 2. custom keys from config.h */
3455         if((customkey = kmap(ksym, e->state))) {
3456                 len = strlen(customkey);
3457                 memcpy(buf, customkey, len);
3458         /* 3. hardcoded (overrides X lookup) */
3459         } else {
3460                 if(len == 0)
3461                         return;
3462
3463                 if(len == 1 && e->state & Mod1Mask) {
3464                         if(IS_SET(MODE_8BIT)) {
3465                                 if(*xstr < 0177) {
3466                                         c = *xstr | B7;
3467                                         ret = utf8encode(&c, cp);
3468                                         cp += ret;
3469                                         len = 0;
3470                                 }
3471                         } else {
3472                                 *cp++ = '\033';
3473                         }
3474                 }
3475
3476                 memcpy(cp, xstr, len);
3477                 len = cp - buf + len;
3478         }
3479
3480         ttywrite(buf, len);
3481         if(IS_SET(MODE_ECHO))
3482                 techo(buf, len);
3483 }
3484
3485
3486 void
3487 cmessage(XEvent *e) {
3488         /*
3489          * See xembed specs
3490          *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3491          */
3492         if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3493                 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3494                         xw.state |= WIN_FOCUSED;
3495                         xseturgency(0);
3496                 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3497                         xw.state &= ~WIN_FOCUSED;
3498                 }
3499         } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3500                 /* Send SIGHUP to shell */
3501                 kill(pid, SIGHUP);
3502                 exit(EXIT_SUCCESS);
3503         }
3504 }
3505
3506 void
3507 cresize(int width, int height) {
3508         int col, row;
3509
3510         if(width != 0)
3511                 xw.w = width;
3512         if(height != 0)
3513                 xw.h = height;
3514
3515         col = (xw.w - 2 * borderpx) / xw.cw;
3516         row = (xw.h - 2 * borderpx) / xw.ch;
3517
3518         tresize(col, row);
3519         xresize(col, row);
3520         ttyresize();
3521 }
3522
3523 void
3524 resize(XEvent *e) {
3525         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3526                 return;
3527
3528         cresize(e->xconfigure.width, e->xconfigure.height);
3529 }
3530
3531 void
3532 run(void) {
3533         XEvent ev;
3534         fd_set rfd;
3535         int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3536         struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
3537
3538         gettimeofday(&lastblink, NULL);
3539         gettimeofday(&last, NULL);
3540
3541         for(xev = actionfps;;) {
3542                 FD_ZERO(&rfd);
3543                 FD_SET(cmdfd, &rfd);
3544                 FD_SET(xfd, &rfd);
3545
3546                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3547                         if(errno == EINTR)
3548                                 continue;
3549                         die("select failed: %s\n", SERRNO);
3550                 }
3551                 if(FD_ISSET(cmdfd, &rfd)) {
3552                         ttyread();
3553                         if(blinktimeout) {
3554                                 blinkset = tattrset(ATTR_BLINK);
3555                                 if(!blinkset && term.mode & ATTR_BLINK)
3556                                         term.mode &= ~(MODE_BLINK);
3557                         }
3558                 }
3559
3560                 if(FD_ISSET(xfd, &rfd))
3561                         xev = actionfps;
3562
3563                 gettimeofday(&now, NULL);
3564                 drawtimeout.tv_sec = 0;
3565                 drawtimeout.tv_usec = (1000/xfps) * 1000;
3566                 tv = &drawtimeout;
3567
3568                 dodraw = 0;
3569                 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3570                         tsetdirtattr(ATTR_BLINK);
3571                         term.mode ^= MODE_BLINK;
3572                         gettimeofday(&lastblink, NULL);
3573                         dodraw = 1;
3574                 }
3575                 if(TIMEDIFF(now, last) \
3576                                 > (xev? (1000/xfps) : (1000/actionfps))) {
3577                         dodraw = 1;
3578                         last = now;
3579                 }
3580
3581                 if(dodraw) {
3582                         while(XPending(xw.dpy)) {
3583                                 XNextEvent(xw.dpy, &ev);
3584                                 if(XFilterEvent(&ev, None))
3585                                         continue;
3586                                 if(handler[ev.type])
3587                                         (handler[ev.type])(&ev);
3588                         }
3589
3590                         draw();
3591                         XFlush(xw.dpy);
3592
3593                         if(xev && !FD_ISSET(xfd, &rfd))
3594                                 xev--;
3595                         if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3596                                 if(blinkset) {
3597                                         if(TIMEDIFF(now, lastblink) \
3598                                                         > blinktimeout) {
3599                                                 drawtimeout.tv_usec = 1;
3600                                         } else {
3601                                                 drawtimeout.tv_usec = (1000 * \
3602                                                         (blinktimeout - \
3603                                                         TIMEDIFF(now,
3604                                                                 lastblink)));
3605                                         }
3606                                 } else {
3607                                         tv = NULL;
3608                                 }
3609                         }
3610                 }
3611         }
3612 }
3613
3614 void
3615 usage(void) {
3616         die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3617         "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3618         " [-t title] [-w windowid] [-e command ...]\n", argv0);
3619 }
3620
3621 int
3622 main(int argc, char *argv[]) {
3623         int bitm, xr, yr;
3624         uint wr, hr;
3625
3626         xw.fw = xw.fh = xw.fx = xw.fy = 0;
3627         xw.isfixed = False;
3628
3629         ARGBEGIN {
3630         case 'a':
3631                 allowaltscreen = false;
3632                 break;
3633         case 'c':
3634                 opt_class = EARGF(usage());
3635                 break;
3636         case 'e':
3637                 /* eat all remaining arguments */
3638                 if(argc > 1)
3639                         opt_cmd = &argv[1];
3640                 goto run;
3641         case 'f':
3642                 opt_font = EARGF(usage());
3643                 break;
3644         case 'g':
3645                 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3646                 if(bitm & XValue)
3647                         xw.fx = xr;
3648                 if(bitm & YValue)
3649                         xw.fy = yr;
3650                 if(bitm & WidthValue)
3651                         xw.fw = (int)wr;
3652                 if(bitm & HeightValue)
3653                         xw.fh = (int)hr;
3654                 if(bitm & XNegative && xw.fx == 0)
3655                         xw.fx = -1;
3656                 if(bitm & XNegative && xw.fy == 0)
3657                         xw.fy = -1;
3658
3659                 if(xw.fh != 0 && xw.fw != 0)
3660                         xw.isfixed = True;
3661                 break;
3662         case 'o':
3663                 opt_io = EARGF(usage());
3664                 break;
3665         case 't':
3666                 opt_title = EARGF(usage());
3667                 break;
3668         case 'w':
3669                 opt_embed = EARGF(usage());
3670                 break;
3671         case 'v':
3672         default:
3673                 usage();
3674         } ARGEND;
3675
3676 run:
3677         setlocale(LC_CTYPE, "");
3678         XSetLocaleModifiers("");
3679         tnew(80, 24);
3680         xinit();
3681         ttynew();
3682         selinit();
3683         if(xw.isfixed)
3684                 cresize(xw.h, xw.w);
3685         run();
3686
3687         return 0;
3688 }
3689