Simple Terminal from SuckLess
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.

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