Xinqi Bao's Git

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