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.

1992 lines
44 KiB

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