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