Xinqi Bao's Git

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