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