x.c.orig 47 KB

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