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