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.

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