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