My patched version of suckless' terminal - st.
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.

2060 lines
46 KiB

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