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