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.

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