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.

2206 lines
50 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. } MouseShortcut;
  35. typedef struct {
  36. KeySym k;
  37. uint mask;
  38. char *s;
  39. /* three-valued logic variables: 0 indifferent, 1 on, -1 off */
  40. signed char appkey; /* application keypad */
  41. signed char appcursor; /* application cursor */
  42. } Key;
  43. /* X modifiers */
  44. #define XK_ANY_MOD UINT_MAX
  45. #define XK_NO_MOD 0
  46. #define XK_SWITCH_MOD (1<<13)
  47. /* function definitions used in config.h */
  48. static void clipcopy(const Arg *);
  49. static void clippaste(const Arg *);
  50. static void numlock(const Arg *);
  51. static void selpaste(const Arg *);
  52. static void zoom(const Arg *);
  53. static void zoomabs(const Arg *);
  54. static void zoomreset(const Arg *);
  55. static void ttysend(const Arg *);
  56. /* config.h for applying patches and the configuration. */
  57. #include "config.h"
  58. /* XEMBED messages */
  59. #define XEMBED_FOCUS_IN 4
  60. #define XEMBED_FOCUS_OUT 5
  61. /* macros */
  62. #define IS_SET(flag) ((win.mode & (flag)) != 0)
  63. #define TRUERED(x) (((x) & 0xff0000) >> 8)
  64. #define TRUEGREEN(x) (((x) & 0xff00))
  65. #define TRUEBLUE(x) (((x) & 0xff) << 8)
  66. typedef XftDraw *Draw;
  67. typedef XftColor Color;
  68. typedef XftGlyphFontSpec GlyphFontSpec;
  69. /* Purely graphic info */
  70. typedef struct {
  71. int tw, th; /* tty width and height */
  72. int w, h; /* window width and height */
  73. int ch; /* char height */
  74. int cw; /* char width */
  75. int mode; /* window state/mode flags */
  76. int cursor; /* cursor style */
  77. } TermWindow;
  78. typedef struct {
  79. Display *dpy;
  80. Colormap cmap;
  81. Window win;
  82. Drawable buf;
  83. GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
  84. Atom xembed, wmdeletewin, netwmname, netwmiconname, netwmpid;
  85. struct {
  86. XIM xim;
  87. XIC xic;
  88. XPoint spot;
  89. XVaNestedList spotlist;
  90. } ime;
  91. Draw draw;
  92. Visual *vis;
  93. XSetWindowAttributes attrs;
  94. int scr;
  95. int isfixed; /* is fixed geometry? */
  96. int depth; /* bit depth */
  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_alpha = NULL;
  226. static char *opt_class = NULL;
  227. static char **opt_cmd = NULL;
  228. static char *opt_embed = NULL;
  229. static char *opt_font = NULL;
  230. static char *opt_io = NULL;
  231. static char *opt_line = NULL;
  232. static char *opt_name = NULL;
  233. static char *opt_title = NULL;
  234. static int oldbutton = 3; /* button event on startup: 3 = release */
  235. static int cursorblinks = 0;
  236. void
  237. clipcopy(const Arg *dummy)
  238. {
  239. Atom clipboard;
  240. free(xsel.clipboard);
  241. xsel.clipboard = NULL;
  242. if (xsel.primary != NULL) {
  243. xsel.clipboard = xstrdup(xsel.primary);
  244. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  245. XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
  246. }
  247. }
  248. void
  249. clippaste(const Arg *dummy)
  250. {
  251. Atom clipboard;
  252. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  253. XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
  254. xw.win, CurrentTime);
  255. }
  256. void
  257. selpaste(const Arg *dummy)
  258. {
  259. XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
  260. xw.win, CurrentTime);
  261. }
  262. void
  263. numlock(const Arg *dummy)
  264. {
  265. win.mode ^= MODE_NUMLOCK;
  266. }
  267. void
  268. zoom(const Arg *arg)
  269. {
  270. Arg larg;
  271. larg.f = usedfontsize + arg->f;
  272. zoomabs(&larg);
  273. }
  274. void
  275. zoomabs(const Arg *arg)
  276. {
  277. xunloadfonts();
  278. xloadfonts(usedfont, arg->f);
  279. xloadsparefonts();
  280. cresize(0, 0);
  281. redraw();
  282. xhints();
  283. }
  284. void
  285. zoomreset(const Arg *arg)
  286. {
  287. Arg larg;
  288. if (defaultfontsize > 0) {
  289. larg.f = defaultfontsize;
  290. zoomabs(&larg);
  291. }
  292. }
  293. void
  294. ttysend(const Arg *arg)
  295. {
  296. ttywrite(arg->s, strlen(arg->s), 1);
  297. }
  298. int
  299. evcol(XEvent *e)
  300. {
  301. int x = e->xbutton.x - borderpx;
  302. LIMIT(x, 0, win.tw - 1);
  303. return x / win.cw;
  304. }
  305. int
  306. evrow(XEvent *e)
  307. {
  308. int y = e->xbutton.y - borderpx;
  309. LIMIT(y, 0, win.th - 1);
  310. return y / win.ch;
  311. }
  312. void
  313. mousesel(XEvent *e, int done)
  314. {
  315. int type, seltype = SEL_REGULAR;
  316. uint state = e->xbutton.state & ~(Button1Mask | forcemousemod);
  317. for (type = 1; type < LEN(selmasks); ++type) {
  318. if (match(selmasks[type], state)) {
  319. seltype = type;
  320. break;
  321. }
  322. }
  323. selextend(evcol(e), evrow(e), seltype, done);
  324. if (done)
  325. setsel(getsel(), e->xbutton.time);
  326. }
  327. void
  328. mousereport(XEvent *e)
  329. {
  330. int len, x = evcol(e), y = evrow(e),
  331. button = e->xbutton.button, state = e->xbutton.state;
  332. char buf[40];
  333. static int ox, oy;
  334. /* from urxvt */
  335. if (e->xbutton.type == MotionNotify) {
  336. if (x == ox && y == oy)
  337. return;
  338. if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
  339. return;
  340. /* MOUSE_MOTION: no reporting if no button is pressed */
  341. if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
  342. return;
  343. button = oldbutton + 32;
  344. ox = x;
  345. oy = y;
  346. } else {
  347. if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
  348. button = 3;
  349. } else {
  350. button -= Button1;
  351. if (button >= 3)
  352. button += 64 - 3;
  353. }
  354. if (e->xbutton.type == ButtonPress) {
  355. oldbutton = button;
  356. ox = x;
  357. oy = y;
  358. } else if (e->xbutton.type == ButtonRelease) {
  359. oldbutton = 3;
  360. /* MODE_MOUSEX10: no button release reporting */
  361. if (IS_SET(MODE_MOUSEX10))
  362. return;
  363. if (button == 64 || button == 65)
  364. return;
  365. }
  366. }
  367. if (!IS_SET(MODE_MOUSEX10)) {
  368. button += ((state & ShiftMask ) ? 4 : 0)
  369. + ((state & Mod4Mask ) ? 8 : 0)
  370. + ((state & ControlMask) ? 16 : 0);
  371. }
  372. if (IS_SET(MODE_MOUSESGR)) {
  373. len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
  374. button, x+1, y+1,
  375. e->xbutton.type == ButtonRelease ? 'm' : 'M');
  376. } else if (x < 223 && y < 223) {
  377. len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
  378. 32+button, 32+x+1, 32+y+1);
  379. } else {
  380. return;
  381. }
  382. ttywrite(buf, len, 0);
  383. }
  384. uint
  385. buttonmask(uint button)
  386. {
  387. return button == Button1 ? Button1Mask
  388. : button == Button2 ? Button2Mask
  389. : button == Button3 ? Button3Mask
  390. : button == Button4 ? Button4Mask
  391. : button == Button5 ? Button5Mask
  392. : 0;
  393. }
  394. int
  395. mouseaction(XEvent *e, uint release)
  396. {
  397. MouseShortcut *ms;
  398. /* ignore Button<N>mask for Button<N> - it's set on release */
  399. uint state = e->xbutton.state & ~buttonmask(e->xbutton.button);
  400. for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
  401. if (ms->release == release &&
  402. ms->button == e->xbutton.button &&
  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. xw.depth);
  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. /* set alpha value of bg color */
  704. if (opt_alpha)
  705. alpha = strtof(opt_alpha, NULL);
  706. dc.col[defaultbg].color.alpha = (unsigned short)(0xffff * alpha);
  707. dc.col[defaultbg].pixel &= 0x00FFFFFF;
  708. dc.col[defaultbg].pixel |= (unsigned char)(0xff * alpha) << 24;
  709. loaded = 1;
  710. }
  711. int
  712. xsetcolorname(int x, const char *name)
  713. {
  714. Color ncolor;
  715. if (!BETWEEN(x, 0, dc.collen))
  716. return 1;
  717. if (!xloadcolor(x, name, &ncolor))
  718. return 1;
  719. XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
  720. dc.col[x] = ncolor;
  721. return 0;
  722. }
  723. /*
  724. * Absolute coordinates.
  725. */
  726. void
  727. xclear(int x1, int y1, int x2, int y2)
  728. {
  729. XftDrawRect(xw.draw,
  730. &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
  731. x1, y1, x2-x1, y2-y1);
  732. }
  733. void
  734. xhints(void)
  735. {
  736. XClassHint class = {opt_name ? opt_name : termname,
  737. opt_class ? opt_class : termname};
  738. XWMHints wm = {.flags = InputHint, .input = 1};
  739. XSizeHints *sizeh;
  740. sizeh = XAllocSizeHints();
  741. sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
  742. sizeh->height = win.h;
  743. sizeh->width = win.w;
  744. sizeh->height_inc = win.ch;
  745. sizeh->width_inc = win.cw;
  746. sizeh->base_height = 2 * borderpx;
  747. sizeh->base_width = 2 * borderpx;
  748. sizeh->min_height = win.ch + 2 * borderpx;
  749. sizeh->min_width = win.cw + 2 * borderpx;
  750. if (xw.isfixed) {
  751. sizeh->flags |= PMaxSize;
  752. sizeh->min_width = sizeh->max_width = win.w;
  753. sizeh->min_height = sizeh->max_height = win.h;
  754. }
  755. if (xw.gm & (XValue|YValue)) {
  756. sizeh->flags |= USPosition | PWinGravity;
  757. sizeh->x = xw.l;
  758. sizeh->y = xw.t;
  759. sizeh->win_gravity = xgeommasktogravity(xw.gm);
  760. }
  761. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
  762. &class);
  763. XFree(sizeh);
  764. }
  765. int
  766. xgeommasktogravity(int mask)
  767. {
  768. switch (mask & (XNegative|YNegative)) {
  769. case 0:
  770. return NorthWestGravity;
  771. case XNegative:
  772. return NorthEastGravity;
  773. case YNegative:
  774. return SouthWestGravity;
  775. }
  776. return SouthEastGravity;
  777. }
  778. int
  779. xloadfont(Font *f, FcPattern *pattern)
  780. {
  781. FcPattern *configured;
  782. FcPattern *match;
  783. FcResult result;
  784. XGlyphInfo extents;
  785. int wantattr, haveattr;
  786. /*
  787. * Manually configure instead of calling XftMatchFont
  788. * so that we can use the configured pattern for
  789. * "missing glyph" lookups.
  790. */
  791. configured = FcPatternDuplicate(pattern);
  792. if (!configured)
  793. return 1;
  794. FcConfigSubstitute(NULL, configured, FcMatchPattern);
  795. XftDefaultSubstitute(xw.dpy, xw.scr, configured);
  796. match = FcFontMatch(NULL, configured, &result);
  797. if (!match) {
  798. FcPatternDestroy(configured);
  799. return 1;
  800. }
  801. if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
  802. FcPatternDestroy(configured);
  803. FcPatternDestroy(match);
  804. return 1;
  805. }
  806. if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
  807. XftResultMatch)) {
  808. /*
  809. * Check if xft was unable to find a font with the appropriate
  810. * slant but gave us one anyway. Try to mitigate.
  811. */
  812. if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
  813. &haveattr) != XftResultMatch) || haveattr < wantattr) {
  814. f->badslant = 1;
  815. fputs("font slant does not match\n", stderr);
  816. }
  817. }
  818. if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
  819. XftResultMatch)) {
  820. if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
  821. &haveattr) != XftResultMatch) || haveattr != wantattr) {
  822. f->badweight = 1;
  823. fputs("font weight does not match\n", stderr);
  824. }
  825. }
  826. XftTextExtentsUtf8(xw.dpy, f->match,
  827. (const FcChar8 *) ascii_printable,
  828. strlen(ascii_printable), &extents);
  829. f->set = NULL;
  830. f->pattern = configured;
  831. f->ascent = f->match->ascent;
  832. f->descent = f->match->descent;
  833. f->lbearing = 0;
  834. f->rbearing = f->match->max_advance_width;
  835. f->height = f->ascent + f->descent;
  836. f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
  837. return 0;
  838. }
  839. void
  840. xloadfonts(char *fontstr, double fontsize)
  841. {
  842. FcPattern *pattern;
  843. double fontval;
  844. if (fontstr[0] == '-')
  845. pattern = XftXlfdParse(fontstr, False, False);
  846. else
  847. pattern = FcNameParse((FcChar8 *)fontstr);
  848. if (!pattern)
  849. die("can't open font %s\n", fontstr);
  850. if (fontsize > 1) {
  851. FcPatternDel(pattern, FC_PIXEL_SIZE);
  852. FcPatternDel(pattern, FC_SIZE);
  853. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
  854. usedfontsize = fontsize;
  855. } else {
  856. if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
  857. FcResultMatch) {
  858. usedfontsize = fontval;
  859. } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
  860. FcResultMatch) {
  861. usedfontsize = -1;
  862. } else {
  863. /*
  864. * Default font size is 12, if none given. This is to
  865. * have a known usedfontsize value.
  866. */
  867. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
  868. usedfontsize = 12;
  869. }
  870. defaultfontsize = usedfontsize;
  871. }
  872. if (xloadfont(&dc.font, pattern))
  873. die("can't open font %s\n", fontstr);
  874. if (usedfontsize < 0) {
  875. FcPatternGetDouble(dc.font.match->pattern,
  876. FC_PIXEL_SIZE, 0, &fontval);
  877. usedfontsize = fontval;
  878. if (fontsize == 0)
  879. defaultfontsize = fontval;
  880. }
  881. /* Setting character width and height. */
  882. win.cw = ceilf(dc.font.width * cwscale);
  883. win.ch = ceilf(dc.font.height * chscale);
  884. FcPatternDel(pattern, FC_SLANT);
  885. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  886. if (xloadfont(&dc.ifont, pattern))
  887. die("can't open font %s\n", fontstr);
  888. FcPatternDel(pattern, FC_WEIGHT);
  889. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  890. if (xloadfont(&dc.ibfont, pattern))
  891. die("can't open font %s\n", fontstr);
  892. FcPatternDel(pattern, FC_SLANT);
  893. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
  894. if (xloadfont(&dc.bfont, pattern))
  895. die("can't open font %s\n", fontstr);
  896. FcPatternDestroy(pattern);
  897. }
  898. int
  899. xloadsparefont(FcPattern *pattern, int flags)
  900. {
  901. FcPattern *match;
  902. FcResult result;
  903. match = FcFontMatch(NULL, pattern, &result);
  904. if (!match) {
  905. return 1;
  906. }
  907. if (!(frc[frclen].font = XftFontOpenPattern(xw.dpy, match))) {
  908. FcPatternDestroy(match);
  909. return 1;
  910. }
  911. frc[frclen].flags = flags;
  912. /* Believe U+0000 glyph will present in each default font */
  913. frc[frclen].unicodep = 0;
  914. frclen++;
  915. return 0;
  916. }
  917. void
  918. xloadsparefonts(void)
  919. {
  920. FcPattern *pattern;
  921. double sizeshift, fontval;
  922. int fc;
  923. char **fp;
  924. if (frclen != 0)
  925. die("can't embed spare fonts. cache isn't empty");
  926. /* Calculate count of spare fonts */
  927. fc = sizeof(font2) / sizeof(*font2);
  928. if (fc == 0)
  929. return;
  930. /* Allocate memory for cache entries. */
  931. if (frccap < 4 * fc) {
  932. frccap += 4 * fc - frccap;
  933. frc = xrealloc(frc, frccap * sizeof(Fontcache));
  934. }
  935. for (fp = font2; fp - font2 < fc; ++fp) {
  936. if (**fp == '-')
  937. pattern = XftXlfdParse(*fp, False, False);
  938. else
  939. pattern = FcNameParse((FcChar8 *)*fp);
  940. if (!pattern)
  941. die("can't open spare font %s\n", *fp);
  942. if (defaultfontsize > 0) {
  943. sizeshift = usedfontsize - defaultfontsize;
  944. if (sizeshift != 0 &&
  945. FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
  946. FcResultMatch) {
  947. fontval += sizeshift;
  948. FcPatternDel(pattern, FC_PIXEL_SIZE);
  949. FcPatternDel(pattern, FC_SIZE);
  950. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, fontval);
  951. }
  952. }
  953. FcPatternAddBool(pattern, FC_SCALABLE, 1);
  954. FcConfigSubstitute(NULL, pattern, FcMatchPattern);
  955. XftDefaultSubstitute(xw.dpy, xw.scr, pattern);
  956. if (xloadsparefont(pattern, FRC_NORMAL))
  957. die("can't open spare font %s\n", *fp);
  958. FcPatternDel(pattern, FC_SLANT);
  959. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  960. if (xloadsparefont(pattern, FRC_ITALIC))
  961. die("can't open spare font %s\n", *fp);
  962. FcPatternDel(pattern, FC_WEIGHT);
  963. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  964. if (xloadsparefont(pattern, FRC_ITALICBOLD))
  965. die("can't open spare font %s\n", *fp);
  966. FcPatternDel(pattern, FC_SLANT);
  967. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
  968. if (xloadsparefont(pattern, FRC_BOLD))
  969. die("can't open spare font %s\n", *fp);
  970. FcPatternDestroy(pattern);
  971. }
  972. }
  973. void
  974. xunloadfont(Font *f)
  975. {
  976. XftFontClose(xw.dpy, f->match);
  977. FcPatternDestroy(f->pattern);
  978. if (f->set)
  979. FcFontSetDestroy(f->set);
  980. }
  981. void
  982. xunloadfonts(void)
  983. {
  984. /* Free the loaded fonts in the font cache. */
  985. while (frclen > 0)
  986. XftFontClose(xw.dpy, frc[--frclen].font);
  987. xunloadfont(&dc.font);
  988. xunloadfont(&dc.bfont);
  989. xunloadfont(&dc.ifont);
  990. xunloadfont(&dc.ibfont);
  991. }
  992. int
  993. ximopen(Display *dpy)
  994. {
  995. XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy };
  996. XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy };
  997. xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
  998. if (xw.ime.xim == NULL)
  999. return 0;
  1000. if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL))
  1001. fprintf(stderr, "XSetIMValues: "
  1002. "Could not set XNDestroyCallback.\n");
  1003. xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot,
  1004. NULL);
  1005. if (xw.ime.xic == NULL) {
  1006. xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle,
  1007. XIMPreeditNothing | XIMStatusNothing,
  1008. XNClientWindow, xw.win,
  1009. XNDestroyCallback, &icdestroy,
  1010. NULL);
  1011. }
  1012. if (xw.ime.xic == NULL)
  1013. fprintf(stderr, "XCreateIC: Could not create input context.\n");
  1014. return 1;
  1015. }
  1016. void
  1017. ximinstantiate(Display *dpy, XPointer client, XPointer call)
  1018. {
  1019. if (ximopen(dpy))
  1020. XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
  1021. ximinstantiate, NULL);
  1022. }
  1023. void
  1024. ximdestroy(XIM xim, XPointer client, XPointer call)
  1025. {
  1026. xw.ime.xim = NULL;
  1027. XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
  1028. ximinstantiate, NULL);
  1029. XFree(xw.ime.spotlist);
  1030. }
  1031. int
  1032. xicdestroy(XIC xim, XPointer client, XPointer call)
  1033. {
  1034. xw.ime.xic = NULL;
  1035. return 1;
  1036. }
  1037. void
  1038. xinit(int cols, int rows)
  1039. {
  1040. XGCValues gcvalues;
  1041. Cursor cursor;
  1042. Window parent;
  1043. pid_t thispid = getpid();
  1044. XColor xmousefg, xmousebg;
  1045. XWindowAttributes attr;
  1046. XVisualInfo vis;
  1047. if (!(xw.dpy = XOpenDisplay(NULL)))
  1048. die("can't open display\n");
  1049. xw.scr = XDefaultScreen(xw.dpy);
  1050. if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0)))) {
  1051. parent = XRootWindow(xw.dpy, xw.scr);
  1052. xw.depth = 32;
  1053. } else {
  1054. XGetWindowAttributes(xw.dpy, parent, &attr);
  1055. xw.depth = attr.depth;
  1056. }
  1057. XMatchVisualInfo(xw.dpy, xw.scr, xw.depth, TrueColor, &vis);
  1058. xw.vis = vis.visual;
  1059. /* font */
  1060. if (!FcInit())
  1061. die("could not init fontconfig.\n");
  1062. usedfont = (opt_font == NULL)? font : opt_font;
  1063. xloadfonts(usedfont, 0);
  1064. /* spare fonts */
  1065. xloadsparefonts();
  1066. /* colors */
  1067. xw.cmap = XCreateColormap(xw.dpy, parent, xw.vis, None);
  1068. xloadcols();
  1069. /* adjust fixed window geometry */
  1070. win.w = 2 * borderpx + cols * win.cw;
  1071. win.h = 2 * borderpx + rows * win.ch;
  1072. if (xw.gm & XNegative)
  1073. xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
  1074. if (xw.gm & YNegative)
  1075. xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
  1076. /* Events */
  1077. xw.attrs.background_pixel = dc.col[defaultbg].pixel;
  1078. xw.attrs.border_pixel = dc.col[defaultbg].pixel;
  1079. xw.attrs.bit_gravity = NorthWestGravity;
  1080. xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
  1081. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  1082. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  1083. xw.attrs.colormap = xw.cmap;
  1084. xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
  1085. win.w, win.h, 0, xw.depth, InputOutput,
  1086. xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
  1087. | CWEventMask | CWColormap, &xw.attrs);
  1088. memset(&gcvalues, 0, sizeof(gcvalues));
  1089. gcvalues.graphics_exposures = False;
  1090. xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h, xw.depth);
  1091. dc.gc = XCreateGC(xw.dpy, xw.buf, GCGraphicsExposures, &gcvalues);
  1092. XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
  1093. XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
  1094. /* font spec buffer */
  1095. xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
  1096. /* Xft rendering context */
  1097. xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  1098. /* input methods */
  1099. if (!ximopen(xw.dpy)) {
  1100. XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL,
  1101. ximinstantiate, NULL);
  1102. }
  1103. /* white cursor, black outline */
  1104. cursor = XCreateFontCursor(xw.dpy, mouseshape);
  1105. XDefineCursor(xw.dpy, xw.win, cursor);
  1106. if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
  1107. xmousefg.red = 0xffff;
  1108. xmousefg.green = 0xffff;
  1109. xmousefg.blue = 0xffff;
  1110. }
  1111. if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
  1112. xmousebg.red = 0x0000;
  1113. xmousebg.green = 0x0000;
  1114. xmousebg.blue = 0x0000;
  1115. }
  1116. XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
  1117. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  1118. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  1119. xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
  1120. xw.netwmiconname = XInternAtom(xw.dpy, "_NET_WM_ICON_NAME", False);
  1121. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  1122. xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
  1123. XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
  1124. PropModeReplace, (uchar *)&thispid, 1);
  1125. win.mode = MODE_NUMLOCK;
  1126. resettitle();
  1127. xhints();
  1128. XMapWindow(xw.dpy, xw.win);
  1129. XSync(xw.dpy, False);
  1130. clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
  1131. clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
  1132. xsel.primary = NULL;
  1133. xsel.clipboard = NULL;
  1134. xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
  1135. if (xsel.xtarget == None)
  1136. xsel.xtarget = XA_STRING;
  1137. }
  1138. int
  1139. xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
  1140. {
  1141. float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
  1142. ushort mode, prevmode = USHRT_MAX;
  1143. Font *font = &dc.font;
  1144. int frcflags = FRC_NORMAL;
  1145. float runewidth = win.cw;
  1146. Rune rune;
  1147. FT_UInt glyphidx;
  1148. FcResult fcres;
  1149. FcPattern *fcpattern, *fontpattern;
  1150. FcFontSet *fcsets[] = { NULL };
  1151. FcCharSet *fccharset;
  1152. int i, f, numspecs = 0;
  1153. for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
  1154. /* Fetch rune and mode for current glyph. */
  1155. rune = glyphs[i].u;
  1156. mode = glyphs[i].mode;
  1157. /* Skip dummy wide-character spacing. */
  1158. if (mode == ATTR_WDUMMY)
  1159. continue;
  1160. /* Determine font for glyph if different from previous glyph. */
  1161. if (prevmode != mode) {
  1162. prevmode = mode;
  1163. font = &dc.font;
  1164. frcflags = FRC_NORMAL;
  1165. runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
  1166. if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
  1167. font = &dc.ibfont;
  1168. frcflags = FRC_ITALICBOLD;
  1169. } else if (mode & ATTR_ITALIC) {
  1170. font = &dc.ifont;
  1171. frcflags = FRC_ITALIC;
  1172. } else if (mode & ATTR_BOLD) {
  1173. font = &dc.bfont;
  1174. frcflags = FRC_BOLD;
  1175. }
  1176. yp = winy + font->ascent;
  1177. }
  1178. /* Lookup character index with default font. */
  1179. glyphidx = XftCharIndex(xw.dpy, font->match, rune);
  1180. if (glyphidx) {
  1181. specs[numspecs].font = font->match;
  1182. specs[numspecs].glyph = glyphidx;
  1183. specs[numspecs].x = (short)xp;
  1184. specs[numspecs].y = (short)yp;
  1185. xp += runewidth;
  1186. numspecs++;
  1187. continue;
  1188. }
  1189. /* Fallback on font cache, search the font cache for match. */
  1190. for (f = 0; f < frclen; f++) {
  1191. glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
  1192. /* Everything correct. */
  1193. if (glyphidx && frc[f].flags == frcflags)
  1194. break;
  1195. /* We got a default font for a not found glyph. */
  1196. if (!glyphidx && frc[f].flags == frcflags
  1197. && frc[f].unicodep == rune) {
  1198. break;
  1199. }
  1200. }
  1201. /* Nothing was found. Use fontconfig to find matching font. */
  1202. if (f >= frclen) {
  1203. if (!font->set)
  1204. font->set = FcFontSort(0, font->pattern,
  1205. 1, 0, &fcres);
  1206. fcsets[0] = font->set;
  1207. /*
  1208. * Nothing was found in the cache. Now use
  1209. * some dozen of Fontconfig calls to get the
  1210. * font for one single character.
  1211. *
  1212. * Xft and fontconfig are design failures.
  1213. */
  1214. fcpattern = FcPatternDuplicate(font->pattern);
  1215. fccharset = FcCharSetCreate();
  1216. FcCharSetAddChar(fccharset, rune);
  1217. FcPatternAddCharSet(fcpattern, FC_CHARSET,
  1218. fccharset);
  1219. FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
  1220. FcConfigSubstitute(0, fcpattern,
  1221. FcMatchPattern);
  1222. FcDefaultSubstitute(fcpattern);
  1223. fontpattern = FcFontSetMatch(0, fcsets, 1,
  1224. fcpattern, &fcres);
  1225. /* Allocate memory for the new cache entry. */
  1226. if (frclen >= frccap) {
  1227. frccap += 16;
  1228. frc = xrealloc(frc, frccap * sizeof(Fontcache));
  1229. }
  1230. frc[frclen].font = XftFontOpenPattern(xw.dpy,
  1231. fontpattern);
  1232. if (!frc[frclen].font)
  1233. die("XftFontOpenPattern failed seeking fallback font: %s\n",
  1234. strerror(errno));
  1235. frc[frclen].flags = frcflags;
  1236. frc[frclen].unicodep = rune;
  1237. glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
  1238. f = frclen;
  1239. frclen++;
  1240. FcPatternDestroy(fcpattern);
  1241. FcCharSetDestroy(fccharset);
  1242. }
  1243. specs[numspecs].font = frc[f].font;
  1244. specs[numspecs].glyph = glyphidx;
  1245. specs[numspecs].x = (short)xp;
  1246. specs[numspecs].y = (short)yp;
  1247. xp += runewidth;
  1248. numspecs++;
  1249. }
  1250. return numspecs;
  1251. }
  1252. void
  1253. xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
  1254. {
  1255. int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
  1256. int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
  1257. width = charlen * win.cw;
  1258. Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
  1259. XRenderColor colfg, colbg;
  1260. XRectangle r;
  1261. /* Fallback on color display for attributes not supported by the font */
  1262. if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
  1263. if (dc.ibfont.badslant || dc.ibfont.badweight)
  1264. base.fg = defaultattr;
  1265. } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
  1266. (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
  1267. base.fg = defaultattr;
  1268. }
  1269. if (IS_TRUECOL(base.fg)) {
  1270. colfg.alpha = 0xffff;
  1271. colfg.red = TRUERED(base.fg);
  1272. colfg.green = TRUEGREEN(base.fg);
  1273. colfg.blue = TRUEBLUE(base.fg);
  1274. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
  1275. fg = &truefg;
  1276. } else {
  1277. fg = &dc.col[base.fg];
  1278. }
  1279. if (IS_TRUECOL(base.bg)) {
  1280. colbg.alpha = 0xffff;
  1281. colbg.green = TRUEGREEN(base.bg);
  1282. colbg.red = TRUERED(base.bg);
  1283. colbg.blue = TRUEBLUE(base.bg);
  1284. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
  1285. bg = &truebg;
  1286. } else {
  1287. bg = &dc.col[base.bg];
  1288. }
  1289. /* Change basic system colors [0-7] to bright system colors [8-15] */
  1290. if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
  1291. fg = &dc.col[base.fg + 8];
  1292. if (IS_SET(MODE_REVERSE)) {
  1293. if (fg == &dc.col[defaultfg]) {
  1294. fg = &dc.col[defaultbg];
  1295. } else {
  1296. colfg.red = ~fg->color.red;
  1297. colfg.green = ~fg->color.green;
  1298. colfg.blue = ~fg->color.blue;
  1299. colfg.alpha = fg->color.alpha;
  1300. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
  1301. &revfg);
  1302. fg = &revfg;
  1303. }
  1304. if (bg == &dc.col[defaultbg]) {
  1305. bg = &dc.col[defaultfg];
  1306. } else {
  1307. colbg.red = ~bg->color.red;
  1308. colbg.green = ~bg->color.green;
  1309. colbg.blue = ~bg->color.blue;
  1310. colbg.alpha = bg->color.alpha;
  1311. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
  1312. &revbg);
  1313. bg = &revbg;
  1314. }
  1315. }
  1316. if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
  1317. colfg.red = fg->color.red / 2;
  1318. colfg.green = fg->color.green / 2;
  1319. colfg.blue = fg->color.blue / 2;
  1320. colfg.alpha = fg->color.alpha;
  1321. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  1322. fg = &revfg;
  1323. }
  1324. if (base.mode & ATTR_REVERSE) {
  1325. temp = fg;
  1326. fg = bg;
  1327. bg = temp;
  1328. }
  1329. if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
  1330. fg = bg;
  1331. if (base.mode & ATTR_INVISIBLE)
  1332. fg = bg;
  1333. /* Intelligent cleaning up of the borders. */
  1334. if (x == 0) {
  1335. xclear(0, (y == 0)? 0 : winy, borderpx,
  1336. winy + win.ch +
  1337. ((winy + win.ch >= borderpx + win.th)? win.h : 0));
  1338. }
  1339. if (winx + width >= borderpx + win.tw) {
  1340. xclear(winx + width, (y == 0)? 0 : winy, win.w,
  1341. ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
  1342. }
  1343. if (y == 0)
  1344. xclear(winx, 0, winx + width, borderpx);
  1345. if (winy + win.ch >= borderpx + win.th)
  1346. xclear(winx, winy + win.ch, winx + width, win.h);
  1347. /* Clean up the region we want to draw to. */
  1348. XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
  1349. /* Set the clip region because Xft is sometimes dirty. */
  1350. r.x = 0;
  1351. r.y = 0;
  1352. r.height = win.ch;
  1353. r.width = width;
  1354. XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
  1355. /* Render the glyphs. */
  1356. XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
  1357. /* Render underline and strikethrough. */
  1358. if (base.mode & ATTR_UNDERLINE) {
  1359. XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
  1360. width, 1);
  1361. }
  1362. if (base.mode & ATTR_STRUCK) {
  1363. XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
  1364. width, 1);
  1365. }
  1366. /* Reset clip to none. */
  1367. XftDrawSetClip(xw.draw, 0);
  1368. }
  1369. void
  1370. xdrawglyph(Glyph g, int x, int y)
  1371. {
  1372. int numspecs;
  1373. XftGlyphFontSpec spec;
  1374. numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
  1375. xdrawglyphfontspecs(&spec, g, numspecs, x, y);
  1376. }
  1377. void
  1378. xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
  1379. {
  1380. Color drawcol;
  1381. /* remove the old cursor */
  1382. if (selected(ox, oy))
  1383. og.mode ^= ATTR_REVERSE;
  1384. xdrawglyph(og, ox, oy);
  1385. if (IS_SET(MODE_HIDE))
  1386. return;
  1387. /*
  1388. * Select the right color for the right mode.
  1389. */
  1390. g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
  1391. if (IS_SET(MODE_REVERSE)) {
  1392. g.mode |= ATTR_REVERSE;
  1393. g.bg = defaultfg;
  1394. if (selected(cx, cy)) {
  1395. drawcol = dc.col[defaultcs];
  1396. g.fg = defaultrcs;
  1397. } else {
  1398. drawcol = dc.col[defaultrcs];
  1399. g.fg = defaultcs;
  1400. }
  1401. } else {
  1402. if (selected(cx, cy)) {
  1403. g.fg = defaultfg;
  1404. g.bg = defaultrcs;
  1405. } else {
  1406. g.fg = defaultbg;
  1407. g.bg = defaultcs;
  1408. }
  1409. drawcol = dc.col[g.bg];
  1410. }
  1411. /* draw the new one */
  1412. if (IS_SET(MODE_FOCUSED)) {
  1413. switch (win.cursor) {
  1414. case 0: /* Blinking block */
  1415. case 1: /* Blinking block (default) */
  1416. if (IS_SET(MODE_BLINK))
  1417. break;
  1418. /* FALLTHROUGH */
  1419. case 2: /* Steady block */
  1420. xdrawglyph(g, cx, cy);
  1421. break;
  1422. case 3: /* Blinking underline */
  1423. if (IS_SET(MODE_BLINK))
  1424. break;
  1425. /* FALLTHROUGH */
  1426. case 4: /* Steady underline */
  1427. XftDrawRect(xw.draw, &drawcol,
  1428. borderpx + cx * win.cw,
  1429. borderpx + (cy + 1) * win.ch - \
  1430. cursorthickness,
  1431. win.cw, cursorthickness);
  1432. break;
  1433. case 5: /* Blinking bar */
  1434. if (IS_SET(MODE_BLINK))
  1435. break;
  1436. /* FALLTHROUGH */
  1437. case 6: /* Steady bar */
  1438. XftDrawRect(xw.draw, &drawcol,
  1439. borderpx + cx * win.cw,
  1440. borderpx + cy * win.ch,
  1441. cursorthickness, win.ch);
  1442. break;
  1443. case 7: /* Blinking st cursor */
  1444. if (IS_SET(MODE_BLINK))
  1445. break;
  1446. /* FALLTHROUGH */
  1447. case 8: /* Steady st cursor */
  1448. g.u = stcursor;
  1449. xdrawglyph(g, cx, cy);
  1450. break;
  1451. }
  1452. } else {
  1453. XftDrawRect(xw.draw, &drawcol,
  1454. borderpx + cx * win.cw,
  1455. borderpx + cy * win.ch,
  1456. win.cw - 1, 1);
  1457. XftDrawRect(xw.draw, &drawcol,
  1458. borderpx + cx * win.cw,
  1459. borderpx + cy * win.ch,
  1460. 1, win.ch - 1);
  1461. XftDrawRect(xw.draw, &drawcol,
  1462. borderpx + (cx + 1) * win.cw - 1,
  1463. borderpx + cy * win.ch,
  1464. 1, win.ch - 1);
  1465. XftDrawRect(xw.draw, &drawcol,
  1466. borderpx + cx * win.cw,
  1467. borderpx + (cy + 1) * win.ch - 1,
  1468. win.cw, 1);
  1469. }
  1470. }
  1471. void
  1472. xsetenv(void)
  1473. {
  1474. char buf[sizeof(long) * 8 + 1];
  1475. snprintf(buf, sizeof(buf), "%lu", xw.win);
  1476. setenv("WINDOWID", buf, 1);
  1477. }
  1478. void
  1479. xseticontitle(char *p)
  1480. {
  1481. XTextProperty prop;
  1482. DEFAULT(p, opt_title);
  1483. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  1484. &prop);
  1485. XSetWMIconName(xw.dpy, xw.win, &prop);
  1486. XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname);
  1487. XFree(prop.value);
  1488. }
  1489. void
  1490. xsettitle(char *p)
  1491. {
  1492. XTextProperty prop;
  1493. DEFAULT(p, opt_title);
  1494. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  1495. &prop);
  1496. XSetWMName(xw.dpy, xw.win, &prop);
  1497. XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
  1498. XFree(prop.value);
  1499. }
  1500. int
  1501. xstartdraw(void)
  1502. {
  1503. return IS_SET(MODE_VISIBLE);
  1504. }
  1505. void
  1506. xdrawline(Line line, int x1, int y1, int x2)
  1507. {
  1508. int i, x, ox, numspecs;
  1509. Glyph base, new;
  1510. XftGlyphFontSpec *specs = xw.specbuf;
  1511. numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
  1512. i = ox = 0;
  1513. for (x = x1; x < x2 && i < numspecs; x++) {
  1514. new = line[x];
  1515. if (new.mode == ATTR_WDUMMY)
  1516. continue;
  1517. if (selected(x, y1))
  1518. new.mode ^= ATTR_REVERSE;
  1519. if (i > 0 && ATTRCMP(base, new)) {
  1520. xdrawglyphfontspecs(specs, base, i, ox, y1);
  1521. specs += i;
  1522. numspecs -= i;
  1523. i = 0;
  1524. }
  1525. if (i == 0) {
  1526. ox = x;
  1527. base = new;
  1528. }
  1529. i++;
  1530. }
  1531. if (i > 0)
  1532. xdrawglyphfontspecs(specs, base, i, ox, y1);
  1533. }
  1534. void
  1535. xfinishdraw(void)
  1536. {
  1537. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
  1538. win.h, 0, 0);
  1539. XSetForeground(xw.dpy, dc.gc,
  1540. dc.col[IS_SET(MODE_REVERSE)?
  1541. defaultfg : defaultbg].pixel);
  1542. }
  1543. void
  1544. xximspot(int x, int y)
  1545. {
  1546. if (xw.ime.xic == NULL)
  1547. return;
  1548. xw.ime.spot.x = borderpx + x * win.cw;
  1549. xw.ime.spot.y = borderpx + (y + 1) * win.ch;
  1550. XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL);
  1551. }
  1552. void
  1553. expose(XEvent *ev)
  1554. {
  1555. redraw();
  1556. }
  1557. void
  1558. visibility(XEvent *ev)
  1559. {
  1560. XVisibilityEvent *e = &ev->xvisibility;
  1561. MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
  1562. }
  1563. void
  1564. unmap(XEvent *ev)
  1565. {
  1566. win.mode &= ~MODE_VISIBLE;
  1567. }
  1568. void
  1569. xsetpointermotion(int set)
  1570. {
  1571. MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
  1572. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
  1573. }
  1574. void
  1575. xsetmode(int set, unsigned int flags)
  1576. {
  1577. int mode = win.mode;
  1578. MODBIT(win.mode, set, flags);
  1579. if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
  1580. redraw();
  1581. }
  1582. int
  1583. xsetcursor(int cursor)
  1584. {
  1585. if (!BETWEEN(cursor, 0, 8)) /* 7-8: st extensions */
  1586. return 1;
  1587. win.cursor = cursor;
  1588. cursorblinks = win.cursor == 0 || win.cursor == 1 ||
  1589. win.cursor == 3 || win.cursor == 5 ||
  1590. win.cursor == 7;
  1591. return 0;
  1592. }
  1593. void
  1594. xseturgency(int add)
  1595. {
  1596. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  1597. MODBIT(h->flags, add, XUrgencyHint);
  1598. XSetWMHints(xw.dpy, xw.win, h);
  1599. XFree(h);
  1600. }
  1601. void
  1602. xbell(void)
  1603. {
  1604. if (!(IS_SET(MODE_FOCUSED)))
  1605. xseturgency(1);
  1606. if (bellvolume)
  1607. XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
  1608. }
  1609. void
  1610. focus(XEvent *ev)
  1611. {
  1612. XFocusChangeEvent *e = &ev->xfocus;
  1613. if (e->mode == NotifyGrab)
  1614. return;
  1615. if (ev->type == FocusIn) {
  1616. if (xw.ime.xic)
  1617. XSetICFocus(xw.ime.xic);
  1618. win.mode |= MODE_FOCUSED;
  1619. xseturgency(0);
  1620. if (IS_SET(MODE_FOCUS))
  1621. ttywrite("\033[I", 3, 0);
  1622. } else {
  1623. if (xw.ime.xic)
  1624. XUnsetICFocus(xw.ime.xic);
  1625. win.mode &= ~MODE_FOCUSED;
  1626. if (IS_SET(MODE_FOCUS))
  1627. ttywrite("\033[O", 3, 0);
  1628. }
  1629. }
  1630. int
  1631. match(uint mask, uint state)
  1632. {
  1633. return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
  1634. }
  1635. char*
  1636. kmap(KeySym k, uint state)
  1637. {
  1638. Key *kp;
  1639. int i;
  1640. /* Check for mapped keys out of X11 function keys. */
  1641. for (i = 0; i < LEN(mappedkeys); i++) {
  1642. if (mappedkeys[i] == k)
  1643. break;
  1644. }
  1645. if (i == LEN(mappedkeys)) {
  1646. if ((k & 0xFFFF) < 0xFD00)
  1647. return NULL;
  1648. }
  1649. for (kp = key; kp < key + LEN(key); kp++) {
  1650. if (kp->k != k)
  1651. continue;
  1652. if (!match(kp->mask, state))
  1653. continue;
  1654. if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
  1655. continue;
  1656. if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
  1657. continue;
  1658. if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
  1659. continue;
  1660. return kp->s;
  1661. }
  1662. return NULL;
  1663. }
  1664. void
  1665. kpress(XEvent *ev)
  1666. {
  1667. XKeyEvent *e = &ev->xkey;
  1668. KeySym ksym;
  1669. char buf[64], *customkey;
  1670. int len;
  1671. Rune c;
  1672. Status status;
  1673. Shortcut *bp;
  1674. if (IS_SET(MODE_KBDLOCK))
  1675. return;
  1676. if (xw.ime.xic)
  1677. len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status);
  1678. else
  1679. len = XLookupString(e, buf, sizeof buf, &ksym, NULL);
  1680. /* 1. shortcuts */
  1681. for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  1682. if (ksym == bp->keysym && match(bp->mod, e->state)) {
  1683. bp->func(&(bp->arg));
  1684. return;
  1685. }
  1686. }
  1687. /* 2. custom keys from config.h */
  1688. if ((customkey = kmap(ksym, e->state))) {
  1689. ttywrite(customkey, strlen(customkey), 1);
  1690. return;
  1691. }
  1692. /* 3. composed string from input method */
  1693. if (len == 0)
  1694. return;
  1695. if (len == 1 && e->state & Mod1Mask) {
  1696. if (IS_SET(MODE_8BIT)) {
  1697. if (*buf < 0177) {
  1698. c = *buf | 0x80;
  1699. len = utf8encode(c, buf);
  1700. }
  1701. } else {
  1702. buf[1] = buf[0];
  1703. buf[0] = '\033';
  1704. len = 2;
  1705. }
  1706. }
  1707. ttywrite(buf, len, 1);
  1708. }
  1709. void
  1710. cmessage(XEvent *e)
  1711. {
  1712. /*
  1713. * See xembed specs
  1714. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  1715. */
  1716. if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  1717. if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  1718. win.mode |= MODE_FOCUSED;
  1719. xseturgency(0);
  1720. } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  1721. win.mode &= ~MODE_FOCUSED;
  1722. }
  1723. } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
  1724. ttyhangup();
  1725. exit(0);
  1726. }
  1727. }
  1728. void
  1729. resize(XEvent *e)
  1730. {
  1731. if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
  1732. return;
  1733. cresize(e->xconfigure.width, e->xconfigure.height);
  1734. }
  1735. void
  1736. run(void)
  1737. {
  1738. XEvent ev;
  1739. int w = win.w, h = win.h;
  1740. fd_set rfd;
  1741. int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing;
  1742. struct timespec seltv, *tv, now, lastblink, trigger;
  1743. double timeout;
  1744. /* Waiting for window mapping */
  1745. do {
  1746. XNextEvent(xw.dpy, &ev);
  1747. /*
  1748. * This XFilterEvent call is required because of XOpenIM. It
  1749. * does filter out the key event and some client message for
  1750. * the input method too.
  1751. */
  1752. if (XFilterEvent(&ev, None))
  1753. continue;
  1754. if (ev.type == ConfigureNotify) {
  1755. w = ev.xconfigure.width;
  1756. h = ev.xconfigure.height;
  1757. }
  1758. } while (ev.type != MapNotify);
  1759. ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
  1760. cresize(w, h);
  1761. for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) {
  1762. FD_ZERO(&rfd);
  1763. FD_SET(ttyfd, &rfd);
  1764. FD_SET(xfd, &rfd);
  1765. if (XPending(xw.dpy))
  1766. timeout = 0; /* existing events might not set xfd */
  1767. seltv.tv_sec = timeout / 1E3;
  1768. seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec);
  1769. tv = timeout >= 0 ? &seltv : NULL;
  1770. if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
  1771. if (errno == EINTR)
  1772. continue;
  1773. die("select failed: %s\n", strerror(errno));
  1774. }
  1775. clock_gettime(CLOCK_MONOTONIC, &now);
  1776. if (FD_ISSET(ttyfd, &rfd))
  1777. ttyread();
  1778. xev = 0;
  1779. while (XPending(xw.dpy)) {
  1780. xev = 1;
  1781. XNextEvent(xw.dpy, &ev);
  1782. if (XFilterEvent(&ev, None))
  1783. continue;
  1784. if (handler[ev.type])
  1785. (handler[ev.type])(&ev);
  1786. }
  1787. /*
  1788. * To reduce flicker and tearing, when new content or event
  1789. * triggers drawing, we first wait a bit to ensure we got
  1790. * everything, and if nothing new arrives - we draw.
  1791. * We start with trying to wait minlatency ms. If more content
  1792. * arrives sooner, we retry with shorter and shorter periods,
  1793. * and eventually draw even without idle after maxlatency ms.
  1794. * Typically this results in low latency while interacting,
  1795. * maximum latency intervals during `cat huge.txt`, and perfect
  1796. * sync with periodic updates from animations/key-repeats/etc.
  1797. */
  1798. if (FD_ISSET(ttyfd, &rfd) || xev) {
  1799. if (!drawing) {
  1800. trigger = now;
  1801. if (IS_SET(MODE_BLINK)) {
  1802. win.mode ^= MODE_BLINK;
  1803. }
  1804. lastblink = now;
  1805. drawing = 1;
  1806. }
  1807. timeout = (maxlatency - TIMEDIFF(now, trigger)) \
  1808. / maxlatency * minlatency;
  1809. if (timeout > 0)
  1810. continue; /* we have time, try to find idle */
  1811. }
  1812. /* idle detected or maxlatency exhausted -> draw */
  1813. timeout = -1;
  1814. if (blinktimeout && (cursorblinks || tattrset(ATTR_BLINK))) {
  1815. timeout = blinktimeout - TIMEDIFF(now, lastblink);
  1816. if (timeout <= 0) {
  1817. if (-timeout > blinktimeout) /* start visible */
  1818. win.mode |= MODE_BLINK;
  1819. win.mode ^= MODE_BLINK;
  1820. tsetdirtattr(ATTR_BLINK);
  1821. lastblink = now;
  1822. timeout = blinktimeout;
  1823. }
  1824. }
  1825. draw();
  1826. XFlush(xw.dpy);
  1827. drawing = 0;
  1828. }
  1829. }
  1830. void
  1831. usage(void)
  1832. {
  1833. die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
  1834. " [-n name] [-o file]\n"
  1835. " [-T title] [-t title] [-w windowid]"
  1836. " [[-e] command [args ...]]\n"
  1837. " %s [-aiv] [-c class] [-f font] [-g geometry]"
  1838. " [-n name] [-o file]\n"
  1839. " [-T title] [-t title] [-w windowid] -l line"
  1840. " [stty_args ...]\n", argv0, argv0);
  1841. }
  1842. int
  1843. main(int argc, char *argv[])
  1844. {
  1845. xw.l = xw.t = 0;
  1846. xw.isfixed = False;
  1847. xsetcursor(cursorstyle);
  1848. ARGBEGIN {
  1849. case 'a':
  1850. allowaltscreen = 0;
  1851. break;
  1852. case 'A':
  1853. opt_alpha = EARGF(usage());
  1854. break;
  1855. case 'c':
  1856. opt_class = EARGF(usage());
  1857. break;
  1858. case 'e':
  1859. if (argc > 0)
  1860. --argc, ++argv;
  1861. goto run;
  1862. case 'f':
  1863. opt_font = EARGF(usage());
  1864. break;
  1865. case 'g':
  1866. xw.gm = XParseGeometry(EARGF(usage()),
  1867. &xw.l, &xw.t, &cols, &rows);
  1868. break;
  1869. case 'i':
  1870. xw.isfixed = 1;
  1871. break;
  1872. case 'o':
  1873. opt_io = EARGF(usage());
  1874. break;
  1875. case 'l':
  1876. opt_line = EARGF(usage());
  1877. break;
  1878. case 'n':
  1879. opt_name = EARGF(usage());
  1880. break;
  1881. case 't':
  1882. case 'T':
  1883. opt_title = EARGF(usage());
  1884. break;
  1885. case 'w':
  1886. opt_embed = EARGF(usage());
  1887. break;
  1888. case 'v':
  1889. die("%s " VERSION "\n", argv0);
  1890. break;
  1891. default:
  1892. usage();
  1893. } ARGEND;
  1894. run:
  1895. if (argc > 0) /* eat all remaining arguments */
  1896. opt_cmd = argv;
  1897. if (!opt_title)
  1898. opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
  1899. setlocale(LC_CTYPE, "");
  1900. XSetLocaleModifiers("");
  1901. cols = MAX(cols, 1);
  1902. rows = MAX(rows, 1);
  1903. tnew(cols, rows);
  1904. xinit(cols, rows);
  1905. xsetenv();
  1906. selinit();
  1907. run();
  1908. return 0;
  1909. }