dmenu.c 22 KB

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