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