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