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