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.

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