x.c 47 KB

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