1
0

x.c 47 KB

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