x: check we still have an XIC context before accessing it
[st.git] / x.c
blobb4886177273fd308baa2e86de1db8eb00b64e7a9
1 /* See LICENSE for license details. */
2 #include <errno.h>
3 #include <math.h>
4 #include <limits.h>
5 #include <locale.h>
6 #include <signal.h>
7 #include <sys/select.h>
8 #include <time.h>
9 #include <unistd.h>
10 #include <libgen.h>
11 #include <X11/Xatom.h>
12 #include <X11/Xlib.h>
13 #include <X11/cursorfont.h>
14 #include <X11/keysym.h>
15 #include <X11/Xft/Xft.h>
16 #include <X11/XKBlib.h>
18 static char *argv0;
19 #include "arg.h"
20 #include "st.h"
21 #include "win.h"
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;
31 typedef struct {
32 uint mod;
33 uint button;
34 void (*func)(const Arg *);
35 const Arg arg;
36 uint release;
37 } MouseShortcut;
39 typedef struct {
40 KeySym k;
41 uint mask;
42 char *s;
43 /* three-valued logic variables: 0 indifferent, 1 on, -1 off */
44 signed char appkey; /* application keypad */
45 signed char appcursor; /* application cursor */
46 } Key;
48 /* X modifiers */
49 #define XK_ANY_MOD UINT_MAX
50 #define XK_NO_MOD 0
51 #define XK_SWITCH_MOD (1<<13)
53 /* function definitions used in config.h */
54 static void clipcopy(const Arg *);
55 static void clippaste(const Arg *);
56 static void numlock(const Arg *);
57 static void selpaste(const Arg *);
58 static void zoom(const Arg *);
59 static void zoomabs(const Arg *);
60 static void zoomreset(const Arg *);
61 static void ttysend(const Arg *);
63 /* config.h for applying patches and the configuration. */
64 #include "config.h"
66 /* XEMBED messages */
67 #define XEMBED_FOCUS_IN 4
68 #define XEMBED_FOCUS_OUT 5
70 /* macros */
71 #define IS_SET(flag) ((win.mode & (flag)) != 0)
72 #define TRUERED(x) (((x) & 0xff0000) >> 8)
73 #define TRUEGREEN(x) (((x) & 0xff00))
74 #define TRUEBLUE(x) (((x) & 0xff) << 8)
76 typedef XftDraw *Draw;
77 typedef XftColor Color;
78 typedef XftGlyphFontSpec GlyphFontSpec;
80 /* Purely graphic info */
81 typedef struct {
82 int tw, th; /* tty width and height */
83 int w, h; /* window width and height */
84 int ch; /* char height */
85 int cw; /* char width */
86 int mode; /* window state/mode flags */
87 int cursor; /* cursor style */
88 } TermWindow;
90 typedef struct {
91 Display *dpy;
92 Colormap cmap;
93 Window win;
94 Drawable buf;
95 GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
96 Atom xembed, wmdeletewin, netwmname, netwmpid;
97 struct {
98 XIM xim;
99 XIC xic;
100 XPoint spot;
101 XVaNestedList spotlist;
102 } ime;
103 Draw draw;
104 Visual *vis;
105 XSetWindowAttributes attrs;
106 int scr;
107 int isfixed; /* is fixed geometry? */
108 int l, t; /* left and top offset */
109 int gm; /* geometry mask */
110 } XWindow;
112 typedef struct {
113 Atom xtarget;
114 char *primary, *clipboard;
115 struct timespec tclick1;
116 struct timespec tclick2;
117 } XSelection;
119 /* Font structure */
120 #define Font Font_
121 typedef struct {
122 int height;
123 int width;
124 int ascent;
125 int descent;
126 int badslant;
127 int badweight;
128 short lbearing;
129 short rbearing;
130 XftFont *match;
131 FcFontSet *set;
132 FcPattern *pattern;
133 } Font;
135 /* Drawing Context */
136 typedef struct {
137 Color *col;
138 size_t collen;
139 Font font, bfont, ifont, ibfont;
140 GC gc;
141 } DC;
143 static inline ushort sixd_to_16bit(int);
144 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
145 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
146 static void xdrawglyph(Glyph, int, int);
147 static void xclear(int, int, int, int);
148 static int xgeommasktogravity(int);
149 static void ximopen(Display *);
150 static void ximinstantiate(Display *, XPointer, XPointer);
151 static void ximdestroy(XIM, XPointer, XPointer);
152 static void xinit(int, int);
153 static void cresize(int, int);
154 static void xresize(int, int);
155 static void xhints(void);
156 static int xloadcolor(int, const char *, Color *);
157 static int xloadfont(Font *, FcPattern *);
158 static void xloadfonts(char *, double);
159 static void xunloadfont(Font *);
160 static void xunloadfonts(void);
161 static void xsetenv(void);
162 static void xseturgency(int);
163 static int evcol(XEvent *);
164 static int evrow(XEvent *);
166 static void expose(XEvent *);
167 static void visibility(XEvent *);
168 static void unmap(XEvent *);
169 static void kpress(XEvent *);
170 static void cmessage(XEvent *);
171 static void resize(XEvent *);
172 static void focus(XEvent *);
173 static int mouseaction(XEvent *, uint);
174 static void brelease(XEvent *);
175 static void bpress(XEvent *);
176 static void bmotion(XEvent *);
177 static void propnotify(XEvent *);
178 static void selnotify(XEvent *);
179 static void selclear_(XEvent *);
180 static void selrequest(XEvent *);
181 static void setsel(char *, Time);
182 static void mousesel(XEvent *, int);
183 static void mousereport(XEvent *);
184 static char *kmap(KeySym, uint);
185 static int match(uint, uint);
187 static void run(void);
188 static void usage(void);
190 static void (*handler[LASTEvent])(XEvent *) = {
191 [KeyPress] = kpress,
192 [ClientMessage] = cmessage,
193 [ConfigureNotify] = resize,
194 [VisibilityNotify] = visibility,
195 [UnmapNotify] = unmap,
196 [Expose] = expose,
197 [FocusIn] = focus,
198 [FocusOut] = focus,
199 [MotionNotify] = bmotion,
200 [ButtonPress] = bpress,
201 [ButtonRelease] = brelease,
203 * Uncomment if you want the selection to disappear when you select something
204 * different in another window.
206 /* [SelectionClear] = selclear_, */
207 [SelectionNotify] = selnotify,
209 * PropertyNotify is only turned on when there is some INCR transfer happening
210 * for the selection retrieval.
212 [PropertyNotify] = propnotify,
213 [SelectionRequest] = selrequest,
216 /* Globals */
217 static DC dc;
218 static XWindow xw;
219 static XSelection xsel;
220 static TermWindow win;
222 /* Font Ring Cache */
223 enum {
224 FRC_NORMAL,
225 FRC_ITALIC,
226 FRC_BOLD,
227 FRC_ITALICBOLD
230 typedef struct {
231 XftFont *font;
232 int flags;
233 Rune unicodep;
234 } Fontcache;
236 /* Fontcache is an array now. A new font will be appended to the array. */
237 static Fontcache *frc = NULL;
238 static int frclen = 0;
239 static int frccap = 0;
240 static char *usedfont = NULL;
241 static double usedfontsize = 0;
242 static double defaultfontsize = 0;
244 static char *opt_class = NULL;
245 static char **opt_cmd = NULL;
246 static char *opt_embed = NULL;
247 static char *opt_font = NULL;
248 static char *opt_io = NULL;
249 static char *opt_line = NULL;
250 static char *opt_name = NULL;
251 static char *opt_title = NULL;
253 static int oldbutton = 3; /* button event on startup: 3 = release */
255 void
256 clipcopy(const Arg *dummy)
258 Atom clipboard;
260 free(xsel.clipboard);
261 xsel.clipboard = NULL;
263 if (xsel.primary != NULL) {
264 xsel.clipboard = xstrdup(xsel.primary);
265 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
266 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
270 void
271 clippaste(const Arg *dummy)
273 Atom clipboard;
275 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
276 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
277 xw.win, CurrentTime);
280 void
281 selpaste(const Arg *dummy)
283 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
284 xw.win, CurrentTime);
287 void
288 numlock(const Arg *dummy)
290 win.mode ^= MODE_NUMLOCK;
293 void
294 zoom(const Arg *arg)
296 Arg larg;
298 larg.f = usedfontsize + arg->f;
299 zoomabs(&larg);
302 void
303 zoomabs(const Arg *arg)
305 xunloadfonts();
306 xloadfonts(usedfont, arg->f);
307 cresize(0, 0);
308 redraw();
309 xhints();
312 void
313 zoomreset(const Arg *arg)
315 Arg larg;
317 if (defaultfontsize > 0) {
318 larg.f = defaultfontsize;
319 zoomabs(&larg);
323 void
324 ttysend(const Arg *arg)
326 ttywrite(arg->s, strlen(arg->s), 1);
330 evcol(XEvent *e)
332 int x = e->xbutton.x - borderpx;
333 LIMIT(x, 0, win.tw - 1);
334 return x / win.cw;
338 evrow(XEvent *e)
340 int y = e->xbutton.y - borderpx;
341 LIMIT(y, 0, win.th - 1);
342 return y / win.ch;
345 void
346 mousesel(XEvent *e, int done)
348 int type, seltype = SEL_REGULAR;
349 uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
351 for (type = 1; type < LEN(selmasks); ++type) {
352 if (match(selmasks[type], state)) {
353 seltype = type;
354 break;
357 selextend(evcol(e), evrow(e), seltype, done);
358 if (done)
359 setsel(getsel(), e->xbutton.time);
362 void
363 mousereport(XEvent *e)
365 int len, x = evcol(e), y = evrow(e),
366 button = e->xbutton.button, state = e->xbutton.state;
367 char buf[40];
368 static int ox, oy;
370 /* from urxvt */
371 if (e->xbutton.type == MotionNotify) {
372 if (x == ox && y == oy)
373 return;
374 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
375 return;
376 /* MOUSE_MOTION: no reporting if no button is pressed */
377 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
378 return;
380 button = oldbutton + 32;
381 ox = x;
382 oy = y;
383 } else {
384 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
385 button = 3;
386 } else {
387 button -= Button1;
388 if (button >= 3)
389 button += 64 - 3;
391 if (e->xbutton.type == ButtonPress) {
392 oldbutton = button;
393 ox = x;
394 oy = y;
395 } else if (e->xbutton.type == ButtonRelease) {
396 oldbutton = 3;
397 /* MODE_MOUSEX10: no button release reporting */
398 if (IS_SET(MODE_MOUSEX10))
399 return;
400 if (button == 64 || button == 65)
401 return;
405 if (!IS_SET(MODE_MOUSEX10)) {
406 button += ((state & ShiftMask ) ? 4 : 0)
407 + ((state & Mod4Mask ) ? 8 : 0)
408 + ((state & ControlMask) ? 16 : 0);
411 if (IS_SET(MODE_MOUSESGR)) {
412 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
413 button, x+1, y+1,
414 e->xbutton.type == ButtonRelease ? 'm' : 'M');
415 } else if (x < 223 && y < 223) {
416 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
417 32+button, 32+x+1, 32+y+1);
418 } else {
419 return;
422 ttywrite(buf, len, 0);
426 mouseaction(XEvent *e, uint release)
428 MouseShortcut *ms;
430 for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
431 if (ms->release == release &&
432 ms->button == e->xbutton.button &&
433 (match(ms->mod, e->xbutton.state) || /* exact or forced */
434 match(ms->mod, e->xbutton.state & ~forcemousemod))) {
435 ms->func(&(ms->arg));
436 return 1;
440 return 0;
443 void
444 bpress(XEvent *e)
446 struct timespec now;
447 int snap;
449 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
450 mousereport(e);
451 return;
454 if (mouseaction(e, 0))
455 return;
457 if (e->xbutton.button == Button1) {
459 * If the user clicks below predefined timeouts specific
460 * snapping behaviour is exposed.
462 clock_gettime(CLOCK_MONOTONIC, &now);
463 if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
464 snap = SNAP_LINE;
465 } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
466 snap = SNAP_WORD;
467 } else {
468 snap = 0;
470 xsel.tclick2 = xsel.tclick1;
471 xsel.tclick1 = now;
473 selstart(evcol(e), evrow(e), snap);
477 void
478 propnotify(XEvent *e)
480 XPropertyEvent *xpev;
481 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
483 xpev = &e->xproperty;
484 if (xpev->state == PropertyNewValue &&
485 (xpev->atom == XA_PRIMARY ||
486 xpev->atom == clipboard)) {
487 selnotify(e);
491 void
492 selnotify(XEvent *e)
494 ulong nitems, ofs, rem;
495 int format;
496 uchar *data, *last, *repl;
497 Atom type, incratom, property = None;
499 incratom = XInternAtom(xw.dpy, "INCR", 0);
501 ofs = 0;
502 if (e->type == SelectionNotify)
503 property = e->xselection.property;
504 else if (e->type == PropertyNotify)
505 property = e->xproperty.atom;
507 if (property == None)
508 return;
510 do {
511 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
512 BUFSIZ/4, False, AnyPropertyType,
513 &type, &format, &nitems, &rem,
514 &data)) {
515 fprintf(stderr, "Clipboard allocation failed\n");
516 return;
519 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
521 * If there is some PropertyNotify with no data, then
522 * this is the signal of the selection owner that all
523 * data has been transferred. We won't need to receive
524 * PropertyNotify events anymore.
526 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
527 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
528 &xw.attrs);
531 if (type == incratom) {
533 * Activate the PropertyNotify events so we receive
534 * when the selection owner does send us the next
535 * chunk of data.
537 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
538 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
539 &xw.attrs);
542 * Deleting the property is the transfer start signal.
544 XDeleteProperty(xw.dpy, xw.win, (int)property);
545 continue;
549 * As seen in getsel:
550 * Line endings are inconsistent in the terminal and GUI world
551 * copy and pasting. When receiving some selection data,
552 * replace all '\n' with '\r'.
553 * FIXME: Fix the computer world.
555 repl = data;
556 last = data + nitems * format / 8;
557 while ((repl = memchr(repl, '\n', last - repl))) {
558 *repl++ = '\r';
561 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
562 ttywrite("\033[200~", 6, 0);
563 ttywrite((char *)data, nitems * format / 8, 1);
564 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
565 ttywrite("\033[201~", 6, 0);
566 XFree(data);
567 /* number of 32-bit chunks returned */
568 ofs += nitems * format / 32;
569 } while (rem > 0);
572 * Deleting the property again tells the selection owner to send the
573 * next data chunk in the property.
575 XDeleteProperty(xw.dpy, xw.win, (int)property);
578 void
579 xclipcopy(void)
581 clipcopy(NULL);
584 void
585 selclear_(XEvent *e)
587 selclear();
590 void
591 selrequest(XEvent *e)
593 XSelectionRequestEvent *xsre;
594 XSelectionEvent xev;
595 Atom xa_targets, string, clipboard;
596 char *seltext;
598 xsre = (XSelectionRequestEvent *) e;
599 xev.type = SelectionNotify;
600 xev.requestor = xsre->requestor;
601 xev.selection = xsre->selection;
602 xev.target = xsre->target;
603 xev.time = xsre->time;
604 if (xsre->property == None)
605 xsre->property = xsre->target;
607 /* reject */
608 xev.property = None;
610 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
611 if (xsre->target == xa_targets) {
612 /* respond with the supported type */
613 string = xsel.xtarget;
614 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
615 XA_ATOM, 32, PropModeReplace,
616 (uchar *) &string, 1);
617 xev.property = xsre->property;
618 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
620 * xith XA_STRING non ascii characters may be incorrect in the
621 * requestor. It is not our problem, use utf8.
623 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
624 if (xsre->selection == XA_PRIMARY) {
625 seltext = xsel.primary;
626 } else if (xsre->selection == clipboard) {
627 seltext = xsel.clipboard;
628 } else {
629 fprintf(stderr,
630 "Unhandled clipboard selection 0x%lx\n",
631 xsre->selection);
632 return;
634 if (seltext != NULL) {
635 XChangeProperty(xsre->display, xsre->requestor,
636 xsre->property, xsre->target,
637 8, PropModeReplace,
638 (uchar *)seltext, strlen(seltext));
639 xev.property = xsre->property;
643 /* all done, send a notification to the listener */
644 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
645 fprintf(stderr, "Error sending SelectionNotify event\n");
648 void
649 setsel(char *str, Time t)
651 if (!str)
652 return;
654 free(xsel.primary);
655 xsel.primary = str;
657 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
658 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
659 selclear();
662 void
663 xsetsel(char *str)
665 setsel(str, CurrentTime);
668 void
669 brelease(XEvent *e)
671 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
672 mousereport(e);
673 return;
676 if (mouseaction(e, 1))
677 return;
678 if (e->xbutton.button == Button1)
679 mousesel(e, 1);
682 void
683 bmotion(XEvent *e)
685 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) {
686 mousereport(e);
687 return;
690 mousesel(e, 0);
693 void
694 cresize(int width, int height)
696 int col, row;
698 if (width != 0)
699 win.w = width;
700 if (height != 0)
701 win.h = height;
703 col = (win.w - 2 * borderpx) / win.cw;
704 row = (win.h - 2 * borderpx) / win.ch;
705 col = MAX(1, col);
706 row = MAX(1, row);
708 tresize(col, row);
709 xresize(col, row);
710 ttyresize(win.tw, win.th);
713 void
714 xresize(int col, int row)
716 win.tw = col * win.cw;
717 win.th = row * win.ch;
719 XFreePixmap(xw.dpy, xw.buf);
720 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
721 DefaultDepth(xw.dpy, xw.scr));
722 XftDrawChange(xw.draw, xw.buf);
723 xclear(0, 0, win.w, win.h);
725 /* resize to new width */
726 xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
729 ushort
730 sixd_to_16bit(int x)
732 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
736 xloadcolor(int i, const char *name, Color *ncolor)
738 XRenderColor color = { .alpha = 0xffff };
740 if (!name) {
741 if (BETWEEN(i, 16, 255)) { /* 256 color */
742 if (i < 6*6*6+16) { /* same colors as xterm */
743 color.red = sixd_to_16bit( ((i-16)/36)%6 );
744 color.green = sixd_to_16bit( ((i-16)/6) %6 );
745 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
746 } else { /* greyscale */
747 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
748 color.green = color.blue = color.red;
750 return XftColorAllocValue(xw.dpy, xw.vis,
751 xw.cmap, &color, ncolor);
752 } else
753 name = colorname[i];
756 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
759 void
760 xloadcols(void)
762 int i;
763 static int loaded;
764 Color *cp;
766 if (loaded) {
767 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
768 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
769 } else {
770 dc.collen = MAX(LEN(colorname), 256);
771 dc.col = xmalloc(dc.collen * sizeof(Color));
774 for (i = 0; i < dc.collen; i++)
775 if (!xloadcolor(i, NULL, &dc.col[i])) {
776 if (colorname[i])
777 die("could not allocate color '%s'\n", colorname[i]);
778 else
779 die("could not allocate color %d\n", i);
781 loaded = 1;
785 xsetcolorname(int x, const char *name)
787 Color ncolor;
789 if (!BETWEEN(x, 0, dc.collen))
790 return 1;
792 if (!xloadcolor(x, name, &ncolor))
793 return 1;
795 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
796 dc.col[x] = ncolor;
798 return 0;
802 * Absolute coordinates.
804 void
805 xclear(int x1, int y1, int x2, int y2)
807 XftDrawRect(xw.draw,
808 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
809 x1, y1, x2-x1, y2-y1);
812 void
813 xhints(void)
815 XClassHint class = {opt_name ? opt_name : termname,
816 opt_class ? opt_class : termname};
817 XWMHints wm = {.flags = InputHint, .input = 1};
818 XSizeHints *sizeh;
820 sizeh = XAllocSizeHints();
822 sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
823 sizeh->height = win.h;
824 sizeh->width = win.w;
825 sizeh->height_inc = win.ch;
826 sizeh->width_inc = win.cw;
827 sizeh->base_height = 2 * borderpx;
828 sizeh->base_width = 2 * borderpx;
829 sizeh->min_height = win.ch + 2 * borderpx;
830 sizeh->min_width = win.cw + 2 * borderpx;
831 if (xw.isfixed) {
832 sizeh->flags |= PMaxSize;
833 sizeh->min_width = sizeh->max_width = win.w;
834 sizeh->min_height = sizeh->max_height = win.h;
836 if (xw.gm & (XValue|YValue)) {
837 sizeh->flags |= USPosition | PWinGravity;
838 sizeh->x = xw.l;
839 sizeh->y = xw.t;
840 sizeh->win_gravity = xgeommasktogravity(xw.gm);
843 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
844 &class);
845 XFree(sizeh);
849 xgeommasktogravity(int mask)
851 switch (mask & (XNegative|YNegative)) {
852 case 0:
853 return NorthWestGravity;
854 case XNegative:
855 return NorthEastGravity;
856 case YNegative:
857 return SouthWestGravity;
860 return SouthEastGravity;
864 xloadfont(Font *f, FcPattern *pattern)
866 FcPattern *configured;
867 FcPattern *match;
868 FcResult result;
869 XGlyphInfo extents;
870 int wantattr, haveattr;
873 * Manually configure instead of calling XftMatchFont
874 * so that we can use the configured pattern for
875 * "missing glyph" lookups.
877 configured = FcPatternDuplicate(pattern);
878 if (!configured)
879 return 1;
881 FcConfigSubstitute(NULL, configured, FcMatchPattern);
882 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
884 match = FcFontMatch(NULL, configured, &result);
885 if (!match) {
886 FcPatternDestroy(configured);
887 return 1;
890 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
891 FcPatternDestroy(configured);
892 FcPatternDestroy(match);
893 return 1;
896 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
897 XftResultMatch)) {
899 * Check if xft was unable to find a font with the appropriate
900 * slant but gave us one anyway. Try to mitigate.
902 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
903 &haveattr) != XftResultMatch) || haveattr < wantattr) {
904 f->badslant = 1;
905 fputs("font slant does not match\n", stderr);
909 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
910 XftResultMatch)) {
911 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
912 &haveattr) != XftResultMatch) || haveattr != wantattr) {
913 f->badweight = 1;
914 fputs("font weight does not match\n", stderr);
918 XftTextExtentsUtf8(xw.dpy, f->match,
919 (const FcChar8 *) ascii_printable,
920 strlen(ascii_printable), &extents);
922 f->set = NULL;
923 f->pattern = configured;
925 f->ascent = f->match->ascent;
926 f->descent = f->match->descent;
927 f->lbearing = 0;
928 f->rbearing = f->match->max_advance_width;
930 f->height = f->ascent + f->descent;
931 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
933 return 0;
936 void
937 xloadfonts(char *fontstr, double fontsize)
939 FcPattern *pattern;
940 double fontval;
942 if (fontstr[0] == '-')
943 pattern = XftXlfdParse(fontstr, False, False);
944 else
945 pattern = FcNameParse((FcChar8 *)fontstr);
947 if (!pattern)
948 die("can't open font %s\n", fontstr);
950 if (fontsize > 1) {
951 FcPatternDel(pattern, FC_PIXEL_SIZE);
952 FcPatternDel(pattern, FC_SIZE);
953 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
954 usedfontsize = fontsize;
955 } else {
956 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
957 FcResultMatch) {
958 usedfontsize = fontval;
959 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
960 FcResultMatch) {
961 usedfontsize = -1;
962 } else {
964 * Default font size is 12, if none given. This is to
965 * have a known usedfontsize value.
967 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
968 usedfontsize = 12;
970 defaultfontsize = usedfontsize;
973 if (xloadfont(&dc.font, pattern))
974 die("can't open font %s\n", fontstr);
976 if (usedfontsize < 0) {
977 FcPatternGetDouble(dc.font.match->pattern,
978 FC_PIXEL_SIZE, 0, &fontval);
979 usedfontsize = fontval;
980 if (fontsize == 0)
981 defaultfontsize = fontval;
984 /* Setting character width and height. */
985 win.cw = ceilf(dc.font.width * cwscale);
986 win.ch = ceilf(dc.font.height * chscale);
988 FcPatternDel(pattern, FC_SLANT);
989 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
990 if (xloadfont(&dc.ifont, pattern))
991 die("can't open font %s\n", fontstr);
993 FcPatternDel(pattern, FC_WEIGHT);
994 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
995 if (xloadfont(&dc.ibfont, pattern))
996 die("can't open font %s\n", fontstr);
998 FcPatternDel(pattern, FC_SLANT);
999 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
1000 if (xloadfont(&dc.bfont, pattern))
1001 die("can't open font %s\n", fontstr);
1003 FcPatternDestroy(pattern);
1006 void
1007 xunloadfont(Font *f)
1009 XftFontClose(xw.dpy, f->match);
1010 FcPatternDestroy(f->pattern);
1011 if (f->set)
1012 FcFontSetDestroy(f->set);
1015 void
1016 xunloadfonts(void)
1018 /* Free the loaded fonts in the font cache. */
1019 while (frclen > 0)
1020 XftFontClose(xw.dpy, frc[--frclen].font);
1022 xunloadfont(&dc.font);
1023 xunloadfont(&dc.bfont);
1024 xunloadfont(&dc.ifont);
1025 xunloadfont(&dc.ibfont);
1028 void
1029 ximopen(Display *dpy)
1031 XIMCallback destroy = { .client_data = NULL, .callback = ximdestroy };
1033 if ((xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
1034 XSetLocaleModifiers("@im=local");
1035 if ((xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
1036 XSetLocaleModifiers("@im=");
1037 if ((xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL)
1038 die("XOpenIM failed. Could not open input device.\n");
1041 if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &destroy, NULL) != NULL)
1042 die("XSetIMValues failed. Could not set input method value.\n");
1043 xw.xic = XCreateIC(xw.ime.xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
1044 XNClientWindow, xw.win, XNFocusWindow, xw.win, NULL);
1045 if (xw.xic == NULL)
1046 die("XCreateIC failed. Could not obtain input method.\n");
1048 xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
1049 NULL);
1052 void
1053 ximinstantiate(Display *dpy, XPointer client, XPointer call)
1055 ximopen(dpy);
1056 XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1057 ximinstantiate, NULL);
1060 void
1061 ximdestroy(XIM xim, XPointer client, XPointer call)
1063 xw.ime.xim = NULL;
1064 xw.ime.xic = NULL;
1065 XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
1066 ximinstantiate, NULL);
1067 XFree(xw.ime.spotlist);
1070 void
1071 xinit(int cols, int rows)
1073 XGCValues gcvalues;
1074 Cursor cursor;
1075 Window parent;
1076 pid_t thispid = getpid();
1077 XColor xmousefg, xmousebg;
1079 if (!(xw.dpy = XOpenDisplay(NULL)))
1080 die("can't open display\n");
1081 xw.scr = XDefaultScreen(xw.dpy);
1082 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
1084 /* font */
1085 if (!FcInit())
1086 die("could not init fontconfig.\n");
1088 usedfont = (opt_font == NULL)? font : opt_font;
1089 xloadfonts(usedfont, 0);
1091 /* colors */
1092 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1093 xloadcols();
1095 /* adjust fixed window geometry */
1096 win.w = 2 * borderpx + cols * win.cw;
1097 win.h = 2 * borderpx + rows * win.ch;
1098 if (xw.gm & XNegative)
1099 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
1100 if (xw.gm & YNegative)
1101 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
1103 /* Events */
1104 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
1105 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
1106 xw.attrs.bit_gravity = NorthWestGravity;
1107 xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
1108 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1109 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1110 xw.attrs.colormap = xw.cmap;
1112 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1113 parent = XRootWindow(xw.dpy, xw.scr);
1114 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1115 win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1116 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1117 | CWEventMask | CWColormap, &xw.attrs);
1119 memset(&gcvalues, 0, sizeof(gcvalues));
1120 gcvalues.graphics_exposures = False;
1121 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
1122 &gcvalues);
1123 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
1124 DefaultDepth(xw.dpy, xw.scr));
1125 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1126 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1128 /* font spec buffer */
1129 xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1131 /* Xft rendering context */
1132 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1134 /* input methods */
1135 ximopen(xw.dpy);
1137 /* white cursor, black outline */
1138 cursor = XCreateFontCursor(xw.dpy, mouseshape);
1139 XDefineCursor(xw.dpy, xw.win, cursor);
1141 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1142 xmousefg.red = 0xffff;
1143 xmousefg.green = 0xffff;
1144 xmousefg.blue = 0xffff;
1147 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1148 xmousebg.red = 0x0000;
1149 xmousebg.green = 0x0000;
1150 xmousebg.blue = 0x0000;
1153 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1155 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1156 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1157 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1158 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1160 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1161 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1162 PropModeReplace, (uchar *)&thispid, 1);
1164 win.mode = MODE_NUMLOCK;
1165 resettitle();
1166 xhints();
1167 XMapWindow(xw.dpy, xw.win);
1168 XSync(xw.dpy, False);
1170 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1171 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1172 xsel.primary = NULL;
1173 xsel.clipboard = NULL;
1174 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1175 if (xsel.xtarget == None)
1176 xsel.xtarget = XA_STRING;
1180 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1182 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1183 ushort mode, prevmode = USHRT_MAX;
1184 Font *font = &dc.font;
1185 int frcflags = FRC_NORMAL;
1186 float runewidth = win.cw;
1187 Rune rune;
1188 FT_UInt glyphidx;
1189 FcResult fcres;
1190 FcPattern *fcpattern, *fontpattern;
1191 FcFontSet *fcsets[] = { NULL };
1192 FcCharSet *fccharset;
1193 int i, f, numspecs = 0;
1195 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1196 /* Fetch rune and mode for current glyph. */
1197 rune = glyphs[i].u;
1198 mode = glyphs[i].mode;
1200 /* Skip dummy wide-character spacing. */
1201 if (mode == ATTR_WDUMMY)
1202 continue;
1204 /* Determine font for glyph if different from previous glyph. */
1205 if (prevmode != mode) {
1206 prevmode = mode;
1207 font = &dc.font;
1208 frcflags = FRC_NORMAL;
1209 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1210 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1211 font = &dc.ibfont;
1212 frcflags = FRC_ITALICBOLD;
1213 } else if (mode & ATTR_ITALIC) {
1214 font = &dc.ifont;
1215 frcflags = FRC_ITALIC;
1216 } else if (mode & ATTR_BOLD) {
1217 font = &dc.bfont;
1218 frcflags = FRC_BOLD;
1220 yp = winy + font->ascent;
1223 /* Lookup character index with default font. */
1224 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1225 if (glyphidx) {
1226 specs[numspecs].font = font->match;
1227 specs[numspecs].glyph = glyphidx;
1228 specs[numspecs].x = (short)xp;
1229 specs[numspecs].y = (short)yp;
1230 xp += runewidth;
1231 numspecs++;
1232 continue;
1235 /* Fallback on font cache, search the font cache for match. */
1236 for (f = 0; f < frclen; f++) {
1237 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1238 /* Everything correct. */
1239 if (glyphidx && frc[f].flags == frcflags)
1240 break;
1241 /* We got a default font for a not found glyph. */
1242 if (!glyphidx && frc[f].flags == frcflags
1243 && frc[f].unicodep == rune) {
1244 break;
1248 /* Nothing was found. Use fontconfig to find matching font. */
1249 if (f >= frclen) {
1250 if (!font->set)
1251 font->set = FcFontSort(0, font->pattern,
1252 1, 0, &fcres);
1253 fcsets[0] = font->set;
1256 * Nothing was found in the cache. Now use
1257 * some dozen of Fontconfig calls to get the
1258 * font for one single character.
1260 * Xft and fontconfig are design failures.
1262 fcpattern = FcPatternDuplicate(font->pattern);
1263 fccharset = FcCharSetCreate();
1265 FcCharSetAddChar(fccharset, rune);
1266 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1267 fccharset);
1268 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1270 FcConfigSubstitute(0, fcpattern,
1271 FcMatchPattern);
1272 FcDefaultSubstitute(fcpattern);
1274 fontpattern = FcFontSetMatch(0, fcsets, 1,
1275 fcpattern, &fcres);
1277 /* Allocate memory for the new cache entry. */
1278 if (frclen >= frccap) {
1279 frccap += 16;
1280 frc = xrealloc(frc, frccap * sizeof(Fontcache));
1283 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1284 fontpattern);
1285 if (!frc[frclen].font)
1286 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1287 strerror(errno));
1288 frc[frclen].flags = frcflags;
1289 frc[frclen].unicodep = rune;
1291 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1293 f = frclen;
1294 frclen++;
1296 FcPatternDestroy(fcpattern);
1297 FcCharSetDestroy(fccharset);
1300 specs[numspecs].font = frc[f].font;
1301 specs[numspecs].glyph = glyphidx;
1302 specs[numspecs].x = (short)xp;
1303 specs[numspecs].y = (short)yp;
1304 xp += runewidth;
1305 numspecs++;
1308 return numspecs;
1311 void
1312 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1314 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1315 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1316 width = charlen * win.cw;
1317 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1318 XRenderColor colfg, colbg;
1319 XRectangle r;
1321 /* Fallback on color display for attributes not supported by the font */
1322 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1323 if (dc.ibfont.badslant || dc.ibfont.badweight)
1324 base.fg = defaultattr;
1325 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1326 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1327 base.fg = defaultattr;
1330 if (IS_TRUECOL(base.fg)) {
1331 colfg.alpha = 0xffff;
1332 colfg.red = TRUERED(base.fg);
1333 colfg.green = TRUEGREEN(base.fg);
1334 colfg.blue = TRUEBLUE(base.fg);
1335 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1336 fg = &truefg;
1337 } else {
1338 fg = &dc.col[base.fg];
1341 if (IS_TRUECOL(base.bg)) {
1342 colbg.alpha = 0xffff;
1343 colbg.green = TRUEGREEN(base.bg);
1344 colbg.red = TRUERED(base.bg);
1345 colbg.blue = TRUEBLUE(base.bg);
1346 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1347 bg = &truebg;
1348 } else {
1349 bg = &dc.col[base.bg];
1352 /* Change basic system colors [0-7] to bright system colors [8-15] */
1353 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1354 fg = &dc.col[base.fg + 8];
1356 if (IS_SET(MODE_REVERSE)) {
1357 if (fg == &dc.col[defaultfg]) {
1358 fg = &dc.col[defaultbg];
1359 } else {
1360 colfg.red = ~fg->color.red;
1361 colfg.green = ~fg->color.green;
1362 colfg.blue = ~fg->color.blue;
1363 colfg.alpha = fg->color.alpha;
1364 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1365 &revfg);
1366 fg = &revfg;
1369 if (bg == &dc.col[defaultbg]) {
1370 bg = &dc.col[defaultfg];
1371 } else {
1372 colbg.red = ~bg->color.red;
1373 colbg.green = ~bg->color.green;
1374 colbg.blue = ~bg->color.blue;
1375 colbg.alpha = bg->color.alpha;
1376 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1377 &revbg);
1378 bg = &revbg;
1382 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1383 colfg.red = fg->color.red / 2;
1384 colfg.green = fg->color.green / 2;
1385 colfg.blue = fg->color.blue / 2;
1386 colfg.alpha = fg->color.alpha;
1387 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1388 fg = &revfg;
1391 if (base.mode & ATTR_REVERSE) {
1392 temp = fg;
1393 fg = bg;
1394 bg = temp;
1397 if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
1398 fg = bg;
1400 if (base.mode & ATTR_INVISIBLE)
1401 fg = bg;
1403 /* Intelligent cleaning up of the borders. */
1404 if (x == 0) {
1405 xclear(0, (y == 0)? 0 : winy, borderpx,
1406 winy + win.ch +
1407 ((winy + win.ch >= borderpx + win.th)? win.h : 0));
1409 if (winx + width >= borderpx + win.tw) {
1410 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1411 ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
1413 if (y == 0)
1414 xclear(winx, 0, winx + width, borderpx);
1415 if (winy + win.ch >= borderpx + win.th)
1416 xclear(winx, winy + win.ch, winx + width, win.h);
1418 /* Clean up the region we want to draw to. */
1419 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1421 /* Set the clip region because Xft is sometimes dirty. */
1422 r.x = 0;
1423 r.y = 0;
1424 r.height = win.ch;
1425 r.width = width;
1426 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1428 /* Render the glyphs. */
1429 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1431 /* Render underline and strikethrough. */
1432 if (base.mode & ATTR_UNDERLINE) {
1433 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1434 width, 1);
1437 if (base.mode & ATTR_STRUCK) {
1438 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1439 width, 1);
1442 /* Reset clip to none. */
1443 XftDrawSetClip(xw.draw, 0);
1446 void
1447 xdrawglyph(Glyph g, int x, int y)
1449 int numspecs;
1450 XftGlyphFontSpec spec;
1452 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1453 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1456 void
1457 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
1459 Color drawcol;
1461 /* remove the old cursor */
1462 if (selected(ox, oy))
1463 og.mode ^= ATTR_REVERSE;
1464 xdrawglyph(og, ox, oy);
1466 if (IS_SET(MODE_HIDE))
1467 return;
1470 * Select the right color for the right mode.
1472 g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
1474 if (IS_SET(MODE_REVERSE)) {
1475 g.mode |= ATTR_REVERSE;
1476 g.bg = defaultfg;
1477 if (selected(cx, cy)) {
1478 drawcol = dc.col[defaultcs];
1479 g.fg = defaultrcs;
1480 } else {
1481 drawcol = dc.col[defaultrcs];
1482 g.fg = defaultcs;
1484 } else {
1485 if (selected(cx, cy)) {
1486 g.fg = defaultfg;
1487 g.bg = defaultrcs;
1488 } else {
1489 g.fg = defaultbg;
1490 g.bg = defaultcs;
1492 drawcol = dc.col[g.bg];
1495 /* draw the new one */
1496 if (IS_SET(MODE_FOCUSED)) {
1497 switch (win.cursor) {
1498 case 7: /* st extension: snowman (U+2603) */
1499 g.u = 0x2603;
1500 case 0: /* Blinking Block */
1501 case 1: /* Blinking Block (Default) */
1502 case 2: /* Steady Block */
1503 xdrawglyph(g, cx, cy);
1504 break;
1505 case 3: /* Blinking Underline */
1506 case 4: /* Steady Underline */
1507 XftDrawRect(xw.draw, &drawcol,
1508 borderpx + cx * win.cw,
1509 borderpx + (cy + 1) * win.ch - \
1510 cursorthickness,
1511 win.cw, cursorthickness);
1512 break;
1513 case 5: /* Blinking bar */
1514 case 6: /* Steady bar */
1515 XftDrawRect(xw.draw, &drawcol,
1516 borderpx + cx * win.cw,
1517 borderpx + cy * win.ch,
1518 cursorthickness, win.ch);
1519 break;
1521 } else {
1522 XftDrawRect(xw.draw, &drawcol,
1523 borderpx + cx * win.cw,
1524 borderpx + cy * win.ch,
1525 win.cw - 1, 1);
1526 XftDrawRect(xw.draw, &drawcol,
1527 borderpx + cx * win.cw,
1528 borderpx + cy * win.ch,
1529 1, win.ch - 1);
1530 XftDrawRect(xw.draw, &drawcol,
1531 borderpx + (cx + 1) * win.cw - 1,
1532 borderpx + cy * win.ch,
1533 1, win.ch - 1);
1534 XftDrawRect(xw.draw, &drawcol,
1535 borderpx + cx * win.cw,
1536 borderpx + (cy + 1) * win.ch - 1,
1537 win.cw, 1);
1541 void
1542 xsetenv(void)
1544 char buf[sizeof(long) * 8 + 1];
1546 snprintf(buf, sizeof(buf), "%lu", xw.win);
1547 setenv("WINDOWID", buf, 1);
1550 void
1551 xsettitle(char *p)
1553 XTextProperty prop;
1554 DEFAULT(p, opt_title);
1556 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1557 &prop);
1558 XSetWMName(xw.dpy, xw.win, &prop);
1559 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1560 XFree(prop.value);
1564 xstartdraw(void)
1566 return IS_SET(MODE_VISIBLE);
1569 void
1570 xdrawline(Line line, int x1, int y1, int x2)
1572 int i, x, ox, numspecs;
1573 Glyph base, new;
1574 XftGlyphFontSpec *specs = xw.specbuf;
1576 numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
1577 i = ox = 0;
1578 for (x = x1; x < x2 && i < numspecs; x++) {
1579 new = line[x];
1580 if (new.mode == ATTR_WDUMMY)
1581 continue;
1582 if (selected(x, y1))
1583 new.mode ^= ATTR_REVERSE;
1584 if (i > 0 && ATTRCMP(base, new)) {
1585 xdrawglyphfontspecs(specs, base, i, ox, y1);
1586 specs += i;
1587 numspecs -= i;
1588 i = 0;
1590 if (i == 0) {
1591 ox = x;
1592 base = new;
1594 i++;
1596 if (i > 0)
1597 xdrawglyphfontspecs(specs, base, i, ox, y1);
1600 void
1601 xfinishdraw(void)
1603 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1604 win.h, 0, 0);
1605 XSetForeground(xw.dpy, dc.gc,
1606 dc.col[IS_SET(MODE_REVERSE)?
1607 defaultfg : defaultbg].pixel);
1610 void
1611 xximspot(int x, int y)
1613 if (xw.ime.xic == NULL)
1614 return;
1616 xw.ime.spot.x = borderpx + x * win.cw;
1617 xw.ime.spot.y = borderpx + (y + 1) * win.ch;
1619 XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
1622 void
1623 expose(XEvent *ev)
1625 redraw();
1628 void
1629 visibility(XEvent *ev)
1631 XVisibilityEvent *e = &ev->xvisibility;
1633 MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
1636 void
1637 unmap(XEvent *ev)
1639 win.mode &= ~MODE_VISIBLE;
1642 void
1643 xsetpointermotion(int set)
1645 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1646 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1649 void
1650 xsetmode(int set, unsigned int flags)
1652 int mode = win.mode;
1653 MODBIT(win.mode, set, flags);
1654 if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
1655 redraw();
1659 xsetcursor(int cursor)
1661 DEFAULT(cursor, 1);
1662 if (!BETWEEN(cursor, 0, 6))
1663 return 1;
1664 win.cursor = cursor;
1665 return 0;
1668 void
1669 xseturgency(int add)
1671 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1673 MODBIT(h->flags, add, XUrgencyHint);
1674 XSetWMHints(xw.dpy, xw.win, h);
1675 XFree(h);
1678 void
1679 xbell(void)
1681 if (!(IS_SET(MODE_FOCUSED)))
1682 xseturgency(1);
1683 if (bellvolume)
1684 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1687 void
1688 focus(XEvent *ev)
1690 XFocusChangeEvent *e = &ev->xfocus;
1692 if (e->mode == NotifyGrab)
1693 return;
1695 if (ev->type == FocusIn) {
1696 if (xw.ime.xic)
1697 XSetICFocus(xw.ime.xic);
1698 win.mode |= MODE_FOCUSED;
1699 xseturgency(0);
1700 if (IS_SET(MODE_FOCUS))
1701 ttywrite("\033[I", 3, 0);
1702 } else {
1703 if (xw.ime.xic)
1704 XUnsetICFocus(xw.ime.xic);
1705 win.mode &= ~MODE_FOCUSED;
1706 if (IS_SET(MODE_FOCUS))
1707 ttywrite("\033[O", 3, 0);
1712 match(uint mask, uint state)
1714 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1717 char*
1718 kmap(KeySym k, uint state)
1720 Key *kp;
1721 int i;
1723 /* Check for mapped keys out of X11 function keys. */
1724 for (i = 0; i < LEN(mappedkeys); i++) {
1725 if (mappedkeys[i] == k)
1726 break;
1728 if (i == LEN(mappedkeys)) {
1729 if ((k & 0xFFFF) < 0xFD00)
1730 return NULL;
1733 for (kp = key; kp < key + LEN(key); kp++) {
1734 if (kp->k != k)
1735 continue;
1737 if (!match(kp->mask, state))
1738 continue;
1740 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1741 continue;
1742 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
1743 continue;
1745 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1746 continue;
1748 return kp->s;
1751 return NULL;
1754 void
1755 kpress(XEvent *ev)
1757 XKeyEvent *e = &ev->xkey;
1758 KeySym ksym;
1759 char buf[64], *customkey;
1760 int len;
1761 Rune c;
1762 Status status;
1763 Shortcut *bp;
1765 if (IS_SET(MODE_KBDLOCK))
1766 return;
1768 len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
1769 /* 1. shortcuts */
1770 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
1771 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1772 bp->func(&(bp->arg));
1773 return;
1777 /* 2. custom keys from config.h */
1778 if ((customkey = kmap(ksym, e->state))) {
1779 ttywrite(customkey, strlen(customkey), 1);
1780 return;
1783 /* 3. composed string from input method */
1784 if (len == 0)
1785 return;
1786 if (len == 1 && e->state & Mod1Mask) {
1787 if (IS_SET(MODE_8BIT)) {
1788 if (*buf < 0177) {
1789 c = *buf | 0x80;
1790 len = utf8encode(c, buf);
1792 } else {
1793 buf[1] = buf[0];
1794 buf[0] = '\033';
1795 len = 2;
1798 ttywrite(buf, len, 1);
1801 void
1802 cmessage(XEvent *e)
1805 * See xembed specs
1806 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1808 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1809 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1810 win.mode |= MODE_FOCUSED;
1811 xseturgency(0);
1812 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1813 win.mode &= ~MODE_FOCUSED;
1815 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1816 ttyhangup();
1817 exit(0);
1821 void
1822 resize(XEvent *e)
1824 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1825 return;
1827 cresize(e->xconfigure.width, e->xconfigure.height);
1830 void
1831 run(void)
1833 XEvent ev;
1834 int w = win.w, h = win.h;
1835 fd_set rfd;
1836 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
1837 int ttyfd;
1838 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
1839 long deltatime;
1841 /* Waiting for window mapping */
1842 do {
1843 XNextEvent(xw.dpy, &ev);
1845 * This XFilterEvent call is required because of XOpenIM. It
1846 * does filter out the key event and some client message for
1847 * the input method too.
1849 if (XFilterEvent(&ev, None))
1850 continue;
1851 if (ev.type == ConfigureNotify) {
1852 w = ev.xconfigure.width;
1853 h = ev.xconfigure.height;
1855 } while (ev.type != MapNotify);
1857 ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
1858 cresize(w, h);
1860 clock_gettime(CLOCK_MONOTONIC, &last);
1861 lastblink = last;
1863 for (xev = actionfps;;) {
1864 FD_ZERO(&rfd);
1865 FD_SET(ttyfd, &rfd);
1866 FD_SET(xfd, &rfd);
1868 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1869 if (errno == EINTR)
1870 continue;
1871 die("select failed: %s\n", strerror(errno));
1873 if (FD_ISSET(ttyfd, &rfd)) {
1874 ttyread();
1875 if (blinktimeout) {
1876 blinkset = tattrset(ATTR_BLINK);
1877 if (!blinkset)
1878 MODBIT(win.mode, 0, MODE_BLINK);
1882 if (FD_ISSET(xfd, &rfd))
1883 xev = actionfps;
1885 clock_gettime(CLOCK_MONOTONIC, &now);
1886 drawtimeout.tv_sec = 0;
1887 drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
1888 tv = &drawtimeout;
1890 dodraw = 0;
1891 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
1892 tsetdirtattr(ATTR_BLINK);
1893 win.mode ^= MODE_BLINK;
1894 lastblink = now;
1895 dodraw = 1;
1897 deltatime = TIMEDIFF(now, last);
1898 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
1899 dodraw = 1;
1900 last = now;
1903 if (dodraw) {
1904 while (XPending(xw.dpy)) {
1905 XNextEvent(xw.dpy, &ev);
1906 if (XFilterEvent(&ev, None))
1907 continue;
1908 if (handler[ev.type])
1909 (handler[ev.type])(&ev);
1912 draw();
1913 XFlush(xw.dpy);
1915 if (xev && !FD_ISSET(xfd, &rfd))
1916 xev--;
1917 if (!FD_ISSET(ttyfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
1918 if (blinkset) {
1919 if (TIMEDIFF(now, lastblink) \
1920 > blinktimeout) {
1921 drawtimeout.tv_nsec = 1000;
1922 } else {
1923 drawtimeout.tv_nsec = (1E6 * \
1924 (blinktimeout - \
1925 TIMEDIFF(now,
1926 lastblink)));
1928 drawtimeout.tv_sec = \
1929 drawtimeout.tv_nsec / 1E9;
1930 drawtimeout.tv_nsec %= (long)1E9;
1931 } else {
1932 tv = NULL;
1939 void
1940 usage(void)
1942 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
1943 " [-n name] [-o file]\n"
1944 " [-T title] [-t title] [-w windowid]"
1945 " [[-e] command [args ...]]\n"
1946 " %s [-aiv] [-c class] [-f font] [-g geometry]"
1947 " [-n name] [-o file]\n"
1948 " [-T title] [-t title] [-w windowid] -l line"
1949 " [stty_args ...]\n", argv0, argv0);
1953 main(int argc, char *argv[])
1955 xw.l = xw.t = 0;
1956 xw.isfixed = False;
1957 win.cursor = cursorshape;
1959 ARGBEGIN {
1960 case 'a':
1961 allowaltscreen = 0;
1962 break;
1963 case 'c':
1964 opt_class = EARGF(usage());
1965 break;
1966 case 'e':
1967 if (argc > 0)
1968 --argc, ++argv;
1969 goto run;
1970 case 'f':
1971 opt_font = EARGF(usage());
1972 break;
1973 case 'g':
1974 xw.gm = XParseGeometry(EARGF(usage()),
1975 &xw.l, &xw.t, &cols, &rows);
1976 break;
1977 case 'i':
1978 xw.isfixed = 1;
1979 break;
1980 case 'o':
1981 opt_io = EARGF(usage());
1982 break;
1983 case 'l':
1984 opt_line = EARGF(usage());
1985 break;
1986 case 'n':
1987 opt_name = EARGF(usage());
1988 break;
1989 case 't':
1990 case 'T':
1991 opt_title = EARGF(usage());
1992 break;
1993 case 'w':
1994 opt_embed = EARGF(usage());
1995 break;
1996 case 'v':
1997 die("%s " VERSION "\n", argv0);
1998 break;
1999 default:
2000 usage();
2001 } ARGEND;
2003 run:
2004 if (argc > 0) /* eat all remaining arguments */
2005 opt_cmd = argv;
2007 if (!opt_title)
2008 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
2010 setlocale(LC_CTYPE, "");
2011 XSetLocaleModifiers("");
2012 cols = MAX(cols, 1);
2013 rows = MAX(rows, 1);
2014 tnew(cols, rows);
2015 xinit(cols, rows);
2016 xsetenv();
2017 selinit();
2018 run();
2020 return 0;