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.

1943 lines
43 KiB

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