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.

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