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