Xinqi Bao's Git

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