Simple Terminal from SuckLess
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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