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.

2046 lines
46KB

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