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.

2018 lines
45 KiB

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