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