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