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.

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