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.

1952 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. free(xsel.clipboard);
  222. xsel.clipboard = NULL;
  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. if (!str)
  549. return;
  550. free(xsel.primary);
  551. xsel.primary = str;
  552. XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
  553. if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
  554. selclear();
  555. }
  556. void
  557. xsetsel(char *str)
  558. {
  559. setsel(str, CurrentTime);
  560. }
  561. void
  562. brelease(XEvent *e)
  563. {
  564. if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
  565. mousereport(e);
  566. return;
  567. }
  568. if (e->xbutton.button == Button2)
  569. selpaste(NULL);
  570. else if (e->xbutton.button == Button1)
  571. mousesel(e, 1);
  572. }
  573. void
  574. bmotion(XEvent *e)
  575. {
  576. if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
  577. mousereport(e);
  578. return;
  579. }
  580. mousesel(e, 0);
  581. }
  582. void
  583. cresize(int width, int height)
  584. {
  585. int col, row;
  586. if (width != 0)
  587. win.w = width;
  588. if (height != 0)
  589. win.h = height;
  590. col = (win.w - 2 * borderpx) / win.cw;
  591. row = (win.h - 2 * borderpx) / win.ch;
  592. tresize(col, row);
  593. xresize(col, row);
  594. ttyresize(win.tw, win.th);
  595. }
  596. void
  597. xresize(int col, int row)
  598. {
  599. win.tw = MAX(1, col * win.cw);
  600. win.th = MAX(1, row * win.ch);
  601. XFreePixmap(xw.dpy, xw.buf);
  602. xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
  603. DefaultDepth(xw.dpy, xw.scr));
  604. XftDrawChange(xw.draw, xw.buf);
  605. xclear(0, 0, win.w, win.h);
  606. /* resize to new width */
  607. xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
  608. }
  609. ushort
  610. sixd_to_16bit(int x)
  611. {
  612. return x == 0 ? 0 : 0x3737 + 0x2828 * x;
  613. }
  614. int
  615. xloadcolor(int i, const char *name, Color *ncolor)
  616. {
  617. XRenderColor color = { .alpha = 0xffff };
  618. if (!name) {
  619. if (BETWEEN(i, 16, 255)) { /* 256 color */
  620. if (i < 6*6*6+16) { /* same colors as xterm */
  621. color.red = sixd_to_16bit( ((i-16)/36)%6 );
  622. color.green = sixd_to_16bit( ((i-16)/6) %6 );
  623. color.blue = sixd_to_16bit( ((i-16)/1) %6 );
  624. } else { /* greyscale */
  625. color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
  626. color.green = color.blue = color.red;
  627. }
  628. return XftColorAllocValue(xw.dpy, xw.vis,
  629. xw.cmap, &color, ncolor);
  630. } else
  631. name = colorname[i];
  632. }
  633. return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
  634. }
  635. void
  636. xloadcols(void)
  637. {
  638. int i;
  639. static int loaded;
  640. Color *cp;
  641. dc.collen = MAX(LEN(colorname), 256);
  642. dc.col = xmalloc(dc.collen * sizeof(Color));
  643. if (loaded) {
  644. for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
  645. XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
  646. }
  647. for (i = 0; i < dc.collen; i++)
  648. if (!xloadcolor(i, NULL, &dc.col[i])) {
  649. if (colorname[i])
  650. die("Could not allocate color '%s'\n", colorname[i]);
  651. else
  652. die("Could not allocate color %d\n", i);
  653. }
  654. loaded = 1;
  655. }
  656. int
  657. xsetcolorname(int x, const char *name)
  658. {
  659. Color ncolor;
  660. if (!BETWEEN(x, 0, dc.collen))
  661. return 1;
  662. if (!xloadcolor(x, name, &ncolor))
  663. return 1;
  664. XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
  665. dc.col[x] = ncolor;
  666. return 0;
  667. }
  668. /*
  669. * Absolute coordinates.
  670. */
  671. void
  672. xclear(int x1, int y1, int x2, int y2)
  673. {
  674. XftDrawRect(xw.draw,
  675. &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
  676. x1, y1, x2-x1, y2-y1);
  677. }
  678. void
  679. xhints(void)
  680. {
  681. XClassHint class = {opt_name ? opt_name : termname,
  682. opt_class ? opt_class : termname};
  683. XWMHints wm = {.flags = InputHint, .input = 1};
  684. XSizeHints *sizeh;
  685. sizeh = XAllocSizeHints();
  686. sizeh->flags = PSize | PResizeInc | PBaseSize;
  687. sizeh->height = win.h;
  688. sizeh->width = win.w;
  689. sizeh->height_inc = win.ch;
  690. sizeh->width_inc = win.cw;
  691. sizeh->base_height = 2 * borderpx;
  692. sizeh->base_width = 2 * borderpx;
  693. if (xw.isfixed) {
  694. sizeh->flags |= PMaxSize | PMinSize;
  695. sizeh->min_width = sizeh->max_width = win.w;
  696. sizeh->min_height = sizeh->max_height = win.h;
  697. }
  698. if (xw.gm & (XValue|YValue)) {
  699. sizeh->flags |= USPosition | PWinGravity;
  700. sizeh->x = xw.l;
  701. sizeh->y = xw.t;
  702. sizeh->win_gravity = xgeommasktogravity(xw.gm);
  703. }
  704. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
  705. &class);
  706. XFree(sizeh);
  707. }
  708. int
  709. xgeommasktogravity(int mask)
  710. {
  711. switch (mask & (XNegative|YNegative)) {
  712. case 0:
  713. return NorthWestGravity;
  714. case XNegative:
  715. return NorthEastGravity;
  716. case YNegative:
  717. return SouthWestGravity;
  718. }
  719. return SouthEastGravity;
  720. }
  721. int
  722. xloadfont(Font *f, FcPattern *pattern)
  723. {
  724. FcPattern *configured;
  725. FcPattern *match;
  726. FcResult result;
  727. XGlyphInfo extents;
  728. int wantattr, haveattr;
  729. /*
  730. * Manually configure instead of calling XftMatchFont
  731. * so that we can use the configured pattern for
  732. * "missing glyph" lookups.
  733. */
  734. configured = FcPatternDuplicate(pattern);
  735. if (!configured)
  736. return 1;
  737. FcConfigSubstitute(NULL, configured, FcMatchPattern);
  738. XftDefaultSubstitute(xw.dpy, xw.scr, configured);
  739. match = FcFontMatch(NULL, configured, &result);
  740. if (!match) {
  741. FcPatternDestroy(configured);
  742. return 1;
  743. }
  744. if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
  745. FcPatternDestroy(configured);
  746. FcPatternDestroy(match);
  747. return 1;
  748. }
  749. if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
  750. XftResultMatch)) {
  751. /*
  752. * Check if xft was unable to find a font with the appropriate
  753. * slant but gave us one anyway. Try to mitigate.
  754. */
  755. if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
  756. &haveattr) != XftResultMatch) || haveattr < wantattr) {
  757. f->badslant = 1;
  758. fputs("st: font slant does not match\n", stderr);
  759. }
  760. }
  761. if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
  762. XftResultMatch)) {
  763. if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
  764. &haveattr) != XftResultMatch) || haveattr != wantattr) {
  765. f->badweight = 1;
  766. fputs("st: font weight does not match\n", stderr);
  767. }
  768. }
  769. XftTextExtentsUtf8(xw.dpy, f->match,
  770. (const FcChar8 *) ascii_printable,
  771. strlen(ascii_printable), &extents);
  772. f->set = NULL;
  773. f->pattern = configured;
  774. f->ascent = f->match->ascent;
  775. f->descent = f->match->descent;
  776. f->lbearing = 0;
  777. f->rbearing = f->match->max_advance_width;
  778. f->height = f->ascent + f->descent;
  779. f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
  780. return 0;
  781. }
  782. void
  783. xloadfonts(char *fontstr, double fontsize)
  784. {
  785. FcPattern *pattern;
  786. double fontval;
  787. if (fontstr[0] == '-') {
  788. pattern = XftXlfdParse(fontstr, False, False);
  789. } else {
  790. pattern = FcNameParse((FcChar8 *)fontstr);
  791. }
  792. if (!pattern)
  793. die("st: can't open font %s\n", fontstr);
  794. if (fontsize > 1) {
  795. FcPatternDel(pattern, FC_PIXEL_SIZE);
  796. FcPatternDel(pattern, FC_SIZE);
  797. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
  798. usedfontsize = fontsize;
  799. } else {
  800. if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
  801. FcResultMatch) {
  802. usedfontsize = fontval;
  803. } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
  804. FcResultMatch) {
  805. usedfontsize = -1;
  806. } else {
  807. /*
  808. * Default font size is 12, if none given. This is to
  809. * have a known usedfontsize value.
  810. */
  811. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
  812. usedfontsize = 12;
  813. }
  814. defaultfontsize = usedfontsize;
  815. }
  816. if (xloadfont(&dc.font, pattern))
  817. die("st: can't open font %s\n", fontstr);
  818. if (usedfontsize < 0) {
  819. FcPatternGetDouble(dc.font.match->pattern,
  820. FC_PIXEL_SIZE, 0, &fontval);
  821. usedfontsize = fontval;
  822. if (fontsize == 0)
  823. defaultfontsize = fontval;
  824. }
  825. /* Setting character width and height. */
  826. win.cw = ceilf(dc.font.width * cwscale);
  827. win.ch = ceilf(dc.font.height * chscale);
  828. FcPatternDel(pattern, FC_SLANT);
  829. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  830. if (xloadfont(&dc.ifont, pattern))
  831. die("st: can't open font %s\n", fontstr);
  832. FcPatternDel(pattern, FC_WEIGHT);
  833. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  834. if (xloadfont(&dc.ibfont, pattern))
  835. die("st: can't open font %s\n", fontstr);
  836. FcPatternDel(pattern, FC_SLANT);
  837. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
  838. if (xloadfont(&dc.bfont, pattern))
  839. die("st: can't open font %s\n", fontstr);
  840. FcPatternDestroy(pattern);
  841. }
  842. void
  843. xunloadfont(Font *f)
  844. {
  845. XftFontClose(xw.dpy, f->match);
  846. FcPatternDestroy(f->pattern);
  847. if (f->set)
  848. FcFontSetDestroy(f->set);
  849. }
  850. void
  851. xunloadfonts(void)
  852. {
  853. /* Free the loaded fonts in the font cache. */
  854. while (frclen > 0)
  855. XftFontClose(xw.dpy, frc[--frclen].font);
  856. xunloadfont(&dc.font);
  857. xunloadfont(&dc.bfont);
  858. xunloadfont(&dc.ifont);
  859. xunloadfont(&dc.ibfont);
  860. }
  861. void
  862. xinit(int cols, int rows)
  863. {
  864. XGCValues gcvalues;
  865. Cursor cursor;
  866. Window parent;
  867. pid_t thispid = getpid();
  868. XColor xmousefg, xmousebg;
  869. if (!(xw.dpy = XOpenDisplay(NULL)))
  870. die("Can't open display\n");
  871. xw.scr = XDefaultScreen(xw.dpy);
  872. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  873. /* font */
  874. if (!FcInit())
  875. die("Could not init fontconfig.\n");
  876. usedfont = (opt_font == NULL)? font : opt_font;
  877. xloadfonts(usedfont, 0);
  878. /* colors */
  879. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  880. xloadcols();
  881. /* adjust fixed window geometry */
  882. win.w = 2 * borderpx + cols * win.cw;
  883. win.h = 2 * borderpx + rows * win.ch;
  884. if (xw.gm & XNegative)
  885. xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
  886. if (xw.gm & YNegative)
  887. xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
  888. /* Events */
  889. xw.attrs.background_pixel = dc.col[defaultbg].pixel;
  890. xw.attrs.border_pixel = dc.col[defaultbg].pixel;
  891. xw.attrs.bit_gravity = NorthWestGravity;
  892. xw.attrs.event_mask = FocusChangeMask | KeyPressMask
  893. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  894. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  895. xw.attrs.colormap = xw.cmap;
  896. if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
  897. parent = XRootWindow(xw.dpy, xw.scr);
  898. xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
  899. win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  900. xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
  901. | CWEventMask | CWColormap, &xw.attrs);
  902. memset(&gcvalues, 0, sizeof(gcvalues));
  903. gcvalues.graphics_exposures = False;
  904. dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
  905. &gcvalues);
  906. xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
  907. DefaultDepth(xw.dpy, xw.scr));
  908. XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
  909. XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
  910. /* font spec buffer */
  911. xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
  912. /* Xft rendering context */
  913. xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  914. /* input methods */
  915. if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  916. XSetLocaleModifiers("@im=local");
  917. if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  918. XSetLocaleModifiers("@im=");
  919. if ((xw.xim = XOpenIM(xw.dpy,
  920. NULL, NULL, NULL)) == NULL) {
  921. die("XOpenIM failed. Could not open input"
  922. " device.\n");
  923. }
  924. }
  925. }
  926. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  927. | XIMStatusNothing, XNClientWindow, xw.win,
  928. XNFocusWindow, xw.win, NULL);
  929. if (xw.xic == NULL)
  930. die("XCreateIC failed. Could not obtain input method.\n");
  931. /* white cursor, black outline */
  932. cursor = XCreateFontCursor(xw.dpy, mouseshape);
  933. XDefineCursor(xw.dpy, xw.win, cursor);
  934. if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
  935. xmousefg.red = 0xffff;
  936. xmousefg.green = 0xffff;
  937. xmousefg.blue = 0xffff;
  938. }
  939. if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
  940. xmousebg.red = 0x0000;
  941. xmousebg.green = 0x0000;
  942. xmousebg.blue = 0x0000;
  943. }
  944. XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
  945. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  946. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  947. xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
  948. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  949. xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
  950. XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
  951. PropModeReplace, (uchar *)&thispid, 1);
  952. win.mode = MODE_NUMLOCK;
  953. resettitle();
  954. XMapWindow(xw.dpy, xw.win);
  955. xhints();
  956. XSync(xw.dpy, False);
  957. clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
  958. clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
  959. xsel.primary = NULL;
  960. xsel.clipboard = NULL;
  961. xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
  962. if (xsel.xtarget == None)
  963. xsel.xtarget = XA_STRING;
  964. }
  965. int
  966. xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
  967. {
  968. float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
  969. ushort mode, prevmode = USHRT_MAX;
  970. Font *font = &dc.font;
  971. int frcflags = FRC_NORMAL;
  972. float runewidth = win.cw;
  973. Rune rune;
  974. FT_UInt glyphidx;
  975. FcResult fcres;
  976. FcPattern *fcpattern, *fontpattern;
  977. FcFontSet *fcsets[] = { NULL };
  978. FcCharSet *fccharset;
  979. int i, f, numspecs = 0;
  980. for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
  981. /* Fetch rune and mode for current glyph. */
  982. rune = glyphs[i].u;
  983. mode = glyphs[i].mode;
  984. /* Skip dummy wide-character spacing. */
  985. if (mode == ATTR_WDUMMY)
  986. continue;
  987. /* Determine font for glyph if different from previous glyph. */
  988. if (prevmode != mode) {
  989. prevmode = mode;
  990. font = &dc.font;
  991. frcflags = FRC_NORMAL;
  992. runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
  993. if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
  994. font = &dc.ibfont;
  995. frcflags = FRC_ITALICBOLD;
  996. } else if (mode & ATTR_ITALIC) {
  997. font = &dc.ifont;
  998. frcflags = FRC_ITALIC;
  999. } else if (mode & ATTR_BOLD) {
  1000. font = &dc.bfont;
  1001. frcflags = FRC_BOLD;
  1002. }
  1003. yp = winy + font->ascent;
  1004. }
  1005. /* Lookup character index with default font. */
  1006. glyphidx = XftCharIndex(xw.dpy, font->match, rune);
  1007. if (glyphidx) {
  1008. specs[numspecs].font = font->match;
  1009. specs[numspecs].glyph = glyphidx;
  1010. specs[numspecs].x = (short)xp;
  1011. specs[numspecs].y = (short)yp;
  1012. xp += runewidth;
  1013. numspecs++;
  1014. continue;
  1015. }
  1016. /* Fallback on font cache, search the font cache for match. */
  1017. for (f = 0; f < frclen; f++) {
  1018. glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
  1019. /* Everything correct. */
  1020. if (glyphidx && frc[f].flags == frcflags)
  1021. break;
  1022. /* We got a default font for a not found glyph. */
  1023. if (!glyphidx && frc[f].flags == frcflags
  1024. && frc[f].unicodep == rune) {
  1025. break;
  1026. }
  1027. }
  1028. /* Nothing was found. Use fontconfig to find matching font. */
  1029. if (f >= frclen) {
  1030. if (!font->set)
  1031. font->set = FcFontSort(0, font->pattern,
  1032. 1, 0, &fcres);
  1033. fcsets[0] = font->set;
  1034. /*
  1035. * Nothing was found in the cache. Now use
  1036. * some dozen of Fontconfig calls to get the
  1037. * font for one single character.
  1038. *
  1039. * Xft and fontconfig are design failures.
  1040. */
  1041. fcpattern = FcPatternDuplicate(font->pattern);
  1042. fccharset = FcCharSetCreate();
  1043. FcCharSetAddChar(fccharset, rune);
  1044. FcPatternAddCharSet(fcpattern, FC_CHARSET,
  1045. fccharset);
  1046. FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
  1047. FcConfigSubstitute(0, fcpattern,
  1048. FcMatchPattern);
  1049. FcDefaultSubstitute(fcpattern);
  1050. fontpattern = FcFontSetMatch(0, fcsets, 1,
  1051. fcpattern, &fcres);
  1052. /*
  1053. * Overwrite or create the new cache entry.
  1054. */
  1055. if (frclen >= LEN(frc)) {
  1056. frclen = LEN(frc) - 1;
  1057. XftFontClose(xw.dpy, frc[frclen].font);
  1058. frc[frclen].unicodep = 0;
  1059. }
  1060. frc[frclen].font = XftFontOpenPattern(xw.dpy,
  1061. fontpattern);
  1062. if (!frc[frclen].font)
  1063. die("XftFontOpenPattern failed seeking fallback font: %s\n",
  1064. strerror(errno));
  1065. frc[frclen].flags = frcflags;
  1066. frc[frclen].unicodep = rune;
  1067. glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
  1068. f = frclen;
  1069. frclen++;
  1070. FcPatternDestroy(fcpattern);
  1071. FcCharSetDestroy(fccharset);
  1072. }
  1073. specs[numspecs].font = frc[f].font;
  1074. specs[numspecs].glyph = glyphidx;
  1075. specs[numspecs].x = (short)xp;
  1076. specs[numspecs].y = (short)yp;
  1077. xp += runewidth;
  1078. numspecs++;
  1079. }
  1080. return numspecs;
  1081. }
  1082. void
  1083. xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
  1084. {
  1085. int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
  1086. int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
  1087. width = charlen * win.cw;
  1088. Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
  1089. XRenderColor colfg, colbg;
  1090. XRectangle r;
  1091. /* Fallback on color display for attributes not supported by the font */
  1092. if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
  1093. if (dc.ibfont.badslant || dc.ibfont.badweight)
  1094. base.fg = defaultattr;
  1095. } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
  1096. (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
  1097. base.fg = defaultattr;
  1098. }
  1099. if (IS_TRUECOL(base.fg)) {
  1100. colfg.alpha = 0xffff;
  1101. colfg.red = TRUERED(base.fg);
  1102. colfg.green = TRUEGREEN(base.fg);
  1103. colfg.blue = TRUEBLUE(base.fg);
  1104. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
  1105. fg = &truefg;
  1106. } else {
  1107. fg = &dc.col[base.fg];
  1108. }
  1109. if (IS_TRUECOL(base.bg)) {
  1110. colbg.alpha = 0xffff;
  1111. colbg.green = TRUEGREEN(base.bg);
  1112. colbg.red = TRUERED(base.bg);
  1113. colbg.blue = TRUEBLUE(base.bg);
  1114. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
  1115. bg = &truebg;
  1116. } else {
  1117. bg = &dc.col[base.bg];
  1118. }
  1119. /* Change basic system colors [0-7] to bright system colors [8-15] */
  1120. if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
  1121. fg = &dc.col[base.fg + 8];
  1122. if (IS_SET(MODE_REVERSE)) {
  1123. if (fg == &dc.col[defaultfg]) {
  1124. fg = &dc.col[defaultbg];
  1125. } else {
  1126. colfg.red = ~fg->color.red;
  1127. colfg.green = ~fg->color.green;
  1128. colfg.blue = ~fg->color.blue;
  1129. colfg.alpha = fg->color.alpha;
  1130. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
  1131. &revfg);
  1132. fg = &revfg;
  1133. }
  1134. if (bg == &dc.col[defaultbg]) {
  1135. bg = &dc.col[defaultfg];
  1136. } else {
  1137. colbg.red = ~bg->color.red;
  1138. colbg.green = ~bg->color.green;
  1139. colbg.blue = ~bg->color.blue;
  1140. colbg.alpha = bg->color.alpha;
  1141. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
  1142. &revbg);
  1143. bg = &revbg;
  1144. }
  1145. }
  1146. if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
  1147. colfg.red = fg->color.red / 2;
  1148. colfg.green = fg->color.green / 2;
  1149. colfg.blue = fg->color.blue / 2;
  1150. colfg.alpha = fg->color.alpha;
  1151. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  1152. fg = &revfg;
  1153. }
  1154. if (base.mode & ATTR_REVERSE) {
  1155. temp = fg;
  1156. fg = bg;
  1157. bg = temp;
  1158. }
  1159. if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
  1160. fg = bg;
  1161. if (base.mode & ATTR_INVISIBLE)
  1162. fg = bg;
  1163. /* Intelligent cleaning up of the borders. */
  1164. if (x == 0) {
  1165. xclear(0, (y == 0)? 0 : winy, borderpx,
  1166. winy + win.ch +
  1167. ((winy + win.ch >= borderpx + win.th)? win.h : 0));
  1168. }
  1169. if (winx + width >= borderpx + win.tw) {
  1170. xclear(winx + width, (y == 0)? 0 : winy, win.w,
  1171. ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
  1172. }
  1173. if (y == 0)
  1174. xclear(winx, 0, winx + width, borderpx);
  1175. if (winy + win.ch >= borderpx + win.th)
  1176. xclear(winx, winy + win.ch, winx + width, win.h);
  1177. /* Clean up the region we want to draw to. */
  1178. XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
  1179. /* Set the clip region because Xft is sometimes dirty. */
  1180. r.x = 0;
  1181. r.y = 0;
  1182. r.height = win.ch;
  1183. r.width = width;
  1184. XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
  1185. /* Render the glyphs. */
  1186. XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
  1187. /* Render underline and strikethrough. */
  1188. if (base.mode & ATTR_UNDERLINE) {
  1189. XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
  1190. width, 1);
  1191. }
  1192. if (base.mode & ATTR_STRUCK) {
  1193. XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
  1194. width, 1);
  1195. }
  1196. /* Reset clip to none. */
  1197. XftDrawSetClip(xw.draw, 0);
  1198. }
  1199. void
  1200. xdrawglyph(Glyph g, int x, int y)
  1201. {
  1202. int numspecs;
  1203. XftGlyphFontSpec spec;
  1204. numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
  1205. xdrawglyphfontspecs(&spec, g, numspecs, x, y);
  1206. }
  1207. void
  1208. xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
  1209. {
  1210. Color drawcol;
  1211. /* remove the old cursor */
  1212. if (selected(ox, oy))
  1213. og.mode ^= ATTR_REVERSE;
  1214. xdrawglyph(og, ox, oy);
  1215. if (IS_SET(MODE_HIDE))
  1216. return;
  1217. /*
  1218. * Select the right color for the right mode.
  1219. */
  1220. g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
  1221. if (IS_SET(MODE_REVERSE)) {
  1222. g.mode |= ATTR_REVERSE;
  1223. g.bg = defaultfg;
  1224. if (selected(cx, cy)) {
  1225. drawcol = dc.col[defaultcs];
  1226. g.fg = defaultrcs;
  1227. } else {
  1228. drawcol = dc.col[defaultrcs];
  1229. g.fg = defaultcs;
  1230. }
  1231. } else {
  1232. if (selected(cx, cy)) {
  1233. g.fg = defaultfg;
  1234. g.bg = defaultrcs;
  1235. } else {
  1236. g.fg = defaultbg;
  1237. g.bg = defaultcs;
  1238. }
  1239. drawcol = dc.col[g.bg];
  1240. }
  1241. /* draw the new one */
  1242. if (IS_SET(MODE_FOCUSED)) {
  1243. switch (win.cursor) {
  1244. case 7: /* st extension: snowman (U+2603) */
  1245. g.u = 0x2603;
  1246. case 0: /* Blinking Block */
  1247. case 1: /* Blinking Block (Default) */
  1248. case 2: /* Steady Block */
  1249. xdrawglyph(g, cx, cy);
  1250. break;
  1251. case 3: /* Blinking Underline */
  1252. case 4: /* Steady Underline */
  1253. XftDrawRect(xw.draw, &drawcol,
  1254. borderpx + cx * win.cw,
  1255. borderpx + (cy + 1) * win.ch - \
  1256. cursorthickness,
  1257. win.cw, cursorthickness);
  1258. break;
  1259. case 5: /* Blinking bar */
  1260. case 6: /* Steady bar */
  1261. XftDrawRect(xw.draw, &drawcol,
  1262. borderpx + cx * win.cw,
  1263. borderpx + cy * win.ch,
  1264. cursorthickness, win.ch);
  1265. break;
  1266. }
  1267. } else {
  1268. XftDrawRect(xw.draw, &drawcol,
  1269. borderpx + cx * win.cw,
  1270. borderpx + cy * win.ch,
  1271. win.cw - 1, 1);
  1272. XftDrawRect(xw.draw, &drawcol,
  1273. borderpx + cx * win.cw,
  1274. borderpx + cy * win.ch,
  1275. 1, win.ch - 1);
  1276. XftDrawRect(xw.draw, &drawcol,
  1277. borderpx + (cx + 1) * win.cw - 1,
  1278. borderpx + cy * win.ch,
  1279. 1, win.ch - 1);
  1280. XftDrawRect(xw.draw, &drawcol,
  1281. borderpx + cx * win.cw,
  1282. borderpx + (cy + 1) * win.ch - 1,
  1283. win.cw, 1);
  1284. }
  1285. }
  1286. void
  1287. xsetenv(void)
  1288. {
  1289. char buf[sizeof(long) * 8 + 1];
  1290. snprintf(buf, sizeof(buf), "%lu", xw.win);
  1291. setenv("WINDOWID", buf, 1);
  1292. }
  1293. void
  1294. xsettitle(char *p)
  1295. {
  1296. XTextProperty prop;
  1297. DEFAULT(p, opt_title);
  1298. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  1299. &prop);
  1300. XSetWMName(xw.dpy, xw.win, &prop);
  1301. XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
  1302. XFree(prop.value);
  1303. }
  1304. int
  1305. xstartdraw(void)
  1306. {
  1307. return IS_SET(MODE_VISIBLE);
  1308. }
  1309. void
  1310. xdrawline(Line line, int x1, int y1, int x2)
  1311. {
  1312. int i, x, ox, numspecs;
  1313. Glyph base, new;
  1314. XftGlyphFontSpec *specs = xw.specbuf;
  1315. numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
  1316. i = ox = 0;
  1317. for (x = x1; x < x2 && i < numspecs; x++) {
  1318. new = line[x];
  1319. if (new.mode == ATTR_WDUMMY)
  1320. continue;
  1321. if (selected(x, y1))
  1322. new.mode ^= ATTR_REVERSE;
  1323. if (i > 0 && ATTRCMP(base, new)) {
  1324. xdrawglyphfontspecs(specs, base, i, ox, y1);
  1325. specs += i;
  1326. numspecs -= i;
  1327. i = 0;
  1328. }
  1329. if (i == 0) {
  1330. ox = x;
  1331. base = new;
  1332. }
  1333. i++;
  1334. }
  1335. if (i > 0)
  1336. xdrawglyphfontspecs(specs, base, i, ox, y1);
  1337. }
  1338. void
  1339. xfinishdraw(void)
  1340. {
  1341. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
  1342. win.h, 0, 0);
  1343. XSetForeground(xw.dpy, dc.gc,
  1344. dc.col[IS_SET(MODE_REVERSE)?
  1345. defaultfg : defaultbg].pixel);
  1346. }
  1347. void
  1348. expose(XEvent *ev)
  1349. {
  1350. redraw();
  1351. }
  1352. void
  1353. visibility(XEvent *ev)
  1354. {
  1355. XVisibilityEvent *e = &ev->xvisibility;
  1356. MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
  1357. }
  1358. void
  1359. unmap(XEvent *ev)
  1360. {
  1361. win.mode &= ~MODE_VISIBLE;
  1362. }
  1363. void
  1364. xsetpointermotion(int set)
  1365. {
  1366. MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
  1367. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
  1368. }
  1369. void
  1370. xsetmode(int set, unsigned int flags)
  1371. {
  1372. int mode = win.mode;
  1373. MODBIT(win.mode, set, flags);
  1374. if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
  1375. redraw();
  1376. }
  1377. int
  1378. xsetcursor(int cursor)
  1379. {
  1380. DEFAULT(cursor, 1);
  1381. if (!BETWEEN(cursor, 0, 6))
  1382. return 1;
  1383. win.cursor = cursor;
  1384. return 0;
  1385. }
  1386. void
  1387. xseturgency(int add)
  1388. {
  1389. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  1390. MODBIT(h->flags, add, XUrgencyHint);
  1391. XSetWMHints(xw.dpy, xw.win, h);
  1392. XFree(h);
  1393. }
  1394. void
  1395. xbell(void)
  1396. {
  1397. if (!(IS_SET(MODE_FOCUSED)))
  1398. xseturgency(1);
  1399. if (bellvolume)
  1400. XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
  1401. }
  1402. void
  1403. focus(XEvent *ev)
  1404. {
  1405. XFocusChangeEvent *e = &ev->xfocus;
  1406. if (e->mode == NotifyGrab)
  1407. return;
  1408. if (ev->type == FocusIn) {
  1409. XSetICFocus(xw.xic);
  1410. win.mode |= MODE_FOCUSED;
  1411. xseturgency(0);
  1412. if (IS_SET(MODE_FOCUS))
  1413. ttywrite("\033[I", 3, 0);
  1414. } else {
  1415. XUnsetICFocus(xw.xic);
  1416. win.mode &= ~MODE_FOCUSED;
  1417. if (IS_SET(MODE_FOCUS))
  1418. ttywrite("\033[O", 3, 0);
  1419. }
  1420. }
  1421. int
  1422. match(uint mask, uint state)
  1423. {
  1424. return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
  1425. }
  1426. char*
  1427. kmap(KeySym k, uint state)
  1428. {
  1429. Key *kp;
  1430. int i;
  1431. /* Check for mapped keys out of X11 function keys. */
  1432. for (i = 0; i < LEN(mappedkeys); i++) {
  1433. if (mappedkeys[i] == k)
  1434. break;
  1435. }
  1436. if (i == LEN(mappedkeys)) {
  1437. if ((k & 0xFFFF) < 0xFD00)
  1438. return NULL;
  1439. }
  1440. for (kp = key; kp < key + LEN(key); kp++) {
  1441. if (kp->k != k)
  1442. continue;
  1443. if (!match(kp->mask, state))
  1444. continue;
  1445. if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
  1446. continue;
  1447. if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
  1448. continue;
  1449. if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
  1450. continue;
  1451. return kp->s;
  1452. }
  1453. return NULL;
  1454. }
  1455. void
  1456. kpress(XEvent *ev)
  1457. {
  1458. XKeyEvent *e = &ev->xkey;
  1459. KeySym ksym;
  1460. char buf[32], *customkey;
  1461. int len;
  1462. Rune c;
  1463. Status status;
  1464. Shortcut *bp;
  1465. if (IS_SET(MODE_KBDLOCK))
  1466. return;
  1467. len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
  1468. /* 1. shortcuts */
  1469. for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  1470. if (ksym == bp->keysym && match(bp->mod, e->state)) {
  1471. bp->func(&(bp->arg));
  1472. return;
  1473. }
  1474. }
  1475. /* 2. custom keys from config.h */
  1476. if ((customkey = kmap(ksym, e->state))) {
  1477. ttywrite(customkey, strlen(customkey), 1);
  1478. return;
  1479. }
  1480. /* 3. composed string from input method */
  1481. if (len == 0)
  1482. return;
  1483. if (len == 1 && e->state & Mod1Mask) {
  1484. if (IS_SET(MODE_8BIT)) {
  1485. if (*buf < 0177) {
  1486. c = *buf | 0x80;
  1487. len = utf8encode(c, buf);
  1488. }
  1489. } else {
  1490. buf[1] = buf[0];
  1491. buf[0] = '\033';
  1492. len = 2;
  1493. }
  1494. }
  1495. ttywrite(buf, len, 1);
  1496. }
  1497. void
  1498. cmessage(XEvent *e)
  1499. {
  1500. /*
  1501. * See xembed specs
  1502. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  1503. */
  1504. if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  1505. if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  1506. win.mode |= MODE_FOCUSED;
  1507. xseturgency(0);
  1508. } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  1509. win.mode &= ~MODE_FOCUSED;
  1510. }
  1511. } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
  1512. ttyhangup();
  1513. exit(0);
  1514. }
  1515. }
  1516. void
  1517. resize(XEvent *e)
  1518. {
  1519. if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
  1520. return;
  1521. cresize(e->xconfigure.width, e->xconfigure.height);
  1522. }
  1523. void
  1524. run(void)
  1525. {
  1526. XEvent ev;
  1527. int w = win.w, h = win.h;
  1528. fd_set rfd;
  1529. int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
  1530. int ttyfd;
  1531. struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
  1532. long deltatime;
  1533. /* Waiting for window mapping */
  1534. do {
  1535. XNextEvent(xw.dpy, &ev);
  1536. /*
  1537. * This XFilterEvent call is required because of XOpenIM. It
  1538. * does filter out the key event and some client message for
  1539. * the input method too.
  1540. */
  1541. if (XFilterEvent(&ev, None))
  1542. continue;
  1543. if (ev.type == ConfigureNotify) {
  1544. w = ev.xconfigure.width;
  1545. h = ev.xconfigure.height;
  1546. }
  1547. } while (ev.type != MapNotify);
  1548. ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
  1549. cresize(w, h);
  1550. clock_gettime(CLOCK_MONOTONIC, &last);
  1551. lastblink = last;
  1552. for (xev = actionfps;;) {
  1553. FD_ZERO(&rfd);
  1554. FD_SET(ttyfd, &rfd);
  1555. FD_SET(xfd, &rfd);
  1556. if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
  1557. if (errno == EINTR)
  1558. continue;
  1559. die("select failed: %s\n", strerror(errno));
  1560. }
  1561. if (FD_ISSET(ttyfd, &rfd)) {
  1562. ttyread();
  1563. if (blinktimeout) {
  1564. blinkset = tattrset(ATTR_BLINK);
  1565. if (!blinkset)
  1566. MODBIT(win.mode, 0, MODE_BLINK);
  1567. }
  1568. }
  1569. if (FD_ISSET(xfd, &rfd))
  1570. xev = actionfps;
  1571. clock_gettime(CLOCK_MONOTONIC, &now);
  1572. drawtimeout.tv_sec = 0;
  1573. drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
  1574. tv = &drawtimeout;
  1575. dodraw = 0;
  1576. if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
  1577. tsetdirtattr(ATTR_BLINK);
  1578. win.mode ^= MODE_BLINK;
  1579. lastblink = now;
  1580. dodraw = 1;
  1581. }
  1582. deltatime = TIMEDIFF(now, last);
  1583. if (deltatime > 1000 / (xev ? xfps : actionfps)) {
  1584. dodraw = 1;
  1585. last = now;
  1586. }
  1587. if (dodraw) {
  1588. while (XPending(xw.dpy)) {
  1589. XNextEvent(xw.dpy, &ev);
  1590. if (XFilterEvent(&ev, None))
  1591. continue;
  1592. if (handler[ev.type])
  1593. (handler[ev.type])(&ev);
  1594. }
  1595. draw();
  1596. XFlush(xw.dpy);
  1597. if (xev && !FD_ISSET(xfd, &rfd))
  1598. xev--;
  1599. if (!FD_ISSET(ttyfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
  1600. if (blinkset) {
  1601. if (TIMEDIFF(now, lastblink) \
  1602. > blinktimeout) {
  1603. drawtimeout.tv_nsec = 1000;
  1604. } else {
  1605. drawtimeout.tv_nsec = (1E6 * \
  1606. (blinktimeout - \
  1607. TIMEDIFF(now,
  1608. lastblink)));
  1609. }
  1610. drawtimeout.tv_sec = \
  1611. drawtimeout.tv_nsec / 1E9;
  1612. drawtimeout.tv_nsec %= (long)1E9;
  1613. } else {
  1614. tv = NULL;
  1615. }
  1616. }
  1617. }
  1618. }
  1619. }
  1620. void
  1621. usage(void)
  1622. {
  1623. die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
  1624. " [-n name] [-o file]\n"
  1625. " [-T title] [-t title] [-w windowid]"
  1626. " [[-e] command [args ...]]\n"
  1627. " %s [-aiv] [-c class] [-f font] [-g geometry]"
  1628. " [-n name] [-o file]\n"
  1629. " [-T title] [-t title] [-w windowid] -l line"
  1630. " [stty_args ...]\n", argv0, argv0);
  1631. }
  1632. int
  1633. main(int argc, char *argv[])
  1634. {
  1635. xw.l = xw.t = 0;
  1636. xw.isfixed = False;
  1637. win.cursor = cursorshape;
  1638. ARGBEGIN {
  1639. case 'a':
  1640. allowaltscreen = 0;
  1641. break;
  1642. case 'c':
  1643. opt_class = EARGF(usage());
  1644. break;
  1645. case 'e':
  1646. if (argc > 0)
  1647. --argc, ++argv;
  1648. goto run;
  1649. case 'f':
  1650. opt_font = EARGF(usage());
  1651. break;
  1652. case 'g':
  1653. xw.gm = XParseGeometry(EARGF(usage()),
  1654. &xw.l, &xw.t, &cols, &rows);
  1655. break;
  1656. case 'i':
  1657. xw.isfixed = 1;
  1658. break;
  1659. case 'o':
  1660. opt_io = EARGF(usage());
  1661. break;
  1662. case 'l':
  1663. opt_line = EARGF(usage());
  1664. break;
  1665. case 'n':
  1666. opt_name = EARGF(usage());
  1667. break;
  1668. case 't':
  1669. case 'T':
  1670. opt_title = EARGF(usage());
  1671. break;
  1672. case 'w':
  1673. opt_embed = EARGF(usage());
  1674. break;
  1675. case 'v':
  1676. die("%s " VERSION "\n", argv0);
  1677. break;
  1678. default:
  1679. usage();
  1680. } ARGEND;
  1681. run:
  1682. if (argc > 0) /* eat all remaining arguments */
  1683. opt_cmd = argv;
  1684. if (!opt_title)
  1685. opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
  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. }