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.

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