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.

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