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.

1819 lines
40 KiB

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