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.

1954 lines
43 KiB

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