Xinqi Bao's Git

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