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.

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