Xinqi Bao's Git

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