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