x.c 48 KB

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