Another copy of my dotfiles. Because I don't completely trust GitHub.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

990 lines
25 KiB

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