Xinqi Bao's Git

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