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.

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