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