logo

st

Unnamed repository; edit this file 'description' to name the repository. git clone https://hacktivis.me/git/st.git

x.c (47419B)


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