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.

1071 lines
27 KiB

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