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.

1966 lines
43 KiB

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