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.

2010 lines
44 KiB

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