Xinqi Bao's Git

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