dmenu.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. /* See LICENSE file for copyright and license details. */
  2. #include <ctype.h>
  3. #include <locale.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <strings.h>
  8. #include <time.h>
  9. #include <unistd.h>
  10. #include <X11/Xlib.h>
  11. #include <X11/Xatom.h>
  12. #include <X11/Xutil.h>
  13. #ifdef XINERAMA
  14. #include <X11/extensions/Xinerama.h>
  15. #endif
  16. #include <X11/Xft/Xft.h>
  17. #include <X11/Xresource.h>
  18. #include "drw.h"
  19. #include "util.h"
  20. /* macros */
  21. #define INTERSECT(x,y,w,h,r) (MAX(0, MIN((x)+(w),(r).x_org+(r).width) - MAX((x),(r).x_org)) \
  22. && MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
  23. #define LENGTH(X) (sizeof X / sizeof X[0])
  24. #define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad)
  25. /* define opaqueness */
  26. #define OPAQUE 0xFFU
  27. /* enums */
  28. enum { SchemeNorm, SchemeSel, SchemeOut, SchemeLast }; /* color schemes */
  29. struct item {
  30. char *text;
  31. struct item *left, *right;
  32. int out;
  33. };
  34. static char text[BUFSIZ] = "";
  35. static char *embed;
  36. static int bh, mw, mh;
  37. static int inputw = 0, promptw, passwd = 0;
  38. static int lrpad; /* sum of left and right padding */
  39. static size_t cursor;
  40. static struct item *items = NULL;
  41. static struct item *matches, *matchend;
  42. static struct item *prev, *curr, *next, *sel;
  43. static int mon = -1, screen;
  44. static Atom clip, utf8;
  45. static Display *dpy;
  46. static Window root, parentwin, win;
  47. static XIC xic;
  48. static Drw *drw;
  49. static int usergb = 0;
  50. static Visual *visual;
  51. static int depth;
  52. static Colormap cmap;
  53. static Clr *scheme[SchemeLast];
  54. #include "config.h"
  55. static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
  56. static char *(*fstrstr)(const char *, const char *) = strstr;
  57. static void
  58. xinitvisual()
  59. {
  60. XVisualInfo *infos;
  61. XRenderPictFormat *fmt;
  62. int nitems;
  63. int i;
  64. XVisualInfo tpl = {
  65. .screen = screen,
  66. .depth = 32,
  67. .class = TrueColor
  68. };
  69. long masks = VisualScreenMask | VisualDepthMask | VisualClassMask;
  70. infos = XGetVisualInfo(dpy, masks, &tpl, &nitems);
  71. visual = NULL;
  72. for (i = 0; i < nitems; i++){
  73. fmt = XRenderFindVisualFormat(dpy, infos[i].visual);
  74. if (fmt->type == PictTypeDirect && fmt->direct.alphaMask) {
  75. visual = infos[i].visual;
  76. depth = infos[i].depth;
  77. cmap = XCreateColormap(dpy, root, visual, AllocNone);
  78. usergb = 1;
  79. break;
  80. }
  81. }
  82. XFree(infos);
  83. if (! visual) {
  84. visual = DefaultVisual(dpy, screen);
  85. depth = DefaultDepth(dpy, screen);
  86. cmap = DefaultColormap(dpy, screen);
  87. }
  88. }
  89. static void
  90. appenditem(struct item *item, struct item **list, struct item **last)
  91. {
  92. if (*last)
  93. (*last)->right = item;
  94. else
  95. *list = item;
  96. item->left = *last;
  97. item->right = NULL;
  98. *last = item;
  99. }
  100. static void
  101. calcoffsets(void)
  102. {
  103. int i, n;
  104. if (lines > 0)
  105. n = lines * bh;
  106. else
  107. n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">"));
  108. /* calculate which items will begin the next page and previous page */
  109. for (i = 0, next = curr; next; next = next->right)
  110. if ((i += (lines > 0) ? bh : MIN(TEXTW(next->text), n)) > n)
  111. break;
  112. for (i = 0, prev = curr; prev && prev->left; prev = prev->left)
  113. if ((i += (lines > 0) ? bh : MIN(TEXTW(prev->left->text), n)) > n)
  114. break;
  115. }
  116. static void
  117. cleanup(void)
  118. {
  119. size_t i;
  120. XUngrabKey(dpy, AnyKey, AnyModifier, root);
  121. for (i = 0; i < SchemeLast; i++)
  122. free(scheme[i]);
  123. drw_free(drw);
  124. XSync(dpy, False);
  125. XCloseDisplay(dpy);
  126. }
  127. static char *
  128. cistrstr(const char *s, const char *sub)
  129. {
  130. size_t len;
  131. for (len = strlen(sub); *s; s++)
  132. if (!strncasecmp(s, sub, len))
  133. return (char *)s;
  134. return NULL;
  135. }
  136. static int
  137. drawitem(struct item *item, int x, int y, int w)
  138. {
  139. if (item == sel)
  140. drw_setscheme(drw, scheme[SchemeSel]);
  141. else if (item->out)
  142. drw_setscheme(drw, scheme[SchemeOut]);
  143. else
  144. drw_setscheme(drw, scheme[SchemeNorm]);
  145. return drw_text(drw, x, y, w, bh, lrpad / 2, item->text, 0);
  146. }
  147. static void
  148. drawmenu(void)
  149. {
  150. unsigned int curpos;
  151. struct item *item;
  152. int x = 0, y = 0, w;
  153. char *censort;
  154. drw_setscheme(drw, scheme[SchemeNorm]);
  155. drw_rect(drw, 0, 0, mw, mh, 1, 1);
  156. if (prompt && *prompt) {
  157. drw_setscheme(drw, scheme[SchemeSel]);
  158. x = drw_text(drw, x, 0, promptw, bh, lrpad / 2, prompt, 0);
  159. }
  160. /* draw input field */
  161. w = (lines > 0 || !matches) ? mw - x : inputw;
  162. drw_setscheme(drw, scheme[SchemeNorm]);
  163. if (passwd) {
  164. censort = ecalloc(1, sizeof(text));
  165. memset(censort, '.', strlen(text));
  166. drw_text(drw, x, 0, w, bh, lrpad / 2, censort, 0);
  167. free(censort);
  168. } else drw_text(drw, x, 0, w, bh, lrpad / 2, text, 0);
  169. curpos = TEXTW(text) - TEXTW(&text[cursor]);
  170. if ((curpos += lrpad / 2 - 1) < w) {
  171. drw_setscheme(drw, scheme[SchemeNorm]);
  172. drw_rect(drw, x + curpos, 2, 2, bh - 4, 1, 0);
  173. }
  174. if (lines > 0) {
  175. /* draw vertical list */
  176. for (item = curr; item != next; item = item->right)
  177. drawitem(item, x, y += bh, mw - x);
  178. } else if (matches) {
  179. /* draw horizontal list */
  180. x += inputw;
  181. w = TEXTW("<");
  182. if (curr->left) {
  183. drw_setscheme(drw, scheme[SchemeNorm]);
  184. drw_text(drw, x, 0, w, bh, lrpad / 2, "<", 0);
  185. }
  186. x += w;
  187. for (item = curr; item != next; item = item->right)
  188. x = drawitem(item, x, 0, MIN(TEXTW(item->text), mw - x - TEXTW(">")));
  189. if (next) {
  190. w = TEXTW(">");
  191. drw_setscheme(drw, scheme[SchemeNorm]);
  192. drw_text(drw, mw - w, 0, w, bh, lrpad / 2, ">", 0);
  193. }
  194. }
  195. drw_map(drw, win, 0, 0, mw, mh);
  196. }
  197. static void
  198. grabfocus(void)
  199. {
  200. struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 };
  201. Window focuswin;
  202. int i, revertwin;
  203. for (i = 0; i < 100; ++i) {
  204. XGetInputFocus(dpy, &focuswin, &revertwin);
  205. if (focuswin == win)
  206. return;
  207. XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
  208. nanosleep(&ts, NULL);
  209. }
  210. die("cannot grab focus");
  211. }
  212. static void
  213. grabkeyboard(void)
  214. {
  215. struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
  216. int i;
  217. if (embed)
  218. return;
  219. /* try to grab keyboard, we may have to wait for another process to ungrab */
  220. for (i = 0; i < 1000; i++) {
  221. if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync,
  222. GrabModeAsync, CurrentTime) == GrabSuccess)
  223. return;
  224. nanosleep(&ts, NULL);
  225. }
  226. die("cannot grab keyboard");
  227. }
  228. static void
  229. match(void)
  230. {
  231. static char **tokv = NULL;
  232. static int tokn = 0;
  233. char buf[sizeof text], *s;
  234. int i, tokc = 0;
  235. size_t len, textsize;
  236. struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
  237. strcpy(buf, text);
  238. /* separate input text into tokens to be matched individually */
  239. for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
  240. if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
  241. die("cannot realloc %u bytes:", tokn * sizeof *tokv);
  242. len = tokc ? strlen(tokv[0]) : 0;
  243. matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
  244. textsize = strlen(text) + 1;
  245. for (item = items; item && item->text; item++) {
  246. for (i = 0; i < tokc; i++)
  247. if (!fstrstr(item->text, tokv[i]))
  248. break;
  249. if (i != tokc) /* not all tokens match */
  250. continue;
  251. /* exact matches go first, then prefixes, then substrings */
  252. if (!tokc || !fstrncmp(text, item->text, textsize))
  253. appenditem(item, &matches, &matchend);
  254. else if (!fstrncmp(tokv[0], item->text, len))
  255. appenditem(item, &lprefix, &prefixend);
  256. else
  257. appenditem(item, &lsubstr, &substrend);
  258. }
  259. if (lprefix) {
  260. if (matches) {
  261. matchend->right = lprefix;
  262. lprefix->left = matchend;
  263. } else
  264. matches = lprefix;
  265. matchend = prefixend;
  266. }
  267. if (lsubstr) {
  268. if (matches) {
  269. matchend->right = lsubstr;
  270. lsubstr->left = matchend;
  271. } else
  272. matches = lsubstr;
  273. matchend = substrend;
  274. }
  275. curr = sel = matches;
  276. calcoffsets();
  277. }
  278. static void
  279. insert(const char *str, ssize_t n)
  280. {
  281. if (strlen(text) + n > sizeof text - 1)
  282. return;
  283. /* move existing text out of the way, insert new text, and update cursor */
  284. memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
  285. if (n > 0)
  286. memcpy(&text[cursor], str, n);
  287. cursor += n;
  288. match();
  289. }
  290. static size_t
  291. nextrune(int inc)
  292. {
  293. ssize_t n;
  294. /* return location of next utf8 rune in the given direction (+1 or -1) */
  295. for (n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc)
  296. ;
  297. return n;
  298. }
  299. static void
  300. movewordedge(int dir)
  301. {
  302. if (dir < 0) { /* move cursor to the start of the word*/
  303. while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
  304. cursor = nextrune(-1);
  305. while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
  306. cursor = nextrune(-1);
  307. } else { /* move cursor to the end of the word */
  308. while (text[cursor] && strchr(worddelimiters, text[cursor]))
  309. cursor = nextrune(+1);
  310. while (text[cursor] && !strchr(worddelimiters, text[cursor]))
  311. cursor = nextrune(+1);
  312. }
  313. }
  314. static void
  315. keypress(XKeyEvent *ev)
  316. {
  317. char buf[32];
  318. int len;
  319. KeySym ksym;
  320. Status status;
  321. len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
  322. switch (status) {
  323. default: /* XLookupNone, XBufferOverflow */
  324. return;
  325. case XLookupChars:
  326. goto insert;
  327. case XLookupKeySym:
  328. case XLookupBoth:
  329. break;
  330. }
  331. if (ev->state & ControlMask) {
  332. switch(ksym) {
  333. case XK_a: ksym = XK_Home; break;
  334. case XK_b: ksym = XK_Left; break;
  335. case XK_c: ksym = XK_Escape; break;
  336. case XK_d: ksym = XK_Delete; break;
  337. case XK_e: ksym = XK_End; break;
  338. case XK_f: ksym = XK_Right; break;
  339. case XK_g: ksym = XK_Escape; break;
  340. case XK_h: ksym = XK_BackSpace; break;
  341. case XK_i: ksym = XK_Tab; break;
  342. case XK_j: /* fallthrough */
  343. case XK_J: /* fallthrough */
  344. case XK_m: /* fallthrough */
  345. case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
  346. case XK_n: ksym = XK_Down; break;
  347. case XK_p: ksym = XK_Up; break;
  348. case XK_k: /* delete right */
  349. text[cursor] = '\0';
  350. match();
  351. break;
  352. case XK_u: /* delete left */
  353. insert(NULL, 0 - cursor);
  354. break;
  355. case XK_w: /* delete word */
  356. while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
  357. insert(NULL, nextrune(-1) - cursor);
  358. while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
  359. insert(NULL, nextrune(-1) - cursor);
  360. break;
  361. case XK_y: /* paste selection */
  362. case XK_Y:
  363. XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
  364. utf8, utf8, win, CurrentTime);
  365. return;
  366. case XK_Left:
  367. movewordedge(-1);
  368. goto draw;
  369. case XK_Right:
  370. movewordedge(+1);
  371. goto draw;
  372. case XK_Return:
  373. case XK_KP_Enter:
  374. break;
  375. case XK_bracketleft:
  376. cleanup();
  377. exit(1);
  378. default:
  379. return;
  380. }
  381. } else if (ev->state & Mod1Mask) {
  382. switch(ksym) {
  383. case XK_b:
  384. movewordedge(-1);
  385. goto draw;
  386. case XK_f:
  387. movewordedge(+1);
  388. goto draw;
  389. case XK_g: ksym = XK_Home; break;
  390. case XK_G: ksym = XK_End; break;
  391. case XK_h: ksym = XK_Up; break;
  392. case XK_j: ksym = XK_Next; break;
  393. case XK_k: ksym = XK_Prior; break;
  394. case XK_l: ksym = XK_Down; break;
  395. default:
  396. return;
  397. }
  398. }
  399. switch(ksym) {
  400. default:
  401. insert:
  402. if (!iscntrl(*buf))
  403. insert(buf, len);
  404. break;
  405. case XK_Delete:
  406. if (text[cursor] == '\0')
  407. return;
  408. cursor = nextrune(+1);
  409. /* fallthrough */
  410. case XK_BackSpace:
  411. if (cursor == 0)
  412. return;
  413. insert(NULL, nextrune(-1) - cursor);
  414. break;
  415. case XK_End:
  416. if (text[cursor] != '\0') {
  417. cursor = strlen(text);
  418. break;
  419. }
  420. if (next) {
  421. /* jump to end of list and position items in reverse */
  422. curr = matchend;
  423. calcoffsets();
  424. curr = prev;
  425. calcoffsets();
  426. while (next && (curr = curr->right))
  427. calcoffsets();
  428. }
  429. sel = matchend;
  430. break;
  431. case XK_Escape:
  432. cleanup();
  433. exit(1);
  434. case XK_Home:
  435. if (sel == matches) {
  436. cursor = 0;
  437. break;
  438. }
  439. sel = curr = matches;
  440. calcoffsets();
  441. break;
  442. case XK_Left:
  443. if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
  444. cursor = nextrune(-1);
  445. break;
  446. }
  447. if (lines > 0)
  448. return;
  449. /* fallthrough */
  450. case XK_Up:
  451. if (sel && sel->left && (sel = sel->left)->right == curr) {
  452. curr = prev;
  453. calcoffsets();
  454. }
  455. break;
  456. case XK_Next:
  457. if (!next)
  458. return;
  459. sel = curr = next;
  460. calcoffsets();
  461. break;
  462. case XK_Prior:
  463. if (!prev)
  464. return;
  465. sel = curr = prev;
  466. calcoffsets();
  467. break;
  468. case XK_Return:
  469. case XK_KP_Enter:
  470. puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
  471. if (!(ev->state & ControlMask)) {
  472. cleanup();
  473. exit(0);
  474. }
  475. if (sel)
  476. sel->out = 1;
  477. break;
  478. case XK_Right:
  479. if (text[cursor] != '\0') {
  480. cursor = nextrune(+1);
  481. break;
  482. }
  483. if (lines > 0)
  484. return;
  485. /* fallthrough */
  486. case XK_Down:
  487. if (sel && sel->right && (sel = sel->right) == next) {
  488. curr = next;
  489. calcoffsets();
  490. }
  491. break;
  492. case XK_Tab:
  493. if (!sel)
  494. return;
  495. strncpy(text, sel->text, sizeof text - 1);
  496. text[sizeof text - 1] = '\0';
  497. cursor = strlen(text);
  498. match();
  499. break;
  500. }
  501. draw:
  502. drawmenu();
  503. }
  504. static void
  505. paste(void)
  506. {
  507. char *p, *q;
  508. int di;
  509. unsigned long dl;
  510. Atom da;
  511. /* we have been given the current selection, now insert it into input */
  512. if (XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
  513. utf8, &da, &di, &dl, &dl, (unsigned char **)&p)
  514. == Success && p) {
  515. insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
  516. XFree(p);
  517. }
  518. drawmenu();
  519. }
  520. static void
  521. readstdin(void)
  522. {
  523. char buf[sizeof text], *p;
  524. size_t i, imax = 0, size = 0;
  525. unsigned int tmpmax = 0;
  526. if(passwd){
  527. inputw = lines = 0;
  528. return;
  529. }
  530. /* read each line from stdin and add it to the item list */
  531. for (i = 0; fgets(buf, sizeof buf, stdin); i++) {
  532. if (i + 1 >= size / sizeof *items)
  533. if (!(items = realloc(items, (size += BUFSIZ))))
  534. die("cannot realloc %u bytes:", size);
  535. if ((p = strchr(buf, '\n')))
  536. *p = '\0';
  537. if (!(items[i].text = strdup(buf)))
  538. die("cannot strdup %u bytes:", strlen(buf) + 1);
  539. items[i].out = 0;
  540. drw_font_getexts(drw->fonts, buf, strlen(buf), &tmpmax, NULL);
  541. if (tmpmax > inputw) {
  542. inputw = tmpmax;
  543. imax = i;
  544. }
  545. }
  546. if (items)
  547. items[i].text = NULL;
  548. inputw = items ? TEXTW(items[imax].text) : 0;
  549. lines = MIN(lines, i);
  550. }
  551. static void
  552. run(void)
  553. {
  554. XEvent ev;
  555. while (!XNextEvent(dpy, &ev)) {
  556. if (XFilterEvent(&ev, None))
  557. continue;
  558. switch(ev.type) {
  559. case Expose:
  560. if (ev.xexpose.count == 0)
  561. drw_map(drw, win, 0, 0, mw, mh);
  562. break;
  563. case FocusIn:
  564. /* regrab focus from parent window */
  565. if (ev.xfocus.window != win)
  566. grabfocus();
  567. break;
  568. case KeyPress:
  569. keypress(&ev.xkey);
  570. break;
  571. case SelectionNotify:
  572. if (ev.xselection.property == utf8)
  573. paste();
  574. break;
  575. case VisibilityNotify:
  576. if (ev.xvisibility.state != VisibilityUnobscured)
  577. XRaiseWindow(dpy, win);
  578. break;
  579. }
  580. }
  581. }
  582. static void
  583. setup(void)
  584. {
  585. int x, y, i, j;
  586. unsigned int du;
  587. XSetWindowAttributes swa;
  588. XIM xim;
  589. Window w, dw, *dws;
  590. XWindowAttributes wa;
  591. XClassHint ch = {"dmenu", "dmenu"};
  592. #ifdef XINERAMA
  593. XineramaScreenInfo *info;
  594. Window pw;
  595. int a, di, n, area = 0;
  596. #endif
  597. /* init appearance */
  598. for (j = 0; j < SchemeLast; j++)
  599. scheme[j] = drw_scm_create(drw, colors[j], alphas[j], 2);
  600. clip = XInternAtom(dpy, "CLIPBOARD", False);
  601. utf8 = XInternAtom(dpy, "UTF8_STRING", False);
  602. /* calculate menu geometry */
  603. bh = drw->fonts->h + 2;
  604. lines = MAX(lines, 0);
  605. mh = (lines + 1) * bh;
  606. #ifdef XINERAMA
  607. i = 0;
  608. if (parentwin == root && (info = XineramaQueryScreens(dpy, &n))) {
  609. XGetInputFocus(dpy, &w, &di);
  610. if (mon >= 0 && mon < n)
  611. i = mon;
  612. else if (w != root && w != PointerRoot && w != None) {
  613. /* find top-level window containing current input focus */
  614. do {
  615. if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
  616. XFree(dws);
  617. } while (w != root && w != pw);
  618. /* find xinerama screen with which the window intersects most */
  619. if (XGetWindowAttributes(dpy, pw, &wa))
  620. for (j = 0; j < n; j++)
  621. if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
  622. area = a;
  623. i = j;
  624. }
  625. }
  626. /* no focused window is on screen, so use pointer location instead */
  627. if (mon < 0 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
  628. for (i = 0; i < n; i++)
  629. if (INTERSECT(x, y, 1, 1, info[i]))
  630. break;
  631. x = info[i].x_org;
  632. y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
  633. mw = info[i].width;
  634. XFree(info);
  635. } else
  636. #endif
  637. {
  638. if (!XGetWindowAttributes(dpy, parentwin, &wa))
  639. die("could not get embedding window attributes: 0x%lx",
  640. parentwin);
  641. x = 0;
  642. y = topbar ? 0 : wa.height - mh;
  643. mw = wa.width;
  644. }
  645. promptw = (prompt && *prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
  646. inputw = MIN(inputw, mw/3);
  647. match();
  648. /* create menu window */
  649. swa.override_redirect = True;
  650. swa.background_pixel = scheme[SchemeNorm][ColBg].pixel;
  651. swa.border_pixel = 0;
  652. swa.colormap = cmap;
  653. swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
  654. win = XCreateWindow(dpy, parentwin, x, y, mw, mh, 0,
  655. depth, InputOutput, visual,
  656. CWOverrideRedirect | CWBackPixel | CWColormap | CWEventMask | CWBorderPixel, &swa);
  657. XSetClassHint(dpy, win, &ch);
  658. /* open input methods */
  659. xim = XOpenIM(dpy, NULL, NULL, NULL);
  660. xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
  661. XNClientWindow, win, XNFocusWindow, win, NULL);
  662. XMapRaised(dpy, win);
  663. XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
  664. if (embed) {
  665. XSelectInput(dpy, parentwin, FocusChangeMask);
  666. if (XQueryTree(dpy, parentwin, &dw, &w, &dws, &du) && dws) {
  667. for (i = 0; i < du && dws[i] != win; ++i)
  668. XSelectInput(dpy, dws[i], FocusChangeMask);
  669. XFree(dws);
  670. }
  671. grabfocus();
  672. }
  673. drw_resize(drw, mw, mh);
  674. drawmenu();
  675. }
  676. static void
  677. usage(void)
  678. {
  679. fputs("usage: dmenu [-bfiPv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
  680. " [-nb color] [-nf color] [-sb color] [-sf color] [-w windowid]\n", stderr);
  681. exit(1);
  682. }
  683. void
  684. read_Xresources(void) {
  685. XrmInitialize();
  686. char* xrm;
  687. if ((xrm = XResourceManagerString(drw->dpy))) {
  688. char *type;
  689. XrmDatabase xdb = XrmGetStringDatabase(xrm);
  690. XrmValue xval;
  691. if (XrmGetResource(xdb, "dmenu.font", "*", &type, &xval) == True) /* font or font set */
  692. fonts[0] = strdup(xval.addr);
  693. if (XrmGetResource(xdb, "dmenu.color0", "*", &type, &xval) == True) /* normal background color */
  694. colors[SchemeNorm][ColBg] = strdup(xval.addr);
  695. if (XrmGetResource(xdb, "dmenu.color7", "*", &type, &xval) == True) /* normal foreground color */
  696. colors[SchemeNorm][ColFg] = strdup(xval.addr);
  697. if (XrmGetResource(xdb, "dmenu.color6", "*", &type, &xval) == True) /* selected background color */
  698. colors[SchemeSel][ColBg] = strdup(xval.addr);
  699. if (XrmGetResource(xdb, "dmenu.color0", "*", &type, &xval) == True) /* selected foreground color */
  700. colors[SchemeSel][ColFg] = strdup(xval.addr);
  701. XrmDestroyDatabase(xdb);
  702. }
  703. }
  704. int
  705. main(int argc, char *argv[])
  706. {
  707. XWindowAttributes wa;
  708. int i, fast = 0;
  709. for (i = 1; i < argc; i++)
  710. /* these options take no arguments */
  711. if (!strcmp(argv[i], "-v")) { /* prints version information */
  712. puts("dmenu-"VERSION);
  713. exit(0);
  714. } else if (!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
  715. topbar = 0;
  716. else if (!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
  717. fast = 1;
  718. else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
  719. fstrncmp = strncasecmp;
  720. fstrstr = cistrstr;
  721. } else if (!strcmp(argv[i], "-P")) /* is the input a password */
  722. passwd = 1;
  723. else if (i + 1 == argc)
  724. usage();
  725. /* these options take one argument */
  726. else if (!strcmp(argv[i], "-l")) /* number of lines in vertical list */
  727. lines = atoi(argv[++i]);
  728. else if (!strcmp(argv[i], "-m"))
  729. mon = atoi(argv[++i]);
  730. else if (!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
  731. prompt = argv[++i];
  732. else if (!strcmp(argv[i], "-fn")) /* font or font set */
  733. fonts[0] = argv[++i];
  734. else if (!strcmp(argv[i], "-nb")) /* normal background color */
  735. colors[SchemeNorm][ColBg] = argv[++i];
  736. else if (!strcmp(argv[i], "-nf")) /* normal foreground color */
  737. colors[SchemeNorm][ColFg] = argv[++i];
  738. else if (!strcmp(argv[i], "-sb")) /* selected background color */
  739. colors[SchemeSel][ColBg] = argv[++i];
  740. else if (!strcmp(argv[i], "-sf")) /* selected foreground color */
  741. colors[SchemeSel][ColFg] = argv[++i];
  742. else if (!strcmp(argv[i], "-w")) /* embedding window id */
  743. embed = argv[++i];
  744. else
  745. usage();
  746. if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
  747. fputs("warning: no locale support\n", stderr);
  748. if (!XSetLocaleModifiers(""))
  749. fputs("warning: no locale modifiers support\n", stderr);
  750. if (!(dpy = XOpenDisplay(NULL)))
  751. die("cannot open display");
  752. screen = DefaultScreen(dpy);
  753. root = RootWindow(dpy, screen);
  754. if (!embed || !(parentwin = strtol(embed, NULL, 0)))
  755. parentwin = root;
  756. if (!XGetWindowAttributes(dpy, parentwin, &wa))
  757. die("could not get embedding window attributes: 0x%lx",
  758. parentwin);
  759. xinitvisual();
  760. drw = drw_create(dpy, screen, root, wa.width, wa.height, visual, depth, cmap);
  761. read_Xresources();
  762. if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
  763. die("no fonts could be loaded.");
  764. lrpad = drw->fonts->h;
  765. #ifdef __OpenBSD__
  766. if (pledge("stdio rpath", NULL) == -1)
  767. die("pledge");
  768. #endif
  769. if (fast && !isatty(0)) {
  770. grabkeyboard();
  771. readstdin();
  772. } else {
  773. readstdin();
  774. grabkeyboard();
  775. }
  776. setup();
  777. run();
  778. return 1; /* unreachable */
  779. }