x.c 47 KB

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