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