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.

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