x.c 47 KB

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