Xinqi Bao's Git

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