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.

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