x.c 47 KB

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