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