dmenu.c 23 KB

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