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