x.c 47 KB

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