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 <limits.h>
  4. #include <locale.h>
  5. #include <signal.h>
  6. #include <sys/select.h>
  7. #include <time.h>
  8. #include <unistd.h>
  9. #include <libgen.h>
  10. #include <X11/Xatom.h>
  11. #include <X11/Xlib.h>
  12. #include <X11/cursorfont.h>
  13. #include <X11/keysym.h>
  14. #include <X11/Xft/Xft.h>
  15. #include <X11/XKBlib.h>
  16. static char *argv0;
  17. #include "arg.h"
  18. #include "st.h"
  19. #include "win.h"
  20. /* types used in config.h */
  21. typedef struct {
  22. uint mod;
  23. KeySym keysym;
  24. void (*func)(const Arg *);
  25. const Arg arg;
  26. } Shortcut;
  27. typedef struct {
  28. uint b;
  29. uint mask;
  30. char *s;
  31. } MouseShortcut;
  32. typedef struct {
  33. KeySym k;
  34. uint mask;
  35. char *s;
  36. /* three-valued logic variables: 0 indifferent, 1 on, -1 off */
  37. signed char appkey; /* application keypad */
  38. signed char appcursor; /* application cursor */
  39. } Key;
  40. /* X modifiers */
  41. #define XK_ANY_MOD UINT_MAX
  42. #define XK_NO_MOD 0
  43. #define XK_SWITCH_MOD (1<<13)
  44. /* function definitions used in config.h */
  45. static void clipcopy(const Arg *);
  46. static void clippaste(const Arg *);
  47. static void numlock(const Arg *);
  48. static void selpaste(const Arg *);
  49. static void zoom(const Arg *);
  50. static void zoomabs(const Arg *);
  51. static void zoomreset(const Arg *);
  52. /* config.h for applying patches and the configuration. */
  53. #include "config.h"
  54. /* XEMBED messages */
  55. #define XEMBED_FOCUS_IN 4
  56. #define XEMBED_FOCUS_OUT 5
  57. /* macros */
  58. #define IS_SET(flag) ((win.mode & (flag)) != 0)
  59. #define TRUERED(x) (((x) & 0xff0000) >> 8)
  60. #define TRUEGREEN(x) (((x) & 0xff00))
  61. #define TRUEBLUE(x) (((x) & 0xff) << 8)
  62. typedef XftDraw *Draw;
  63. typedef XftColor Color;
  64. typedef XftGlyphFontSpec GlyphFontSpec;
  65. /* Purely graphic info */
  66. typedef struct {
  67. int tw, th; /* tty width and height */
  68. int w, h; /* window width and height */
  69. int ch; /* char height */
  70. int cw; /* char width */
  71. int mode; /* window state/mode flags */
  72. int cursor; /* cursor style */
  73. } TermWindow;
  74. typedef struct {
  75. Display *dpy;
  76. Colormap cmap;
  77. Window win;
  78. Drawable buf;
  79. GlyphFontSpec *specbuf; /* font spec buffer used for rendering */
  80. Atom xembed, wmdeletewin, netwmname, netwmpid;
  81. XIM xim;
  82. XIC xic;
  83. Draw draw;
  84. Visual *vis;
  85. XSetWindowAttributes attrs;
  86. int scr;
  87. int isfixed; /* is fixed geometry? */
  88. int l, t; /* left and top offset */
  89. int gm; /* geometry mask */
  90. } XWindow;
  91. typedef struct {
  92. Atom xtarget;
  93. char *primary, *clipboard;
  94. struct timespec tclick1;
  95. struct timespec tclick2;
  96. } XSelection;
  97. /* Font structure */
  98. #define Font Font_
  99. typedef struct {
  100. int height;
  101. int width;
  102. int ascent;
  103. int descent;
  104. int badslant;
  105. int badweight;
  106. short lbearing;
  107. short rbearing;
  108. XftFont *match;
  109. FcFontSet *set;
  110. FcPattern *pattern;
  111. } Font;
  112. /* Drawing Context */
  113. typedef struct {
  114. Color *col;
  115. size_t collen;
  116. Font font, bfont, ifont, ibfont;
  117. GC gc;
  118. } DC;
  119. static inline ushort sixd_to_16bit(int);
  120. static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
  121. static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
  122. static void xdrawglyph(Glyph, int, int);
  123. static void xclear(int, int, int, int);
  124. static int xgeommasktogravity(int);
  125. static void xinit(int, int);
  126. static void cresize(int, int);
  127. static void xresize(int, int);
  128. static void xhints(void);
  129. static int xloadcolor(int, const char *, Color *);
  130. static int xloadfont(Font *, FcPattern *);
  131. static void xloadfonts(char *, double);
  132. static void xunloadfont(Font *);
  133. static void xunloadfonts(void);
  134. static void xsetenv(void);
  135. static void xseturgency(int);
  136. static int evcol(XEvent *);
  137. static int evrow(XEvent *);
  138. static void expose(XEvent *);
  139. static void visibility(XEvent *);
  140. static void unmap(XEvent *);
  141. static void kpress(XEvent *);
  142. static void cmessage(XEvent *);
  143. static void resize(XEvent *);
  144. static void focus(XEvent *);
  145. static void brelease(XEvent *);
  146. static void bpress(XEvent *);
  147. static void bmotion(XEvent *);
  148. static void propnotify(XEvent *);
  149. static void selnotify(XEvent *);
  150. static void selclear_(XEvent *);
  151. static void selrequest(XEvent *);
  152. static void setsel(char *, Time);
  153. static void mousesel(XEvent *, int);
  154. static void mousereport(XEvent *);
  155. static char *kmap(KeySym, uint);
  156. static int match(uint, uint);
  157. static void run(void);
  158. static void usage(void);
  159. static void (*handler[LASTEvent])(XEvent *) = {
  160. [KeyPress] = kpress,
  161. [ClientMessage] = cmessage,
  162. [ConfigureNotify] = resize,
  163. [VisibilityNotify] = visibility,
  164. [UnmapNotify] = unmap,
  165. [Expose] = expose,
  166. [FocusIn] = focus,
  167. [FocusOut] = focus,
  168. [MotionNotify] = bmotion,
  169. [ButtonPress] = bpress,
  170. [ButtonRelease] = brelease,
  171. /*
  172. * Uncomment if you want the selection to disappear when you select something
  173. * different in another window.
  174. */
  175. /* [SelectionClear] = selclear_, */
  176. [SelectionNotify] = selnotify,
  177. /*
  178. * PropertyNotify is only turned on when there is some INCR transfer happening
  179. * for the selection retrieval.
  180. */
  181. [PropertyNotify] = propnotify,
  182. [SelectionRequest] = selrequest,
  183. };
  184. /* Globals */
  185. static DC dc;
  186. static XWindow xw;
  187. static XSelection xsel;
  188. static TermWindow win;
  189. /* Font Ring Cache */
  190. enum {
  191. FRC_NORMAL,
  192. FRC_ITALIC,
  193. FRC_BOLD,
  194. FRC_ITALICBOLD
  195. };
  196. typedef struct {
  197. XftFont *font;
  198. int flags;
  199. Rune unicodep;
  200. } Fontcache;
  201. /* Fontcache is an array now. A new font will be appended to the array. */
  202. static Fontcache frc[16];
  203. static int frclen = 0;
  204. static char *usedfont = NULL;
  205. static double usedfontsize = 0;
  206. static double defaultfontsize = 0;
  207. static char *opt_class = NULL;
  208. static char **opt_cmd = NULL;
  209. static char *opt_embed = NULL;
  210. static char *opt_font = NULL;
  211. static char *opt_io = NULL;
  212. static char *opt_line = NULL;
  213. static char *opt_name = NULL;
  214. static char *opt_title = NULL;
  215. static int oldbutton = 3; /* button event on startup: 3 = release */
  216. void
  217. clipcopy(const Arg *dummy)
  218. {
  219. Atom clipboard;
  220. if (xsel.clipboard != NULL)
  221. free(xsel.clipboard);
  222. if (xsel.primary != NULL) {
  223. xsel.clipboard = xstrdup(xsel.primary);
  224. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  225. XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
  226. }
  227. }
  228. void
  229. clippaste(const Arg *dummy)
  230. {
  231. Atom clipboard;
  232. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  233. XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard,
  234. xw.win, CurrentTime);
  235. }
  236. void
  237. selpaste(const Arg *dummy)
  238. {
  239. XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY,
  240. xw.win, CurrentTime);
  241. }
  242. void
  243. numlock(const Arg *dummy)
  244. {
  245. win.mode ^= MODE_NUMLOCK;
  246. }
  247. void
  248. zoom(const Arg *arg)
  249. {
  250. Arg larg;
  251. larg.f = usedfontsize + arg->f;
  252. zoomabs(&larg);
  253. }
  254. void
  255. zoomabs(const Arg *arg)
  256. {
  257. xunloadfonts();
  258. xloadfonts(usedfont, arg->f);
  259. cresize(0, 0);
  260. redraw();
  261. xhints();
  262. }
  263. void
  264. zoomreset(const Arg *arg)
  265. {
  266. Arg larg;
  267. if (defaultfontsize > 0) {
  268. larg.f = defaultfontsize;
  269. zoomabs(&larg);
  270. }
  271. }
  272. int
  273. evcol(XEvent *e)
  274. {
  275. int x = e->xbutton.x - borderpx;
  276. LIMIT(x, 0, win.tw - 1);
  277. return x / win.cw;
  278. }
  279. int
  280. evrow(XEvent *e)
  281. {
  282. int y = e->xbutton.y - borderpx;
  283. LIMIT(y, 0, win.th - 1);
  284. return y / win.ch;
  285. }
  286. void
  287. mousesel(XEvent *e, int done)
  288. {
  289. int type, seltype = SEL_REGULAR;
  290. uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
  291. for (type = 1; type < LEN(selmasks); ++type) {
  292. if (match(selmasks[type], state)) {
  293. seltype = type;
  294. break;
  295. }
  296. }
  297. selextend(evcol(e), evrow(e), seltype, done);
  298. if (done)
  299. setsel(getsel(), e->xbutton.time);
  300. }
  301. void
  302. mousereport(XEvent *e)
  303. {
  304. int len, x = evcol(e), y = evrow(e),
  305. button = e->xbutton.button, state = e->xbutton.state;
  306. char buf[40];
  307. static int ox, oy;
  308. /* from urxvt */
  309. if (e->xbutton.type == MotionNotify) {
  310. if (x == ox && y == oy)
  311. return;
  312. if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
  313. return;
  314. /* MOUSE_MOTION: no reporting if no button is pressed */
  315. if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
  316. return;
  317. button = oldbutton + 32;
  318. ox = x;
  319. oy = y;
  320. } else {
  321. if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
  322. button = 3;
  323. } else {
  324. button -= Button1;
  325. if (button >= 3)
  326. button += 64 - 3;
  327. }
  328. if (e->xbutton.type == ButtonPress) {
  329. oldbutton = button;
  330. ox = x;
  331. oy = y;
  332. } else if (e->xbutton.type == ButtonRelease) {
  333. oldbutton = 3;
  334. /* MODE_MOUSEX10: no button release reporting */
  335. if (IS_SET(MODE_MOUSEX10))
  336. return;
  337. if (button == 64 || button == 65)
  338. return;
  339. }
  340. }
  341. if (!IS_SET(MODE_MOUSEX10)) {
  342. button += ((state & ShiftMask ) ? 4 : 0)
  343. + ((state & Mod4Mask ) ? 8 : 0)
  344. + ((state & ControlMask) ? 16 : 0);
  345. }
  346. if (IS_SET(MODE_MOUSESGR)) {
  347. len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
  348. button, x+1, y+1,
  349. e->xbutton.type == ButtonRelease ? 'm' : 'M');
  350. } else if (x < 223 && y < 223) {
  351. len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
  352. 32+button, 32+x+1, 32+y+1);
  353. } else {
  354. return;
  355. }
  356. ttywrite(buf, len, 0);
  357. }
  358. void
  359. bpress(XEvent *e)
  360. {
  361. struct timespec now;
  362. MouseShortcut *ms;
  363. int snap;
  364. if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
  365. mousereport(e);
  366. return;
  367. }
  368. for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
  369. if (e->xbutton.button == ms->b
  370. && match(ms->mask, e->xbutton.state)) {
  371. ttywrite(ms->s, strlen(ms->s), 1);
  372. return;
  373. }
  374. }
  375. if (e->xbutton.button == Button1) {
  376. /*
  377. * If the user clicks below predefined timeouts specific
  378. * snapping behaviour is exposed.
  379. */
  380. clock_gettime(CLOCK_MONOTONIC, &now);
  381. if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) {
  382. snap = SNAP_LINE;
  383. } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) {
  384. snap = SNAP_WORD;
  385. } else {
  386. snap = 0;
  387. }
  388. xsel.tclick2 = xsel.tclick1;
  389. xsel.tclick1 = now;
  390. selstart(evcol(e), evrow(e), snap);
  391. }
  392. }
  393. void
  394. propnotify(XEvent *e)
  395. {
  396. XPropertyEvent *xpev;
  397. Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  398. xpev = &e->xproperty;
  399. if (xpev->state == PropertyNewValue &&
  400. (xpev->atom == XA_PRIMARY ||
  401. xpev->atom == clipboard)) {
  402. selnotify(e);
  403. }
  404. }
  405. void
  406. selnotify(XEvent *e)
  407. {
  408. ulong nitems, ofs, rem;
  409. int format;
  410. uchar *data, *last, *repl;
  411. Atom type, incratom, property = None;
  412. incratom = XInternAtom(xw.dpy, "INCR", 0);
  413. ofs = 0;
  414. if (e->type == SelectionNotify)
  415. property = e->xselection.property;
  416. else if (e->type == PropertyNotify)
  417. property = e->xproperty.atom;
  418. if (property == None)
  419. return;
  420. do {
  421. if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
  422. BUFSIZ/4, False, AnyPropertyType,
  423. &type, &format, &nitems, &rem,
  424. &data)) {
  425. fprintf(stderr, "Clipboard allocation failed\n");
  426. return;
  427. }
  428. if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
  429. /*
  430. * If there is some PropertyNotify with no data, then
  431. * this is the signal of the selection owner that all
  432. * data has been transferred. We won't need to receive
  433. * PropertyNotify events anymore.
  434. */
  435. MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
  436. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
  437. &xw.attrs);
  438. }
  439. if (type == incratom) {
  440. /*
  441. * Activate the PropertyNotify events so we receive
  442. * when the selection owner does send us the next
  443. * chunk of data.
  444. */
  445. MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
  446. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
  447. &xw.attrs);
  448. /*
  449. * Deleting the property is the transfer start signal.
  450. */
  451. XDeleteProperty(xw.dpy, xw.win, (int)property);
  452. continue;
  453. }
  454. /*
  455. * As seen in getsel:
  456. * Line endings are inconsistent in the terminal and GUI world
  457. * copy and pasting. When receiving some selection data,
  458. * replace all '\n' with '\r'.
  459. * FIXME: Fix the computer world.
  460. */
  461. repl = data;
  462. last = data + nitems * format / 8;
  463. while ((repl = memchr(repl, '\n', last - repl))) {
  464. *repl++ = '\r';
  465. }
  466. if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
  467. ttywrite("\033[200~", 6, 0);
  468. ttywrite((char *)data, nitems * format / 8, 1);
  469. if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
  470. ttywrite("\033[201~", 6, 0);
  471. XFree(data);
  472. /* number of 32-bit chunks returned */
  473. ofs += nitems * format / 32;
  474. } while (rem > 0);
  475. /*
  476. * Deleting the property again tells the selection owner to send the
  477. * next data chunk in the property.
  478. */
  479. XDeleteProperty(xw.dpy, xw.win, (int)property);
  480. }
  481. void
  482. xclipcopy(void)
  483. {
  484. clipcopy(NULL);
  485. }
  486. void
  487. selclear_(XEvent *e)
  488. {
  489. selclear();
  490. }
  491. void
  492. selrequest(XEvent *e)
  493. {
  494. XSelectionRequestEvent *xsre;
  495. XSelectionEvent xev;
  496. Atom xa_targets, string, clipboard;
  497. char *seltext;
  498. xsre = (XSelectionRequestEvent *) e;
  499. xev.type = SelectionNotify;
  500. xev.requestor = xsre->requestor;
  501. xev.selection = xsre->selection;
  502. xev.target = xsre->target;
  503. xev.time = xsre->time;
  504. if (xsre->property == None)
  505. xsre->property = xsre->target;
  506. /* reject */
  507. xev.property = None;
  508. xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
  509. if (xsre->target == xa_targets) {
  510. /* respond with the supported type */
  511. string = xsel.xtarget;
  512. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  513. XA_ATOM, 32, PropModeReplace,
  514. (uchar *) &string, 1);
  515. xev.property = xsre->property;
  516. } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
  517. /*
  518. * xith XA_STRING non ascii characters may be incorrect in the
  519. * requestor. It is not our problem, use utf8.
  520. */
  521. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  522. if (xsre->selection == XA_PRIMARY) {
  523. seltext = xsel.primary;
  524. } else if (xsre->selection == clipboard) {
  525. seltext = xsel.clipboard;
  526. } else {
  527. fprintf(stderr,
  528. "Unhandled clipboard selection 0x%lx\n",
  529. xsre->selection);
  530. return;
  531. }
  532. if (seltext != NULL) {
  533. XChangeProperty(xsre->display, xsre->requestor,
  534. xsre->property, xsre->target,
  535. 8, PropModeReplace,
  536. (uchar *)seltext, strlen(seltext));
  537. xev.property = xsre->property;
  538. }
  539. }
  540. /* all done, send a notification to the listener */
  541. if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
  542. fprintf(stderr, "Error sending SelectionNotify event\n");
  543. }
  544. void
  545. setsel(char *str, Time t)
  546. {
  547. free(xsel.primary);
  548. xsel.primary = str;
  549. XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
  550. if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
  551. selclear();
  552. }
  553. void
  554. xsetsel(char *str)
  555. {
  556. setsel(str, CurrentTime);
  557. }
  558. void
  559. brelease(XEvent *e)
  560. {
  561. if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
  562. mousereport(e);
  563. return;
  564. }
  565. if (e->xbutton.button == Button2)
  566. selpaste(NULL);
  567. else if (e->xbutton.button == Button1)
  568. mousesel(e, 1);
  569. }
  570. void
  571. bmotion(XEvent *e)
  572. {
  573. if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
  574. mousereport(e);
  575. return;
  576. }
  577. mousesel(e, 0);
  578. }
  579. void
  580. cresize(int width, int height)
  581. {
  582. int col, row;
  583. if (width != 0)
  584. win.w = width;
  585. if (height != 0)
  586. win.h = height;
  587. col = (win.w - 2 * borderpx) / win.cw;
  588. row = (win.h - 2 * borderpx) / win.ch;
  589. tresize(col, row);
  590. xresize(col, row);
  591. ttyresize(win.tw, win.th);
  592. }
  593. void
  594. xresize(int col, int row)
  595. {
  596. win.tw = MAX(1, col * win.cw);
  597. win.th = MAX(1, row * win.ch);
  598. XFreePixmap(xw.dpy, xw.buf);
  599. xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
  600. DefaultDepth(xw.dpy, xw.scr));
  601. XftDrawChange(xw.draw, xw.buf);
  602. xclear(0, 0, win.w, win.h);
  603. /* resize to new width */
  604. xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
  605. }
  606. ushort
  607. sixd_to_16bit(int x)
  608. {
  609. return x == 0 ? 0 : 0x3737 + 0x2828 * x;
  610. }
  611. int
  612. xloadcolor(int i, const char *name, Color *ncolor)
  613. {
  614. XRenderColor color = { .alpha = 0xffff };
  615. if (!name) {
  616. if (BETWEEN(i, 16, 255)) { /* 256 color */
  617. if (i < 6*6*6+16) { /* same colors as xterm */
  618. color.red = sixd_to_16bit( ((i-16)/36)%6 );
  619. color.green = sixd_to_16bit( ((i-16)/6) %6 );
  620. color.blue = sixd_to_16bit( ((i-16)/1) %6 );
  621. } else { /* greyscale */
  622. color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
  623. color.green = color.blue = color.red;
  624. }
  625. return XftColorAllocValue(xw.dpy, xw.vis,
  626. xw.cmap, &color, ncolor);
  627. } else
  628. name = colorname[i];
  629. }
  630. return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
  631. }
  632. void
  633. xloadcols(void)
  634. {
  635. int i;
  636. static int loaded;
  637. Color *cp;
  638. dc.collen = MAX(LEN(colorname), 256);
  639. dc.col = xmalloc(dc.collen * sizeof(Color));
  640. if (loaded) {
  641. for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
  642. XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
  643. }
  644. for (i = 0; i < dc.collen; i++)
  645. if (!xloadcolor(i, NULL, &dc.col[i])) {
  646. if (colorname[i])
  647. die("Could not allocate color '%s'\n", colorname[i]);
  648. else
  649. die("Could not allocate color %d\n", i);
  650. }
  651. loaded = 1;
  652. }
  653. int
  654. xsetcolorname(int x, const char *name)
  655. {
  656. Color ncolor;
  657. if (!BETWEEN(x, 0, dc.collen))
  658. return 1;
  659. if (!xloadcolor(x, name, &ncolor))
  660. return 1;
  661. XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
  662. dc.col[x] = ncolor;
  663. return 0;
  664. }
  665. /*
  666. * Absolute coordinates.
  667. */
  668. void
  669. xclear(int x1, int y1, int x2, int y2)
  670. {
  671. XftDrawRect(xw.draw,
  672. &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
  673. x1, y1, x2-x1, y2-y1);
  674. }
  675. void
  676. xhints(void)
  677. {
  678. XClassHint class = {opt_name ? opt_name : termname,
  679. opt_class ? opt_class : termname};
  680. XWMHints wm = {.flags = InputHint, .input = 1};
  681. XSizeHints *sizeh = NULL;
  682. sizeh = XAllocSizeHints();
  683. sizeh->flags = PSize | PResizeInc | PBaseSize;
  684. sizeh->height = win.h;
  685. sizeh->width = win.w;
  686. sizeh->height_inc = win.ch;
  687. sizeh->width_inc = win.cw;
  688. sizeh->base_height = 2 * borderpx;
  689. sizeh->base_width = 2 * borderpx;
  690. if (xw.isfixed) {
  691. sizeh->flags |= PMaxSize | PMinSize;
  692. sizeh->min_width = sizeh->max_width = win.w;
  693. sizeh->min_height = sizeh->max_height = win.h;
  694. }
  695. if (xw.gm & (XValue|YValue)) {
  696. sizeh->flags |= USPosition | PWinGravity;
  697. sizeh->x = xw.l;
  698. sizeh->y = xw.t;
  699. sizeh->win_gravity = xgeommasktogravity(xw.gm);
  700. }
  701. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
  702. &class);
  703. XFree(sizeh);
  704. }
  705. int
  706. xgeommasktogravity(int mask)
  707. {
  708. switch (mask & (XNegative|YNegative)) {
  709. case 0:
  710. return NorthWestGravity;
  711. case XNegative:
  712. return NorthEastGravity;
  713. case YNegative:
  714. return SouthWestGravity;
  715. }
  716. return SouthEastGravity;
  717. }
  718. int
  719. xloadfont(Font *f, FcPattern *pattern)
  720. {
  721. FcPattern *configured;
  722. FcPattern *match;
  723. FcResult result;
  724. XGlyphInfo extents;
  725. int wantattr, haveattr;
  726. /*
  727. * Manually configure instead of calling XftMatchFont
  728. * so that we can use the configured pattern for
  729. * "missing glyph" lookups.
  730. */
  731. configured = FcPatternDuplicate(pattern);
  732. if (!configured)
  733. return 1;
  734. FcConfigSubstitute(NULL, configured, FcMatchPattern);
  735. XftDefaultSubstitute(xw.dpy, xw.scr, configured);
  736. match = FcFontMatch(NULL, configured, &result);
  737. if (!match) {
  738. FcPatternDestroy(configured);
  739. return 1;
  740. }
  741. if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
  742. FcPatternDestroy(configured);
  743. FcPatternDestroy(match);
  744. return 1;
  745. }
  746. if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
  747. XftResultMatch)) {
  748. /*
  749. * Check if xft was unable to find a font with the appropriate
  750. * slant but gave us one anyway. Try to mitigate.
  751. */
  752. if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
  753. &haveattr) != XftResultMatch) || haveattr < wantattr) {
  754. f->badslant = 1;
  755. fputs("st: font slant does not match\n", stderr);
  756. }
  757. }
  758. if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
  759. XftResultMatch)) {
  760. if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
  761. &haveattr) != XftResultMatch) || haveattr != wantattr) {
  762. f->badweight = 1;
  763. fputs("st: font weight does not match\n", stderr);
  764. }
  765. }
  766. XftTextExtentsUtf8(xw.dpy, f->match,
  767. (const FcChar8 *) ascii_printable,
  768. strlen(ascii_printable), &extents);
  769. f->set = NULL;
  770. f->pattern = configured;
  771. f->ascent = f->match->ascent;
  772. f->descent = f->match->descent;
  773. f->lbearing = 0;
  774. f->rbearing = f->match->max_advance_width;
  775. f->height = f->ascent + f->descent;
  776. f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
  777. return 0;
  778. }
  779. void
  780. xloadfonts(char *fontstr, double fontsize)
  781. {
  782. FcPattern *pattern;
  783. double fontval;
  784. float ceilf(float);
  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. }