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.

1823 lines
41 KiB

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