Xinqi Bao's Git

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