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