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.

1955 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. col = MAX(1, col);
  593. row = MAX(1, row);
  594. tresize(col, row);
  595. xresize(col, row);
  596. ttyresize(win.tw, win.th);
  597. }
  598. void
  599. xresize(int col, int row)
  600. {
  601. win.tw = col * win.cw;
  602. win.th = row * win.ch;
  603. XFreePixmap(xw.dpy, xw.buf);
  604. xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
  605. DefaultDepth(xw.dpy, xw.scr));
  606. XftDrawChange(xw.draw, xw.buf);
  607. xclear(0, 0, win.w, win.h);
  608. /* resize to new width */
  609. xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec));
  610. }
  611. ushort
  612. sixd_to_16bit(int x)
  613. {
  614. return x == 0 ? 0 : 0x3737 + 0x2828 * x;
  615. }
  616. int
  617. xloadcolor(int i, const char *name, Color *ncolor)
  618. {
  619. XRenderColor color = { .alpha = 0xffff };
  620. if (!name) {
  621. if (BETWEEN(i, 16, 255)) { /* 256 color */
  622. if (i < 6*6*6+16) { /* same colors as xterm */
  623. color.red = sixd_to_16bit( ((i-16)/36)%6 );
  624. color.green = sixd_to_16bit( ((i-16)/6) %6 );
  625. color.blue = sixd_to_16bit( ((i-16)/1) %6 );
  626. } else { /* greyscale */
  627. color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
  628. color.green = color.blue = color.red;
  629. }
  630. return XftColorAllocValue(xw.dpy, xw.vis,
  631. xw.cmap, &color, ncolor);
  632. } else
  633. name = colorname[i];
  634. }
  635. return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
  636. }
  637. void
  638. xloadcols(void)
  639. {
  640. int i;
  641. static int loaded;
  642. Color *cp;
  643. dc.collen = MAX(LEN(colorname), 256);
  644. dc.col = xmalloc(dc.collen * sizeof(Color));
  645. if (loaded) {
  646. for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp)
  647. XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
  648. }
  649. for (i = 0; i < dc.collen; i++)
  650. if (!xloadcolor(i, NULL, &dc.col[i])) {
  651. if (colorname[i])
  652. die("could not allocate color '%s'\n", colorname[i]);
  653. else
  654. die("could not allocate color %d\n", i);
  655. }
  656. loaded = 1;
  657. }
  658. int
  659. xsetcolorname(int x, const char *name)
  660. {
  661. Color ncolor;
  662. if (!BETWEEN(x, 0, dc.collen))
  663. return 1;
  664. if (!xloadcolor(x, name, &ncolor))
  665. return 1;
  666. XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
  667. dc.col[x] = ncolor;
  668. return 0;
  669. }
  670. /*
  671. * Absolute coordinates.
  672. */
  673. void
  674. xclear(int x1, int y1, int x2, int y2)
  675. {
  676. XftDrawRect(xw.draw,
  677. &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
  678. x1, y1, x2-x1, y2-y1);
  679. }
  680. void
  681. xhints(void)
  682. {
  683. XClassHint class = {opt_name ? opt_name : termname,
  684. opt_class ? opt_class : termname};
  685. XWMHints wm = {.flags = InputHint, .input = 1};
  686. XSizeHints *sizeh;
  687. sizeh = XAllocSizeHints();
  688. sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize;
  689. sizeh->height = win.h;
  690. sizeh->width = win.w;
  691. sizeh->height_inc = win.ch;
  692. sizeh->width_inc = win.cw;
  693. sizeh->base_height = 2 * borderpx;
  694. sizeh->base_width = 2 * borderpx;
  695. sizeh->min_height = win.ch + 2 * borderpx;
  696. sizeh->min_width = win.cw + 2 * borderpx;
  697. if (xw.isfixed) {
  698. sizeh->flags |= PMaxSize;
  699. sizeh->min_width = sizeh->max_width = win.w;
  700. sizeh->min_height = sizeh->max_height = win.h;
  701. }
  702. if (xw.gm & (XValue|YValue)) {
  703. sizeh->flags |= USPosition | PWinGravity;
  704. sizeh->x = xw.l;
  705. sizeh->y = xw.t;
  706. sizeh->win_gravity = xgeommasktogravity(xw.gm);
  707. }
  708. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
  709. &class);
  710. XFree(sizeh);
  711. }
  712. int
  713. xgeommasktogravity(int mask)
  714. {
  715. switch (mask & (XNegative|YNegative)) {
  716. case 0:
  717. return NorthWestGravity;
  718. case XNegative:
  719. return NorthEastGravity;
  720. case YNegative:
  721. return SouthWestGravity;
  722. }
  723. return SouthEastGravity;
  724. }
  725. int
  726. xloadfont(Font *f, FcPattern *pattern)
  727. {
  728. FcPattern *configured;
  729. FcPattern *match;
  730. FcResult result;
  731. XGlyphInfo extents;
  732. int wantattr, haveattr;
  733. /*
  734. * Manually configure instead of calling XftMatchFont
  735. * so that we can use the configured pattern for
  736. * "missing glyph" lookups.
  737. */
  738. configured = FcPatternDuplicate(pattern);
  739. if (!configured)
  740. return 1;
  741. FcConfigSubstitute(NULL, configured, FcMatchPattern);
  742. XftDefaultSubstitute(xw.dpy, xw.scr, configured);
  743. match = FcFontMatch(NULL, configured, &result);
  744. if (!match) {
  745. FcPatternDestroy(configured);
  746. return 1;
  747. }
  748. if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
  749. FcPatternDestroy(configured);
  750. FcPatternDestroy(match);
  751. return 1;
  752. }
  753. if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) ==
  754. XftResultMatch)) {
  755. /*
  756. * Check if xft was unable to find a font with the appropriate
  757. * slant but gave us one anyway. Try to mitigate.
  758. */
  759. if ((XftPatternGetInteger(f->match->pattern, "slant", 0,
  760. &haveattr) != XftResultMatch) || haveattr < wantattr) {
  761. f->badslant = 1;
  762. fputs("font slant does not match\n", stderr);
  763. }
  764. }
  765. if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) ==
  766. XftResultMatch)) {
  767. if ((XftPatternGetInteger(f->match->pattern, "weight", 0,
  768. &haveattr) != XftResultMatch) || haveattr != wantattr) {
  769. f->badweight = 1;
  770. fputs("font weight does not match\n", stderr);
  771. }
  772. }
  773. XftTextExtentsUtf8(xw.dpy, f->match,
  774. (const FcChar8 *) ascii_printable,
  775. strlen(ascii_printable), &extents);
  776. f->set = NULL;
  777. f->pattern = configured;
  778. f->ascent = f->match->ascent;
  779. f->descent = f->match->descent;
  780. f->lbearing = 0;
  781. f->rbearing = f->match->max_advance_width;
  782. f->height = f->ascent + f->descent;
  783. f->width = DIVCEIL(extents.xOff, strlen(ascii_printable));
  784. return 0;
  785. }
  786. void
  787. xloadfonts(char *fontstr, double fontsize)
  788. {
  789. FcPattern *pattern;
  790. double fontval;
  791. if (fontstr[0] == '-')
  792. pattern = XftXlfdParse(fontstr, False, False);
  793. else
  794. pattern = FcNameParse((FcChar8 *)fontstr);
  795. if (!pattern)
  796. die("can't open font %s\n", fontstr);
  797. if (fontsize > 1) {
  798. FcPatternDel(pattern, FC_PIXEL_SIZE);
  799. FcPatternDel(pattern, FC_SIZE);
  800. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
  801. usedfontsize = fontsize;
  802. } else {
  803. if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
  804. FcResultMatch) {
  805. usedfontsize = fontval;
  806. } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
  807. FcResultMatch) {
  808. usedfontsize = -1;
  809. } else {
  810. /*
  811. * Default font size is 12, if none given. This is to
  812. * have a known usedfontsize value.
  813. */
  814. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
  815. usedfontsize = 12;
  816. }
  817. defaultfontsize = usedfontsize;
  818. }
  819. if (xloadfont(&dc.font, pattern))
  820. die("can't open font %s\n", fontstr);
  821. if (usedfontsize < 0) {
  822. FcPatternGetDouble(dc.font.match->pattern,
  823. FC_PIXEL_SIZE, 0, &fontval);
  824. usedfontsize = fontval;
  825. if (fontsize == 0)
  826. defaultfontsize = fontval;
  827. }
  828. /* Setting character width and height. */
  829. win.cw = ceilf(dc.font.width * cwscale);
  830. win.ch = ceilf(dc.font.height * chscale);
  831. FcPatternDel(pattern, FC_SLANT);
  832. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  833. if (xloadfont(&dc.ifont, pattern))
  834. die("can't open font %s\n", fontstr);
  835. FcPatternDel(pattern, FC_WEIGHT);
  836. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  837. if (xloadfont(&dc.ibfont, pattern))
  838. die("can't open font %s\n", fontstr);
  839. FcPatternDel(pattern, FC_SLANT);
  840. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
  841. if (xloadfont(&dc.bfont, pattern))
  842. die("can't open font %s\n", fontstr);
  843. FcPatternDestroy(pattern);
  844. }
  845. void
  846. xunloadfont(Font *f)
  847. {
  848. XftFontClose(xw.dpy, f->match);
  849. FcPatternDestroy(f->pattern);
  850. if (f->set)
  851. FcFontSetDestroy(f->set);
  852. }
  853. void
  854. xunloadfonts(void)
  855. {
  856. /* Free the loaded fonts in the font cache. */
  857. while (frclen > 0)
  858. XftFontClose(xw.dpy, frc[--frclen].font);
  859. xunloadfont(&dc.font);
  860. xunloadfont(&dc.bfont);
  861. xunloadfont(&dc.ifont);
  862. xunloadfont(&dc.ibfont);
  863. }
  864. void
  865. xinit(int cols, int rows)
  866. {
  867. XGCValues gcvalues;
  868. Cursor cursor;
  869. Window parent;
  870. pid_t thispid = getpid();
  871. XColor xmousefg, xmousebg;
  872. if (!(xw.dpy = XOpenDisplay(NULL)))
  873. die("can't open display\n");
  874. xw.scr = XDefaultScreen(xw.dpy);
  875. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  876. /* font */
  877. if (!FcInit())
  878. die("could not init fontconfig.\n");
  879. usedfont = (opt_font == NULL)? font : opt_font;
  880. xloadfonts(usedfont, 0);
  881. /* colors */
  882. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  883. xloadcols();
  884. /* adjust fixed window geometry */
  885. win.w = 2 * borderpx + cols * win.cw;
  886. win.h = 2 * borderpx + rows * win.ch;
  887. if (xw.gm & XNegative)
  888. xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2;
  889. if (xw.gm & YNegative)
  890. xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2;
  891. /* Events */
  892. xw.attrs.background_pixel = dc.col[defaultbg].pixel;
  893. xw.attrs.border_pixel = dc.col[defaultbg].pixel;
  894. xw.attrs.bit_gravity = NorthWestGravity;
  895. xw.attrs.event_mask = FocusChangeMask | KeyPressMask
  896. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  897. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  898. xw.attrs.colormap = xw.cmap;
  899. if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
  900. parent = XRootWindow(xw.dpy, xw.scr);
  901. xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
  902. win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  903. xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
  904. | CWEventMask | CWColormap, &xw.attrs);
  905. memset(&gcvalues, 0, sizeof(gcvalues));
  906. gcvalues.graphics_exposures = False;
  907. dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
  908. &gcvalues);
  909. xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h,
  910. DefaultDepth(xw.dpy, xw.scr));
  911. XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
  912. XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h);
  913. /* font spec buffer */
  914. xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec));
  915. /* Xft rendering context */
  916. xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  917. /* input methods */
  918. if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  919. XSetLocaleModifiers("@im=local");
  920. if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  921. XSetLocaleModifiers("@im=");
  922. if ((xw.xim = XOpenIM(xw.dpy,
  923. NULL, NULL, NULL)) == NULL) {
  924. die("XOpenIM failed. Could not open input"
  925. " device.\n");
  926. }
  927. }
  928. }
  929. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  930. | XIMStatusNothing, XNClientWindow, xw.win,
  931. XNFocusWindow, xw.win, NULL);
  932. if (xw.xic == NULL)
  933. die("XCreateIC failed. Could not obtain input method.\n");
  934. /* white cursor, black outline */
  935. cursor = XCreateFontCursor(xw.dpy, mouseshape);
  936. XDefineCursor(xw.dpy, xw.win, cursor);
  937. if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
  938. xmousefg.red = 0xffff;
  939. xmousefg.green = 0xffff;
  940. xmousefg.blue = 0xffff;
  941. }
  942. if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
  943. xmousebg.red = 0x0000;
  944. xmousebg.green = 0x0000;
  945. xmousebg.blue = 0x0000;
  946. }
  947. XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
  948. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  949. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  950. xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
  951. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  952. xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
  953. XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
  954. PropModeReplace, (uchar *)&thispid, 1);
  955. win.mode = MODE_NUMLOCK;
  956. resettitle();
  957. XMapWindow(xw.dpy, xw.win);
  958. xhints();
  959. XSync(xw.dpy, False);
  960. clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1);
  961. clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2);
  962. xsel.primary = NULL;
  963. xsel.clipboard = NULL;
  964. xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
  965. if (xsel.xtarget == None)
  966. xsel.xtarget = XA_STRING;
  967. }
  968. int
  969. xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
  970. {
  971. float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp;
  972. ushort mode, prevmode = USHRT_MAX;
  973. Font *font = &dc.font;
  974. int frcflags = FRC_NORMAL;
  975. float runewidth = win.cw;
  976. Rune rune;
  977. FT_UInt glyphidx;
  978. FcResult fcres;
  979. FcPattern *fcpattern, *fontpattern;
  980. FcFontSet *fcsets[] = { NULL };
  981. FcCharSet *fccharset;
  982. int i, f, numspecs = 0;
  983. for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
  984. /* Fetch rune and mode for current glyph. */
  985. rune = glyphs[i].u;
  986. mode = glyphs[i].mode;
  987. /* Skip dummy wide-character spacing. */
  988. if (mode == ATTR_WDUMMY)
  989. continue;
  990. /* Determine font for glyph if different from previous glyph. */
  991. if (prevmode != mode) {
  992. prevmode = mode;
  993. font = &dc.font;
  994. frcflags = FRC_NORMAL;
  995. runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
  996. if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
  997. font = &dc.ibfont;
  998. frcflags = FRC_ITALICBOLD;
  999. } else if (mode & ATTR_ITALIC) {
  1000. font = &dc.ifont;
  1001. frcflags = FRC_ITALIC;
  1002. } else if (mode & ATTR_BOLD) {
  1003. font = &dc.bfont;
  1004. frcflags = FRC_BOLD;
  1005. }
  1006. yp = winy + font->ascent;
  1007. }
  1008. /* Lookup character index with default font. */
  1009. glyphidx = XftCharIndex(xw.dpy, font->match, rune);
  1010. if (glyphidx) {
  1011. specs[numspecs].font = font->match;
  1012. specs[numspecs].glyph = glyphidx;
  1013. specs[numspecs].x = (short)xp;
  1014. specs[numspecs].y = (short)yp;
  1015. xp += runewidth;
  1016. numspecs++;
  1017. continue;
  1018. }
  1019. /* Fallback on font cache, search the font cache for match. */
  1020. for (f = 0; f < frclen; f++) {
  1021. glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
  1022. /* Everything correct. */
  1023. if (glyphidx && frc[f].flags == frcflags)
  1024. break;
  1025. /* We got a default font for a not found glyph. */
  1026. if (!glyphidx && frc[f].flags == frcflags
  1027. && frc[f].unicodep == rune) {
  1028. break;
  1029. }
  1030. }
  1031. /* Nothing was found. Use fontconfig to find matching font. */
  1032. if (f >= frclen) {
  1033. if (!font->set)
  1034. font->set = FcFontSort(0, font->pattern,
  1035. 1, 0, &fcres);
  1036. fcsets[0] = font->set;
  1037. /*
  1038. * Nothing was found in the cache. Now use
  1039. * some dozen of Fontconfig calls to get the
  1040. * font for one single character.
  1041. *
  1042. * Xft and fontconfig are design failures.
  1043. */
  1044. fcpattern = FcPatternDuplicate(font->pattern);
  1045. fccharset = FcCharSetCreate();
  1046. FcCharSetAddChar(fccharset, rune);
  1047. FcPatternAddCharSet(fcpattern, FC_CHARSET,
  1048. fccharset);
  1049. FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
  1050. FcConfigSubstitute(0, fcpattern,
  1051. FcMatchPattern);
  1052. FcDefaultSubstitute(fcpattern);
  1053. fontpattern = FcFontSetMatch(0, fcsets, 1,
  1054. fcpattern, &fcres);
  1055. /*
  1056. * Overwrite or create the new cache entry.
  1057. */
  1058. if (frclen >= LEN(frc)) {
  1059. frclen = LEN(frc) - 1;
  1060. XftFontClose(xw.dpy, frc[frclen].font);
  1061. frc[frclen].unicodep = 0;
  1062. }
  1063. frc[frclen].font = XftFontOpenPattern(xw.dpy,
  1064. fontpattern);
  1065. if (!frc[frclen].font)
  1066. die("XftFontOpenPattern failed seeking fallback font: %s\n",
  1067. strerror(errno));
  1068. frc[frclen].flags = frcflags;
  1069. frc[frclen].unicodep = rune;
  1070. glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
  1071. f = frclen;
  1072. frclen++;
  1073. FcPatternDestroy(fcpattern);
  1074. FcCharSetDestroy(fccharset);
  1075. }
  1076. specs[numspecs].font = frc[f].font;
  1077. specs[numspecs].glyph = glyphidx;
  1078. specs[numspecs].x = (short)xp;
  1079. specs[numspecs].y = (short)yp;
  1080. xp += runewidth;
  1081. numspecs++;
  1082. }
  1083. return numspecs;
  1084. }
  1085. void
  1086. xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
  1087. {
  1088. int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
  1089. int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch,
  1090. width = charlen * win.cw;
  1091. Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
  1092. XRenderColor colfg, colbg;
  1093. XRectangle r;
  1094. /* Fallback on color display for attributes not supported by the font */
  1095. if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) {
  1096. if (dc.ibfont.badslant || dc.ibfont.badweight)
  1097. base.fg = defaultattr;
  1098. } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) ||
  1099. (base.mode & ATTR_BOLD && dc.bfont.badweight)) {
  1100. base.fg = defaultattr;
  1101. }
  1102. if (IS_TRUECOL(base.fg)) {
  1103. colfg.alpha = 0xffff;
  1104. colfg.red = TRUERED(base.fg);
  1105. colfg.green = TRUEGREEN(base.fg);
  1106. colfg.blue = TRUEBLUE(base.fg);
  1107. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
  1108. fg = &truefg;
  1109. } else {
  1110. fg = &dc.col[base.fg];
  1111. }
  1112. if (IS_TRUECOL(base.bg)) {
  1113. colbg.alpha = 0xffff;
  1114. colbg.green = TRUEGREEN(base.bg);
  1115. colbg.red = TRUERED(base.bg);
  1116. colbg.blue = TRUEBLUE(base.bg);
  1117. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
  1118. bg = &truebg;
  1119. } else {
  1120. bg = &dc.col[base.bg];
  1121. }
  1122. /* Change basic system colors [0-7] to bright system colors [8-15] */
  1123. if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
  1124. fg = &dc.col[base.fg + 8];
  1125. if (IS_SET(MODE_REVERSE)) {
  1126. if (fg == &dc.col[defaultfg]) {
  1127. fg = &dc.col[defaultbg];
  1128. } else {
  1129. colfg.red = ~fg->color.red;
  1130. colfg.green = ~fg->color.green;
  1131. colfg.blue = ~fg->color.blue;
  1132. colfg.alpha = fg->color.alpha;
  1133. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
  1134. &revfg);
  1135. fg = &revfg;
  1136. }
  1137. if (bg == &dc.col[defaultbg]) {
  1138. bg = &dc.col[defaultfg];
  1139. } else {
  1140. colbg.red = ~bg->color.red;
  1141. colbg.green = ~bg->color.green;
  1142. colbg.blue = ~bg->color.blue;
  1143. colbg.alpha = bg->color.alpha;
  1144. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
  1145. &revbg);
  1146. bg = &revbg;
  1147. }
  1148. }
  1149. if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
  1150. colfg.red = fg->color.red / 2;
  1151. colfg.green = fg->color.green / 2;
  1152. colfg.blue = fg->color.blue / 2;
  1153. colfg.alpha = fg->color.alpha;
  1154. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  1155. fg = &revfg;
  1156. }
  1157. if (base.mode & ATTR_REVERSE) {
  1158. temp = fg;
  1159. fg = bg;
  1160. bg = temp;
  1161. }
  1162. if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK)
  1163. fg = bg;
  1164. if (base.mode & ATTR_INVISIBLE)
  1165. fg = bg;
  1166. /* Intelligent cleaning up of the borders. */
  1167. if (x == 0) {
  1168. xclear(0, (y == 0)? 0 : winy, borderpx,
  1169. winy + win.ch +
  1170. ((winy + win.ch >= borderpx + win.th)? win.h : 0));
  1171. }
  1172. if (winx + width >= borderpx + win.tw) {
  1173. xclear(winx + width, (y == 0)? 0 : winy, win.w,
  1174. ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch)));
  1175. }
  1176. if (y == 0)
  1177. xclear(winx, 0, winx + width, borderpx);
  1178. if (winy + win.ch >= borderpx + win.th)
  1179. xclear(winx, winy + win.ch, winx + width, win.h);
  1180. /* Clean up the region we want to draw to. */
  1181. XftDrawRect(xw.draw, bg, winx, winy, width, win.ch);
  1182. /* Set the clip region because Xft is sometimes dirty. */
  1183. r.x = 0;
  1184. r.y = 0;
  1185. r.height = win.ch;
  1186. r.width = width;
  1187. XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
  1188. /* Render the glyphs. */
  1189. XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
  1190. /* Render underline and strikethrough. */
  1191. if (base.mode & ATTR_UNDERLINE) {
  1192. XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
  1193. width, 1);
  1194. }
  1195. if (base.mode & ATTR_STRUCK) {
  1196. XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
  1197. width, 1);
  1198. }
  1199. /* Reset clip to none. */
  1200. XftDrawSetClip(xw.draw, 0);
  1201. }
  1202. void
  1203. xdrawglyph(Glyph g, int x, int y)
  1204. {
  1205. int numspecs;
  1206. XftGlyphFontSpec spec;
  1207. numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
  1208. xdrawglyphfontspecs(&spec, g, numspecs, x, y);
  1209. }
  1210. void
  1211. xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og)
  1212. {
  1213. Color drawcol;
  1214. /* remove the old cursor */
  1215. if (selected(ox, oy))
  1216. og.mode ^= ATTR_REVERSE;
  1217. xdrawglyph(og, ox, oy);
  1218. if (IS_SET(MODE_HIDE))
  1219. return;
  1220. /*
  1221. * Select the right color for the right mode.
  1222. */
  1223. g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE;
  1224. if (IS_SET(MODE_REVERSE)) {
  1225. g.mode |= ATTR_REVERSE;
  1226. g.bg = defaultfg;
  1227. if (selected(cx, cy)) {
  1228. drawcol = dc.col[defaultcs];
  1229. g.fg = defaultrcs;
  1230. } else {
  1231. drawcol = dc.col[defaultrcs];
  1232. g.fg = defaultcs;
  1233. }
  1234. } else {
  1235. if (selected(cx, cy)) {
  1236. g.fg = defaultfg;
  1237. g.bg = defaultrcs;
  1238. } else {
  1239. g.fg = defaultbg;
  1240. g.bg = defaultcs;
  1241. }
  1242. drawcol = dc.col[g.bg];
  1243. }
  1244. /* draw the new one */
  1245. if (IS_SET(MODE_FOCUSED)) {
  1246. switch (win.cursor) {
  1247. case 7: /* st extension: snowman (U+2603) */
  1248. g.u = 0x2603;
  1249. case 0: /* Blinking Block */
  1250. case 1: /* Blinking Block (Default) */
  1251. case 2: /* Steady Block */
  1252. xdrawglyph(g, cx, cy);
  1253. break;
  1254. case 3: /* Blinking Underline */
  1255. case 4: /* Steady Underline */
  1256. XftDrawRect(xw.draw, &drawcol,
  1257. borderpx + cx * win.cw,
  1258. borderpx + (cy + 1) * win.ch - \
  1259. cursorthickness,
  1260. win.cw, cursorthickness);
  1261. break;
  1262. case 5: /* Blinking bar */
  1263. case 6: /* Steady bar */
  1264. XftDrawRect(xw.draw, &drawcol,
  1265. borderpx + cx * win.cw,
  1266. borderpx + cy * win.ch,
  1267. cursorthickness, win.ch);
  1268. break;
  1269. }
  1270. } else {
  1271. XftDrawRect(xw.draw, &drawcol,
  1272. borderpx + cx * win.cw,
  1273. borderpx + cy * win.ch,
  1274. win.cw - 1, 1);
  1275. XftDrawRect(xw.draw, &drawcol,
  1276. borderpx + cx * win.cw,
  1277. borderpx + cy * win.ch,
  1278. 1, win.ch - 1);
  1279. XftDrawRect(xw.draw, &drawcol,
  1280. borderpx + (cx + 1) * win.cw - 1,
  1281. borderpx + cy * win.ch,
  1282. 1, win.ch - 1);
  1283. XftDrawRect(xw.draw, &drawcol,
  1284. borderpx + cx * win.cw,
  1285. borderpx + (cy + 1) * win.ch - 1,
  1286. win.cw, 1);
  1287. }
  1288. }
  1289. void
  1290. xsetenv(void)
  1291. {
  1292. char buf[sizeof(long) * 8 + 1];
  1293. snprintf(buf, sizeof(buf), "%lu", xw.win);
  1294. setenv("WINDOWID", buf, 1);
  1295. }
  1296. void
  1297. xsettitle(char *p)
  1298. {
  1299. XTextProperty prop;
  1300. DEFAULT(p, opt_title);
  1301. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  1302. &prop);
  1303. XSetWMName(xw.dpy, xw.win, &prop);
  1304. XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
  1305. XFree(prop.value);
  1306. }
  1307. int
  1308. xstartdraw(void)
  1309. {
  1310. return IS_SET(MODE_VISIBLE);
  1311. }
  1312. void
  1313. xdrawline(Line line, int x1, int y1, int x2)
  1314. {
  1315. int i, x, ox, numspecs;
  1316. Glyph base, new;
  1317. XftGlyphFontSpec *specs = xw.specbuf;
  1318. numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
  1319. i = ox = 0;
  1320. for (x = x1; x < x2 && i < numspecs; x++) {
  1321. new = line[x];
  1322. if (new.mode == ATTR_WDUMMY)
  1323. continue;
  1324. if (selected(x, y1))
  1325. new.mode ^= ATTR_REVERSE;
  1326. if (i > 0 && ATTRCMP(base, new)) {
  1327. xdrawglyphfontspecs(specs, base, i, ox, y1);
  1328. specs += i;
  1329. numspecs -= i;
  1330. i = 0;
  1331. }
  1332. if (i == 0) {
  1333. ox = x;
  1334. base = new;
  1335. }
  1336. i++;
  1337. }
  1338. if (i > 0)
  1339. xdrawglyphfontspecs(specs, base, i, ox, y1);
  1340. }
  1341. void
  1342. xfinishdraw(void)
  1343. {
  1344. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
  1345. win.h, 0, 0);
  1346. XSetForeground(xw.dpy, dc.gc,
  1347. dc.col[IS_SET(MODE_REVERSE)?
  1348. defaultfg : defaultbg].pixel);
  1349. }
  1350. void
  1351. expose(XEvent *ev)
  1352. {
  1353. redraw();
  1354. }
  1355. void
  1356. visibility(XEvent *ev)
  1357. {
  1358. XVisibilityEvent *e = &ev->xvisibility;
  1359. MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
  1360. }
  1361. void
  1362. unmap(XEvent *ev)
  1363. {
  1364. win.mode &= ~MODE_VISIBLE;
  1365. }
  1366. void
  1367. xsetpointermotion(int set)
  1368. {
  1369. MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
  1370. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
  1371. }
  1372. void
  1373. xsetmode(int set, unsigned int flags)
  1374. {
  1375. int mode = win.mode;
  1376. MODBIT(win.mode, set, flags);
  1377. if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
  1378. redraw();
  1379. }
  1380. int
  1381. xsetcursor(int cursor)
  1382. {
  1383. DEFAULT(cursor, 1);
  1384. if (!BETWEEN(cursor, 0, 6))
  1385. return 1;
  1386. win.cursor = cursor;
  1387. return 0;
  1388. }
  1389. void
  1390. xseturgency(int add)
  1391. {
  1392. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  1393. MODBIT(h->flags, add, XUrgencyHint);
  1394. XSetWMHints(xw.dpy, xw.win, h);
  1395. XFree(h);
  1396. }
  1397. void
  1398. xbell(void)
  1399. {
  1400. if (!(IS_SET(MODE_FOCUSED)))
  1401. xseturgency(1);
  1402. if (bellvolume)
  1403. XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
  1404. }
  1405. void
  1406. focus(XEvent *ev)
  1407. {
  1408. XFocusChangeEvent *e = &ev->xfocus;
  1409. if (e->mode == NotifyGrab)
  1410. return;
  1411. if (ev->type == FocusIn) {
  1412. XSetICFocus(xw.xic);
  1413. win.mode |= MODE_FOCUSED;
  1414. xseturgency(0);
  1415. if (IS_SET(MODE_FOCUS))
  1416. ttywrite("\033[I", 3, 0);
  1417. } else {
  1418. XUnsetICFocus(xw.xic);
  1419. win.mode &= ~MODE_FOCUSED;
  1420. if (IS_SET(MODE_FOCUS))
  1421. ttywrite("\033[O", 3, 0);
  1422. }
  1423. }
  1424. int
  1425. match(uint mask, uint state)
  1426. {
  1427. return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
  1428. }
  1429. char*
  1430. kmap(KeySym k, uint state)
  1431. {
  1432. Key *kp;
  1433. int i;
  1434. /* Check for mapped keys out of X11 function keys. */
  1435. for (i = 0; i < LEN(mappedkeys); i++) {
  1436. if (mappedkeys[i] == k)
  1437. break;
  1438. }
  1439. if (i == LEN(mappedkeys)) {
  1440. if ((k & 0xFFFF) < 0xFD00)
  1441. return NULL;
  1442. }
  1443. for (kp = key; kp < key + LEN(key); kp++) {
  1444. if (kp->k != k)
  1445. continue;
  1446. if (!match(kp->mask, state))
  1447. continue;
  1448. if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
  1449. continue;
  1450. if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
  1451. continue;
  1452. if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
  1453. continue;
  1454. return kp->s;
  1455. }
  1456. return NULL;
  1457. }
  1458. void
  1459. kpress(XEvent *ev)
  1460. {
  1461. XKeyEvent *e = &ev->xkey;
  1462. KeySym ksym;
  1463. char buf[32], *customkey;
  1464. int len;
  1465. Rune c;
  1466. Status status;
  1467. Shortcut *bp;
  1468. if (IS_SET(MODE_KBDLOCK))
  1469. return;
  1470. len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
  1471. /* 1. shortcuts */
  1472. for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  1473. if (ksym == bp->keysym && match(bp->mod, e->state)) {
  1474. bp->func(&(bp->arg));
  1475. return;
  1476. }
  1477. }
  1478. /* 2. custom keys from config.h */
  1479. if ((customkey = kmap(ksym, e->state))) {
  1480. ttywrite(customkey, strlen(customkey), 1);
  1481. return;
  1482. }
  1483. /* 3. composed string from input method */
  1484. if (len == 0)
  1485. return;
  1486. if (len == 1 && e->state & Mod1Mask) {
  1487. if (IS_SET(MODE_8BIT)) {
  1488. if (*buf < 0177) {
  1489. c = *buf | 0x80;
  1490. len = utf8encode(c, buf);
  1491. }
  1492. } else {
  1493. buf[1] = buf[0];
  1494. buf[0] = '\033';
  1495. len = 2;
  1496. }
  1497. }
  1498. ttywrite(buf, len, 1);
  1499. }
  1500. void
  1501. cmessage(XEvent *e)
  1502. {
  1503. /*
  1504. * See xembed specs
  1505. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  1506. */
  1507. if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  1508. if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  1509. win.mode |= MODE_FOCUSED;
  1510. xseturgency(0);
  1511. } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  1512. win.mode &= ~MODE_FOCUSED;
  1513. }
  1514. } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
  1515. ttyhangup();
  1516. exit(0);
  1517. }
  1518. }
  1519. void
  1520. resize(XEvent *e)
  1521. {
  1522. if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
  1523. return;
  1524. cresize(e->xconfigure.width, e->xconfigure.height);
  1525. }
  1526. void
  1527. run(void)
  1528. {
  1529. XEvent ev;
  1530. int w = win.w, h = win.h;
  1531. fd_set rfd;
  1532. int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
  1533. int ttyfd;
  1534. struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
  1535. long deltatime;
  1536. /* Waiting for window mapping */
  1537. do {
  1538. XNextEvent(xw.dpy, &ev);
  1539. /*
  1540. * This XFilterEvent call is required because of XOpenIM. It
  1541. * does filter out the key event and some client message for
  1542. * the input method too.
  1543. */
  1544. if (XFilterEvent(&ev, None))
  1545. continue;
  1546. if (ev.type == ConfigureNotify) {
  1547. w = ev.xconfigure.width;
  1548. h = ev.xconfigure.height;
  1549. }
  1550. } while (ev.type != MapNotify);
  1551. ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
  1552. cresize(w, h);
  1553. clock_gettime(CLOCK_MONOTONIC, &last);
  1554. lastblink = last;
  1555. for (xev = actionfps;;) {
  1556. FD_ZERO(&rfd);
  1557. FD_SET(ttyfd, &rfd);
  1558. FD_SET(xfd, &rfd);
  1559. if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
  1560. if (errno == EINTR)
  1561. continue;
  1562. die("select failed: %s\n", strerror(errno));
  1563. }
  1564. if (FD_ISSET(ttyfd, &rfd)) {
  1565. ttyread();
  1566. if (blinktimeout) {
  1567. blinkset = tattrset(ATTR_BLINK);
  1568. if (!blinkset)
  1569. MODBIT(win.mode, 0, MODE_BLINK);
  1570. }
  1571. }
  1572. if (FD_ISSET(xfd, &rfd))
  1573. xev = actionfps;
  1574. clock_gettime(CLOCK_MONOTONIC, &now);
  1575. drawtimeout.tv_sec = 0;
  1576. drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
  1577. tv = &drawtimeout;
  1578. dodraw = 0;
  1579. if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
  1580. tsetdirtattr(ATTR_BLINK);
  1581. win.mode ^= MODE_BLINK;
  1582. lastblink = now;
  1583. dodraw = 1;
  1584. }
  1585. deltatime = TIMEDIFF(now, last);
  1586. if (deltatime > 1000 / (xev ? xfps : actionfps)) {
  1587. dodraw = 1;
  1588. last = now;
  1589. }
  1590. if (dodraw) {
  1591. while (XPending(xw.dpy)) {
  1592. XNextEvent(xw.dpy, &ev);
  1593. if (XFilterEvent(&ev, None))
  1594. continue;
  1595. if (handler[ev.type])
  1596. (handler[ev.type])(&ev);
  1597. }
  1598. draw();
  1599. XFlush(xw.dpy);
  1600. if (xev && !FD_ISSET(xfd, &rfd))
  1601. xev--;
  1602. if (!FD_ISSET(ttyfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
  1603. if (blinkset) {
  1604. if (TIMEDIFF(now, lastblink) \
  1605. > blinktimeout) {
  1606. drawtimeout.tv_nsec = 1000;
  1607. } else {
  1608. drawtimeout.tv_nsec = (1E6 * \
  1609. (blinktimeout - \
  1610. TIMEDIFF(now,
  1611. lastblink)));
  1612. }
  1613. drawtimeout.tv_sec = \
  1614. drawtimeout.tv_nsec / 1E9;
  1615. drawtimeout.tv_nsec %= (long)1E9;
  1616. } else {
  1617. tv = NULL;
  1618. }
  1619. }
  1620. }
  1621. }
  1622. }
  1623. void
  1624. usage(void)
  1625. {
  1626. die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
  1627. " [-n name] [-o file]\n"
  1628. " [-T title] [-t title] [-w windowid]"
  1629. " [[-e] command [args ...]]\n"
  1630. " %s [-aiv] [-c class] [-f font] [-g geometry]"
  1631. " [-n name] [-o file]\n"
  1632. " [-T title] [-t title] [-w windowid] -l line"
  1633. " [stty_args ...]\n", argv0, argv0);
  1634. }
  1635. int
  1636. main(int argc, char *argv[])
  1637. {
  1638. xw.l = xw.t = 0;
  1639. xw.isfixed = False;
  1640. win.cursor = cursorshape;
  1641. ARGBEGIN {
  1642. case 'a':
  1643. allowaltscreen = 0;
  1644. break;
  1645. case 'c':
  1646. opt_class = EARGF(usage());
  1647. break;
  1648. case 'e':
  1649. if (argc > 0)
  1650. --argc, ++argv;
  1651. goto run;
  1652. case 'f':
  1653. opt_font = EARGF(usage());
  1654. break;
  1655. case 'g':
  1656. xw.gm = XParseGeometry(EARGF(usage()),
  1657. &xw.l, &xw.t, &cols, &rows);
  1658. break;
  1659. case 'i':
  1660. xw.isfixed = 1;
  1661. break;
  1662. case 'o':
  1663. opt_io = EARGF(usage());
  1664. break;
  1665. case 'l':
  1666. opt_line = EARGF(usage());
  1667. break;
  1668. case 'n':
  1669. opt_name = EARGF(usage());
  1670. break;
  1671. case 't':
  1672. case 'T':
  1673. opt_title = EARGF(usage());
  1674. break;
  1675. case 'w':
  1676. opt_embed = EARGF(usage());
  1677. break;
  1678. case 'v':
  1679. die("%s " VERSION "\n", argv0);
  1680. break;
  1681. default:
  1682. usage();
  1683. } ARGEND;
  1684. run:
  1685. if (argc > 0) /* eat all remaining arguments */
  1686. opt_cmd = argv;
  1687. if (!opt_title)
  1688. opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
  1689. setlocale(LC_CTYPE, "");
  1690. XSetLocaleModifiers("");
  1691. cols = MAX(cols, 1);
  1692. rows = MAX(rows, 1);
  1693. tnew(cols, rows);
  1694. xinit(cols, rows);
  1695. xsetenv();
  1696. selinit();
  1697. run();
  1698. return 0;
  1699. }