dmenu.c 20 KB

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