x.c 50 KB

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