Xinqi Bao's Git

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