My build of the simple terminal from suckless.org.
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 

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