My build of suckless st terminal
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2040 lines
45 KiB

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