Xinqi Bao's Git

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