x.c 47 KB

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