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