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.

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