Xinqi Bao's Git

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