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