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.

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