My build of suckless st terminal
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.

2021 lines
45 KiB

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