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.

1989 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. ttyresize(win.tw, win.th);
  247. redraw();
  248. xhints();
  249. }
  250. void
  251. zoomreset(const Arg *arg)
  252. {
  253. Arg larg;
  254. if (defaultfontsize > 0) {
  255. larg.f = defaultfontsize;
  256. zoomabs(&larg);
  257. }
  258. }
  259. int
  260. x2col(int x)
  261. {
  262. x -= borderpx;
  263. x /= win.cw;
  264. return LIMIT(x, 0, term.col-1);
  265. }
  266. int
  267. y2row(int y)
  268. {
  269. y -= borderpx;
  270. y /= win.ch;
  271. return LIMIT(y, 0, term.row-1);
  272. }
  273. void
  274. getbuttoninfo(XEvent *e)
  275. {
  276. int type;
  277. uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
  278. sel.alt = IS_SET(MODE_ALTSCREEN);
  279. sel.oe.x = x2col(e->xbutton.x);
  280. sel.oe.y = y2row(e->xbutton.y);
  281. selnormalize();
  282. sel.type = SEL_REGULAR;
  283. for (type = 1; type < LEN(selmasks); ++type) {
  284. if (match(selmasks[type], state)) {
  285. sel.type = type;
  286. break;
  287. }
  288. }
  289. }
  290. void
  291. mousereport(XEvent *e)
  292. {
  293. int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
  294. button = e->xbutton.button, state = e->xbutton.state,
  295. len;
  296. char buf[40];
  297. static int ox, oy;
  298. /* from urxvt */
  299. if (e->xbutton.type == MotionNotify) {
  300. if (x == ox && y == oy)
  301. return;
  302. if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
  303. return;
  304. /* MOUSE_MOTION: no reporting if no button is pressed */
  305. if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
  306. return;
  307. button = oldbutton + 32;
  308. ox = x;
  309. oy = y;
  310. } else {
  311. if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
  312. button = 3;
  313. } else {
  314. button -= Button1;
  315. if (button >= 3)
  316. button += 64 - 3;
  317. }
  318. if (e->xbutton.type == ButtonPress) {
  319. oldbutton = button;
  320. ox = x;
  321. oy = y;
  322. } else if (e->xbutton.type == ButtonRelease) {
  323. oldbutton = 3;
  324. /* MODE_MOUSEX10: no button release reporting */
  325. if (IS_SET(MODE_MOUSEX10))
  326. return;
  327. if (button == 64 || button == 65)
  328. return;
  329. }
  330. }
  331. if (!IS_SET(MODE_MOUSEX10)) {
  332. button += ((state & ShiftMask ) ? 4 : 0)
  333. + ((state & Mod4Mask ) ? 8 : 0)
  334. + ((state & ControlMask) ? 16 : 0);
  335. }
  336. if (IS_SET(MODE_MOUSESGR)) {
  337. len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
  338. button, x+1, y+1,
  339. e->xbutton.type == ButtonRelease ? 'm' : 'M');
  340. } else if (x < 223 && y < 223) {
  341. len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
  342. 32+button, 32+x+1, 32+y+1);
  343. } else {
  344. return;
  345. }
  346. ttywrite(buf, len);
  347. }
  348. void
  349. bpress(XEvent *e)
  350. {
  351. struct timespec now;
  352. MouseShortcut *ms;
  353. if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
  354. mousereport(e);
  355. return;
  356. }
  357. for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) {
  358. if (e->xbutton.button == ms->b
  359. && match(ms->mask, e->xbutton.state)) {
  360. ttysend(ms->s, strlen(ms->s));
  361. return;
  362. }
  363. }
  364. if (e->xbutton.button == Button1) {
  365. clock_gettime(CLOCK_MONOTONIC, &now);
  366. /* Clear previous selection, logically and visually. */
  367. selclear_(NULL);
  368. sel.mode = SEL_EMPTY;
  369. sel.type = SEL_REGULAR;
  370. sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
  371. sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
  372. /*
  373. * If the user clicks below predefined timeouts specific
  374. * snapping behaviour is exposed.
  375. */
  376. if (TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
  377. sel.snap = SNAP_LINE;
  378. } else if (TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
  379. sel.snap = SNAP_WORD;
  380. } else {
  381. sel.snap = 0;
  382. }
  383. selnormalize();
  384. if (sel.snap != 0)
  385. sel.mode = SEL_READY;
  386. tsetdirt(sel.nb.y, sel.ne.y);
  387. sel.tclick2 = sel.tclick1;
  388. sel.tclick1 = now;
  389. }
  390. }
  391. void
  392. propnotify(XEvent *e)
  393. {
  394. XPropertyEvent *xpev;
  395. Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  396. xpev = &e->xproperty;
  397. if (xpev->state == PropertyNewValue &&
  398. (xpev->atom == XA_PRIMARY ||
  399. xpev->atom == clipboard)) {
  400. selnotify(e);
  401. }
  402. }
  403. void
  404. selnotify(XEvent *e)
  405. {
  406. ulong nitems, ofs, rem;
  407. int format;
  408. uchar *data, *last, *repl;
  409. Atom type, incratom, property;
  410. incratom = XInternAtom(xw.dpy, "INCR", 0);
  411. ofs = 0;
  412. if (e->type == SelectionNotify) {
  413. property = e->xselection.property;
  414. } else if(e->type == PropertyNotify) {
  415. property = e->xproperty.atom;
  416. } else {
  417. return;
  418. }
  419. if (property == None)
  420. return;
  421. do {
  422. if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
  423. BUFSIZ/4, False, AnyPropertyType,
  424. &type, &format, &nitems, &rem,
  425. &data)) {
  426. fprintf(stderr, "Clipboard allocation failed\n");
  427. return;
  428. }
  429. if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
  430. /*
  431. * If there is some PropertyNotify with no data, then
  432. * this is the signal of the selection owner that all
  433. * data has been transferred. We won't need to receive
  434. * PropertyNotify events anymore.
  435. */
  436. MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
  437. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
  438. &xw.attrs);
  439. }
  440. if (type == incratom) {
  441. /*
  442. * Activate the PropertyNotify events so we receive
  443. * when the selection owner does send us the next
  444. * chunk of data.
  445. */
  446. MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
  447. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
  448. &xw.attrs);
  449. /*
  450. * Deleting the property is the transfer start signal.
  451. */
  452. XDeleteProperty(xw.dpy, xw.win, (int)property);
  453. continue;
  454. }
  455. /*
  456. * As seen in getsel:
  457. * Line endings are inconsistent in the terminal and GUI world
  458. * copy and pasting. When receiving some selection data,
  459. * replace all '\n' with '\r'.
  460. * FIXME: Fix the computer world.
  461. */
  462. repl = data;
  463. last = data + nitems * format / 8;
  464. while ((repl = memchr(repl, '\n', last - repl))) {
  465. *repl++ = '\r';
  466. }
  467. if (IS_SET(MODE_BRCKTPASTE) && ofs == 0)
  468. ttywrite("\033[200~", 6);
  469. ttysend((char *)data, nitems * format / 8);
  470. if (IS_SET(MODE_BRCKTPASTE) && rem == 0)
  471. ttywrite("\033[201~", 6);
  472. XFree(data);
  473. /* number of 32-bit chunks returned */
  474. ofs += nitems * format / 32;
  475. } while (rem > 0);
  476. /*
  477. * Deleting the property again tells the selection owner to send the
  478. * next data chunk in the property.
  479. */
  480. XDeleteProperty(xw.dpy, xw.win, (int)property);
  481. }
  482. void
  483. xclipcopy(void)
  484. {
  485. clipcopy(NULL);
  486. }
  487. void
  488. selclear_(XEvent *e)
  489. {
  490. selclear();
  491. }
  492. void
  493. selrequest(XEvent *e)
  494. {
  495. XSelectionRequestEvent *xsre;
  496. XSelectionEvent xev;
  497. Atom xa_targets, string, clipboard;
  498. char *seltext;
  499. xsre = (XSelectionRequestEvent *) e;
  500. xev.type = SelectionNotify;
  501. xev.requestor = xsre->requestor;
  502. xev.selection = xsre->selection;
  503. xev.target = xsre->target;
  504. xev.time = xsre->time;
  505. if (xsre->property == None)
  506. xsre->property = xsre->target;
  507. /* reject */
  508. xev.property = None;
  509. xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
  510. if (xsre->target == xa_targets) {
  511. /* respond with the supported type */
  512. string = xsel.xtarget;
  513. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  514. XA_ATOM, 32, PropModeReplace,
  515. (uchar *) &string, 1);
  516. xev.property = xsre->property;
  517. } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) {
  518. /*
  519. * xith XA_STRING non ascii characters may be incorrect in the
  520. * requestor. It is not our problem, use utf8.
  521. */
  522. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  523. if (xsre->selection == XA_PRIMARY) {
  524. seltext = sel.primary;
  525. } else if (xsre->selection == clipboard) {
  526. seltext = sel.clipboard;
  527. } else {
  528. fprintf(stderr,
  529. "Unhandled clipboard selection 0x%lx\n",
  530. xsre->selection);
  531. return;
  532. }
  533. if (seltext != NULL) {
  534. XChangeProperty(xsre->display, xsre->requestor,
  535. xsre->property, xsre->target,
  536. 8, PropModeReplace,
  537. (uchar *)seltext, strlen(seltext));
  538. xev.property = xsre->property;
  539. }
  540. }
  541. /* all done, send a notification to the listener */
  542. if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
  543. fprintf(stderr, "Error sending SelectionNotify event\n");
  544. }
  545. void
  546. setsel(char *str, Time t)
  547. {
  548. free(sel.primary);
  549. sel.primary = str;
  550. XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
  551. if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
  552. selclear_(NULL);
  553. }
  554. void
  555. xsetsel(char *str)
  556. {
  557. setsel(str, CurrentTime);
  558. }
  559. void
  560. brelease(XEvent *e)
  561. {
  562. if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
  563. mousereport(e);
  564. return;
  565. }
  566. if (e->xbutton.button == Button2) {
  567. selpaste(NULL);
  568. } else if (e->xbutton.button == Button1) {
  569. if (sel.mode == SEL_READY) {
  570. getbuttoninfo(e);
  571. setsel(getsel(), e->xbutton.time);
  572. } else
  573. selclear_(NULL);
  574. sel.mode = SEL_IDLE;
  575. tsetdirt(sel.nb.y, sel.ne.y);
  576. }
  577. }
  578. void
  579. bmotion(XEvent *e)
  580. {
  581. int oldey, oldex, oldsby, oldsey;
  582. if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
  583. mousereport(e);
  584. return;
  585. }
  586. if (!sel.mode)
  587. return;
  588. sel.mode = SEL_READY;
  589. oldey = sel.oe.y;
  590. oldex = sel.oe.x;
  591. oldsby = sel.nb.y;
  592. oldsey = sel.ne.y;
  593. getbuttoninfo(e);
  594. if (oldey != sel.oe.y || oldex != sel.oe.x)
  595. tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
  596. }
  597. void
  598. cresize(int width, int height)
  599. {
  600. int col, row;
  601. if (width != 0)
  602. win.w = width;
  603. if (height != 0)
  604. win.h = height;
  605. col = (win.w - 2 * borderpx) / win.cw;
  606. row = (win.h - 2 * borderpx) / win.ch;
  607. tresize(col, row);
  608. xresize(col, row);
  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. int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
  1223. Color drawcol;
  1224. LIMIT(oldx, 0, term.col-1);
  1225. LIMIT(oldy, 0, term.row-1);
  1226. curx = term.c.x;
  1227. /* adjust position if in dummy */
  1228. if (term.line[oldy][oldx].mode & ATTR_WDUMMY)
  1229. oldx--;
  1230. if (term.line[term.c.y][curx].mode & ATTR_WDUMMY)
  1231. curx--;
  1232. /* remove the old cursor */
  1233. og = term.line[oldy][oldx];
  1234. if (ena_sel && selected(oldx, oldy))
  1235. og.mode ^= ATTR_REVERSE;
  1236. xdrawglyph(og, oldx, oldy);
  1237. g.u = term.line[term.c.y][term.c.x].u;
  1238. g.mode |= term.line[term.c.y][term.c.x].mode &
  1239. (ATTR_BOLD | ATTR_ITALIC | ATTR_UNDERLINE | ATTR_STRUCK);
  1240. /*
  1241. * Select the right color for the right mode.
  1242. */
  1243. if (IS_SET(MODE_REVERSE)) {
  1244. g.mode |= ATTR_REVERSE;
  1245. g.bg = defaultfg;
  1246. if (ena_sel && selected(term.c.x, term.c.y)) {
  1247. drawcol = dc.col[defaultcs];
  1248. g.fg = defaultrcs;
  1249. } else {
  1250. drawcol = dc.col[defaultrcs];
  1251. g.fg = defaultcs;
  1252. }
  1253. } else {
  1254. if (ena_sel && selected(term.c.x, term.c.y)) {
  1255. drawcol = dc.col[defaultrcs];
  1256. g.fg = defaultfg;
  1257. g.bg = defaultrcs;
  1258. } else {
  1259. drawcol = dc.col[defaultcs];
  1260. }
  1261. }
  1262. if (IS_SET(MODE_HIDE))
  1263. return;
  1264. /* draw the new one */
  1265. if (win.state & WIN_FOCUSED) {
  1266. switch (win.cursor) {
  1267. case 7: /* st extension: snowman */
  1268. utf8decode("", &g.u, UTF_SIZ);
  1269. case 0: /* Blinking Block */
  1270. case 1: /* Blinking Block (Default) */
  1271. case 2: /* Steady Block */
  1272. g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
  1273. xdrawglyph(g, term.c.x, term.c.y);
  1274. break;
  1275. case 3: /* Blinking Underline */
  1276. case 4: /* Steady Underline */
  1277. XftDrawRect(xw.draw, &drawcol,
  1278. borderpx + curx * win.cw,
  1279. borderpx + (term.c.y + 1) * win.ch - \
  1280. cursorthickness,
  1281. win.cw, cursorthickness);
  1282. break;
  1283. case 5: /* Blinking bar */
  1284. case 6: /* Steady bar */
  1285. XftDrawRect(xw.draw, &drawcol,
  1286. borderpx + curx * win.cw,
  1287. borderpx + term.c.y * win.ch,
  1288. cursorthickness, win.ch);
  1289. break;
  1290. }
  1291. } else {
  1292. XftDrawRect(xw.draw, &drawcol,
  1293. borderpx + curx * win.cw,
  1294. borderpx + term.c.y * win.ch,
  1295. win.cw - 1, 1);
  1296. XftDrawRect(xw.draw, &drawcol,
  1297. borderpx + curx * win.cw,
  1298. borderpx + term.c.y * win.ch,
  1299. 1, win.ch - 1);
  1300. XftDrawRect(xw.draw, &drawcol,
  1301. borderpx + (curx + 1) * win.cw - 1,
  1302. borderpx + term.c.y * win.ch,
  1303. 1, win.ch - 1);
  1304. XftDrawRect(xw.draw, &drawcol,
  1305. borderpx + curx * win.cw,
  1306. borderpx + (term.c.y + 1) * win.ch - 1,
  1307. win.cw, 1);
  1308. }
  1309. oldx = curx, oldy = term.c.y;
  1310. }
  1311. void
  1312. xsetenv(void)
  1313. {
  1314. char buf[sizeof(long) * 8 + 1];
  1315. snprintf(buf, sizeof(buf), "%lu", xw.win);
  1316. setenv("WINDOWID", buf, 1);
  1317. }
  1318. void
  1319. xsettitle(char *p)
  1320. {
  1321. XTextProperty prop;
  1322. DEFAULT(p, "st");
  1323. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  1324. &prop);
  1325. XSetWMName(xw.dpy, xw.win, &prop);
  1326. XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
  1327. XFree(prop.value);
  1328. }
  1329. void
  1330. draw(void)
  1331. {
  1332. drawregion(0, 0, term.col, term.row);
  1333. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w,
  1334. win.h, 0, 0);
  1335. XSetForeground(xw.dpy, dc.gc,
  1336. dc.col[IS_SET(MODE_REVERSE)?
  1337. defaultfg : defaultbg].pixel);
  1338. }
  1339. void
  1340. drawregion(int x1, int y1, int x2, int y2)
  1341. {
  1342. int i, x, y, ox, numspecs;
  1343. Glyph base, new;
  1344. XftGlyphFontSpec *specs;
  1345. int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
  1346. if (!(win.state & WIN_VISIBLE))
  1347. return;
  1348. for (y = y1; y < y2; y++) {
  1349. if (!term.dirty[y])
  1350. continue;
  1351. term.dirty[y] = 0;
  1352. specs = xw.specbuf;
  1353. numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
  1354. i = ox = 0;
  1355. for (x = x1; x < x2 && i < numspecs; x++) {
  1356. new = term.line[y][x];
  1357. if (new.mode == ATTR_WDUMMY)
  1358. continue;
  1359. if (ena_sel && selected(x, y))
  1360. new.mode ^= ATTR_REVERSE;
  1361. if (i > 0 && ATTRCMP(base, new)) {
  1362. xdrawglyphfontspecs(specs, base, i, ox, y);
  1363. specs += i;
  1364. numspecs -= i;
  1365. i = 0;
  1366. }
  1367. if (i == 0) {
  1368. ox = x;
  1369. base = new;
  1370. }
  1371. i++;
  1372. }
  1373. if (i > 0)
  1374. xdrawglyphfontspecs(specs, base, i, ox, y);
  1375. }
  1376. xdrawcursor();
  1377. }
  1378. void
  1379. expose(XEvent *ev)
  1380. {
  1381. redraw();
  1382. }
  1383. void
  1384. visibility(XEvent *ev)
  1385. {
  1386. XVisibilityEvent *e = &ev->xvisibility;
  1387. MODBIT(win.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
  1388. }
  1389. void
  1390. unmap(XEvent *ev)
  1391. {
  1392. win.state &= ~WIN_VISIBLE;
  1393. }
  1394. void
  1395. xsetpointermotion(int set)
  1396. {
  1397. MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
  1398. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
  1399. }
  1400. int
  1401. xsetcursor(int cursor)
  1402. {
  1403. DEFAULT(cursor, 1);
  1404. if (!BETWEEN(cursor, 0, 6))
  1405. return 1;
  1406. win.cursor = cursor;
  1407. return 0;
  1408. }
  1409. void
  1410. xseturgency(int add)
  1411. {
  1412. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  1413. MODBIT(h->flags, add, XUrgencyHint);
  1414. XSetWMHints(xw.dpy, xw.win, h);
  1415. XFree(h);
  1416. }
  1417. void
  1418. xbell(void)
  1419. {
  1420. if (!(win.state & WIN_FOCUSED))
  1421. xseturgency(1);
  1422. if (bellvolume)
  1423. XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
  1424. }
  1425. void
  1426. focus(XEvent *ev)
  1427. {
  1428. XFocusChangeEvent *e = &ev->xfocus;
  1429. if (e->mode == NotifyGrab)
  1430. return;
  1431. if (ev->type == FocusIn) {
  1432. XSetICFocus(xw.xic);
  1433. win.state |= WIN_FOCUSED;
  1434. xseturgency(0);
  1435. if (IS_SET(MODE_FOCUS))
  1436. ttywrite("\033[I", 3);
  1437. } else {
  1438. XUnsetICFocus(xw.xic);
  1439. win.state &= ~WIN_FOCUSED;
  1440. if (IS_SET(MODE_FOCUS))
  1441. ttywrite("\033[O", 3);
  1442. }
  1443. }
  1444. int
  1445. match(uint mask, uint state)
  1446. {
  1447. return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
  1448. }
  1449. char*
  1450. kmap(KeySym k, uint state)
  1451. {
  1452. Key *kp;
  1453. int i;
  1454. /* Check for mapped keys out of X11 function keys. */
  1455. for (i = 0; i < LEN(mappedkeys); i++) {
  1456. if (mappedkeys[i] == k)
  1457. break;
  1458. }
  1459. if (i == LEN(mappedkeys)) {
  1460. if ((k & 0xFFFF) < 0xFD00)
  1461. return NULL;
  1462. }
  1463. for (kp = key; kp < key + LEN(key); kp++) {
  1464. if (kp->k != k)
  1465. continue;
  1466. if (!match(kp->mask, state))
  1467. continue;
  1468. if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
  1469. continue;
  1470. if (term.numlock && kp->appkey == 2)
  1471. continue;
  1472. if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
  1473. continue;
  1474. if (IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
  1475. continue;
  1476. return kp->s;
  1477. }
  1478. return NULL;
  1479. }
  1480. void
  1481. kpress(XEvent *ev)
  1482. {
  1483. XKeyEvent *e = &ev->xkey;
  1484. KeySym ksym;
  1485. char buf[32], *customkey;
  1486. int len;
  1487. Rune c;
  1488. Status status;
  1489. Shortcut *bp;
  1490. if (IS_SET(MODE_KBDLOCK))
  1491. return;
  1492. len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
  1493. /* 1. shortcuts */
  1494. for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  1495. if (ksym == bp->keysym && match(bp->mod, e->state)) {
  1496. bp->func(&(bp->arg));
  1497. return;
  1498. }
  1499. }
  1500. /* 2. custom keys from config.h */
  1501. if ((customkey = kmap(ksym, e->state))) {
  1502. ttysend(customkey, strlen(customkey));
  1503. return;
  1504. }
  1505. /* 3. composed string from input method */
  1506. if (len == 0)
  1507. return;
  1508. if (len == 1 && e->state & Mod1Mask) {
  1509. if (IS_SET(MODE_8BIT)) {
  1510. if (*buf < 0177) {
  1511. c = *buf | 0x80;
  1512. len = utf8encode(c, buf);
  1513. }
  1514. } else {
  1515. buf[1] = buf[0];
  1516. buf[0] = '\033';
  1517. len = 2;
  1518. }
  1519. }
  1520. ttysend(buf, len);
  1521. }
  1522. void
  1523. cmessage(XEvent *e)
  1524. {
  1525. /*
  1526. * See xembed specs
  1527. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  1528. */
  1529. if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  1530. if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  1531. win.state |= WIN_FOCUSED;
  1532. xseturgency(0);
  1533. } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  1534. win.state &= ~WIN_FOCUSED;
  1535. }
  1536. } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
  1537. /* Send SIGHUP to shell */
  1538. kill(pid, SIGHUP);
  1539. exit(0);
  1540. }
  1541. }
  1542. void
  1543. resize(XEvent *e)
  1544. {
  1545. if (e->xconfigure.width == win.w && e->xconfigure.height == win.h)
  1546. return;
  1547. cresize(e->xconfigure.width, e->xconfigure.height);
  1548. ttyresize(win.tw, win.th);
  1549. }
  1550. void
  1551. run(void)
  1552. {
  1553. XEvent ev;
  1554. int w = win.w, h = win.h;
  1555. fd_set rfd;
  1556. int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
  1557. struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
  1558. long deltatime;
  1559. /* Waiting for window mapping */
  1560. do {
  1561. XNextEvent(xw.dpy, &ev);
  1562. /*
  1563. * This XFilterEvent call is required because of XOpenIM. It
  1564. * does filter out the key event and some client message for
  1565. * the input method too.
  1566. */
  1567. if (XFilterEvent(&ev, None))
  1568. continue;
  1569. if (ev.type == ConfigureNotify) {
  1570. w = ev.xconfigure.width;
  1571. h = ev.xconfigure.height;
  1572. }
  1573. } while (ev.type != MapNotify);
  1574. cresize(w, h);
  1575. ttynew(opt_line, opt_io, opt_cmd);
  1576. ttyresize(win.tw, win.th);
  1577. clock_gettime(CLOCK_MONOTONIC, &last);
  1578. lastblink = last;
  1579. for (xev = actionfps;;) {
  1580. FD_ZERO(&rfd);
  1581. FD_SET(cmdfd, &rfd);
  1582. FD_SET(xfd, &rfd);
  1583. if (pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
  1584. if (errno == EINTR)
  1585. continue;
  1586. die("select failed: %s\n", strerror(errno));
  1587. }
  1588. if (FD_ISSET(cmdfd, &rfd)) {
  1589. ttyread();
  1590. if (blinktimeout) {
  1591. blinkset = tattrset(ATTR_BLINK);
  1592. if (!blinkset)
  1593. MODBIT(term.mode, 0, MODE_BLINK);
  1594. }
  1595. }
  1596. if (FD_ISSET(xfd, &rfd))
  1597. xev = actionfps;
  1598. clock_gettime(CLOCK_MONOTONIC, &now);
  1599. drawtimeout.tv_sec = 0;
  1600. drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
  1601. tv = &drawtimeout;
  1602. dodraw = 0;
  1603. if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
  1604. tsetdirtattr(ATTR_BLINK);
  1605. term.mode ^= MODE_BLINK;
  1606. lastblink = now;
  1607. dodraw = 1;
  1608. }
  1609. deltatime = TIMEDIFF(now, last);
  1610. if (deltatime > 1000 / (xev ? xfps : actionfps)) {
  1611. dodraw = 1;
  1612. last = now;
  1613. }
  1614. if (dodraw) {
  1615. while (XPending(xw.dpy)) {
  1616. XNextEvent(xw.dpy, &ev);
  1617. if (XFilterEvent(&ev, None))
  1618. continue;
  1619. if (handler[ev.type])
  1620. (handler[ev.type])(&ev);
  1621. }
  1622. draw();
  1623. XFlush(xw.dpy);
  1624. if (xev && !FD_ISSET(xfd, &rfd))
  1625. xev--;
  1626. if (!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
  1627. if (blinkset) {
  1628. if (TIMEDIFF(now, lastblink) \
  1629. > blinktimeout) {
  1630. drawtimeout.tv_nsec = 1000;
  1631. } else {
  1632. drawtimeout.tv_nsec = (1E6 * \
  1633. (blinktimeout - \
  1634. TIMEDIFF(now,
  1635. lastblink)));
  1636. }
  1637. drawtimeout.tv_sec = \
  1638. drawtimeout.tv_nsec / 1E9;
  1639. drawtimeout.tv_nsec %= (long)1E9;
  1640. } else {
  1641. tv = NULL;
  1642. }
  1643. }
  1644. }
  1645. }
  1646. }
  1647. void
  1648. usage(void)
  1649. {
  1650. die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]"
  1651. " [-n name] [-o file]\n"
  1652. " [-T title] [-t title] [-w windowid]"
  1653. " [[-e] command [args ...]]\n"
  1654. " %s [-aiv] [-c class] [-f font] [-g geometry]"
  1655. " [-n name] [-o file]\n"
  1656. " [-T title] [-t title] [-w windowid] -l line"
  1657. " [stty_args ...]\n", argv0, argv0);
  1658. }
  1659. int
  1660. main(int argc, char *argv[])
  1661. {
  1662. xw.l = xw.t = 0;
  1663. xw.isfixed = False;
  1664. win.cursor = cursorshape;
  1665. ARGBEGIN {
  1666. case 'a':
  1667. allowaltscreen = 0;
  1668. break;
  1669. case 'c':
  1670. opt_class = EARGF(usage());
  1671. break;
  1672. case 'e':
  1673. if (argc > 0)
  1674. --argc, ++argv;
  1675. goto run;
  1676. case 'f':
  1677. opt_font = EARGF(usage());
  1678. break;
  1679. case 'g':
  1680. xw.gm = XParseGeometry(EARGF(usage()),
  1681. &xw.l, &xw.t, &cols, &rows);
  1682. break;
  1683. case 'i':
  1684. xw.isfixed = 1;
  1685. break;
  1686. case 'o':
  1687. opt_io = EARGF(usage());
  1688. break;
  1689. case 'l':
  1690. opt_line = EARGF(usage());
  1691. break;
  1692. case 'n':
  1693. opt_name = EARGF(usage());
  1694. break;
  1695. case 't':
  1696. case 'T':
  1697. opt_title = EARGF(usage());
  1698. break;
  1699. case 'w':
  1700. opt_embed = EARGF(usage());
  1701. break;
  1702. case 'v':
  1703. die("%s " VERSION " (c) 2010-2016 st engineers\n", argv0);
  1704. break;
  1705. default:
  1706. usage();
  1707. } ARGEND;
  1708. run:
  1709. if (argc > 0) {
  1710. /* eat all remaining arguments */
  1711. opt_cmd = argv;
  1712. if (!opt_title && !opt_line)
  1713. opt_title = basename(xstrdup(argv[0]));
  1714. }
  1715. setlocale(LC_CTYPE, "");
  1716. XSetLocaleModifiers("");
  1717. tnew(MAX(cols, 1), MAX(rows, 1));
  1718. xinit();
  1719. xsetenv();
  1720. selinit();
  1721. run();
  1722. return 0;
  1723. }