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