Xinqi Bao's Git

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