My build of suckless st terminal
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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