Another copy of my dotfiles. Because I don't completely trust GitHub.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2219 lines
50 KiB

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