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.

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