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.

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