Xinqi Bao's Git

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