Simple Terminal from SuckLess
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.

1951 lines
43 KiB

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