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.

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