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.

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