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.

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