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.

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