Xinqi Bao's Git

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