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.

1986 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. /* Allocate memory for the new cache entry. */
  1079. if (frclen >= frccap) {
  1080. frccap += 16;
  1081. frc = xrealloc(frc, frccap * sizeof(Fontcache));
  1082. }
  1083. frc[frclen].font = XftFontOpenPattern(xw.dpy,
  1084. fontpattern);
  1085. if (!frc[frclen].font)
  1086. die("XftFontOpenPattern failed seeking fallback font: %s\n",
  1087. strerror(errno));
  1088. frc[frclen].flags = frcflags;
  1089. frc[frclen].unicodep = rune;
  1090. glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
  1091. f = frclen;
  1092. frclen++;
  1093. FcPatternDestroy(fcpattern);
  1094. FcCharSetDestroy(fccharset);
  1095. }
  1096. specs[numspecs].font = frc[f].font;
  1097. specs[numspecs].glyph = glyphidx;
  1098. specs[numspecs].x = (short)xp;
  1099. specs[numspecs].y = (short)yp;
  1100. xp += runewidth;
  1101. numspecs++;
  1102. }
  1103. return numspecs;
  1104. }
  1105. void
  1106. xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
  1107. {
  1108. int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
  1109. int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
  1110. width = charlen * win.cw;
  1111. Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
  1112. XRenderColor colfg, colbg;
  1113. XRectangle r;
  1114. /* Fallback on color display for attributes not supported by the font */
  1115. if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
  1116. if (dc.ibfont.badslant || dc.ibfont.badweight)
  1117. base.fg = defaultattr;
  1118. } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
  1119. (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
  1120. base.fg = defaultattr;
  1121. }
  1122. if (IS_TRUECOL(base.fg)) {
  1123. colfg.alpha = 0xffff;
  1124. colfg.red = TRUERED(base.fg);
  1125. colfg.green = TRUEGREEN(base.fg);
  1126. colfg.blue = TRUEBLUE(base.fg);
  1127. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
  1128. fg = &truefg;
  1129. } else {
  1130. fg = &dc.col[base.fg];
  1131. }
  1132. if (IS_TRUECOL(base.bg)) {
  1133. colbg.alpha = 0xffff;
  1134. colbg.green = TRUEGREEN(base.bg);
  1135. colbg.red = TRUERED(base.bg);
  1136. colbg.blue = TRUEBLUE(base.bg);
  1137. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
  1138. bg = &truebg;
  1139. } else {
  1140. bg = &dc.col[base.bg];
  1141. }
  1142. /* Change basic system colors [0-7] to bright system colors [8-15] */
  1143. if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
  1144. fg = &dc.col[base.fg + 8];
  1145. if (IS_SET(MODE_REVERSE)) {
  1146. if (fg == &dc.col[defaultfg]) {
  1147. fg = &dc.col[defaultbg];
  1148. } else {
  1149. colfg.red = ~fg->color.red;
  1150. colfg.green = ~fg->color.green;
  1151. colfg.blue = ~fg->color.blue;
  1152. colfg.alpha = fg->color.alpha;
  1153. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
  1154. &revfg);
  1155. fg = &revfg;
  1156. }
  1157. if (bg == &dc.col[defaultbg]) {
  1158. bg = &dc.col[defaultfg];
  1159. } else {
  1160. colbg.red = ~bg->color.red;
  1161. colbg.green = ~bg->color.green;
  1162. colbg.blue = ~bg->color.blue;
  1163. colbg.alpha = bg->color.alpha;
  1164. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
  1165. &revbg);
  1166. bg = &revbg;
  1167. }
  1168. }
  1169. if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
  1170. colfg.red = fg->color.red / 2;
  1171. colfg.green = fg->color.green / 2;
  1172. colfg.blue = fg->color.blue / 2;
  1173. colfg.alpha = fg->color.alpha;
  1174. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  1175. fg = &revfg;
  1176. }
  1177. if (base.mode & ATTR_REVERSE) {
  1178. temp = fg;
  1179. fg = bg;
  1180. bg = temp;
  1181. }
  1182. if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
  1183. fg = bg;
  1184. if (base.mode & ATTR_INVISIBLE)
  1185. fg = bg;
  1186. /* Intelligent cleaning up of the borders. */
  1187. if (x == 0) {
  1188. xclear(0, (y == 0)? 0 : winy, borderpx,
  1189. winy + win.ch +
  1190. ((winy + win.ch >= borderpx + win.th)? win.h : 0));
  1191. }
  1192. if (winx + width >= borderpx + win.tw) {
  1193. xclear(winx + width, (y == 0)? 0 : winy, win.w,
  1194. ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
  1195. }
  1196. if (y == 0)
  1197. xclear(winx, 0, winx + width, borderpx);
  1198. if (winy + win.ch >= borderpx + win.th)
  1199. xclear(winx, winy + win.ch, winx + width, win.h);
  1200. /* Clean up the region we want to draw to. */
  1201. XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
  1202. /* Set the clip region because Xft is sometimes dirty. */
  1203. r.x = 0;
  1204. r.y = 0;
  1205. r.height = win.ch;
  1206. r.width = width;
  1207. XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
  1208. /* Render the glyphs. */
  1209. XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
  1210. /* Render underline and strikethrough. */
  1211. if (base.mode & ATTR_UNDERLINE) {
  1212. XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
  1213. width, 1);
  1214. }
  1215. if (base.mode & ATTR_STRUCK) {
  1216. XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
  1217. width, 1);
  1218. }
  1219. /* Reset clip to none. */
  1220. XftDrawSetClip(xw.draw, 0);
  1221. }
  1222. void
  1223. xdrawglyph(Glyph g, int x, int y)
  1224. {
  1225. int numspecs;
  1226. XftGlyphFontSpec spec;
  1227. numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
  1228. xdrawglyphfontspecs(&spec, g, numspecs, x, y);
  1229. }
  1230. void
  1231. xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
  1232. {
  1233. Color drawcol;
  1234. /* remove the old cursor */
  1235. if (selected(ox, oy))
  1236. og.mode ^= ATTR_REVERSE;
  1237. xdrawglyph(og, ox, oy);
  1238. if (IS_SET(MODE_HIDE))
  1239. return;
  1240. /*
  1241. * Select the right color for the right mode.
  1242. */
  1243. g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
  1244. if (IS_SET(MODE_REVERSE)) {
  1245. g.mode |= ATTR_REVERSE;
  1246. g.bg = defaultfg;
  1247. if (selected(cx, cy)) {
  1248. drawcol = dc.col[defaultcs];
  1249. g.fg = defaultrcs;
  1250. } else {
  1251. drawcol = dc.col[defaultrcs];
  1252. g.fg = defaultcs;
  1253. }
  1254. } else {
  1255. if (selected(cx, cy)) {
  1256. g.fg = defaultfg;
  1257. g.bg = defaultrcs;
  1258. } else {
  1259. g.fg = defaultbg;
  1260. g.bg = defaultcs;
  1261. }
  1262. drawcol = dc.col[g.bg];
  1263. }
  1264. /* draw the new one */
  1265. if (IS_SET(MODE_FOCUSED)) {
  1266. switch (win.cursor) {
  1267. case 7: /* st extension: snowman (U+2603) */
  1268. g.u = 0x2603;
  1269. case 0: /* Blinking Block */
  1270. case 1: /* Blinking Block (Default) */
  1271. case 2: /* Steady Block */
  1272. xdrawglyph(g, cx, cy);
  1273. break;
  1274. case 3: /* Blinking Underline */
  1275. case 4: /* Steady Underline */
  1276. XftDrawRect(xw.draw, &drawcol,
  1277. borderpx + cx * win.cw,
  1278. borderpx + (cy + 1) * win.ch - \
  1279. cursorthickness,
  1280. win.cw, cursorthickness);
  1281. break;
  1282. case 5: /* Blinking bar */
  1283. case 6: /* Steady bar */
  1284. XftDrawRect(xw.draw, &drawcol,
  1285. borderpx + cx * win.cw,
  1286. borderpx + cy * win.ch,
  1287. cursorthickness, win.ch);
  1288. break;
  1289. }
  1290. } else {
  1291. XftDrawRect(xw.draw, &drawcol,
  1292. borderpx + cx * win.cw,
  1293. borderpx + cy * win.ch,
  1294. win.cw - 1, 1);
  1295. XftDrawRect(xw.draw, &drawcol,
  1296. borderpx + cx * win.cw,
  1297. borderpx + cy * win.ch,
  1298. 1, win.ch - 1);
  1299. XftDrawRect(xw.draw, &drawcol,
  1300. borderpx + (cx + 1) * win.cw - 1,
  1301. borderpx + cy * win.ch,
  1302. 1, win.ch - 1);
  1303. XftDrawRect(xw.draw, &drawcol,
  1304. borderpx + cx * win.cw,
  1305. borderpx + (cy + 1) * win.ch - 1,
  1306. win.cw, 1);
  1307. }
  1308. }
  1309. void
  1310. xsetenv(void)
  1311. {
  1312. char buf[sizeof(long) * 8 + 1];
  1313. snprintf(buf, sizeof(buf), "%lu", xw.win);
  1314. setenv("WINDOWID", buf, 1);
  1315. }
  1316. void
  1317. xsettitle(char *p)
  1318. {
  1319. XTextProperty prop;
  1320. DEFAULT(p, opt_title);
  1321. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  1322. &prop);
  1323. XSetWMName(xw.dpy, xw.win, &prop);
  1324. XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
  1325. XFree(prop.value);
  1326. }
  1327. int
  1328. xstartdraw(void)
  1329. {
  1330. return IS_SET(MODE_VISIBLE);
  1331. }
  1332. void
  1333. xdrawline(Line line, int x1, int y1, int x2)
  1334. {
  1335. int i, x, ox, numspecs;
  1336. Glyph base, new;
  1337. XftGlyphFontSpec *specs = xw.specbuf;
  1338. numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
  1339. i = ox = 0;
  1340. for (x = x1; x < x2 && i < numspecs; x++) {
  1341. new = line[x];
  1342. if (new.mode == ATTR_WDUMMY)
  1343. continue;
  1344. if (selected(x, y1))
  1345. new.mode ^= ATTR_REVERSE;
  1346. if (i > 0 && ATTRCMP(base, new)) {
  1347. xdrawglyphfontspecs(specs, base, i, ox, y1);
  1348. specs += i;
  1349. numspecs -= i;
  1350. i = 0;
  1351. }
  1352. if (i == 0) {
  1353. ox = x;
  1354. base = new;
  1355. }
  1356. i++;
  1357. }
  1358. if (i > 0)
  1359. xdrawglyphfontspecs(specs, base, i, ox, y1);
  1360. }
  1361. void
  1362. xfinishdraw(void)
  1363. {
  1364. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
  1365. win.h, 0, 0);
  1366. XSetForeground(xw.dpy, dc.gc,
  1367. dc.col[IS_SET(MODE_REVERSE)?
  1368. defaultfg : defaultbg].pixel);
  1369. }
  1370. void
  1371. xximspot(int x, int y)
  1372. {
  1373. XPoint spot = { borderpx + x * win.cw, borderpx + (y + 1) * win.ch };
  1374. XVaNestedList attr = XVaCreateNestedList(0, XNSpotLocation, &spot, NULL);
  1375. XSetICValues(xw.xic, XNPreeditAttributes, attr, NULL);
  1376. XFree(attr);
  1377. }
  1378. void
  1379. expose(XEvent *ev)
  1380. {
  1381. redraw();
  1382. }
  1383. void
  1384. visibility(XEvent *ev)
  1385. {
  1386. XVisibilityEvent *e = &ev->xvisibility;
  1387. MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
  1388. }
  1389. void
  1390. unmap(XEvent *ev)
  1391. {
  1392. win.mode &= ~MODE_VISIBLE;
  1393. }
  1394. void
  1395. xsetpointermotion(int set)
  1396. {
  1397. MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
  1398. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
  1399. }
  1400. void
  1401. xsetmode(int set, unsigned int flags)
  1402. {
  1403. int mode = win.mode;
  1404. MODBIT(win.mode, set, flags);
  1405. if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
  1406. redraw();
  1407. }
  1408. int
  1409. xsetcursor(int cursor)
  1410. {
  1411. DEFAULT(cursor, 1);
  1412. if (!BETWEEN(cursor, 0, 6))
  1413. return 1;
  1414. win.cursor = cursor;
  1415. return 0;
  1416. }
  1417. void
  1418. xseturgency(int add)
  1419. {
  1420. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  1421. MODBIT(h->flags, add, XUrgencyHint);
  1422. XSetWMHints(xw.dpy, xw.win, h);
  1423. XFree(h);
  1424. }
  1425. void
  1426. xbell(void)
  1427. {
  1428. if (!(IS_SET(MODE_FOCUSED)))
  1429. xseturgency(1);
  1430. if (bellvolume)
  1431. XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
  1432. }
  1433. void
  1434. focus(XEvent *ev)
  1435. {
  1436. XFocusChangeEvent *e = &ev->xfocus;
  1437. if (e->mode == NotifyGrab)
  1438. return;
  1439. if (ev->type == FocusIn) {
  1440. XSetICFocus(xw.xic);
  1441. win.mode |= MODE_FOCUSED;
  1442. xseturgency(0);
  1443. if (IS_SET(MODE_FOCUS))
  1444. ttywrite("\033[I", 3, 0);
  1445. } else {
  1446. XUnsetICFocus(xw.xic);
  1447. win.mode &= ~MODE_FOCUSED;
  1448. if (IS_SET(MODE_FOCUS))
  1449. ttywrite("\033[O", 3, 0);
  1450. }
  1451. }
  1452. int
  1453. match(uint mask, uint state)
  1454. {
  1455. return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
  1456. }
  1457. char*
  1458. kmap(KeySym k, uint state)
  1459. {
  1460. Key *kp;
  1461. int i;
  1462. /* Check for mapped keys out of X11 function keys. */
  1463. for (i = 0; i < LEN(mappedkeys); i++) {
  1464. if (mappedkeys[i] == k)
  1465. break;
  1466. }
  1467. if (i == LEN(mappedkeys)) {
  1468. if ((k & 0xFFFF) < 0xFD00)
  1469. return NULL;
  1470. }
  1471. for (kp = key; kp < key + LEN(key); kp++) {
  1472. if (kp->k != k)
  1473. continue;
  1474. if (!match(kp->mask, state))
  1475. continue;
  1476. if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
  1477. continue;
  1478. if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
  1479. continue;
  1480. if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
  1481. continue;
  1482. return kp->s;
  1483. }
  1484. return NULL;
  1485. }
  1486. void
  1487. kpress(XEvent *ev)
  1488. {
  1489. XKeyEvent *e = &ev->xkey;
  1490. KeySym ksym;
  1491. char buf[32], *customkey;
  1492. int len;
  1493. Rune c;
  1494. Status status;
  1495. Shortcut *bp;
  1496. if (IS_SET(MODE_KBDLOCK))
  1497. return;
  1498. len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
  1499. /* 1. shortcuts */
  1500. for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  1501. if (ksym == bp->keysym && match(bp->mod, e->state)) {
  1502. bp->func(&(bp->arg));
  1503. return;
  1504. }
  1505. }
  1506. /* 2. custom keys from config.h */
  1507. if ((customkey = kmap(ksym, e->state))) {
  1508. ttywrite(customkey, strlen(customkey), 1);
  1509. return;
  1510. }
  1511. /* 3. composed string from input method */
  1512. if (len == 0)
  1513. return;
  1514. if (len == 1 && e->state & Mod1Mask) {
  1515. if (IS_SET(MODE_8BIT)) {
  1516. if (*buf < 0177) {
  1517. c = *buf | 0x80;
  1518. len = utf8encode(c, buf);
  1519. }
  1520. } else {
  1521. buf[1] = buf[0];
  1522. buf[0] = '\033';
  1523. len = 2;
  1524. }
  1525. }
  1526. ttywrite(buf, len, 1);
  1527. }
  1528. void
  1529. cmessage(XEvent *e)
  1530. {
  1531. /*
  1532. * See xembed specs
  1533. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  1534. */
  1535. if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  1536. if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  1537. win.mode |= MODE_FOCUSED;
  1538. xseturgency(0);
  1539. } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  1540. win.mode &= ~MODE_FOCUSED;
  1541. }
  1542. } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
  1543. ttyhangup();
  1544. exit(0);
  1545. }
  1546. }
  1547. void
  1548. resize(XEvent *e)
  1549. {
  1550. if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
  1551. return;
  1552. cresize(e->xconfigure.width, e->xconfigure.height);
  1553. }
  1554. void
  1555. run(void)
  1556. {
  1557. XEvent ev;
  1558. int w = win.w, h = win.h;
  1559. fd_set rfd;
  1560. int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
  1561. int ttyfd;
  1562. struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
  1563. long deltatime;
  1564. /* Waiting for window mapping */
  1565. do {
  1566. XNextEvent(xw.dpy, &ev);
  1567. /*
  1568. * This XFilterEvent call is required because of XOpenIM. It
  1569. * does filter out the key event and some client message for
  1570. * the input method too.
  1571. */
  1572. if (XFilterEvent(&ev, None))
  1573. continue;
  1574. if (ev.type == ConfigureNotify) {
  1575. w = ev.xconfigure.width;
  1576. h = ev.xconfigure.height;
  1577. }
  1578. } while (ev.type != MapNotify);
  1579. ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
  1580. cresize(w, h);
  1581. clock_gettime(CLOCK_MONOTONIC, &last);
  1582. lastblink = last;
  1583. for (xev = actionfps;;) {
  1584. FD_ZERO(&rfd);
  1585. FD_SET(ttyfd, &rfd);
  1586. FD_SET(xfd, &rfd);
  1587. if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
  1588. if (errno == EINTR)
  1589. continue;
  1590. die("select failed: %s\n", strerror(errno));
  1591. }
  1592. if (FD_ISSET(ttyfd, &rfd)) {
  1593. ttyread();
  1594. if (blinktimeout) {
  1595. blinkset = tattrset(ATTR_BLINK);
  1596. if (!blinkset)
  1597. MODBIT(win.mode, 0, MODE_BLINK);
  1598. }
  1599. }
  1600. if (FD_ISSET(xfd, &rfd))
  1601. xev = actionfps;
  1602. clock_gettime(CLOCK_MONOTONIC, &now);
  1603. drawtimeout.tv_sec = 0;
  1604. drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
  1605. tv = &drawtimeout;
  1606. dodraw = 0;
  1607. if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
  1608. tsetdirtattr(ATTR_BLINK);
  1609. win.mode ^= MODE_BLINK;
  1610. lastblink = now;
  1611. dodraw = 1;
  1612. }
  1613. deltatime = TIMEDIFF(now, last);
  1614. if (deltatime > 1000 / (xev ? xfps : actionfps)) {
  1615. dodraw = 1;
  1616. last = now;
  1617. }
  1618. if (dodraw) {
  1619. while (XPending(xw.dpy)) {
  1620. XNextEvent(xw.dpy, &ev);
  1621. if (XFilterEvent(&ev, None))
  1622. continue;
  1623. if (handler[ev.type])
  1624. (handler[ev.type])(&ev);
  1625. }
  1626. draw();
  1627. XFlush(xw.dpy);
  1628. if (xev && !FD_ISSET(xfd, &rfd))
  1629. xev--;
  1630. if (!FD_ISSET(ttyfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
  1631. if (blinkset) {
  1632. if (TIMEDIFF(now, lastblink) \
  1633. > blinktimeout) {
  1634. drawtimeout.tv_nsec = 1000;
  1635. } else {
  1636. drawtimeout.tv_nsec = (1E6 * \
  1637. (blinktimeout - \
  1638. TIMEDIFF(now,
  1639. lastblink)));
  1640. }
  1641. drawtimeout.tv_sec = \
  1642. drawtimeout.tv_nsec / 1E9;
  1643. drawtimeout.tv_nsec %= (long)1E9;
  1644. } else {
  1645. tv = NULL;
  1646. }
  1647. }
  1648. }
  1649. }
  1650. }
  1651. void
  1652. usage(void)
  1653. {
  1654. die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
  1655. " [-n name] [-o file]\n"
  1656. " [-T title] [-t title] [-w windowid]"
  1657. " [[-e] command [args ...]]\n"
  1658. " %s [-aiv] [-c class] [-f font] [-g geometry]"
  1659. " [-n name] [-o file]\n"
  1660. " [-T title] [-t title] [-w windowid] -l line"
  1661. " [stty_args ...]\n", argv0, argv0);
  1662. }
  1663. int
  1664. main(int argc, char *argv[])
  1665. {
  1666. xw.l = xw.t = 0;
  1667. xw.isfixed = False;
  1668. win.cursor = cursorshape;
  1669. ARGBEGIN {
  1670. case 'a':
  1671. allowaltscreen = 0;
  1672. break;
  1673. case 'c':
  1674. opt_class = EARGF(usage());
  1675. break;
  1676. case 'e':
  1677. if (argc > 0)
  1678. --argc, ++argv;
  1679. goto run;
  1680. case 'f':
  1681. opt_font = EARGF(usage());
  1682. break;
  1683. case 'g':
  1684. xw.gm = XParseGeometry(EARGF(usage()),
  1685. &xw.l, &xw.t, &cols, &rows);
  1686. break;
  1687. case 'i':
  1688. xw.isfixed = 1;
  1689. break;
  1690. case 'o':
  1691. opt_io = EARGF(usage());
  1692. break;
  1693. case 'l':
  1694. opt_line = EARGF(usage());
  1695. break;
  1696. case 'n':
  1697. opt_name = EARGF(usage());
  1698. break;
  1699. case 't':
  1700. case 'T':
  1701. opt_title = EARGF(usage());
  1702. break;
  1703. case 'w':
  1704. opt_embed = EARGF(usage());
  1705. break;
  1706. case 'v':
  1707. die("%s " VERSION "\n", argv0);
  1708. break;
  1709. default:
  1710. usage();
  1711. } ARGEND;
  1712. run:
  1713. if (argc > 0) /* eat all remaining arguments */
  1714. opt_cmd = argv;
  1715. if (!opt_title)
  1716. opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
  1717. setlocale(LC_CTYPE, "");
  1718. XSetLocaleModifiers("");
  1719. cols = MAX(cols, 1);
  1720. rows = MAX(rows, 1);
  1721. tnew(cols, rows);
  1722. xinit(cols, rows);
  1723. xsetenv();
  1724. selinit();
  1725. run();
  1726. return 0;
  1727. }