Xinqi Bao's Git

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