Xinqi Bao's Git

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