Simple Terminal from SuckLess
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.

1967 lines
43 KiB

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