My build of suckless st terminal
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1994 lines
44 KiB

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