My build of the simple terminal from suckless.org.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 

2070 lignes
46 KiB

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