my config
[azarus-st.git] / x.c
blob0562571d396a14242dbc5fff34d62900457a38b0
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 /* alpha */
52 #define OPAQUE 0Xff
53 #define USE_ARGB (alpha != OPAQUE && opt_embed == NULL)
55 /* function definitions used in config.h */
56 static void clipcopy(const Arg *);
57 static void clippaste(const Arg *);
58 static void numlock(const Arg *);
59 static void selpaste(const Arg *);
60 static void zoom(const Arg *);
61 static void zoomabs(const Arg *);
62 static void zoomreset(const Arg *);
64 /* config.h for applying patches and the configuration. */
65 #include "config.h"
67 /* XEMBED messages */
68 #define XEMBED_FOCUS_IN 4
69 #define XEMBED_FOCUS_OUT 5
71 /* macros */
72 #define IS_SET(flag) ((win.mode & (flag)) != 0)
73 #define TRUERED(x) (((x) & 0xff0000) >> 8)
74 #define TRUEGREEN(x) (((x) & 0xff00))
75 #define TRUEBLUE(x) (((x) & 0xff) << 8)
77 typedef XftDraw *Draw;
78 typedef XftColor Color;
79 typedef XftGlyphFontSpec GlyphFontSpec;
81 /* Purely graphic info */
82 typedef struct {
83 int tw, th; /* tty width and height */
84 int w, h; /* window width and height */
85 int ch; /* char height */
86 int cw; /* char width */
87 int mode; /* window state/mode flags */
88 int cursor; /* cursor style */
89 } TermWindow;
91 typedef struct {
92 Display *dpy;
93 Colormap cmap;
94 Window win;
95 Drawable buf;
96 GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
97 Atom xembed, wmdeletewin, netwmname, netwmpid;
98 XIM xim;
99 XIC xic;
100 Draw draw;
101 Visual *vis;
102 XSetWindowAttributes attrs;
103 int scr;
104 int isfixed; /* is fixed geometry? */
105 int depth; /* bit depth */
106 int l, t; /* left and top offset */
107 int gm; /* geometry mask */
108 } XWindow;
110 typedef struct {
111 Atom xtarget;
112 char *primary, *clipboard;
113 struct timespec tclick1;
114 struct timespec tclick2;
115 } XSelection;
117 /* Font structure */
118 #define Font Font_
119 typedef struct {
120 int height;
121 int width;
122 int ascent;
123 int descent;
124 int badslant;
125 int badweight;
126 short lbearing;
127 short rbearing;
128 XftFont *match;
129 FcFontSet *set;
130 FcPattern *pattern;
131 } Font;
133 /* Drawing Context */
134 typedef struct {
135 Color *col;
136 size_t collen;
137 Font font, bfont, ifont, ibfont;
138 GC gc;
139 } DC;
141 static inline ushort sixd_to_16bit(int);
142 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
143 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
144 static void xdrawglyph(Glyph, int, int);
145 static void xclear(int, int, int, int);
146 static int xgeommasktogravity(int);
147 static void xinit(int, int);
148 static void cresize(int, int);
149 static void xresize(int, int);
150 static void xhints(void);
151 static int xloadcolor(int, const char *, Color *);
152 static int xloadfont(Font *, FcPattern *);
153 static void xloadfonts(char *, double);
154 static void xunloadfont(Font *);
155 static void xunloadfonts(void);
156 static void xsetenv(void);
157 static void xseturgency(int);
158 static int evcol(XEvent *);
159 static int evrow(XEvent *);
161 static void expose(XEvent *);
162 static void visibility(XEvent *);
163 static void unmap(XEvent *);
164 static void kpress(XEvent *);
165 static void cmessage(XEvent *);
166 static void resize(XEvent *);
167 static void focus(XEvent *);
168 static void brelease(XEvent *);
169 static void bpress(XEvent *);
170 static void bmotion(XEvent *);
171 static void propnotify(XEvent *);
172 static void selnotify(XEvent *);
173 static void selclear_(XEvent *);
174 static void selrequest(XEvent *);
175 static void setsel(char *, Time);
176 static void mousesel(XEvent *, int);
177 static void mousereport(XEvent *);
178 static char *kmap(KeySym, uint);
179 static int match(uint, uint);
181 static void run(void);
182 static void usage(void);
184 static void (*handler[LASTEvent])(XEvent *) = {
185 [KeyPress] = kpress,
186 [ClientMessage] = cmessage,
187 [ConfigureNotify] = resize,
188 [VisibilityNotify] = visibility,
189 [UnmapNotify] = unmap,
190 [Expose] = expose,
191 [FocusIn] = focus,
192 [FocusOut] = focus,
193 [MotionNotify] = bmotion,
194 [ButtonPress] = bpress,
195 [ButtonRelease] = brelease,
197 * Uncomment if you want the selection to disappear when you select something
198 * different in another window.
200 /* [SelectionClear] = selclear_, */
201 [SelectionNotify] = selnotify,
203 * PropertyNotify is only turned on when there is some INCR transfer happening
204 * for the selection retrieval.
206 [PropertyNotify] = propnotify,
207 [SelectionRequest] = selrequest,
210 /* Globals */
211 static DC dc;
212 static XWindow xw;
213 static XSelection xsel;
214 static TermWindow win;
216 /* Font Ring Cache */
217 enum {
218 FRC_NORMAL,
219 FRC_ITALIC,
220 FRC_BOLD,
221 FRC_ITALICBOLD
224 typedef struct {
225 XftFont *font;
226 int flags;
227 Rune unicodep;
228 } Fontcache;
230 /* Fontcache is an array now. A new font will be appended to the array. */
231 static Fontcache frc[16];
232 static int frclen = 0;
233 static char *usedfont = NULL;
234 static double usedfontsize = 0;
235 static double defaultfontsize = 0;
237 static char *opt_class = NULL;
238 static char **opt_cmd = NULL;
239 static char *opt_embed = NULL;
240 static char *opt_font = NULL;
241 static char *opt_io = NULL;
242 static char *opt_line = NULL;
243 static char *opt_name = NULL;
244 static char *opt_title = NULL;
246 static int oldbutton = 3; /* button event on startup: 3 = release */
248 void
249 clipcopy(const Arg *dummy)
251 Atom clipboard;
253 free(xsel.clipboard);
254 xsel.clipboard = NULL;
256 if (xsel.primary != NULL) {
257 xsel.clipboard = xstrdup(xsel.primary);
258 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
259 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
263 void
264 clippaste(const Arg *dummy)
266 Atom clipboard;
268 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
269 XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
270 xw.win, CurrentTime);
273 void
274 selpaste(const Arg *dummy)
276 XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
277 xw.win, CurrentTime);
280 void
281 numlock(const Arg *dummy)
283 win.mode ^= MODE_NUMLOCK;
286 void
287 zoom(const Arg *arg)
289 Arg larg;
291 larg.f = usedfontsize + arg->f;
292 zoomabs(&larg);
295 void
296 zoomabs(const Arg *arg)
298 xunloadfonts();
299 xloadfonts(usedfont, arg->f);
300 cresize(0, 0);
301 redraw();
302 xhints();
305 void
306 zoomreset(const Arg *arg)
308 Arg larg;
310 if (defaultfontsize > 0) {
311 larg.f = defaultfontsize;
312 zoomabs(&larg);
317 evcol(XEvent *e)
319 int x = e->xbutton.x - borderpx;
320 LIMIT(x, 0, win.tw - 1);
321 return x / win.cw;
325 evrow(XEvent *e)
327 int y = e->xbutton.y - borderpx;
328 LIMIT(y, 0, win.th - 1);
329 return y / win.ch;
332 void
333 mousesel(XEvent *e, int done)
335 int type, seltype = SEL_REGULAR;
336 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
338 for (type = 1; type < LEN(selmasks); ++type) {
339 if (match(selmasks[type], state)) {
340 seltype = type;
341 break;
344 selextend(evcol(e), evrow(e), seltype, done);
345 if (done)
346 setsel(getsel(), e->xbutton.time);
349 void
350 mousereport(XEvent *e)
352 int len, x = evcol(e), y = evrow(e),
353 button = e->xbutton.button, state = e->xbutton.state;
354 char buf[40];
355 static int ox, oy;
357 /* from urxvt */
358 if (e->xbutton.type == MotionNotify) {
359 if (x == ox && y == oy)
360 return;
361 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
362 return;
363 /* MOUSE_MOTION: no reporting if no button is pressed */
364 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
365 return;
367 button = oldbutton + 32;
368 ox = x;
369 oy = y;
370 } else {
371 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
372 button = 3;
373 } else {
374 button -= Button1;
375 if (button >= 3)
376 button += 64 - 3;
378 if (e->xbutton.type == ButtonPress) {
379 oldbutton = button;
380 ox = x;
381 oy = y;
382 } else if (e->xbutton.type == ButtonRelease) {
383 oldbutton = 3;
384 /* MODE_MOUSEX10: no button release reporting */
385 if (IS_SET(MODE_MOUSEX10))
386 return;
387 if (button == 64 || button == 65)
388 return;
392 if (!IS_SET(MODE_MOUSEX10)) {
393 button += ((state & ShiftMask ) ? 4 : 0)
394 + ((state & Mod4Mask ) ? 8 : 0)
395 + ((state & ControlMask) ? 16 : 0);
398 if (IS_SET(MODE_MOUSESGR)) {
399 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
400 button, x+1, y+1,
401 e->xbutton.type == ButtonRelease ? 'm' : 'M');
402 } else if (x < 223 && y < 223) {
403 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
404 32+button, 32+x+1, 32+y+1);
405 } else {
406 return;
409 ttywrite(buf, len, 0);
412 void
413 bpress(XEvent *e)
415 struct timespec now;
416 MouseShortcut *ms;
417 int snap;
419 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
420 mousereport(e);
421 return;
424 for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
425 if (e->xbutton.button == ms->b
426 && match(ms->mask, e->xbutton.state)) {
427 ttywrite(ms->s, strlen(ms->s), 1);
428 return;
432 if (e->xbutton.button == Button1) {
434 * If the user clicks below predefined timeouts specific
435 * snapping behaviour is exposed.
437 clock_gettime(CLOCK_MONOTONIC, &now);
438 if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
439 snap = SNAP_LINE;
440 } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
441 snap = SNAP_WORD;
442 } else {
443 snap = 0;
445 xsel.tclick2 = xsel.tclick1;
446 xsel.tclick1 = now;
448 selstart(evcol(e), evrow(e), snap);
452 void
453 propnotify(XEvent *e)
455 XPropertyEvent *xpev;
456 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
458 xpev = &e->xproperty;
459 if (xpev->state == PropertyNewValue &&
460 (xpev->atom == XA_PRIMARY ||
461 xpev->atom == clipboard)) {
462 selnotify(e);
466 void
467 selnotify(XEvent *e)
469 ulong nitems, ofs, rem;
470 int format;
471 uchar *data, *last, *repl;
472 Atom type, incratom, property = None;
474 incratom = XInternAtom(xw.dpy, "INCR", 0);
476 ofs = 0;
477 if (e->type == SelectionNotify)
478 property = e->xselection.property;
479 else if (e->type == PropertyNotify)
480 property = e->xproperty.atom;
482 if (property == None)
483 return;
485 do {
486 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
487 BUFSIZ/4, False, AnyPropertyType,
488 &type, &format, &nitems, &rem,
489 &data)) {
490 fprintf(stderr, "Clipboard allocation failed\n");
491 return;
494 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
496 * If there is some PropertyNotify with no data, then
497 * this is the signal of the selection owner that all
498 * data has been transferred. We won't need to receive
499 * PropertyNotify events anymore.
501 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
502 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
503 &xw.attrs);
506 if (type == incratom) {
508 * Activate the PropertyNotify events so we receive
509 * when the selection owner does send us the next
510 * chunk of data.
512 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
513 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
514 &xw.attrs);
517 * Deleting the property is the transfer start signal.
519 XDeleteProperty(xw.dpy, xw.win, (int)property);
520 continue;
524 * As seen in getsel:
525 * Line endings are inconsistent in the terminal and GUI world
526 * copy and pasting. When receiving some selection data,
527 * replace all '\n' with '\r'.
528 * FIXME: Fix the computer world.
530 repl = data;
531 last = data + nitems * format / 8;
532 while ((repl = memchr(repl, '\n', last - repl))) {
533 *repl++ = '\r';
536 if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
537 ttywrite("\033[200~", 6, 0);
538 ttywrite((char *)data, nitems * format / 8, 1);
539 if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
540 ttywrite("\033[201~", 6, 0);
541 XFree(data);
542 /* number of 32-bit chunks returned */
543 ofs += nitems * format / 32;
544 } while (rem > 0);
547 * Deleting the property again tells the selection owner to send the
548 * next data chunk in the property.
550 XDeleteProperty(xw.dpy, xw.win, (int)property);
553 void
554 xclipcopy(void)
556 clipcopy(NULL);
559 void
560 selclear_(XEvent *e)
562 selclear();
565 void
566 selrequest(XEvent *e)
568 XSelectionRequestEvent *xsre;
569 XSelectionEvent xev;
570 Atom xa_targets, string, clipboard;
571 char *seltext;
573 xsre = (XSelectionRequestEvent *) e;
574 xev.type = SelectionNotify;
575 xev.requestor = xsre->requestor;
576 xev.selection = xsre->selection;
577 xev.target = xsre->target;
578 xev.time = xsre->time;
579 if (xsre->property == None)
580 xsre->property = xsre->target;
582 /* reject */
583 xev.property = None;
585 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
586 if (xsre->target == xa_targets) {
587 /* respond with the supported type */
588 string = xsel.xtarget;
589 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
590 XA_ATOM, 32, PropModeReplace,
591 (uchar *) &string, 1);
592 xev.property = xsre->property;
593 } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
595 * xith XA_STRING non ascii characters may be incorrect in the
596 * requestor. It is not our problem, use utf8.
598 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
599 if (xsre->selection == XA_PRIMARY) {
600 seltext = xsel.primary;
601 } else if (xsre->selection == clipboard) {
602 seltext = xsel.clipboard;
603 } else {
604 fprintf(stderr,
605 "Unhandled clipboard selection 0x%lx\n",
606 xsre->selection);
607 return;
609 if (seltext != NULL) {
610 XChangeProperty(xsre->display, xsre->requestor,
611 xsre->property, xsre->target,
612 8, PropModeReplace,
613 (uchar *)seltext, strlen(seltext));
614 xev.property = xsre->property;
618 /* all done, send a notification to the listener */
619 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
620 fprintf(stderr, "Error sending SelectionNotify event\n");
623 void
624 setsel(char *str, Time t)
626 if (!str)
627 return;
629 free(xsel.primary);
630 xsel.primary = str;
632 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
633 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
634 selclear();
637 void
638 xsetsel(char *str)
640 setsel(str, CurrentTime);
643 void
644 brelease(XEvent *e)
646 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
647 mousereport(e);
648 return;
651 if (e->xbutton.button == Button2)
652 selpaste(NULL);
653 else if (e->xbutton.button == Button1)
654 mousesel(e, 1);
657 void
658 bmotion(XEvent *e)
660 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
661 mousereport(e);
662 return;
665 mousesel(e, 0);
668 void
669 cresize(int width, int height)
671 int col, row;
673 if (width != 0)
674 win.w = width;
675 if (height != 0)
676 win.h = height;
678 col = (win.w - 2 * borderpx) / win.cw;
679 row = (win.h - 2 * borderpx) / win.ch;
681 tresize(col, row);
682 xresize(col, row);
683 ttyresize(win.tw, win.th);
686 void
687 xresize(int col, int row)
689 win.tw = MAX(1, col * win.cw);
690 win.th = MAX(1, row * win.ch);
692 XFreePixmap(xw.dpy, xw.buf);
693 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
694 xw.depth);
695 XftDrawChange(xw.draw, xw.buf);
696 xclear(0, 0, win.w, win.h);
698 /* resize to new width */
699 xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
702 ushort
703 sixd_to_16bit(int x)
705 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
709 xloadcolor(int i, const char *name, Color *ncolor)
711 XRenderColor color = { .alpha = 0xffff };
713 if (!name) {
714 if (BETWEEN(i, 16, 255)) { /* 256 color */
715 if (i < 6*6*6+16) { /* same colors as xterm */
716 color.red = sixd_to_16bit( ((i-16)/36)%6 );
717 color.green = sixd_to_16bit( ((i-16)/6) %6 );
718 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
719 } else { /* greyscale */
720 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
721 color.green = color.blue = color.red;
723 return XftColorAllocValue(xw.dpy, xw.vis,
724 xw.cmap, &color, ncolor);
725 } else
726 name = colorname[i];
729 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
732 void
733 xloadcols(void)
735 int i;
736 static int loaded;
737 Color *cp;
739 dc.collen = MAX(LEN(colorname), 256);
740 dc.col = xmalloc(dc.collen * sizeof(Color));
742 if (loaded) {
743 for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
744 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
747 for (i = 0; i < dc.collen; i++)
748 if (!xloadcolor(i, NULL, &dc.col[i])) {
749 if (colorname[i])
750 die("could not allocate color '%s'\n", colorname[i]);
751 else
752 die("could not allocate color %d\n", i);
755 /* set alpha value of bg color */
756 if (USE_ARGB) {
757 dc.col[defaultbg].color.alpha = (0xffff * alpha) / OPAQUE;
758 dc.col[defaultbg].pixel &= 0x00111111;
759 dc.col[defaultbg].pixel |= alpha << 24;
761 loaded = 1;
765 xsetcolorname(int x, const char *name)
767 Color ncolor;
769 if (!BETWEEN(x, 0, dc.collen))
770 return 1;
773 if (!xloadcolor(x, name, &ncolor))
774 return 1;
776 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
777 dc.col[x] = ncolor;
779 return 0;
782 void
783 xtermclear(int col1, int row1, int col2, int row2)
785 XftDrawRect(xw.draw,
786 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
787 borderpx + col1 * win.cw,
788 borderpx + row1 * win.ch,
789 (col2-col1+1) * win.cw,
790 (row2-row1+1) * win.ch);
794 * Absolute coordinates.
796 void
797 xclear(int x1, int y1, int x2, int y2)
799 XftDrawRect(xw.draw,
800 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
801 x1, y1, x2-x1, y2-y1);
804 void
805 xhints(void)
807 XClassHint class = {opt_name ? opt_name : termname,
808 opt_class ? opt_class : termname};
809 XWMHints wm = {.flags = InputHint, .input = 1};
810 XSizeHints *sizeh;
812 sizeh = XAllocSizeHints();
814 sizeh->flags = PSize | PResizeInc | PBaseSize;
815 sizeh->height = win.h;
816 sizeh->width = win.w;
817 sizeh->height_inc = win.ch;
818 sizeh->width_inc = win.cw;
819 sizeh->base_height = 2 * borderpx;
820 sizeh->base_width = 2 * borderpx;
821 if (xw.isfixed) {
822 sizeh->flags |= PMaxSize | PMinSize;
823 sizeh->min_width = sizeh->max_width = win.w;
824 sizeh->min_height = sizeh->max_height = win.h;
826 if (xw.gm & (XValue|YValue)) {
827 sizeh->flags |= USPosition | PWinGravity;
828 sizeh->x = xw.l;
829 sizeh->y = xw.t;
830 sizeh->win_gravity = xgeommasktogravity(xw.gm);
833 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
834 &class);
835 XFree(sizeh);
839 xgeommasktogravity(int mask)
841 switch (mask & (XNegative|YNegative)) {
842 case 0:
843 return NorthWestGravity;
844 case XNegative:
845 return NorthEastGravity;
846 case YNegative:
847 return SouthWestGravity;
850 return SouthEastGravity;
854 xloadfont(Font *f, FcPattern *pattern)
856 FcPattern *configured;
857 FcPattern *match;
858 FcResult result;
859 XGlyphInfo extents;
860 int wantattr, haveattr;
863 * Manually configure instead of calling XftMatchFont
864 * so that we can use the configured pattern for
865 * "missing glyph" lookups.
867 configured = FcPatternDuplicate(pattern);
868 if (!configured)
869 return 1;
871 FcConfigSubstitute(NULL, configured, FcMatchPattern);
872 XftDefaultSubstitute(xw.dpy, xw.scr, configured);
874 match = FcFontMatch(NULL, configured, &result);
875 if (!match) {
876 FcPatternDestroy(configured);
877 return 1;
880 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
881 FcPatternDestroy(configured);
882 FcPatternDestroy(match);
883 return 1;
886 if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
887 XftResultMatch)) {
889 * Check if xft was unable to find a font with the appropriate
890 * slant but gave us one anyway. Try to mitigate.
892 if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
893 &haveattr) != XftResultMatch) || haveattr < wantattr) {
894 f->badslant = 1;
895 fputs("font slant does not match\n", stderr);
899 if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
900 XftResultMatch)) {
901 if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
902 &haveattr) != XftResultMatch) || haveattr != wantattr) {
903 f->badweight = 1;
904 fputs("font weight does not match\n", stderr);
908 XftTextExtentsUtf8(xw.dpy, f->match,
909 (const FcChar8 *) ascii_printable,
910 strlen(ascii_printable), &extents);
912 f->set = NULL;
913 f->pattern = configured;
915 f->ascent = f->match->ascent;
916 f->descent = f->match->descent;
917 f->lbearing = 0;
918 f->rbearing = f->match->max_advance_width;
920 f->height = f->ascent + f->descent;
921 f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
923 return 0;
926 void
927 xloadfonts(char *fontstr, double fontsize)
929 FcPattern *pattern;
930 double fontval;
932 if (fontstr[0] == '-')
933 pattern = XftXlfdParse(fontstr, False, False);
934 else
935 pattern = FcNameParse((FcChar8 *)fontstr);
937 if (!pattern)
938 die("can't open font %s\n", fontstr);
940 if (fontsize > 1) {
941 FcPatternDel(pattern, FC_PIXEL_SIZE);
942 FcPatternDel(pattern, FC_SIZE);
943 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
944 usedfontsize = fontsize;
945 } else {
946 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
947 FcResultMatch) {
948 usedfontsize = fontval;
949 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
950 FcResultMatch) {
951 usedfontsize = -1;
952 } else {
954 * Default font size is 12, if none given. This is to
955 * have a known usedfontsize value.
957 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
958 usedfontsize = 12;
960 defaultfontsize = usedfontsize;
963 if (xloadfont(&dc.font, pattern))
964 die("can't open font %s\n", fontstr);
966 if (usedfontsize < 0) {
967 FcPatternGetDouble(dc.font.match->pattern,
968 FC_PIXEL_SIZE, 0, &fontval);
969 usedfontsize = fontval;
970 if (fontsize == 0)
971 defaultfontsize = fontval;
974 /* Setting character width and height. */
975 win.cw = ceilf(dc.font.width * cwscale);
976 win.ch = ceilf(dc.font.height * chscale);
978 FcPatternDel(pattern, FC_SLANT);
979 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
980 if (xloadfont(&dc.ifont, pattern))
981 die("can't open font %s\n", fontstr);
983 FcPatternDel(pattern, FC_WEIGHT);
984 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
985 if (xloadfont(&dc.ibfont, pattern))
986 die("can't open font %s\n", fontstr);
988 FcPatternDel(pattern, FC_SLANT);
989 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
990 if (xloadfont(&dc.bfont, pattern))
991 die("can't open font %s\n", fontstr);
993 FcPatternDestroy(pattern);
996 void
997 xunloadfont(Font *f)
999 XftFontClose(xw.dpy, f->match);
1000 FcPatternDestroy(f->pattern);
1001 if (f->set)
1002 FcFontSetDestroy(f->set);
1005 void
1006 xunloadfonts(void)
1008 /* Free the loaded fonts in the font cache. */
1009 while (frclen > 0)
1010 XftFontClose(xw.dpy, frc[--frclen].font);
1012 xunloadfont(&dc.font);
1013 xunloadfont(&dc.bfont);
1014 xunloadfont(&dc.ifont);
1015 xunloadfont(&dc.ibfont);
1018 void
1019 xinit(int cols, int rows)
1021 XGCValues gcvalues;
1022 Cursor cursor;
1023 Window parent;
1024 pid_t thispid = getpid();
1025 XColor xmousefg, xmousebg;
1027 if (!(xw.dpy = XOpenDisplay(NULL)))
1028 die("can't open display\n");
1029 xw.scr = XDefaultScreen(xw.dpy);
1030 xw.depth = (USE_ARGB) ? 32: XDefaultDepth(xw.dpy, xw.scr);
1031 if (!USE_ARGB)
1032 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
1033 else {
1034 XVisualInfo *vis;
1035 XRenderPictFormat *fmt;
1036 int nvi;
1037 int i;
1039 XVisualInfo tpl = {
1040 .screen = xw.scr,
1041 .depth = 32,
1042 .class = TrueColor
1045 vis = XGetVisualInfo(xw.dpy,
1046 VisualScreenMask | VisualDepthMask | VisualClassMask,
1047 &tpl, &nvi);
1048 xw.vis = NULL;
1049 for (i = 0; i < nvi; i++) {
1050 fmt = XRenderFindVisualFormat(xw.dpy, vis[i].visual);
1051 if (fmt->type == PictTypeDirect && fmt->direct.alphaMask) {
1052 xw.vis = vis[i].visual;
1053 break;
1057 XFree(vis);
1059 if (!xw.vis) {
1060 fprintf(stderr, "Couldn't find ARGB visual.\n");
1061 exit(1);
1065 /* font */
1066 if (!FcInit())
1067 die("could not init fontconfig.\n");
1069 usedfont = (opt_font == NULL)? font : opt_font;
1070 xloadfonts(usedfont, 0);
1072 /* colors */
1073 if (!USE_ARGB)
1074 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1075 else
1076 xw.cmap = XCreateColormap(xw.dpy, XRootWindow(xw.dpy, xw.scr),
1077 xw.vis, None);
1078 xloadcols();
1080 /* adjust fixed window geometry */
1081 win.w = 2 * borderpx + cols * win.cw;
1082 win.h = 2 * borderpx + rows * win.ch;
1083 if (xw.gm & XNegative)
1084 xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
1085 if (xw.gm & YNegative)
1086 xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
1088 /* Events */
1089 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
1090 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
1091 xw.attrs.bit_gravity = NorthWestGravity;
1092 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
1093 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1094 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
1095 xw.attrs.colormap = xw.cmap;
1097 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
1098 parent = XRootWindow(xw.dpy, xw.scr);
1099 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
1100 win.w, win.h, 0, xw.depth, InputOutput,
1101 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
1102 | CWEventMask | CWColormap, &xw.attrs);
1104 memset(&gcvalues, 0, sizeof(gcvalues));
1105 gcvalues.graphics_exposures = False;
1106 xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h, xw.depth);
1107 dc.gc = XCreateGC(xw.dpy, (USE_ARGB) ? xw.buf: parent,
1108 GCGraphicsExposures, &gcvalues);
1109 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
1110 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
1112 /* font spec buffer */
1113 xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
1115 /* Xft rendering context */
1116 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
1118 /* input methods */
1119 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
1120 XSetLocaleModifiers("@im=local");
1121 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
1122 XSetLocaleModifiers("@im=");
1123 if ((xw.xim = XOpenIM(xw.dpy,
1124 NULL, NULL, NULL)) == NULL) {
1125 die("XOpenIM failed. Could not open input"
1126 " device.\n");
1130 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
1131 | XIMStatusNothing, XNClientWindow, xw.win,
1132 XNFocusWindow, xw.win, NULL);
1133 if (xw.xic == NULL)
1134 die("XCreateIC failed. Could not obtain input method.\n");
1136 /* white cursor, black outline */
1137 cursor = XCreateFontCursor(xw.dpy, mouseshape);
1138 XDefineCursor(xw.dpy, xw.win, cursor);
1140 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
1141 xmousefg.red = 0xffff;
1142 xmousefg.green = 0xffff;
1143 xmousefg.blue = 0xffff;
1146 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
1147 xmousebg.red = 0x0000;
1148 xmousebg.green = 0x0000;
1149 xmousebg.blue = 0x0000;
1152 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
1154 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1155 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
1156 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
1157 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
1159 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
1160 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
1161 PropModeReplace, (uchar *)&thispid, 1);
1163 win.mode = MODE_NUMLOCK;
1164 resettitle();
1165 XMapWindow(xw.dpy, xw.win);
1166 xhints();
1167 XSync(xw.dpy, False);
1169 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
1170 clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
1171 xsel.primary = NULL;
1172 xsel.clipboard = NULL;
1173 xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
1174 if (xsel.xtarget == None)
1175 xsel.xtarget = XA_STRING;
1179 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
1181 float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
1182 ushort mode, prevmode = USHRT_MAX;
1183 Font *font = &dc.font;
1184 int frcflags = FRC_NORMAL;
1185 float runewidth = win.cw;
1186 Rune rune;
1187 FT_UInt glyphidx;
1188 FcResult fcres;
1189 FcPattern *fcpattern, *fontpattern;
1190 FcFontSet *fcsets[] = { NULL };
1191 FcCharSet *fccharset;
1192 int i, f, numspecs = 0;
1194 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
1195 /* Fetch rune and mode for current glyph. */
1196 rune = glyphs[i].u;
1197 mode = glyphs[i].mode;
1199 /* Skip dummy wide-character spacing. */
1200 if (mode == ATTR_WDUMMY)
1201 continue;
1203 /* Determine font for glyph if different from previous glyph. */
1204 if (prevmode != mode) {
1205 prevmode = mode;
1206 font = &dc.font;
1207 frcflags = FRC_NORMAL;
1208 runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
1209 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
1210 font = &dc.ibfont;
1211 frcflags = FRC_ITALICBOLD;
1212 } else if (mode & ATTR_ITALIC) {
1213 font = &dc.ifont;
1214 frcflags = FRC_ITALIC;
1215 } else if (mode & ATTR_BOLD) {
1216 font = &dc.bfont;
1217 frcflags = FRC_BOLD;
1219 yp = winy + font->ascent;
1222 /* Lookup character index with default font. */
1223 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
1224 if (glyphidx) {
1225 specs[numspecs].font = font->match;
1226 specs[numspecs].glyph = glyphidx;
1227 specs[numspecs].x = (short)xp;
1228 specs[numspecs].y = (short)yp;
1229 xp += runewidth;
1230 numspecs++;
1231 continue;
1234 /* Fallback on font cache, search the font cache for match. */
1235 for (f = 0; f < frclen; f++) {
1236 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
1237 /* Everything correct. */
1238 if (glyphidx && frc[f].flags == frcflags)
1239 break;
1240 /* We got a default font for a not found glyph. */
1241 if (!glyphidx && frc[f].flags == frcflags
1242 && frc[f].unicodep == rune) {
1243 break;
1247 /* Nothing was found. Use fontconfig to find matching font. */
1248 if (f >= frclen) {
1249 if (!font->set)
1250 font->set = FcFontSort(0, font->pattern,
1251 1, 0, &fcres);
1252 fcsets[0] = font->set;
1255 * Nothing was found in the cache. Now use
1256 * some dozen of Fontconfig calls to get the
1257 * font for one single character.
1259 * Xft and fontconfig are design failures.
1261 fcpattern = FcPatternDuplicate(font->pattern);
1262 fccharset = FcCharSetCreate();
1264 FcCharSetAddChar(fccharset, rune);
1265 FcPatternAddCharSet(fcpattern, FC_CHARSET,
1266 fccharset);
1267 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
1269 FcConfigSubstitute(0, fcpattern,
1270 FcMatchPattern);
1271 FcDefaultSubstitute(fcpattern);
1273 fontpattern = FcFontSetMatch(0, fcsets, 1,
1274 fcpattern, &fcres);
1277 * Overwrite or create the new cache entry.
1279 if (frclen >= LEN(frc)) {
1280 frclen = LEN(frc) - 1;
1281 XftFontClose(xw.dpy, frc[frclen].font);
1282 frc[frclen].unicodep = 0;
1285 frc[frclen].font = XftFontOpenPattern(xw.dpy,
1286 fontpattern);
1287 if (!frc[frclen].font)
1288 die("XftFontOpenPattern failed seeking fallback font: %s\n",
1289 strerror(errno));
1290 frc[frclen].flags = frcflags;
1291 frc[frclen].unicodep = rune;
1293 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
1295 f = frclen;
1296 frclen++;
1298 FcPatternDestroy(fcpattern);
1299 FcCharSetDestroy(fccharset);
1302 specs[numspecs].font = frc[f].font;
1303 specs[numspecs].glyph = glyphidx;
1304 specs[numspecs].x = (short)xp;
1305 specs[numspecs].y = (short)yp;
1306 xp += runewidth;
1307 numspecs++;
1310 return numspecs;
1313 void
1314 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
1316 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
1317 int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
1318 width = charlen * win.cw;
1319 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
1320 XRenderColor colfg, colbg;
1321 XRectangle r;
1323 /* Fallback on color display for attributes not supported by the font */
1324 if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
1325 if (dc.ibfont.badslant || dc.ibfont.badweight)
1326 base.fg = defaultattr;
1327 } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
1328 (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
1329 base.fg = defaultattr;
1332 if (IS_TRUECOL(base.fg)) {
1333 colfg.alpha = 0xffff;
1334 colfg.red = TRUERED(base.fg);
1335 colfg.green = TRUEGREEN(base.fg);
1336 colfg.blue = TRUEBLUE(base.fg);
1337 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
1338 fg = &truefg;
1339 } else {
1340 fg = &dc.col[base.fg];
1343 if (IS_TRUECOL(base.bg)) {
1344 colbg.alpha = 0xffff;
1345 colbg.green = TRUEGREEN(base.bg);
1346 colbg.red = TRUERED(base.bg);
1347 colbg.blue = TRUEBLUE(base.bg);
1348 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
1349 bg = &truebg;
1350 } else {
1351 bg = &dc.col[base.bg];
1354 /* Change basic system colors [0-7] to bright system colors [8-15] */
1355 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
1356 fg = &dc.col[base.fg + 8];
1358 if (IS_SET(MODE_REVERSE)) {
1359 if (fg == &dc.col[defaultfg]) {
1360 fg = &dc.col[defaultbg];
1361 } else {
1362 colfg.red = ~fg->color.red;
1363 colfg.green = ~fg->color.green;
1364 colfg.blue = ~fg->color.blue;
1365 colfg.alpha = fg->color.alpha;
1366 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
1367 &revfg);
1368 fg = &revfg;
1371 if (bg == &dc.col[defaultbg]) {
1372 bg = &dc.col[defaultfg];
1373 } else {
1374 colbg.red = ~bg->color.red;
1375 colbg.green = ~bg->color.green;
1376 colbg.blue = ~bg->color.blue;
1377 colbg.alpha = bg->color.alpha;
1378 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
1379 &revbg);
1380 bg = &revbg;
1384 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
1385 colfg.red = fg->color.red / 2;
1386 colfg.green = fg->color.green / 2;
1387 colfg.blue = fg->color.blue / 2;
1388 colfg.alpha = fg->color.alpha;
1389 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
1390 fg = &revfg;
1393 if (base.mode & ATTR_REVERSE) {
1394 temp = fg;
1395 fg = bg;
1396 bg = temp;
1399 if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
1400 fg = bg;
1402 if (base.mode & ATTR_INVISIBLE)
1403 fg = bg;
1405 /* Intelligent cleaning up of the borders. */
1406 if (x == 0) {
1407 xclear(0, (y == 0)? 0 : winy, borderpx,
1408 winy + win.ch +
1409 ((winy + win.ch >= borderpx + win.th)? win.h : 0));
1411 if (winx + width >= borderpx + win.tw) {
1412 xclear(winx + width, (y == 0)? 0 : winy, win.w,
1413 ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
1415 if (y == 0)
1416 xclear(winx, 0, winx + width, borderpx);
1417 if (winy + win.ch >= borderpx + win.th)
1418 xclear(winx, winy + win.ch, winx + width, win.h);
1420 /* Clean up the region we want to draw to. */
1421 XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
1423 /* Set the clip region because Xft is sometimes dirty. */
1424 r.x = 0;
1425 r.y = 0;
1426 r.height = win.ch;
1427 r.width = width;
1428 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
1430 /* Render the glyphs. */
1431 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
1433 /* Render underline and strikethrough. */
1434 if (base.mode & ATTR_UNDERLINE) {
1435 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
1436 width, 1);
1439 if (base.mode & ATTR_STRUCK) {
1440 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
1441 width, 1);
1444 /* Reset clip to none. */
1445 XftDrawSetClip(xw.draw, 0);
1448 void
1449 xdrawglyph(Glyph g, int x, int y)
1451 int numspecs;
1452 XftGlyphFontSpec spec;
1454 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
1455 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
1458 void
1459 xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
1461 Color drawcol;
1463 /* remove the old cursor */
1464 if (selected(ox, oy))
1465 og.mode ^= ATTR_REVERSE;
1466 xdrawglyph(og, ox, oy);
1468 if (IS_SET(MODE_HIDE))
1469 return;
1472 * Select the right color for the right mode.
1474 g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
1476 if (IS_SET(MODE_REVERSE)) {
1477 g.mode |= ATTR_REVERSE;
1478 g.bg = defaultfg;
1479 if (selected(cx, cy)) {
1480 drawcol = dc.col[defaultcs];
1481 g.fg = defaultrcs;
1482 } else {
1483 drawcol = dc.col[defaultrcs];
1484 g.fg = defaultcs;
1486 } else {
1487 if (selected(cx, cy)) {
1488 g.fg = defaultfg;
1489 g.bg = defaultrcs;
1490 } else {
1491 g.fg = defaultbg;
1492 g.bg = defaultcs;
1494 drawcol = dc.col[g.bg];
1497 /* draw the new one */
1498 if (IS_SET(MODE_FOCUSED)) {
1499 switch (win.cursor) {
1500 case 7: /* st extension: snowman (U+2603) */
1501 g.u = 0x2603;
1502 case 0: /* Blinking Block */
1503 case 1: /* Blinking Block (Default) */
1504 case 2: /* Steady Block */
1505 xdrawglyph(g, cx, cy);
1506 break;
1507 case 3: /* Blinking Underline */
1508 case 4: /* Steady Underline */
1509 XftDrawRect(xw.draw, &drawcol,
1510 borderpx + cx * win.cw,
1511 borderpx + (cy + 1) * win.ch - \
1512 cursorthickness,
1513 win.cw, cursorthickness);
1514 break;
1515 case 5: /* Blinking bar */
1516 case 6: /* Steady bar */
1517 XftDrawRect(xw.draw, &drawcol,
1518 borderpx + cx * win.cw,
1519 borderpx + cy * win.ch,
1520 cursorthickness, win.ch);
1521 break;
1523 } else {
1524 XftDrawRect(xw.draw, &drawcol,
1525 borderpx + cx * win.cw,
1526 borderpx + cy * win.ch,
1527 win.cw - 1, 1);
1528 XftDrawRect(xw.draw, &drawcol,
1529 borderpx + cx * win.cw,
1530 borderpx + cy * win.ch,
1531 1, win.ch - 1);
1532 XftDrawRect(xw.draw, &drawcol,
1533 borderpx + (cx + 1) * win.cw - 1,
1534 borderpx + cy * win.ch,
1535 1, win.ch - 1);
1536 XftDrawRect(xw.draw, &drawcol,
1537 borderpx + cx * win.cw,
1538 borderpx + (cy + 1) * win.ch - 1,
1539 win.cw, 1);
1543 void
1544 xsetenv(void)
1546 char buf[sizeof(long) * 8 + 1];
1548 snprintf(buf, sizeof(buf), "%lu", xw.win);
1549 setenv("WINDOWID", buf, 1);
1552 void
1553 xsettitle(char *p)
1555 XTextProperty prop;
1556 DEFAULT(p, opt_title);
1558 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
1559 &prop);
1560 XSetWMName(xw.dpy, xw.win, &prop);
1561 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
1562 XFree(prop.value);
1566 xstartdraw(void)
1568 return IS_SET(MODE_VISIBLE);
1571 void
1572 xdrawline(Line line, int x1, int y1, int x2)
1574 int i, x, ox, numspecs;
1575 Glyph base, new;
1576 XftGlyphFontSpec *specs = xw.specbuf;
1578 numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
1579 i = ox = 0;
1580 for (x = x1; x < x2 && i < numspecs; x++) {
1581 new = line[x];
1582 if (new.mode == ATTR_WDUMMY)
1583 continue;
1584 if (selected(x, y1))
1585 new.mode ^= ATTR_REVERSE;
1586 if (i > 0 && ATTRCMP(base, new)) {
1587 xdrawglyphfontspecs(specs, base, i, ox, y1);
1588 specs += i;
1589 numspecs -= i;
1590 i = 0;
1592 if (i == 0) {
1593 ox = x;
1594 base = new;
1596 i++;
1598 if (i > 0)
1599 xdrawglyphfontspecs(specs, base, i, ox, y1);
1602 void
1603 xfinishdraw(void)
1605 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
1606 win.h, 0, 0);
1607 XSetForeground(xw.dpy, dc.gc,
1608 dc.col[IS_SET(MODE_REVERSE)?
1609 defaultfg : defaultbg].pixel);
1612 void
1613 expose(XEvent *ev)
1615 redraw();
1618 void
1619 visibility(XEvent *ev)
1621 XVisibilityEvent *e = &ev->xvisibility;
1623 MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
1626 void
1627 unmap(XEvent *ev)
1629 win.mode &= ~MODE_VISIBLE;
1632 void
1633 xsetpointermotion(int set)
1635 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
1636 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
1639 void
1640 xsetmode(int set, unsigned int flags)
1642 int mode = win.mode;
1643 MODBIT(win.mode, set, flags);
1644 if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
1645 redraw();
1649 xsetcursor(int cursor)
1651 DEFAULT(cursor, 1);
1652 if (!BETWEEN(cursor, 0, 6))
1653 return 1;
1654 win.cursor = cursor;
1655 return 0;
1658 void
1659 xseturgency(int add)
1661 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
1663 MODBIT(h->flags, add, XUrgencyHint);
1664 XSetWMHints(xw.dpy, xw.win, h);
1665 XFree(h);
1668 void
1669 xbell(void)
1671 if (!(IS_SET(MODE_FOCUSED)))
1672 xseturgency(1);
1673 if (bellvolume)
1674 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
1677 void
1678 focus(XEvent *ev)
1680 XFocusChangeEvent *e = &ev->xfocus;
1682 if (e->mode == NotifyGrab)
1683 return;
1685 if (ev->type == FocusIn) {
1686 XSetICFocus(xw.xic);
1687 win.mode |= MODE_FOCUSED;
1688 xseturgency(0);
1689 if (IS_SET(MODE_FOCUS))
1690 ttywrite("\033[I", 3, 0);
1691 } else {
1692 XUnsetICFocus(xw.xic);
1693 win.mode &= ~MODE_FOCUSED;
1694 if (IS_SET(MODE_FOCUS))
1695 ttywrite("\033[O", 3, 0);
1700 match(uint mask, uint state)
1702 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
1705 char*
1706 kmap(KeySym k, uint state)
1708 Key *kp;
1709 int i;
1711 /* Check for mapped keys out of X11 function keys. */
1712 for (i = 0; i < LEN(mappedkeys); i++) {
1713 if (mappedkeys[i] == k)
1714 break;
1716 if (i == LEN(mappedkeys)) {
1717 if ((k & 0xFFFF) < 0xFD00)
1718 return NULL;
1721 for (kp = key; kp < key + LEN(key); kp++) {
1722 if (kp->k != k)
1723 continue;
1725 if (!match(kp->mask, state))
1726 continue;
1728 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
1729 continue;
1730 if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
1731 continue;
1733 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
1734 continue;
1736 return kp->s;
1739 return NULL;
1742 void
1743 kpress(XEvent *ev)
1745 XKeyEvent *e = &ev->xkey;
1746 KeySym ksym;
1747 char buf[32], *customkey;
1748 int len;
1749 Rune c;
1750 Status status;
1751 Shortcut *bp;
1753 if (IS_SET(MODE_KBDLOCK))
1754 return;
1756 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
1757 /* 1. shortcuts */
1758 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
1759 if (ksym == bp->keysym && match(bp->mod, e->state)) {
1760 bp->func(&(bp->arg));
1761 return;
1765 /* 2. custom keys from config.h */
1766 if ((customkey = kmap(ksym, e->state))) {
1767 ttywrite(customkey, strlen(customkey), 1);
1768 return;
1771 /* 3. composed string from input method */
1772 if (len == 0)
1773 return;
1774 if (len == 1 && e->state & Mod1Mask) {
1775 if (IS_SET(MODE_8BIT)) {
1776 if (*buf < 0177) {
1777 c = *buf | 0x80;
1778 len = utf8encode(c, buf);
1780 } else {
1781 buf[1] = buf[0];
1782 buf[0] = '\033';
1783 len = 2;
1786 ttywrite(buf, len, 1);
1790 void
1791 cmessage(XEvent *e)
1794 * See xembed specs
1795 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
1797 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
1798 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
1799 win.mode |= MODE_FOCUSED;
1800 xseturgency(0);
1801 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
1802 win.mode &= ~MODE_FOCUSED;
1804 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
1805 ttyhangup();
1806 exit(0);
1810 void
1811 resize(XEvent *e)
1813 if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
1814 return;
1816 cresize(e->xconfigure.width, e->xconfigure.height);
1819 void
1820 run(void)
1822 XEvent ev;
1823 int w = win.w, h = win.h;
1824 fd_set rfd;
1825 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
1826 int ttyfd;
1827 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
1828 long deltatime;
1830 /* Waiting for window mapping */
1831 do {
1832 XNextEvent(xw.dpy, &ev);
1834 * This XFilterEvent call is required because of XOpenIM. It
1835 * does filter out the key event and some client message for
1836 * the input method too.
1838 if (XFilterEvent(&ev, None))
1839 continue;
1840 if (ev.type == ConfigureNotify) {
1841 w = ev.xconfigure.width;
1842 h = ev.xconfigure.height;
1844 } while (ev.type != MapNotify);
1846 ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
1847 cresize(w, h);
1849 clock_gettime(CLOCK_MONOTONIC, &last);
1850 lastblink = last;
1852 for (xev = actionfps;;) {
1853 FD_ZERO(&rfd);
1854 FD_SET(ttyfd, &rfd);
1855 FD_SET(xfd, &rfd);
1857 if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
1858 if (errno == EINTR)
1859 continue;
1860 die("select failed: %s\n", strerror(errno));
1862 if (FD_ISSET(ttyfd, &rfd)) {
1863 ttyread();
1864 if (blinktimeout) {
1865 blinkset = tattrset(ATTR_BLINK);
1866 if (!blinkset)
1867 MODBIT(win.mode, 0, MODE_BLINK);
1871 if (FD_ISSET(xfd, &rfd))
1872 xev = actionfps;
1874 clock_gettime(CLOCK_MONOTONIC, &now);
1875 drawtimeout.tv_sec = 0;
1876 drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
1877 tv = &drawtimeout;
1879 dodraw = 0;
1880 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
1881 tsetdirtattr(ATTR_BLINK);
1882 win.mode ^= MODE_BLINK;
1883 lastblink = now;
1884 dodraw = 1;
1886 deltatime = TIMEDIFF(now, last);
1887 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
1888 dodraw = 1;
1889 last = now;
1892 if (dodraw) {
1893 while (XPending(xw.dpy)) {
1894 XNextEvent(xw.dpy, &ev);
1895 if (XFilterEvent(&ev, None))
1896 continue;
1897 if (handler[ev.type])
1898 (handler[ev.type])(&ev);
1901 draw();
1902 XFlush(xw.dpy);
1904 if (xev && !FD_ISSET(xfd, &rfd))
1905 xev--;
1906 if (!FD_ISSET(ttyfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
1907 if (blinkset) {
1908 if (TIMEDIFF(now, lastblink) \
1909 > blinktimeout) {
1910 drawtimeout.tv_nsec = 1000;
1911 } else {
1912 drawtimeout.tv_nsec = (1E6 * \
1913 (blinktimeout - \
1914 TIMEDIFF(now,
1915 lastblink)));
1917 drawtimeout.tv_sec = \
1918 drawtimeout.tv_nsec / 1E9;
1919 drawtimeout.tv_nsec %= (long)1E9;
1920 } else {
1921 tv = NULL;
1928 void
1929 usage(void)
1931 die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
1932 " [-n name] [-o file]\n"
1933 " [-T title] [-t title] [-w windowid]"
1934 " [[-e] command [args ...]]\n"
1935 " %s [-aiv] [-c class] [-f font] [-g geometry]"
1936 " [-n name] [-o file]\n"
1937 " [-T title] [-t title] [-w windowid] -l line"
1938 " [stty_args ...]\n", argv0, argv0);
1942 main(int argc, char *argv[])
1944 xw.l = xw.t = 0;
1945 xw.isfixed = False;
1946 win.cursor = cursorshape;
1948 ARGBEGIN {
1949 case 'a':
1950 allowaltscreen = 0;
1951 break;
1952 case 'c':
1953 opt_class = EARGF(usage());
1954 break;
1955 case 'e':
1956 if (argc > 0)
1957 --argc, ++argv;
1958 goto run;
1959 case 'f':
1960 opt_font = EARGF(usage());
1961 break;
1962 case 'g':
1963 xw.gm = XParseGeometry(EARGF(usage()),
1964 &xw.l, &xw.t, &cols, &rows);
1965 break;
1966 case 'i':
1967 xw.isfixed = 1;
1968 break;
1969 case 'o':
1970 opt_io = EARGF(usage());
1971 break;
1972 case 'l':
1973 opt_line = EARGF(usage());
1974 break;
1975 case 'n':
1976 opt_name = EARGF(usage());
1977 break;
1978 case 't':
1979 case 'T':
1980 opt_title = EARGF(usage());
1981 break;
1982 case 'w':
1983 opt_embed = EARGF(usage());
1984 break;
1985 case 'v':
1986 die("%s " VERSION "\n", argv0);
1987 break;
1988 default:
1989 usage();
1990 } ARGEND;
1992 run:
1993 if (argc > 0) /* eat all remaining arguments */
1994 opt_cmd = argv;
1996 if (!opt_title)
1997 opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
1999 setlocale(LC_CTYPE, "");
2000 XSetLocaleModifiers("");
2001 cols = MAX(cols, 1);
2002 rows = MAX(rows, 1);
2003 tnew(cols, rows);
2004 xinit(cols, rows);
2005 xsetenv();
2006 selinit();
2007 run();
2009 return 0;