x.c 48 KB

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