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.

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