My build of the simple terminal from suckless.org.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 

2088 lignes
47 KiB

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