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.

1949 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 (selected(cx, cy)) {
  1225. g.bg = defaultrcs;
  1226. g.fg = defaultfg;
  1227. } else {
  1228. g.bg = defaultcs;
  1229. g.fg = defaultbg;
  1230. }
  1231. drawcol = dc.col[g.bg];
  1232. if (IS_SET(MODE_REVERSE)) {
  1233. drawcol.color.red = ~drawcol.color.red;
  1234. drawcol.color.green = ~drawcol.color.green;
  1235. drawcol.color.blue = ~drawcol.color.blue;
  1236. }
  1237. /* draw the new one */
  1238. if (IS_SET(MODE_FOCUSED)) {
  1239. switch (win.cursor) {
  1240. case 7: /* st extension: snowman (U+2603) */
  1241. g.u = 0x2603;
  1242. case 0: /* Blinking Block */
  1243. case 1: /* Blinking Block (Default) */
  1244. case 2: /* Steady Block */
  1245. xdrawglyph(g, cx, cy);
  1246. break;
  1247. case 3: /* Blinking Underline */
  1248. case 4: /* Steady Underline */
  1249. XftDrawRect(xw.draw, &drawcol,
  1250. borderpx + cx * win.cw,
  1251. borderpx + (cy + 1) * win.ch - \
  1252. cursorthickness,
  1253. win.cw, cursorthickness);
  1254. break;
  1255. case 5: /* Blinking bar */
  1256. case 6: /* Steady bar */
  1257. XftDrawRect(xw.draw, &drawcol,
  1258. borderpx + cx * win.cw,
  1259. borderpx + cy * win.ch,
  1260. cursorthickness, win.ch);
  1261. break;
  1262. }
  1263. } else {
  1264. XftDrawRect(xw.draw, &drawcol,
  1265. borderpx + cx * win.cw,
  1266. borderpx + cy * win.ch,
  1267. win.cw - 1, 1);
  1268. XftDrawRect(xw.draw, &drawcol,
  1269. borderpx + cx * win.cw,
  1270. borderpx + cy * win.ch,
  1271. 1, win.ch - 1);
  1272. XftDrawRect(xw.draw, &drawcol,
  1273. borderpx + (cx + 1) * win.cw - 1,
  1274. borderpx + cy * win.ch,
  1275. 1, win.ch - 1);
  1276. XftDrawRect(xw.draw, &drawcol,
  1277. borderpx + cx * win.cw,
  1278. borderpx + (cy + 1) * win.ch - 1,
  1279. win.cw, 1);
  1280. }
  1281. }
  1282. void
  1283. xsetenv(void)
  1284. {
  1285. char buf[sizeof(long) * 8 + 1];
  1286. snprintf(buf, sizeof(buf), "%lu", xw.win);
  1287. setenv("WINDOWID", buf, 1);
  1288. }
  1289. void
  1290. xsettitle(char *p)
  1291. {
  1292. XTextProperty prop;
  1293. DEFAULT(p, opt_title);
  1294. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  1295. &prop);
  1296. XSetWMName(xw.dpy, xw.win, &prop);
  1297. XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
  1298. XFree(prop.value);
  1299. }
  1300. int
  1301. xstartdraw(void)
  1302. {
  1303. return IS_SET(MODE_VISIBLE);
  1304. }
  1305. void
  1306. xdrawline(Line line, int x1, int y1, int x2)
  1307. {
  1308. int i, x, ox, numspecs;
  1309. Glyph base, new;
  1310. XftGlyphFontSpec *specs = xw.specbuf;
  1311. numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1);
  1312. i = ox = 0;
  1313. for (x = x1; x < x2 && i < numspecs; x++) {
  1314. new = line[x];
  1315. if (new.mode == ATTR_WDUMMY)
  1316. continue;
  1317. if (selected(x, y1))
  1318. new.mode ^= ATTR_REVERSE;
  1319. if (i > 0 && ATTRCMP(base, new)) {
  1320. xdrawglyphfontspecs(specs, base, i, ox, y1);
  1321. specs += i;
  1322. numspecs -= i;
  1323. i = 0;
  1324. }
  1325. if (i == 0) {
  1326. ox = x;
  1327. base = new;
  1328. }
  1329. i++;
  1330. }
  1331. if (i > 0)
  1332. xdrawglyphfontspecs(specs, base, i, ox, y1);
  1333. }
  1334. void
  1335. xfinishdraw(void)
  1336. {
  1337. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
  1338. win.h, 0, 0);
  1339. XSetForeground(xw.dpy, dc.gc,
  1340. dc.col[IS_SET(MODE_REVERSE)?
  1341. defaultfg : defaultbg].pixel);
  1342. }
  1343. void
  1344. expose(XEvent *ev)
  1345. {
  1346. redraw();
  1347. }
  1348. void
  1349. visibility(XEvent *ev)
  1350. {
  1351. XVisibilityEvent *e = &ev->xvisibility;
  1352. MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE);
  1353. }
  1354. void
  1355. unmap(XEvent *ev)
  1356. {
  1357. win.mode &= ~MODE_VISIBLE;
  1358. }
  1359. void
  1360. xsetpointermotion(int set)
  1361. {
  1362. MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
  1363. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
  1364. }
  1365. void
  1366. xsetmode(int set, unsigned int flags)
  1367. {
  1368. int mode = win.mode;
  1369. MODBIT(win.mode, set, flags);
  1370. if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE))
  1371. redraw();
  1372. }
  1373. int
  1374. xsetcursor(int cursor)
  1375. {
  1376. DEFAULT(cursor, 1);
  1377. if (!BETWEEN(cursor, 0, 6))
  1378. return 1;
  1379. win.cursor = cursor;
  1380. return 0;
  1381. }
  1382. void
  1383. xseturgency(int add)
  1384. {
  1385. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  1386. MODBIT(h->flags, add, XUrgencyHint);
  1387. XSetWMHints(xw.dpy, xw.win, h);
  1388. XFree(h);
  1389. }
  1390. void
  1391. xbell(void)
  1392. {
  1393. if (!(IS_SET(MODE_FOCUSED)))
  1394. xseturgency(1);
  1395. if (bellvolume)
  1396. XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
  1397. }
  1398. void
  1399. focus(XEvent *ev)
  1400. {
  1401. XFocusChangeEvent *e = &ev->xfocus;
  1402. if (e->mode == NotifyGrab)
  1403. return;
  1404. if (ev->type == FocusIn) {
  1405. XSetICFocus(xw.xic);
  1406. win.mode |= MODE_FOCUSED;
  1407. xseturgency(0);
  1408. if (IS_SET(MODE_FOCUS))
  1409. ttywrite("\033[I", 3, 0);
  1410. } else {
  1411. XUnsetICFocus(xw.xic);
  1412. win.mode &= ~MODE_FOCUSED;
  1413. if (IS_SET(MODE_FOCUS))
  1414. ttywrite("\033[O", 3, 0);
  1415. }
  1416. }
  1417. int
  1418. match(uint mask, uint state)
  1419. {
  1420. return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
  1421. }
  1422. char*
  1423. kmap(KeySym k, uint state)
  1424. {
  1425. Key *kp;
  1426. int i;
  1427. /* Check for mapped keys out of X11 function keys. */
  1428. for (i = 0; i < LEN(mappedkeys); i++) {
  1429. if (mappedkeys[i] == k)
  1430. break;
  1431. }
  1432. if (i == LEN(mappedkeys)) {
  1433. if ((k & 0xFFFF) < 0xFD00)
  1434. return NULL;
  1435. }
  1436. for (kp = key; kp < key + LEN(key); kp++) {
  1437. if (kp->k != k)
  1438. continue;
  1439. if (!match(kp->mask, state))
  1440. continue;
  1441. if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
  1442. continue;
  1443. if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2)
  1444. continue;
  1445. if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
  1446. continue;
  1447. return kp->s;
  1448. }
  1449. return NULL;
  1450. }
  1451. void
  1452. kpress(XEvent *ev)
  1453. {
  1454. XKeyEvent *e = &ev->xkey;
  1455. KeySym ksym;
  1456. char buf[32], *customkey;
  1457. int len;
  1458. Rune c;
  1459. Status status;
  1460. Shortcut *bp;
  1461. if (IS_SET(MODE_KBDLOCK))
  1462. return;
  1463. len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
  1464. /* 1. shortcuts */
  1465. for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  1466. if (ksym == bp->keysym && match(bp->mod, e->state)) {
  1467. bp->func(&(bp->arg));
  1468. return;
  1469. }
  1470. }
  1471. /* 2. custom keys from config.h */
  1472. if ((customkey = kmap(ksym, e->state))) {
  1473. ttywrite(customkey, strlen(customkey), 1);
  1474. return;
  1475. }
  1476. /* 3. composed string from input method */
  1477. if (len == 0)
  1478. return;
  1479. if (len == 1 && e->state & Mod1Mask) {
  1480. if (IS_SET(MODE_8BIT)) {
  1481. if (*buf < 0177) {
  1482. c = *buf | 0x80;
  1483. len = utf8encode(c, buf);
  1484. }
  1485. } else {
  1486. buf[1] = buf[0];
  1487. buf[0] = '\033';
  1488. len = 2;
  1489. }
  1490. }
  1491. ttywrite(buf, len, 1);
  1492. }
  1493. void
  1494. cmessage(XEvent *e)
  1495. {
  1496. /*
  1497. * See xembed specs
  1498. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  1499. */
  1500. if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  1501. if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  1502. win.mode |= MODE_FOCUSED;
  1503. xseturgency(0);
  1504. } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  1505. win.mode &= ~MODE_FOCUSED;
  1506. }
  1507. } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
  1508. ttyhangup();
  1509. exit(0);
  1510. }
  1511. }
  1512. void
  1513. resize(XEvent *e)
  1514. {
  1515. if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
  1516. return;
  1517. cresize(e->xconfigure.width, e->xconfigure.height);
  1518. }
  1519. void
  1520. run(void)
  1521. {
  1522. XEvent ev;
  1523. int w = win.w, h = win.h;
  1524. fd_set rfd;
  1525. int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
  1526. int ttyfd;
  1527. struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
  1528. long deltatime;
  1529. /* Waiting for window mapping */
  1530. do {
  1531. XNextEvent(xw.dpy, &ev);
  1532. /*
  1533. * This XFilterEvent call is required because of XOpenIM. It
  1534. * does filter out the key event and some client message for
  1535. * the input method too.
  1536. */
  1537. if (XFilterEvent(&ev, None))
  1538. continue;
  1539. if (ev.type == ConfigureNotify) {
  1540. w = ev.xconfigure.width;
  1541. h = ev.xconfigure.height;
  1542. }
  1543. } while (ev.type != MapNotify);
  1544. ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd);
  1545. cresize(w, h);
  1546. clock_gettime(CLOCK_MONOTONIC, &last);
  1547. lastblink = last;
  1548. for (xev = actionfps;;) {
  1549. FD_ZERO(&rfd);
  1550. FD_SET(ttyfd, &rfd);
  1551. FD_SET(xfd, &rfd);
  1552. if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
  1553. if (errno == EINTR)
  1554. continue;
  1555. die("select failed: %s\n", strerror(errno));
  1556. }
  1557. if (FD_ISSET(ttyfd, &rfd)) {
  1558. ttyread();
  1559. if (blinktimeout) {
  1560. blinkset = tattrset(ATTR_BLINK);
  1561. if (!blinkset)
  1562. MODBIT(win.mode, 0, MODE_BLINK);
  1563. }
  1564. }
  1565. if (FD_ISSET(xfd, &rfd))
  1566. xev = actionfps;
  1567. clock_gettime(CLOCK_MONOTONIC, &now);
  1568. drawtimeout.tv_sec = 0;
  1569. drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
  1570. tv = &drawtimeout;
  1571. dodraw = 0;
  1572. if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
  1573. tsetdirtattr(ATTR_BLINK);
  1574. win.mode ^= MODE_BLINK;
  1575. lastblink = now;
  1576. dodraw = 1;
  1577. }
  1578. deltatime = TIMEDIFF(now, last);
  1579. if (deltatime > 1000 / (xev ? xfps : actionfps)) {
  1580. dodraw = 1;
  1581. last = now;
  1582. }
  1583. if (dodraw) {
  1584. while (XPending(xw.dpy)) {
  1585. XNextEvent(xw.dpy, &ev);
  1586. if (XFilterEvent(&ev, None))
  1587. continue;
  1588. if (handler[ev.type])
  1589. (handler[ev.type])(&ev);
  1590. }
  1591. draw();
  1592. XFlush(xw.dpy);
  1593. if (xev && !FD_ISSET(xfd, &rfd))
  1594. xev--;
  1595. if (!FD_ISSET(ttyfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
  1596. if (blinkset) {
  1597. if (TIMEDIFF(now, lastblink) \
  1598. > blinktimeout) {
  1599. drawtimeout.tv_nsec = 1000;
  1600. } else {
  1601. drawtimeout.tv_nsec = (1E6 * \
  1602. (blinktimeout - \
  1603. TIMEDIFF(now,
  1604. lastblink)));
  1605. }
  1606. drawtimeout.tv_sec = \
  1607. drawtimeout.tv_nsec / 1E9;
  1608. drawtimeout.tv_nsec %= (long)1E9;
  1609. } else {
  1610. tv = NULL;
  1611. }
  1612. }
  1613. }
  1614. }
  1615. }
  1616. void
  1617. usage(void)
  1618. {
  1619. die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
  1620. " [-n name] [-o file]\n"
  1621. " [-T title] [-t title] [-w windowid]"
  1622. " [[-e] command [args ...]]\n"
  1623. " %s [-aiv] [-c class] [-f font] [-g geometry]"
  1624. " [-n name] [-o file]\n"
  1625. " [-T title] [-t title] [-w windowid] -l line"
  1626. " [stty_args ...]\n", argv0, argv0);
  1627. }
  1628. int
  1629. main(int argc, char *argv[])
  1630. {
  1631. xw.l = xw.t = 0;
  1632. xw.isfixed = False;
  1633. win.cursor = cursorshape;
  1634. ARGBEGIN {
  1635. case 'a':
  1636. allowaltscreen = 0;
  1637. break;
  1638. case 'c':
  1639. opt_class = EARGF(usage());
  1640. break;
  1641. case 'e':
  1642. if (argc > 0)
  1643. --argc, ++argv;
  1644. goto run;
  1645. case 'f':
  1646. opt_font = EARGF(usage());
  1647. break;
  1648. case 'g':
  1649. xw.gm = XParseGeometry(EARGF(usage()),
  1650. &xw.l, &xw.t, &cols, &rows);
  1651. break;
  1652. case 'i':
  1653. xw.isfixed = 1;
  1654. break;
  1655. case 'o':
  1656. opt_io = EARGF(usage());
  1657. break;
  1658. case 'l':
  1659. opt_line = EARGF(usage());
  1660. break;
  1661. case 'n':
  1662. opt_name = EARGF(usage());
  1663. break;
  1664. case 't':
  1665. case 'T':
  1666. opt_title = EARGF(usage());
  1667. break;
  1668. case 'w':
  1669. opt_embed = EARGF(usage());
  1670. break;
  1671. case 'v':
  1672. die("%s " VERSION "\n", argv0);
  1673. break;
  1674. default:
  1675. usage();
  1676. } ARGEND;
  1677. run:
  1678. if (argc > 0) /* eat all remaining arguments */
  1679. opt_cmd = argv;
  1680. if (!opt_title)
  1681. opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0];
  1682. setlocale(LC_CTYPE, "");
  1683. XSetLocaleModifiers("");
  1684. cols = MAX(cols, 1);
  1685. rows = MAX(rows, 1);
  1686. tnew(cols, rows);
  1687. xinit(cols, rows);
  1688. xsetenv();
  1689. selinit();
  1690. run();
  1691. return 0;
  1692. }