]> Sergey Matveev's repositories - st.git/blob - x.c
Optimisations
[st.git] / x.c
1 /* See LICENSE for license details. */
2 #include <errno.h>
3 #include <math.h>
4 #include <limits.h>
5 #include <locale.h>
6 #include <signal.h>
7 #include <sys/select.h>
8 #include <time.h>
9 #include <unistd.h>
10 #include <libgen.h>
11 #include <X11/Xatom.h>
12 #include <X11/Xlib.h>
13 #include <X11/cursorfont.h>
14 #include <X11/keysym.h>
15 #include <X11/Xft/Xft.h>
16 #include <X11/XKBlib.h>
17
18 char *argv0;
19 #include "arg.h"
20 #include "st.h"
21 #include "win.h"
22
23 /* types used in config.h */
24 typedef struct {
25         uint mod;
26         KeySym keysym;
27         void (*func)(const Arg *);
28         const Arg arg;
29 } Shortcut;
30
31 typedef struct {
32         uint mod;
33         uint button;
34         void (*func)(const Arg *);
35         const Arg arg;
36         uint  release;
37 } MouseShortcut;
38
39 typedef struct {
40         KeySym k;
41         uint mask;
42         char *s;
43         /* three-valued logic variables: 0 indifferent, 1 on, -1 off */
44         signed char appkey;    /* application keypad */
45         signed char appcursor; /* application cursor */
46 } Key;
47
48 /* X modifiers */
49 #define XK_ANY_MOD    UINT_MAX
50 #define XK_NO_MOD     0
51 #define XK_SWITCH_MOD (1<<13|1<<14)
52
53 /* function definitions used in config.h */
54 static void clipcopy(const Arg *);
55 static void clippaste(const Arg *);
56 static void numlock(const Arg *);
57 static void selpaste(const Arg *);
58 static void zoom(const Arg *);
59 static void zoomabs(const Arg *);
60 static void zoomreset(const Arg *);
61 static void ttysend(const Arg *);
62
63 /* config.h for applying patches and the configuration. */
64 #include "config.h"
65
66 /* XEMBED messages */
67 #define XEMBED_FOCUS_IN  4
68 #define XEMBED_FOCUS_OUT 5
69
70 /* macros */
71 #define IS_SET(flag)            ((win.mode & (flag)) != 0)
72 #define TRUERED(x)              (((x) & 0xff0000) >> 8)
73 #define TRUEGREEN(x)            (((x) & 0xff00))
74 #define TRUEBLUE(x)             (((x) & 0xff) << 8)
75
76 typedef XftDraw *Draw;
77 typedef XftColor Color;
78 typedef XftGlyphFontSpec GlyphFontSpec;
79
80 /* Purely graphic info */
81 typedef struct {
82         int tw, th; /* tty width and height */
83         int w, h; /* window width and height */
84         int ch; /* char height */
85         int cw; /* char width  */
86         int mode; /* window state/mode flags */
87         int cursor; /* cursor style */
88 } TermWindow;
89
90 typedef struct {
91         Display *dpy;
92         Colormap cmap;
93         Window win;
94         Drawable buf;
95         GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
96         Atom xembed, wmdeletewin, netwmname, netwmiconname, netwmpid;
97         struct {
98                 XIM xim;
99                 XIC xic;
100                 XPoint spot;
101                 XVaNestedList spotlist;
102         } ime;
103         Draw draw;
104         Visual *vis;
105         XSetWindowAttributes attrs;
106         int scr;
107         int isfixed; /* is fixed geometry? */
108         int l, t; /* left and top offset */
109         int gm; /* geometry mask */
110 } XWindow;
111
112 typedef struct {
113         Atom xtarget;
114         char *primary, *clipboard;
115         struct timespec tclick1;
116         struct timespec tclick2;
117 } XSelection;
118
119 /* Font structure */
120 #define Font Font_
121 typedef struct {
122         int height;
123         int width;
124         int ascent;
125         int descent;
126         int badslant;
127         int badweight;
128         short lbearing;
129         short rbearing;
130         XftFont *match;
131         FcFontSet *set;
132         FcPattern *pattern;
133 } Font;
134
135 /* Drawing Context */
136 typedef struct {
137         Color *col;
138         size_t collen;
139         Font font, bfont, ifont, ibfont;
140         GC gc;
141 } DC;
142
143 static inline ushort sixd_to_16bit(int);
144 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
145 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
146 static void xdrawglyph(Glyph, int, int);
147 static void xclear(int, int, int, int);
148 static int xgeommasktogravity(int);
149 static int ximopen(Display *);
150 static void ximinstantiate(Display *, XPointer, XPointer);
151 static void ximdestroy(XIM, XPointer, XPointer);
152 static int xicdestroy(XIC, XPointer, XPointer);
153 static void xinit(int, int);
154 static void cresize(int, int);
155 static void xresize(int, int);
156 static void xhints(void);
157 static int xloadcolor(int, const char *, Color *);
158 static int xloadfont(Font *, FcPattern *);
159 static void xloadfonts(const char *, double);
160 static void xunloadfont(Font *);
161 static void xunloadfonts(void);
162 static void xsetenv(void);
163 static void xseturgency(int);
164 static int evcol(XEvent *);
165 static int evrow(XEvent *);
166
167 static void expose(XEvent *);
168 static void visibility(XEvent *);
169 static void unmap(XEvent *);
170 static void kpress(XEvent *);
171 static void cmessage(XEvent *);
172 static void resize(XEvent *);
173 static void focus(XEvent *);
174 static uint buttonmask(uint);
175 static int mouseaction(XEvent *, uint);
176 static void brelease(XEvent *);
177 static void bpress(XEvent *);
178 static void bmotion(XEvent *);
179 static void propnotify(XEvent *);
180 static void selnotify(XEvent *);
181 static void selclear_(XEvent *);
182 static void selrequest(XEvent *);
183 static void setsel(char *, Time);
184 static void mousesel(XEvent *, int);
185 static void mousereport(XEvent *);
186 static char *kmap(KeySym, uint);
187 static int match(uint, uint);
188
189 static void run(void);
190 static void usage(void);
191
192 static void (*handler[LASTEvent])(XEvent *) = {
193         [KeyPress] = kpress,
194         [ClientMessage] = cmessage,
195         [ConfigureNotify] = resize,
196         [VisibilityNotify] = visibility,
197         [UnmapNotify] = unmap,
198         [Expose] = expose,
199         [FocusIn] = focus,
200         [FocusOut] = focus,
201         [MotionNotify] = bmotion,
202         [ButtonPress] = bpress,
203         [ButtonRelease] = brelease,
204 /*
205  * Uncomment if you want the selection to disappear when you select something
206  * different in another window.
207  */
208 /*      [SelectionClear] = selclear_, */
209         [SelectionNotify] = selnotify,
210 /*
211  * PropertyNotify is only turned on when there is some INCR transfer happening
212  * for the selection retrieval.
213  */
214         [PropertyNotify] = propnotify,
215         [SelectionRequest] = selrequest,
216 };
217
218 /* Globals */
219 static DC dc;
220 static XWindow xw;
221 static XSelection xsel;
222 static TermWindow win;
223
224 /* Font Ring Cache */
225 enum {
226         FRC_NORMAL,
227         FRC_ITALIC,
228         FRC_BOLD,
229         FRC_ITALICBOLD
230 };
231
232 typedef struct {
233         XftFont *font;
234         int flags;
235         Rune unicodep;
236 } Fontcache;
237
238 /* Fontcache is an array now. A new font will be appended to the array. */
239 static Fontcache *frc = NULL;
240 static int frclen = 0;
241 static int frccap = 0;
242 static char *usedfont = NULL;
243 static double usedfontsize = 0;
244 static double defaultfontsize = 0;
245
246 static char *opt_class = NULL;
247 static char **opt_cmd  = NULL;
248 static char *opt_embed = NULL;
249 static char *opt_font  = NULL;
250 static char *opt_io    = NULL;
251 static char *opt_line  = NULL;
252 static char *opt_name  = NULL;
253 static char *opt_title = NULL;
254
255 static uint buttons; /* bit field of pressed buttons */
256 static int cursorblinks = 0;
257
258 void
259 clipcopy(const Arg *dummy)
260 {
261         Atom clipboard;
262
263         free(xsel.clipboard);
264         xsel.clipboard = NULL;
265
266         if (xsel.primary != NULL) {
267                 xsel.clipboard = xstrdup(xsel.primary);
268                 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
269                 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
270         }
271 }
272
273 void
274 clippaste(const Arg *dummy)
275 {
276         Atom clipboard;
277
278         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
279         XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
280                         xw.win, CurrentTime);
281 }
282
283 void
284 selpaste(const Arg *dummy)
285 {
286         XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
287                         xw.win, CurrentTime);
288 }
289
290 void
291 numlock(const Arg *dummy)
292 {
293         win.mode ^= MODE_NUMLOCK;
294 }
295
296 void
297 zoom(const Arg *arg)
298 {
299         Arg larg;
300
301         larg.f = usedfontsize + arg->f;
302         zoomabs(&larg);
303 }
304
305 void
306 zoomabs(const Arg *arg)
307 {
308         xunloadfonts();
309         xloadfonts(usedfont, arg->f);
310         cresize(0, 0);
311         redraw();
312         xhints();
313 }
314
315 void
316 zoomreset(const Arg *arg)
317 {
318         Arg larg;
319
320         if (defaultfontsize > 0) {
321                 larg.f = defaultfontsize;
322                 zoomabs(&larg);
323         }
324 }
325
326 void
327 ttysend(const Arg *arg)
328 {
329         ttywrite(arg->s, strlen(arg->s), 1);
330 }
331
332 int
333 evcol(XEvent *e)
334 {
335         int x = e->xbutton.x - borderpx;
336         LIMIT(x, 0, win.tw - 1);
337         return x / win.cw;
338 }
339
340 int
341 evrow(XEvent *e)
342 {
343         int y = e->xbutton.y - borderpx;
344         LIMIT(y, 0, win.th - 1);
345         return y / win.ch;
346 }
347
348 void
349 mousesel(XEvent *e, int done)
350 {
351         int type, seltype = SEL_REGULAR;
352         uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
353
354         for (type = 1; type < LEN(selmasks); ++type) {
355                 if (match(selmasks[type], state)) {
356                         seltype = type;
357                         break;
358                 }
359         }
360         selextend(evcol(e), evrow(e), seltype, done);
361         if (done)
362                 setsel(getsel(), e->xbutton.time);
363 }
364
365 void
366 mousereport(XEvent *e)
367 {
368         int len, btn, code;
369         int x = evcol(e), y = evrow(e);
370         int state = e->xbutton.state;
371         char buf[40];
372         static int ox, oy;
373
374         if (e->type == MotionNotify) {
375                 if (x == ox && y == oy)
376                         return;
377                 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
378                         return;
379                 /* MODE_MOUSEMOTION: no reporting if no button is pressed */
380                 if (IS_SET(MODE_MOUSEMOTION) && buttons == 0)
381                         return;
382                 /* Set btn to lowest-numbered pressed button, or 12 if no
383                  * buttons are pressed. */
384                 for (btn = 1; btn <= 11 && !(buttons & (1<<(btn-1))); btn++)
385                         ;
386                 code = 32;
387         } else {
388                 btn = e->xbutton.button;
389                 /* Only buttons 1 through 11 can be encoded */
390                 if (btn < 1 || btn > 11)
391                         return;
392                 if (e->type == ButtonRelease) {
393                         /* MODE_MOUSEX10: no button release reporting */
394                         if (IS_SET(MODE_MOUSEX10))
395                                 return;
396                         /* Don't send release events for the scroll wheel */
397                         if (btn == 4 || btn == 5)
398                                 return;
399                 }
400                 code = 0;
401         }
402
403         ox = x;
404         oy = y;
405
406         /* Encode btn into code. If no button is pressed for a motion event in
407          * MODE_MOUSEMANY, then encode it as a release. */
408         if ((!IS_SET(MODE_MOUSESGR) && e->type == ButtonRelease) || btn == 12)
409                 code += 3;
410         else if (btn >= 8)
411                 code += 128 + btn - 8;
412         else if (btn >= 4)
413                 code += 64 + btn - 4;
414         else
415                 code += btn - 1;
416
417         if (!IS_SET(MODE_MOUSEX10)) {
418                 code += ((state & ShiftMask  ) ?  4 : 0)
419                       + ((state & Mod1Mask   ) ?  8 : 0) /* meta key: alt */
420                       + ((state & ControlMask) ? 16 : 0);
421         }
422
423         if (IS_SET(MODE_MOUSESGR)) {
424                 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
425                                 code, x+1, y+1,
426                                 e->type == ButtonRelease ? 'm' : 'M');
427         } else if (x < 223 && y < 223) {
428                 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
429                                 32+code, 32+x+1, 32+y+1);
430         } else {
431                 return;
432         }
433
434         ttywrite(buf, len, 0);
435 }
436
437 uint
438 buttonmask(uint button)
439 {
440         return button == Button1 ? Button1Mask
441              : button == Button2 ? Button2Mask
442              : button == Button3 ? Button3Mask
443              : button == Button4 ? Button4Mask
444              : button == Button5 ? Button5Mask
445              : 0;
446 }
447
448 int
449 mouseaction(XEvent *e, uint release)
450 {
451         MouseShortcut *ms;
452
453         /* ignore Button<N>mask for Button<N> - it's set on release */
454         uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
455
456         for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
457                 if (ms->release == release &&
458                     ms->button == e->xbutton.button &&
459                     (match(ms->mod, state) ||  /* exact or forced */
460                      match(ms->mod, state & ~forcemousemod))) {
461                         ms->func(&(ms->arg));
462                         return 1;
463                 }
464         }
465
466         return 0;
467 }
468
469 void
470 bpress(XEvent *e)
471 {
472         int btn = e->xbutton.button;
473         struct timespec now;
474         int snap;
475
476         if (1 <= btn && btn <= 11)
477                 buttons |= 1 << (btn-1);
478
479         if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
480                 mousereport(e);
481                 return;
482         }
483
484         if (mouseaction(e, 0))
485                 return;
486
487         if (btn == Button1) {
488                 /*
489                  * If the user clicks below predefined timeouts specific
490                  * snapping behaviour is exposed.
491                  */
492                 clock_gettime(CLOCK_MONOTONIC, &now);
493                 if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
494                         snap = SNAP_LINE;
495                 } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
496                         snap = SNAP_WORD;
497                 } else {
498                         snap = 0;
499                 }
500                 xsel.tclick2 = xsel.tclick1;
501                 xsel.tclick1 = now;
502
503                 selstart(evcol(e), evrow(e), snap);
504         }
505 }
506
507 void
508 propnotify(XEvent *e)
509 {
510         XPropertyEvent *xpev;
511         Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
512
513         xpev = &e->xproperty;
514         if (xpev->state == PropertyNewValue &&
515                         (xpev->atom == XA_PRIMARY ||
516                          xpev->atom == clipboard)) {
517                 selnotify(e);
518         }
519 }
520
521 void
522 selnotify(XEvent *e)
523 {
524         ulong nitems, ofs, rem;
525         int format;
526         uchar *data, *last, *repl;
527         Atom type, incratom, property = None;
528
529         incratom = XInternAtom(xw.dpy, "INCR", 0);
530
531         ofs = 0;
532         if (e->type == SelectionNotify)
533                 property = e->xselection.property;
534         else if (e->type == PropertyNotify)
535                 property = e->xproperty.atom;
536
537         if (property == None)
538                 return;
539
540         do {
541                 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
542                                         BUFSIZ/4, False, AnyPropertyType,
543                                         &type, &format, &nitems, &rem,
544                                         &data)) {
545                         fprintf(stderr, "Clipboard allocation failed\n");
546                         return;
547                 }
548
549                 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
550                         /*
551                          * If there is some PropertyNotify with no data, then
552                          * this is the signal of the selection owner that all
553                          * data has been transferred. We won't need to receive
554                          * PropertyNotify events anymore.
555                          */
556                         MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
557                         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
558                                         &xw.attrs);
559                 }
560
561                 if (type == incratom) {
562                         /*
563                          * Activate the PropertyNotify events so we receive
564                          * when the selection owner does send us the next
565                          * chunk of data.
566                          */
567                         MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
568                         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
569                                         &xw.attrs);
570
571                         /*
572                          * Deleting the property is the transfer start signal.
573                          */
574                         XDeleteProperty(xw.dpy, xw.win, (int)property);
575                         continue;
576                 }
577
578                 /*
579                  * As seen in getsel:
580                  * Line endings are inconsistent in the terminal and GUI world
581                  * copy and pasting. When receiving some selection data,
582                  * replace all '\n' with '\r'.
583                  * FIXME: Fix the computer world.
584                  */
585                 repl = data;
586                 last = data + nitems * format / 8;
587                 while ((repl = memchr(repl, '\n', last - repl))) {
588                         *repl++ = '\r';
589                 }
590
591                 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
592                         ttywrite("\033[200~", 6, 0);
593                 ttywrite((char *)data, nitems * format / 8, 1);
594                 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
595                         ttywrite("\033[201~", 6, 0);
596                 XFree(data);
597                 /* number of 32-bit chunks returned */
598                 ofs += nitems * format / 32;
599         } while (rem > 0);
600
601         /*
602          * Deleting the property again tells the selection owner to send the
603          * next data chunk in the property.
604          */
605         XDeleteProperty(xw.dpy, xw.win, (int)property);
606 }
607
608 void
609 xclipcopy(void)
610 {
611         clipcopy(NULL);
612 }
613
614 void
615 selclear_(XEvent *e)
616 {
617         selclear();
618 }
619
620 void
621 selrequest(XEvent *e)
622 {
623         XSelectionRequestEvent *xsre;
624         XSelectionEvent xev;
625         Atom xa_targets, string, clipboard;
626         char *seltext;
627
628         xsre = (XSelectionRequestEvent *) e;
629         xev.type = SelectionNotify;
630         xev.requestor = xsre->requestor;
631         xev.selection = xsre->selection;
632         xev.target = xsre->target;
633         xev.time = xsre->time;
634         if (xsre->property == None)
635                 xsre->property = xsre->target;
636
637         /* reject */
638         xev.property = None;
639
640         xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
641         if (xsre->target == xa_targets) {
642                 /* respond with the supported type */
643                 string = xsel.xtarget;
644                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
645                                 XA_ATOM, 32, PropModeReplace,
646                                 (uchar *) &string, 1);
647                 xev.property = xsre->property;
648         } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
649                 /*
650                  * xith XA_STRING non ascii characters may be incorrect in the
651                  * requestor. It is not our problem, use utf8.
652                  */
653                 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
654                 if (xsre->selection == XA_PRIMARY) {
655                         seltext = xsel.primary;
656                 } else if (xsre->selection == clipboard) {
657                         seltext = xsel.clipboard;
658                 } else {
659                         fprintf(stderr,
660                                 "Unhandled clipboard selection 0x%lx\n",
661                                 xsre->selection);
662                         return;
663                 }
664                 if (seltext != NULL) {
665                         XChangeProperty(xsre->display, xsre->requestor,
666                                         xsre->property, xsre->target,
667                                         8, PropModeReplace,
668                                         (uchar *)seltext, strlen(seltext));
669                         xev.property = xsre->property;
670                 }
671         }
672
673         /* all done, send a notification to the listener */
674         if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
675                 fprintf(stderr, "Error sending SelectionNotify event\n");
676 }
677
678 void
679 setsel(char *str, Time t)
680 {
681         if (!str)
682                 return;
683
684         free(xsel.primary);
685         xsel.primary = str;
686
687         XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
688         if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
689                 selclear();
690 }
691
692 void
693 xsetsel(char *str)
694 {
695         setsel(str, CurrentTime);
696 }
697
698 void
699 brelease(XEvent *e)
700 {
701         int btn = e->xbutton.button;
702
703         if (1 <= btn && btn <= 11)
704                 buttons &= ~(1 << (btn-1));
705
706         if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
707                 mousereport(e);
708                 return;
709         }
710
711         if (mouseaction(e, 1))
712                 return;
713         if (btn == Button1)
714                 mousesel(e, 1);
715 }
716
717 void
718 bmotion(XEvent *e)
719 {
720         if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
721                 mousereport(e);
722                 return;
723         }
724
725         mousesel(e, 0);
726 }
727
728 void
729 cresize(int width, int height)
730 {
731         int col, row;
732
733         if (width != 0)
734                 win.w = width;
735         if (height != 0)
736                 win.h = height;
737
738         col = (win.w - 2 * borderpx) / win.cw;
739         row = (win.h - 2 * borderpx) / win.ch;
740         col = MAX(1, col);
741         row = MAX(1, row);
742
743         tresize(col, row);
744         xresize(col, row);
745         ttyresize(win.tw, win.th);
746 }
747
748 void
749 xresize(int col, int row)
750 {
751         win.tw = col * win.cw;
752         win.th = row * win.ch;
753
754         XFreePixmap(xw.dpy, xw.buf);
755         xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
756                         DefaultDepth(xw.dpy, xw.scr));
757         XftDrawChange(xw.draw, xw.buf);
758         xclear(0, 0, win.w, win.h);
759
760         /* resize to new width */
761         xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
762 }
763
764 ushort
765 sixd_to_16bit(int x)
766 {
767         return x == 0 ? 0 : 0x3737 + 0x2828 * x;
768 }
769
770 int
771 xloadcolor(int i, const char *name, Color *ncolor)
772 {
773         XRenderColor color = { .alpha = 0xffff };
774
775         if (!name) {
776                 if (BETWEEN(i, 16, 255)) { /* 256 color */
777                         if (i < 6*6*6+16) { /* same colors as xterm */
778                                 color.red   = sixd_to_16bit( ((i-16)/36)%6 );
779                                 color.green = sixd_to_16bit( ((i-16)/6) %6 );
780                                 color.blue  = sixd_to_16bit( ((i-16)/1) %6 );
781                         } else { /* greyscale */
782                                 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
783                                 color.green = color.blue = color.red;
784                         }
785                         return XftColorAllocValue(xw.dpy, xw.vis,
786                                                   xw.cmap, &color, ncolor);
787                 } else
788                         name = colorname[i];
789         }
790
791         return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
792 }
793
794 void
795 xloadcols(void)
796 {
797         int i;
798         static int loaded;
799         Color *cp;
800
801         if (loaded) {
802                 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
803                         XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
804         } else {
805                 dc.collen = MAX(LEN(colorname), 256);
806                 dc.col = xmalloc(dc.collen * sizeof(Color));
807         }
808
809         for (i = 0; i < dc.collen; i++)
810                 if (!xloadcolor(i, NULL, &dc.col[i])) {
811                         if (colorname[i])
812                                 die("could not allocate color '%s'\n", colorname[i]);
813                         else
814                                 die("could not allocate color %d\n", i);
815                 }
816         loaded = 1;
817 }
818
819 int
820 xgetcolor(int x, unsigned char *r, unsigned char *g, unsigned char *b)
821 {
822         if (!BETWEEN(x, 0, dc.collen - 1))
823                 return 1;
824
825         *r = dc.col[x].color.red >> 8;
826         *g = dc.col[x].color.green >> 8;
827         *b = dc.col[x].color.blue >> 8;
828
829         return 0;
830 }
831
832 int
833 xsetcolorname(int x, const char *name)
834 {
835         Color ncolor;
836
837         if (!BETWEEN(x, 0, dc.collen - 1))
838                 return 1;
839
840         if (!xloadcolor(x, name, &ncolor))
841                 return 1;
842
843         XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
844         dc.col[x] = ncolor;
845
846         return 0;
847 }
848
849 /*
850  * Absolute coordinates.
851  */
852 void
853 xclear(int x1, int y1, int x2, int y2)
854 {
855         XftDrawRect(xw.draw,
856                         &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
857                         x1, y1, x2-x1, y2-y1);
858 }
859
860 void
861 xhints(void)
862 {
863         XClassHint class = {opt_name ? opt_name : termname,
864                             opt_class ? opt_class : termname};
865         XWMHints wm = {.flags = InputHint, .input = 1};
866         XSizeHints *sizeh;
867
868         sizeh = XAllocSizeHints();
869
870         sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
871         sizeh->height = win.h;
872         sizeh->width = win.w;
873         sizeh->height_inc = win.ch;
874         sizeh->width_inc = win.cw;
875         sizeh->base_height = 2 * borderpx;
876         sizeh->base_width = 2 * borderpx;
877         sizeh->min_height = win.ch + 2 * borderpx;
878         sizeh->min_width = win.cw + 2 * borderpx;
879         if (xw.isfixed) {
880                 sizeh->flags |= PMaxSize;
881                 sizeh->min_width = sizeh->max_width = win.w;
882                 sizeh->min_height = sizeh->max_height = win.h;
883         }
884         if (xw.gm & (XValue|YValue)) {
885                 sizeh->flags |= USPosition | PWinGravity;
886                 sizeh->x = xw.l;
887                 sizeh->y = xw.t;
888                 sizeh->win_gravity = xgeommasktogravity(xw.gm);
889         }
890
891         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
892                         &class);
893         XFree(sizeh);
894 }
895
896 int
897 xgeommasktogravity(int mask)
898 {
899         switch (mask & (XNegative|YNegative)) {
900         case 0:
901                 return NorthWestGravity;
902         case XNegative:
903                 return NorthEastGravity;
904         case YNegative:
905                 return SouthWestGravity;
906         }
907
908         return SouthEastGravity;
909 }
910
911 int
912 xloadfont(Font *f, FcPattern *pattern)
913 {
914         FcPattern *configured;
915         FcPattern *match;
916         FcResult result;
917         XGlyphInfo extents;
918         int wantattr, haveattr;
919
920         /*
921          * Manually configure instead of calling XftMatchFont
922          * so that we can use the configured pattern for
923          * "missing glyph" lookups.
924          */
925         configured = FcPatternDuplicate(pattern);
926         if (!configured)
927                 return 1;
928
929         FcConfigSubstitute(NULL, configured, FcMatchPattern);
930         XftDefaultSubstitute(xw.dpy, xw.scr, configured);
931
932         match = FcFontMatch(NULL, configured, &result);
933         if (!match) {
934                 FcPatternDestroy(configured);
935                 return 1;
936         }
937
938         if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
939                 FcPatternDestroy(configured);
940                 FcPatternDestroy(match);
941                 return 1;
942         }
943
944         if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
945             XftResultMatch)) {
946                 /*
947                  * Check if xft was unable to find a font with the appropriate
948                  * slant but gave us one anyway. Try to mitigate.
949                  */
950                 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
951                     &haveattr) != XftResultMatch) || haveattr < wantattr) {
952                         f->badslant = 1;
953                         fputs("font slant does not match\n", stderr);
954                 }
955         }
956
957         if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
958             XftResultMatch)) {
959                 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
960                     &haveattr) != XftResultMatch) || haveattr != wantattr) {
961                         f->badweight = 1;
962                         fputs("font weight does not match\n", stderr);
963                 }
964         }
965
966         XftTextExtentsUtf8(xw.dpy, f->match,
967                 (const FcChar8 *) ascii_printable,
968                 strlen(ascii_printable), &extents);
969
970         f->set = NULL;
971         f->pattern = configured;
972
973         f->ascent = f->match->ascent;
974         f->descent = f->match->descent;
975         f->lbearing = 0;
976         f->rbearing = f->match->max_advance_width;
977
978         f->height = f->ascent + f->descent;
979         f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
980
981         return 0;
982 }
983
984 void
985 xloadfonts(const char *fontstr, double fontsize)
986 {
987         FcPattern *pattern;
988         double fontval;
989
990         if (fontstr[0] == '-')
991                 pattern = XftXlfdParse(fontstr, False, False);
992         else
993                 pattern = FcNameParse((const FcChar8 *)fontstr);
994
995         if (!pattern)
996                 die("can't open font %s\n", fontstr);
997
998         if (fontsize > 1) {
999                 FcPatternDel(pattern, FC_PIXEL_SIZE);
1000                 FcPatternDel(pattern, FC_SIZE);
1001                 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
1002                 usedfontsize = fontsize;
1003         } else {
1004                 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
1005                                 FcResultMatch) {
1006                         usedfontsize = fontval;
1007                 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
1008                                 FcResultMatch) {
1009                         usedfontsize = -1;
1010                 } else {
1011                         /*
1012                          * Default font size is 12, if none given. This is to
1013                          * have a known usedfontsize value.
1014                          */
1015                         FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
1016                         usedfontsize = 12;
1017                 }
1018                 defaultfontsize = usedfontsize;
1019         }
1020
1021         if (xloadfont(&dc.font, pattern))
1022                 die("can't open font %s\n", fontstr);
1023
1024         if (usedfontsize < 0) {
1025                 FcPatternGetDouble(dc.font.match->pattern,
1026                                    FC_PIXEL_SIZE, 0, &fontval);
1027                 usedfontsize = fontval;
1028                 if (fontsize == 0)
1029                         defaultfontsize = fontval;
1030         }
1031
1032         /* Setting character width and height. */
1033         win.cw = ceilf(dc.font.width * cwscale);
1034         win.ch = ceilf(dc.font.height * chscale);
1035
1036         FcPatternDel(pattern, FC_SLANT);
1037         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1038         if (xloadfont(&dc.ifont, pattern))
1039                 die("can't open font %s\n", fontstr);
1040
1041         FcPatternDel(pattern, FC_WEIGHT);
1042         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1043         if (xloadfont(&dc.ibfont, pattern))
1044                 die("can't open font %s\n", fontstr);
1045
1046         FcPatternDel(pattern, FC_SLANT);
1047         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
1048         if (xloadfont(&dc.bfont, pattern))
1049                 die("can't open font %s\n", fontstr);
1050
1051         FcPatternDestroy(pattern);
1052 }
1053
1054 void
1055 xunloadfont(Font *f)
1056 {
1057         XftFontClose(xw.dpy, f->match);
1058         FcPatternDestroy(f->pattern);
1059         if (f->set)
1060                 FcFontSetDestroy(f->set);
1061 }
1062
1063 void
1064 xunloadfonts(void)
1065 {
1066         /* Free the loaded fonts in the font cache.  */
1067         while (frclen > 0)
1068                 XftFontClose(xw.dpy, frc[--frclen].font);
1069
1070         xunloadfont(&dc.font);
1071         xunloadfont(&dc.bfont);
1072         xunloadfont(&dc.ifont);
1073         xunloadfont(&dc.ibfont);
1074 }
1075
1076 int
1077 ximopen(Display *dpy)
1078 {
1079         XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
1080         XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
1081
1082         xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1083         if (xw.ime.xim == NULL)
1084                 return 0;
1085
1086         if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
1087                 fprintf(stderr, "XSetIMValues: "
1088                                 "Could not set XNDestroyCallback.\n");
1089
1090         xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
1091                                               NULL);
1092
1093         if (xw.ime.xic == NULL) {
1094                 xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
1095                                        XIMPreeditNothing | XIMStatusNothing,
1096                                        XNClientWindow, xw.win,
1097                                        XNDestroyCallback, &icdestroy,
1098                                        NULL);
1099         }
1100         if (xw.ime.xic == NULL)
1101                 fprintf(stderr, "XCreateIC: Could not create input context.\n");
1102
1103         return 1;
1104 }
1105
1106 void
1107 ximinstantiate(Display *dpy, XPointer client, XPointer call)
1108 {
1109         if (ximopen(dpy))
1110                 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1111                                                  ximinstantiate, NULL);
1112 }
1113
1114 void
1115 ximdestroy(XIM xim, XPointer client, XPointer call)
1116 {
1117         xw.ime.xim = NULL;
1118         XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1119                                        ximinstantiate, NULL);
1120         XFree(xw.ime.spotlist);
1121 }
1122
1123 int
1124 xicdestroy(XIC xim, XPointer client, XPointer call)
1125 {
1126         xw.ime.xic = NULL;
1127         return 1;
1128 }
1129
1130 void
1131 xinit(int cols, int rows)
1132 {
1133         XGCValues gcvalues;
1134         Cursor cursor;
1135         Window parent;
1136         pid_t thispid = getpid();
1137         XColor xmousefg, xmousebg;
1138
1139         if (!(xw.dpy = XOpenDisplay(NULL)))
1140                 die("can't open display\n");
1141         xw.scr = XDefaultScreen(xw.dpy);
1142         xw.vis = XDefaultVisual(xw.dpy, xw.scr);
1143
1144         /* font */
1145         if (!FcInit())
1146                 die("could not init fontconfig.\n");
1147
1148         usedfont = (opt_font == NULL)? font : opt_font;
1149         xloadfonts(usedfont, 0);
1150
1151         /* colors */
1152         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1153         xloadcols();
1154
1155         /* adjust fixed window geometry */
1156         win.w = 2 * borderpx + cols * win.cw;
1157         win.h = 2 * borderpx + rows * win.ch;
1158         if (xw.gm & XNegative)
1159                 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
1160         if (xw.gm & YNegative)
1161                 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
1162
1163         /* Events */
1164         xw.attrs.background_pixel = dc.col[defaultbg].pixel;
1165         xw.attrs.border_pixel = dc.col[defaultbg].pixel;
1166         xw.attrs.bit_gravity = NorthWestGravity;
1167         xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
1168                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1169                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1170         xw.attrs.colormap = xw.cmap;
1171
1172         if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1173                 parent = XRootWindow(xw.dpy, xw.scr);
1174         xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1175                         win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1176                         xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1177                         | CWEventMask | CWColormap, &xw.attrs);
1178
1179         memset(&gcvalues, 0, sizeof(gcvalues));
1180         gcvalues.graphics_exposures = False;
1181         dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
1182                         &gcvalues);
1183         xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1184                         DefaultDepth(xw.dpy, xw.scr));
1185         XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1186         XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1187
1188         /* font spec buffer */
1189         xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1190
1191         /* Xft rendering context */
1192         xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1193
1194         /* input methods */
1195         if (!ximopen(xw.dpy)) {
1196                 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1197                                                ximinstantiate, NULL);
1198         }
1199
1200         /* white cursor, black outline */
1201         cursor = XCreateFontCursor(xw.dpy, mouseshape);
1202         XDefineCursor(xw.dpy, xw.win, cursor);
1203
1204         if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1205                 xmousefg.red   = 0xffff;
1206                 xmousefg.green = 0xffff;
1207                 xmousefg.blue  = 0xffff;
1208         }
1209
1210         if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1211                 xmousebg.red   = 0x0000;
1212                 xmousebg.green = 0x0000;
1213                 xmousebg.blue  = 0x0000;
1214         }
1215
1216         XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1217
1218         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1219         xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1220         xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1221         xw.netwmiconname = XInternAtom(xw.dpy, "_NET_WM_ICON_NAME", False);
1222         XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1223
1224         xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1225         XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1226                         PropModeReplace, (uchar *)&thispid, 1);
1227
1228         win.mode = MODE_NUMLOCK;
1229         resettitle();
1230         xhints();
1231         XMapWindow(xw.dpy, xw.win);
1232         XSync(xw.dpy, False);
1233
1234         clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1235         clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1236         xsel.primary = NULL;
1237         xsel.clipboard = NULL;
1238         xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1239         if (xsel.xtarget == None)
1240                 xsel.xtarget = XA_STRING;
1241 }
1242
1243 int
1244 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1245 {
1246         float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1247         ushort mode, prevmode = USHRT_MAX;
1248         Font *font = &dc.font;
1249         int frcflags = FRC_NORMAL;
1250         float runewidth = win.cw;
1251         Rune rune;
1252         FT_UInt glyphidx;
1253         FcResult fcres;
1254         FcPattern *fcpattern, *fontpattern;
1255         FcFontSet *fcsets[] = { NULL };
1256         FcCharSet *fccharset;
1257         int i, f, numspecs = 0;
1258
1259         for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1260                 /* Fetch rune and mode for current glyph. */
1261                 rune = glyphs[i].u;
1262                 mode = glyphs[i].mode;
1263
1264                 /* Skip dummy wide-character spacing. */
1265                 if (mode == ATTR_WDUMMY)
1266                         continue;
1267
1268                 /* Determine font for glyph if different from previous glyph. */
1269                 if (prevmode != mode) {
1270                         prevmode = mode;
1271                         font = &dc.font;
1272                         frcflags = FRC_NORMAL;
1273                         runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1274                         if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1275                                 font = &dc.ibfont;
1276                                 frcflags = FRC_ITALICBOLD;
1277                         } else if (mode & ATTR_ITALIC) {
1278                                 font = &dc.ifont;
1279                                 frcflags = FRC_ITALIC;
1280                         } else if (mode & ATTR_BOLD) {
1281                                 font = &dc.bfont;
1282                                 frcflags = FRC_BOLD;
1283                         }
1284                         yp = winy + font->ascent;
1285                 }
1286
1287                 /* Lookup character index with default font. */
1288                 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1289                 if (glyphidx) {
1290                         specs[numspecs].font = font->match;
1291                         specs[numspecs].glyph = glyphidx;
1292                         specs[numspecs].x = (short)xp;
1293                         specs[numspecs].y = (short)yp;
1294                         xp += runewidth;
1295                         numspecs++;
1296                         continue;
1297                 }
1298
1299                 /* Fallback on font cache, search the font cache for match. */
1300                 for (f = 0; f < frclen; f++) {
1301                         glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1302                         /* Everything correct. */
1303                         if (glyphidx && frc[f].flags == frcflags)
1304                                 break;
1305                         /* We got a default font for a not found glyph. */
1306                         if (!glyphidx && frc[f].flags == frcflags
1307                                         && frc[f].unicodep == rune) {
1308                                 break;
1309                         }
1310                 }
1311
1312                 /* Nothing was found. Use fontconfig to find matching font. */
1313                 if (f >= frclen) {
1314                         if (!font->set)
1315                                 font->set = FcFontSort(0, font->pattern,
1316                                                        1, 0, &fcres);
1317                         fcsets[0] = font->set;
1318
1319                         /*
1320                          * Nothing was found in the cache. Now use
1321                          * some dozen of Fontconfig calls to get the
1322                          * font for one single character.
1323                          *
1324                          * Xft and fontconfig are design failures.
1325                          */
1326                         fcpattern = FcPatternDuplicate(font->pattern);
1327                         fccharset = FcCharSetCreate();
1328
1329                         FcCharSetAddChar(fccharset, rune);
1330                         FcPatternAddCharSet(fcpattern, FC_CHARSET,
1331                                         fccharset);
1332                         FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1333
1334                         FcConfigSubstitute(0, fcpattern,
1335                                         FcMatchPattern);
1336                         FcDefaultSubstitute(fcpattern);
1337
1338                         fontpattern = FcFontSetMatch(0, fcsets, 1,
1339                                         fcpattern, &fcres);
1340
1341                         /* Allocate memory for the new cache entry. */
1342                         if (frclen >= frccap) {
1343                                 frccap += 16;
1344                                 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1345                         }
1346
1347                         frc[frclen].font = XftFontOpenPattern(xw.dpy,
1348                                         fontpattern);
1349                         if (!frc[frclen].font)
1350                                 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1351                                         strerror(errno));
1352                         frc[frclen].flags = frcflags;
1353                         frc[frclen].unicodep = rune;
1354
1355                         glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1356
1357                         f = frclen;
1358                         frclen++;
1359
1360                         FcPatternDestroy(fcpattern);
1361                         FcCharSetDestroy(fccharset);
1362                 }
1363
1364                 specs[numspecs].font = frc[f].font;
1365                 specs[numspecs].glyph = glyphidx;
1366                 specs[numspecs].x = (short)xp;
1367                 specs[numspecs].y = (short)yp;
1368                 xp += runewidth;
1369                 numspecs++;
1370         }
1371
1372         return numspecs;
1373 }
1374
1375 void
1376 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1377 {
1378         int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1379         int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1380             width = charlen * win.cw;
1381         Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1382         XRenderColor colfg, colbg;
1383         XRectangle r;
1384
1385         if (base.mode & ATTR_ITALIC) {
1386                 base.fg = defaultattr;
1387         }
1388
1389         if (IS_TRUECOL(base.fg)) {
1390                 colfg.alpha = 0xffff;
1391                 colfg.red = TRUERED(base.fg);
1392                 colfg.green = TRUEGREEN(base.fg);
1393                 colfg.blue = TRUEBLUE(base.fg);
1394                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1395                 fg = &truefg;
1396         } else {
1397                 fg = &dc.col[base.fg];
1398         }
1399
1400         if (IS_TRUECOL(base.bg)) {
1401                 colbg.alpha = 0xffff;
1402                 colbg.green = TRUEGREEN(base.bg);
1403                 colbg.red = TRUERED(base.bg);
1404                 colbg.blue = TRUEBLUE(base.bg);
1405                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1406                 bg = &truebg;
1407         } else {
1408                 bg = &dc.col[base.bg];
1409         }
1410
1411         /* Change basic system colors [0-7] to bright system colors [8-15] */
1412         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1413                 fg = &dc.col[base.fg + 8];
1414
1415         if (IS_SET(MODE_REVERSE)) {
1416                 if (fg == &dc.col[defaultfg]) {
1417                         fg = &dc.col[defaultbg];
1418                 } else {
1419                         colfg.red = ~fg->color.red;
1420                         colfg.green = ~fg->color.green;
1421                         colfg.blue = ~fg->color.blue;
1422                         colfg.alpha = fg->color.alpha;
1423                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1424                                         &revfg);
1425                         fg = &revfg;
1426                 }
1427
1428                 if (bg == &dc.col[defaultbg]) {
1429                         bg = &dc.col[defaultfg];
1430                 } else {
1431                         colbg.red = ~bg->color.red;
1432                         colbg.green = ~bg->color.green;
1433                         colbg.blue = ~bg->color.blue;
1434                         colbg.alpha = bg->color.alpha;
1435                         XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1436                                         &revbg);
1437                         bg = &revbg;
1438                 }
1439         }
1440
1441         if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1442                 colfg.red = fg->color.red / 2;
1443                 colfg.green = fg->color.green / 2;
1444                 colfg.blue = fg->color.blue / 2;
1445                 colfg.alpha = fg->color.alpha;
1446                 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1447                 fg = &revfg;
1448         }
1449
1450         if (base.mode & ATTR_REVERSE) {
1451                 temp = fg;
1452                 fg = bg;
1453                 bg = temp;
1454         }
1455
1456         if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
1457                 fg = bg;
1458
1459         if (base.mode & ATTR_INVISIBLE)
1460                 fg = bg;
1461
1462         /* Intelligent cleaning up of the borders. */
1463         if (x == 0) {
1464                 xclear(0, (y == 0)? 0 : winy, borderpx,
1465                         winy + win.ch +
1466                         ((winy + win.ch >= borderpx + win.th)? win.h : 0));
1467         }
1468         if (winx + width >= borderpx + win.tw) {
1469                 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1470                         ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
1471         }
1472         if (y == 0)
1473                 xclear(winx, 0, winx + width, borderpx);
1474         if (winy + win.ch >= borderpx + win.th)
1475                 xclear(winx, winy + win.ch, winx + width, win.h);
1476
1477         /* Clean up the region we want to draw to. */
1478         XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1479
1480         /* Set the clip region because Xft is sometimes dirty. */
1481         r.x = 0;
1482         r.y = 0;
1483         r.height = win.ch;
1484         r.width = width;
1485         XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1486
1487         /* Render the glyphs. */
1488         XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1489
1490         /* Render underline and strikethrough. */
1491         if (base.mode & ATTR_UNDERLINE) {
1492                 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent * chscale + 1,
1493                                 width, 1);
1494         }
1495
1496         if (base.mode & ATTR_STRUCK) {
1497                 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent * chscale / 3,
1498                                 width, 1);
1499         }
1500
1501         /* Reset clip to none. */
1502         XftDrawSetClip(xw.draw, 0);
1503 }
1504
1505 void
1506 xdrawglyph(Glyph g, int x, int y)
1507 {
1508         int numspecs;
1509         XftGlyphFontSpec spec;
1510
1511         numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1512         xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1513 }
1514
1515 void
1516 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
1517 {
1518         Color drawcol;
1519
1520         /* remove the old cursor */
1521         if (selected(ox, oy))
1522                 og.mode ^= ATTR_REVERSE;
1523         xdrawglyph(og, ox, oy);
1524
1525         if (IS_SET(MODE_HIDE))
1526                 return;
1527
1528         /*
1529          * Select the right color for the right mode.
1530          */
1531         g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
1532
1533         if (IS_SET(MODE_REVERSE)) {
1534                 g.mode |= ATTR_REVERSE;
1535                 g.bg = defaultfg;
1536                 if (selected(cx, cy)) {
1537                         drawcol = dc.col[defaultcs];
1538                         g.fg = defaultrcs;
1539                 } else {
1540                         drawcol = dc.col[defaultrcs];
1541                         g.fg = defaultcs;
1542                 }
1543         } else {
1544                 if (selected(cx, cy)) {
1545                         g.fg = defaultfg;
1546                         g.bg = defaultrcs;
1547                 } else {
1548                         g.fg = defaultbg;
1549                         g.bg = defaultcs;
1550                 }
1551                 drawcol = dc.col[g.bg];
1552         }
1553
1554         /* draw the new one */
1555         if (IS_SET(MODE_FOCUSED)) {
1556                 switch (win.cursor) {
1557                 case 0: /* Blinking block */
1558                 case 1: /* Blinking block (default) */
1559                         if (IS_SET(MODE_BLINK))
1560                                 break;
1561                         /* FALLTHROUGH */
1562                 case 2: /* Steady block */
1563                         xdrawglyph(g, cx, cy);
1564                         break;
1565                 case 3: /* Blinking underline */
1566                         if (IS_SET(MODE_BLINK))
1567                                 break;
1568                         /* FALLTHROUGH */
1569                 case 4: /* Steady underline */
1570                         XftDrawRect(xw.draw, &drawcol,
1571                                         borderpx + cx * win.cw,
1572                                         borderpx + (cy + 1) * win.ch - \
1573                                                 cursorthickness,
1574                                         win.cw, cursorthickness);
1575                         break;
1576                 case 5: /* Blinking bar */
1577                         if (IS_SET(MODE_BLINK))
1578                                 break;
1579                         /* FALLTHROUGH */
1580                 case 6: /* Steady bar */
1581                         XftDrawRect(xw.draw, &drawcol,
1582                                         borderpx + cx * win.cw,
1583                                         borderpx + cy * win.ch,
1584                                         cursorthickness, win.ch);
1585                         break;
1586                 case 7: /* Blinking st cursor */
1587                         if (IS_SET(MODE_BLINK))
1588                                 break;
1589                         /* FALLTHROUGH */
1590                 case 8: /* Steady st cursor */
1591                         g.u = 0x2603; /* snowman (U+2603) */
1592                         xdrawglyph(g, cx, cy);
1593                         break;
1594                 }
1595         } else {
1596                 XftDrawRect(xw.draw, &drawcol,
1597                                 borderpx + cx * win.cw,
1598                                 borderpx + cy * win.ch,
1599                                 win.cw - 1, 1);
1600                 XftDrawRect(xw.draw, &drawcol,
1601                                 borderpx + cx * win.cw,
1602                                 borderpx + cy * win.ch,
1603                                 1, win.ch - 1);
1604                 XftDrawRect(xw.draw, &drawcol,
1605                                 borderpx + (cx + 1) * win.cw - 1,
1606                                 borderpx + cy * win.ch,
1607                                 1, win.ch - 1);
1608                 XftDrawRect(xw.draw, &drawcol,
1609                                 borderpx + cx * win.cw,
1610                                 borderpx + (cy + 1) * win.ch - 1,
1611                                 win.cw, 1);
1612         }
1613 }
1614
1615 void
1616 xsetenv(void)
1617 {
1618         char buf[sizeof(long) * 8 + 1];
1619
1620         snprintf(buf, sizeof(buf), "%lu", xw.win);
1621         setenv("WINDOWID", buf, 1);
1622 }
1623
1624 void
1625 xseticontitle(char *p)
1626 {
1627         XTextProperty prop;
1628         DEFAULT(p, opt_title);
1629
1630         if (p[0] == '\0')
1631                 p = opt_title;
1632
1633         if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1634                                         &prop) != Success)
1635                 return;
1636         XSetWMIconName(xw.dpy, xw.win, &prop);
1637         XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname);
1638         XFree(prop.value);
1639 }
1640
1641 void
1642 xsettitle(char *p)
1643 {
1644         XTextProperty prop;
1645         DEFAULT(p, opt_title);
1646
1647         if (p[0] == '\0')
1648                 p = opt_title;
1649
1650         if (Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1651                                         &prop) != Success)
1652                 return;
1653         XSetWMName(xw.dpy, xw.win, &prop);
1654         XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1655         XFree(prop.value);
1656 }
1657
1658 int
1659 xstartdraw(void)
1660 {
1661         return IS_SET(MODE_VISIBLE);
1662 }
1663
1664 void
1665 xdrawline(Line line, int x1, int y1, int x2)
1666 {
1667         int i, x, ox, numspecs;
1668         Glyph base, new;
1669         XftGlyphFontSpec *specs = xw.specbuf;
1670
1671         numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
1672         i = ox = 0;
1673         for (x = x1; x < x2 && i < numspecs; x++) {
1674                 new = line[x];
1675                 if (new.mode == ATTR_WDUMMY)
1676                         continue;
1677                 if (selected(x, y1))
1678                         new.mode ^= ATTR_REVERSE;
1679                 if (i > 0 && ATTRCMP(base, new)) {
1680                         xdrawglyphfontspecs(specs, base, i, ox, y1);
1681                         specs += i;
1682                         numspecs -= i;
1683                         i = 0;
1684                 }
1685                 if (i == 0) {
1686                         ox = x;
1687                         base = new;
1688                 }
1689                 i++;
1690         }
1691         if (i > 0)
1692                 xdrawglyphfontspecs(specs, base, i, ox, y1);
1693 }
1694
1695 void
1696 xfinishdraw(void)
1697 {
1698         XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1699                         win.h, 0, 0);
1700         XSetForeground(xw.dpy, dc.gc,
1701                         dc.col[IS_SET(MODE_REVERSE)?
1702                                 defaultfg : defaultbg].pixel);
1703 }
1704
1705 void
1706 xximspot(int x, int y)
1707 {
1708         if (xw.ime.xic == NULL)
1709                 return;
1710
1711         xw.ime.spot.x = borderpx + x * win.cw;
1712         xw.ime.spot.y = borderpx + (y + 1) * win.ch;
1713
1714         XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
1715 }
1716
1717 void
1718 expose(XEvent *ev)
1719 {
1720         redraw();
1721 }
1722
1723 void
1724 visibility(XEvent *ev)
1725 {
1726         XVisibilityEvent *e = &ev->xvisibility;
1727
1728         MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
1729 }
1730
1731 void
1732 unmap(XEvent *ev)
1733 {
1734         win.mode &= ~MODE_VISIBLE;
1735 }
1736
1737 void
1738 xsetpointermotion(int set)
1739 {
1740         MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1741         XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1742 }
1743
1744 void
1745 xsetmode(int set, unsigned int flags)
1746 {
1747         int mode = win.mode;
1748         MODBIT(win.mode, set, flags);
1749         if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
1750                 redraw();
1751 }
1752
1753 int
1754 xsetcursor(int cursor)
1755 {
1756         if (!BETWEEN(cursor, 0, 8)) /* 7-8: st extensions */
1757                 return 1;
1758         win.cursor = cursor;
1759         cursorblinks = win.cursor == 0 || win.cursor == 1 ||
1760                        win.cursor == 3 || win.cursor == 5 ||
1761                        win.cursor == 7;
1762         return 0;
1763 }
1764
1765 void
1766 xseturgency(int add)
1767 {
1768         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1769
1770         MODBIT(h->flags, add, XUrgencyHint);
1771         XSetWMHints(xw.dpy, xw.win, h);
1772         XFree(h);
1773 }
1774
1775 void
1776 xbell(void)
1777 {
1778         if (!(IS_SET(MODE_FOCUSED)))
1779                 xseturgency(1);
1780         if (bellvolume)
1781                 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1782 }
1783
1784 void
1785 focus(XEvent *ev)
1786 {
1787         XFocusChangeEvent *e = &ev->xfocus;
1788
1789         if (e->mode == NotifyGrab)
1790                 return;
1791
1792         if (ev->type == FocusIn) {
1793                 if (xw.ime.xic)
1794                         XSetICFocus(xw.ime.xic);
1795                 win.mode |= MODE_FOCUSED;
1796                 xseturgency(0);
1797                 if (IS_SET(MODE_FOCUS))
1798                         ttywrite("\033[I", 3, 0);
1799         } else {
1800                 if (xw.ime.xic)
1801                         XUnsetICFocus(xw.ime.xic);
1802                 win.mode &= ~MODE_FOCUSED;
1803                 if (IS_SET(MODE_FOCUS))
1804                         ttywrite("\033[O", 3, 0);
1805         }
1806 }
1807
1808 int
1809 match(uint mask, uint state)
1810 {
1811         return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1812 }
1813
1814 char*
1815 kmap(KeySym k, uint state)
1816 {
1817         Key *kp;
1818         int i;
1819
1820         /* Check for mapped keys out of X11 function keys. */
1821         for (i = 0; i < LEN(mappedkeys); i++) {
1822                 if (mappedkeys[i] == k)
1823                         break;
1824         }
1825         if (i == LEN(mappedkeys)) {
1826                 if ((k & 0xFFFF) < 0xFD00)
1827                         return NULL;
1828         }
1829
1830         for (kp = key; kp < key + LEN(key); kp++) {
1831                 if (kp->k != k)
1832                         continue;
1833
1834                 if (!match(kp->mask, state))
1835                         continue;
1836
1837                 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1838                         continue;
1839                 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
1840                         continue;
1841
1842                 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1843                         continue;
1844
1845                 return kp->s;
1846         }
1847
1848         return NULL;
1849 }
1850
1851 void
1852 kpress(XEvent *ev)
1853 {
1854         XKeyEvent *e = &ev->xkey;
1855         KeySym ksym = NoSymbol;
1856         char buf[64], *customkey;
1857         int len;
1858         Rune c;
1859         Status status;
1860         Shortcut *bp;
1861
1862         if (IS_SET(MODE_KBDLOCK))
1863                 return;
1864
1865         if (xw.ime.xic) {
1866                 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
1867                 if (status == XBufferOverflow)
1868                         return;
1869         } else {
1870                 len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
1871         }
1872         /* 1. shortcuts */
1873         for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
1874                 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1875                         bp->func(&(bp->arg));
1876                         return;
1877                 }
1878         }
1879
1880         /* 2. custom keys from config.h */
1881         if ((customkey = kmap(ksym, e->state))) {
1882                 ttywrite(customkey, strlen(customkey), 1);
1883                 return;
1884         }
1885
1886         /* 3. composed string from input method */
1887         if (len == 0)
1888                 return;
1889         if (len == 1 && e->state & Mod1Mask) {
1890                 if (IS_SET(MODE_8BIT)) {
1891                         if (*buf < 0177) {
1892                                 c = *buf | 0x80;
1893                                 len = utf8encode(c, buf);
1894                         }
1895                 } else {
1896                         buf[1] = buf[0];
1897                         buf[0] = '\033';
1898                         len = 2;
1899                 }
1900         }
1901         ttywrite(buf, len, 1);
1902 }
1903
1904 void
1905 cmessage(XEvent *e)
1906 {
1907         /*
1908          * See xembed specs
1909          *  http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1910          */
1911         if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1912                 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1913                         win.mode |= MODE_FOCUSED;
1914                         xseturgency(0);
1915                 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1916                         win.mode &= ~MODE_FOCUSED;
1917                 }
1918         } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1919                 ttyhangup();
1920                 exit(0);
1921         }
1922 }
1923
1924 void
1925 resize(XEvent *e)
1926 {
1927         if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1928                 return;
1929
1930         cresize(e->xconfigure.width, e->xconfigure.height);
1931 }
1932
1933 void
1934 run(void)
1935 {
1936         XEvent ev;
1937         int w = win.w, h = win.h;
1938         fd_set rfd;
1939         int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
1940         struct timespec seltv, *tv, now, lastblink, trigger;
1941         double timeout;
1942
1943         /* Waiting for window mapping */
1944         do {
1945                 XNextEvent(xw.dpy, &ev);
1946                 /*
1947                  * This XFilterEvent call is required because of XOpenIM. It
1948                  * does filter out the key event and some client message for
1949                  * the input method too.
1950                  */
1951                 if (XFilterEvent(&ev, None))
1952                         continue;
1953                 if (ev.type == ConfigureNotify) {
1954                         w = ev.xconfigure.width;
1955                         h = ev.xconfigure.height;
1956                 }
1957         } while (ev.type != MapNotify);
1958
1959         ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
1960         cresize(w, h);
1961
1962         for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
1963                 FD_ZERO(&rfd);
1964                 FD_SET(ttyfd, &rfd);
1965                 FD_SET(xfd, &rfd);
1966
1967                 if (XPending(xw.dpy))
1968                         timeout = 0;  /* existing events might not set xfd */
1969
1970                 seltv.tv_sec = timeout / 1E3;
1971                 seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
1972                 tv = timeout >= 0 ? &seltv : NULL;
1973
1974                 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1975                         if (errno == EINTR)
1976                                 continue;
1977                         die("select failed: %s\n", strerror(errno));
1978                 }
1979                 clock_gettime(CLOCK_MONOTONIC, &now);
1980
1981                 if (FD_ISSET(ttyfd, &rfd))
1982                         ttyread();
1983
1984                 xev = 0;
1985                 while (XPending(xw.dpy)) {
1986                         xev = 1;
1987                         XNextEvent(xw.dpy, &ev);
1988                         if (XFilterEvent(&ev, None))
1989                                 continue;
1990                         if (handler[ev.type])
1991                                 (handler[ev.type])(&ev);
1992                 }
1993
1994                 /*
1995                  * To reduce flicker and tearing, when new content or event
1996                  * triggers drawing, we first wait a bit to ensure we got
1997                  * everything, and if nothing new arrives - we draw.
1998                  * We start with trying to wait minlatency ms. If more content
1999                  * arrives sooner, we retry with shorter and shorter periods,
2000                  * and eventually draw even without idle after maxlatency ms.
2001                  * Typically this results in low latency while interacting,
2002                  * maximum latency intervals during `cat huge.txt`, and perfect
2003                  * sync with periodic updates from animations/key-repeats/etc.
2004                  */
2005                 if (FD_ISSET(ttyfd, &rfd) || xev) {
2006                         if (!drawing) {
2007                                 trigger = now;
2008                                 if (IS_SET(MODE_BLINK)) {
2009                                         win.mode ^= MODE_BLINK;
2010                                 }
2011                                 lastblink = now;
2012                                 drawing = 1;
2013                         }
2014                         timeout = (maxlatency - TIMEDIFF(now, trigger)) \
2015                                   / maxlatency * minlatency;
2016                         if (timeout > 0)
2017                                 continue;  /* we have time, try to find idle */
2018                 }
2019
2020                 /* idle detected or maxlatency exhausted -> draw */
2021                 timeout = -1;
2022                 if (blinktimeout && (cursorblinks || tattrset(ATTR_BLINK))) {
2023                         timeout = blinktimeout - TIMEDIFF(now, lastblink);
2024                         if (timeout <= 0) {
2025                                 if (-timeout > blinktimeout) /* start visible */
2026                                         win.mode |= MODE_BLINK;
2027                                 win.mode ^= MODE_BLINK;
2028                                 tsetdirtattr(ATTR_BLINK);
2029                                 lastblink = now;
2030                                 timeout = blinktimeout;
2031                         }
2032                 }
2033
2034                 draw();
2035                 XFlush(xw.dpy);
2036                 drawing = 0;
2037         }
2038 }
2039
2040 void
2041 usage(void)
2042 {
2043         die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
2044             " [-n name] [-o file]\n"
2045             "          [-T title] [-t title] [-w windowid]"
2046             " [[-e] command [args ...]]\n"
2047             "       %s [-aiv] [-c class] [-f font] [-g geometry]"
2048             " [-n name] [-o file]\n"
2049             "          [-T title] [-t title] [-w windowid] -l line"
2050             " [stty_args ...]\n", argv0, argv0);
2051 }
2052
2053 int
2054 main(int argc, char *argv[])
2055 {
2056         xw.l = xw.t = 0;
2057         xw.isfixed = False;
2058         xsetcursor(cursorshape);
2059
2060         ARGBEGIN {
2061         case 'a':
2062                 allowaltscreen = 0;
2063                 break;
2064         case 'c':
2065                 opt_class = EARGF(usage());
2066                 break;
2067         case 'e':
2068                 if (argc > 0)
2069                         --argc, ++argv;
2070                 goto run;
2071         case 'f':
2072                 opt_font = EARGF(usage());
2073                 break;
2074         case 'g':
2075                 xw.gm = XParseGeometry(EARGF(usage()),
2076                                 &xw.l, &xw.t, &cols, &rows);
2077                 break;
2078         case 'i':
2079                 xw.isfixed = 1;
2080                 break;
2081         case 'o':
2082                 opt_io = EARGF(usage());
2083                 break;
2084         case 'l':
2085                 opt_line = EARGF(usage());
2086                 break;
2087         case 'n':
2088                 opt_name = EARGF(usage());
2089                 break;
2090         case 't':
2091         case 'T':
2092                 opt_title = EARGF(usage());
2093                 break;
2094         case 'w':
2095                 opt_embed = EARGF(usage());
2096                 break;
2097         case 'v':
2098                 die("%s " VERSION "\n", argv0);
2099                 break;
2100         default:
2101                 usage();
2102         } ARGEND;
2103
2104 run:
2105         if (argc > 0) /* eat all remaining arguments */
2106                 opt_cmd = argv;
2107
2108         if (!opt_title)
2109                 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2110
2111         setlocale(LC_CTYPE, "");
2112         XSetLocaleModifiers("");
2113         cols = MAX(cols, 1);
2114         rows = MAX(rows, 1);
2115         tnew(cols, rows);
2116         xinit(cols, rows);
2117         xsetenv();
2118         selinit();
2119         run();
2120
2121         return 0;
2122 }