My build of suckless st terminal
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1990 lines
44 KiB

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