x.c.orig 46 KB

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