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.

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