Xinqi Bao's Git

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