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.

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