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