1 /* See LICENSE file for copyright and license details. */
13 #include <X11/Xatom.h>
14 #include <X11/Xutil.h>
16 #include <X11/extensions/Xinerama.h>
18 #include <X11/Xft/Xft.h>
24 #define INTERSECT(x,y,w,h,r) (MAX(0, MIN((x)+(w),(r).x_org+(r).width) - MAX((x),(r).x_org)) \
25 * MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
26 #define LENGTH(X) (sizeof X / sizeof X[0])
27 #define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad)
28 #define NUMBERSMAXDIGITS 100
29 #define NUMBERSBUFSIZE (NUMBERSMAXDIGITS * 2) + 1
32 enum { SchemeNorm, SchemeSel, SchemeNormHighlight, SchemeSelHighlight,
33 SchemeOut, SchemeLast }; /* color schemes */
38 struct item *left, *right;
43 static char numbers[NUMBERSBUFSIZE] = "";
44 static char text[BUFSIZ] = "";
46 static int bh, mw, mh;
47 static int inputw = 0, promptw, passwd = 0;
48 static int lrpad; /* sum of left and right padding */
50 static struct item *items = NULL;
51 static struct item *matches, *matchend;
52 static struct item *prev, *curr, *next, *sel;
53 static int mon = -1, screen;
55 static Atom clip, utf8;
57 static Window root, parentwin, win;
61 static Clr *scheme[SchemeLast];
65 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
66 static char *(*fstrstr)(const char *, const char *) = strstr;
69 appenditem(struct item *item, struct item **list, struct item **last)
72 (*last)->right = item;
89 n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">"));
90 /* calculate which items will begin the next page and previous page */
91 for (i = 0, next = curr; next; next = next->right)
92 if ((i += (lines > 0) ? bh : MIN(TEXTW(next->text), n)) > n)
94 for (i = 0, prev = curr; prev && prev->left; prev = prev->left)
95 if ((i += (lines > 0) ? bh : MIN(TEXTW(prev->left->text), n)) > n)
104 XUngrabKey(dpy, AnyKey, AnyModifier, root);
105 for (i = 0; i < SchemeLast; i++)
113 cistrstr(const char *s, const char *sub)
117 for (len = strlen(sub); *s; s++)
118 if (!strncasecmp(s, sub, len))
124 drawhighlights(struct item *item, int x, int y, int maxw)
130 if (!(strlen(item->text) && strlen(text)))
133 drw_setscheme(drw, scheme[item == sel
135 : SchemeNormHighlight]);
136 for (i = 0, highlight = item->text; *highlight && text[i];) {
137 if (*highlight == text[i]) {
138 /* get indentation */
141 indent = TEXTW(item->text);
144 /* highlight character */
149 x + indent - (lrpad / 2),
151 MIN(maxw - indent, TEXTW(highlight) - lrpad),
163 drawitem(struct item *item, int x, int y, int w)
167 drw_setscheme(drw, scheme[SchemeSel]);
169 drw_setscheme(drw, scheme[SchemeOut]);
171 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);
181 unsigned int numer = 0, denom = 0;
185 for (item = matchend; item && item->left; item = item->left)
188 for (item = items; item && item->text; item++)
190 snprintf(numbers, NUMBERSBUFSIZE, "%d/%d", numer, denom);
201 drw_setscheme(drw, scheme[SchemeNorm]);
202 drw_rect(drw, 0, 0, mw, mh, 1, 1);
204 if (prompt && *prompt) {
205 drw_setscheme(drw, scheme[SchemeSel]);
206 x = drw_text(drw, x, 0, promptw, bh, lrpad / 2, prompt, 0);
208 /* draw input field */
209 w = (lines > 0 || !matches) ? mw - x : inputw;
210 drw_setscheme(drw, scheme[SchemeNorm]);
212 censort = ecalloc(1, sizeof(text));
213 memset(censort, '*', strlen(text));
214 drw_text(drw, x, 0, w, bh, lrpad / 2, censort, 0);
216 } else drw_text(drw, x, 0, w, bh, lrpad / 2, text, 0);
218 curpos = TEXTW(text) - TEXTW(&text[cursor]);
219 if ((curpos += lrpad / 2 - 1) < w) {
220 drw_setscheme(drw, scheme[SchemeNorm]);
221 drw_rect(drw, x + curpos, 2, 2, bh - 4, 1, 0);
224 recalculatenumbers();
226 /* draw vertical list */
227 for (item = curr; item != next; item = item->right)
228 drawitem(item, x, y += bh, mw - x);
229 } else if (matches) {
230 /* draw horizontal list */
234 drw_setscheme(drw, scheme[SchemeNorm]);
235 drw_text(drw, x, 0, w, bh, lrpad / 2, "<", 0);
238 for (item = curr; item != next; item = item->right)
239 x = drawitem(item, x, 0, MIN(TEXTW(item->text), mw - x - TEXTW(">") - TEXTW(numbers)));
242 drw_setscheme(drw, scheme[SchemeNorm]);
243 drw_text(drw, mw - w - TEXTW(numbers), 0, w, bh, lrpad / 2, ">", 0);
246 drw_setscheme(drw, scheme[SchemeNorm]);
247 drw_text(drw, mw - TEXTW(numbers), 0, TEXTW(numbers), bh, lrpad / 2, numbers, 0);
248 drw_map(drw, win, 0, 0, mw, mh);
254 struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 };
258 for (i = 0; i < 100; ++i) {
259 XGetInputFocus(dpy, &focuswin, &revertwin);
262 XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
263 nanosleep(&ts, NULL);
265 die("cannot grab focus");
271 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
276 /* try to grab keyboard, we may have to wait for another process to ungrab */
277 for (i = 0; i < 1000; i++) {
278 if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync,
279 GrabModeAsync, CurrentTime) == GrabSuccess)
281 nanosleep(&ts, NULL);
283 die("cannot grab keyboard");
287 compare_distance(const void *a, const void *b)
289 struct item *da = *(struct item **) a;
290 struct item *db = *(struct item **) b;
297 return da->distance == db->distance ? 0 : da->distance < db->distance ? -1 : 1;
303 /* bang - we have so much memory */
305 struct item **fuzzymatches = NULL;
307 int number_of_matches = 0, i, pidx, sidx, eidx;
308 int text_len = strlen(text), itext_len;
310 matches = matchend = NULL;
312 /* walk through all items */
313 for (it = items; it && it->text; it++) {
315 itext_len = strlen(it->text);
316 pidx = 0; /* pointer */
317 sidx = eidx = -1; /* start of match, end of match */
318 /* walk through item text */
319 for (i = 0; i < itext_len && (c = it->text[i]); i++) {
320 /* fuzzy match pattern */
321 if (!fstrncmp(&text[pidx], &c, 1)) {
325 if (pidx == text_len) {
331 /* build list of matches */
333 /* compute distance */
334 /* add penalty if match starts late (log(sidx+2))
335 * add penalty for long a match without many matching characters */
336 it->distance = log(sidx + 2) + (double)(eidx - sidx - text_len);
337 /* fprintf(stderr, "distance %s %f\n", it->text, it->distance); */
338 appenditem(it, &matches, &matchend);
342 appenditem(it, &matches, &matchend);
346 if (number_of_matches) {
347 /* initialize array with matches */
348 if (!(fuzzymatches = realloc(fuzzymatches, number_of_matches * sizeof(struct item*))))
349 die("cannot realloc %u bytes:", number_of_matches * sizeof(struct item*));
350 for (i = 0, it = matches; it && i < number_of_matches; i++, it = it->right) {
351 fuzzymatches[i] = it;
353 /* sort matches according to distance */
354 qsort(fuzzymatches, number_of_matches, sizeof(struct item*), compare_distance);
355 /* rebuild list of matches */
356 matches = matchend = NULL;
357 for (i = 0, it = fuzzymatches[i]; i < number_of_matches && it && \
358 it->text; i++, it = fuzzymatches[i]) {
359 appenditem(it, &matches, &matchend);
363 curr = sel = matches;
374 static char **tokv = NULL;
377 char buf[sizeof text], *s;
379 size_t len, textsize;
380 struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
383 /* separate input text into tokens to be matched individually */
384 for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
385 if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
386 die("cannot realloc %u bytes:", tokn * sizeof *tokv);
387 len = tokc ? strlen(tokv[0]) : 0;
389 matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
390 textsize = strlen(text) + 1;
391 for (item = items; item && item->text; item++) {
392 for (i = 0; i < tokc; i++)
393 if (!fstrstr(item->text, tokv[i]))
395 if (i != tokc) /* not all tokens match */
397 /* exact matches go first, then prefixes, then substrings */
398 if (!tokc || !fstrncmp(text, item->text, textsize))
399 appenditem(item, &matches, &matchend);
400 else if (!fstrncmp(tokv[0], item->text, len))
401 appenditem(item, &lprefix, &prefixend);
403 appenditem(item, &lsubstr, &substrend);
407 matchend->right = lprefix;
408 lprefix->left = matchend;
411 matchend = prefixend;
415 matchend->right = lsubstr;
416 lsubstr->left = matchend;
419 matchend = substrend;
421 curr = sel = matches;
426 insert(const char *str, ssize_t n)
428 if (strlen(text) + n > sizeof text - 1)
430 /* move existing text out of the way, insert new text, and update cursor */
431 memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
433 memcpy(&text[cursor], str, n);
443 /* return location of next utf8 rune in the given direction (+1 or -1) */
444 for (n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc)
450 movewordedge(int dir)
452 if (dir < 0) { /* move cursor to the start of the word*/
453 while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
454 cursor = nextrune(-1);
455 while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
456 cursor = nextrune(-1);
457 } else { /* move cursor to the end of the word */
458 while (text[cursor] && strchr(worddelimiters, text[cursor]))
459 cursor = nextrune(+1);
460 while (text[cursor] && !strchr(worddelimiters, text[cursor]))
461 cursor = nextrune(+1);
466 keypress(XKeyEvent *ev)
473 len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
475 default: /* XLookupNone, XBufferOverflow */
484 if (ev->state & ControlMask) {
486 case XK_a: ksym = XK_Home; break;
487 case XK_b: ksym = XK_Left; break;
488 case XK_c: ksym = XK_Escape; break;
489 case XK_d: ksym = XK_Delete; break;
490 case XK_e: ksym = XK_End; break;
491 case XK_f: ksym = XK_Right; break;
492 case XK_g: ksym = XK_Escape; break;
493 case XK_h: ksym = XK_BackSpace; break;
494 case XK_i: ksym = XK_Tab; break;
495 case XK_j: /* fallthrough */
496 case XK_J: /* fallthrough */
497 case XK_m: /* fallthrough */
498 case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
499 case XK_n: ksym = XK_Down; break;
500 case XK_p: ksym = XK_Up; break;
502 case XK_k: /* delete right */
506 case XK_u: /* delete left */
507 insert(NULL, 0 - cursor);
509 case XK_w: /* delete word */
510 while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
511 insert(NULL, nextrune(-1) - cursor);
512 while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
513 insert(NULL, nextrune(-1) - cursor);
515 case XK_v: /* paste selection */
517 XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
518 utf8, utf8, win, CurrentTime);
535 } else if (ev->state & Mod1Mask) {
543 case XK_g: ksym = XK_Home; break;
544 case XK_G: ksym = XK_End; break;
545 case XK_h: ksym = XK_Up; break;
546 case XK_j: ksym = XK_Next; break;
547 case XK_k: ksym = XK_Prior; break;
548 case XK_l: ksym = XK_Down; break;
561 if (text[cursor] == '\0')
563 cursor = nextrune(+1);
568 insert(NULL, nextrune(-1) - cursor);
571 if (text[cursor] != '\0') {
572 cursor = strlen(text);
576 /* jump to end of list and position items in reverse */
581 while (next && (curr = curr->right))
590 if (sel == matches) {
594 sel = curr = matches;
598 if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
599 cursor = nextrune(-1);
606 if (sel && sel->left && (sel = sel->left)->right == curr) {
625 puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
626 if (!(ev->state & ControlMask)) {
634 if (text[cursor] != '\0') {
635 cursor = nextrune(+1);
642 if (sel && sel->right && (sel = sel->right) == next) {
650 strncpy(text, sel->text, sizeof text - 1);
651 text[sizeof text - 1] = '\0';
652 cursor = strlen(text);
669 /* we have been given the current selection, now insert it into input */
670 if (XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
671 utf8, &da, &di, &dl, &dl, (unsigned char **)&p)
673 insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
682 char buf[sizeof text], *p;
683 size_t i, imax = 0, size = 0;
684 unsigned int tmpmax = 0;
691 /* read each line from stdin and add it to the item list */
692 for (i = 0; fgets(buf, sizeof buf, stdin); i++) {
693 if (i + 1 >= size / sizeof *items)
694 if (!(items = realloc(items, (size += BUFSIZ))))
695 die("cannot realloc %u bytes:", size);
696 if ((p = strchr(buf, '\n')))
698 if (!(items[i].text = strdup(buf)))
699 die("cannot strdup %u bytes:", strlen(buf) + 1);
701 drw_font_getexts(drw->fonts, buf, strlen(buf), &tmpmax, NULL);
702 if (tmpmax > inputw) {
708 items[i].text = NULL;
709 inputw = items ? TEXTW(items[imax].text) : 0;
710 lines = MIN(lines, i);
718 while (!XNextEvent(dpy, &ev)) {
719 if (XFilterEvent(&ev, win))
723 if (ev.xdestroywindow.window != win)
728 if (ev.xexpose.count == 0)
729 drw_map(drw, win, 0, 0, mw, mh);
732 /* regrab focus from parent window */
733 if (ev.xfocus.window != win)
739 case SelectionNotify:
740 if (ev.xselection.property == utf8)
743 case VisibilityNotify:
744 if (ev.xvisibility.state != VisibilityUnobscured)
745 XRaiseWindow(dpy, win);
756 XSetWindowAttributes swa;
759 XWindowAttributes wa;
760 XClassHint ch = {"dmenu", "dmenu"};
762 XineramaScreenInfo *info;
764 int a, di, n, area = 0;
766 /* init appearance */
767 for (j = 0; j < SchemeLast; j++)
768 scheme[j] = drw_scm_create(drw, colors[j], 2);
770 clip = XInternAtom(dpy, "CLIPBOARD", False);
771 utf8 = XInternAtom(dpy, "UTF8_STRING", False);
773 /* calculate menu geometry */
774 bh = drw->fonts->h + 2;
775 lines = MAX(lines, 0);
776 mh = (lines + 1) * bh;
779 if (parentwin == root && (info = XineramaQueryScreens(dpy, &n))) {
780 XGetInputFocus(dpy, &w, &di);
781 if (mon >= 0 && mon < n)
783 else if (w != root && w != PointerRoot && w != None) {
784 /* find top-level window containing current input focus */
786 if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
788 } while (w != root && w != pw);
789 /* find xinerama screen with which the window intersects most */
790 if (XGetWindowAttributes(dpy, pw, &wa))
791 for (j = 0; j < n; j++)
792 if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
797 /* no focused window is on screen, so use pointer location instead */
798 if (mon < 0 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
799 for (i = 0; i < n; i++)
800 if (INTERSECT(x, y, 1, 1, info[i]))
804 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
810 if (!XGetWindowAttributes(dpy, parentwin, &wa))
811 die("could not get embedding window attributes: 0x%lx",
814 y = topbar ? 0 : wa.height - mh;
817 promptw = (prompt && *prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
818 inputw = MIN(inputw, mw/3);
821 /* create menu window */
822 swa.override_redirect = True;
823 swa.background_pixel = scheme[SchemeNorm][ColBg].pixel;
824 swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
825 win = XCreateWindow(dpy, parentwin, x, y, mw, mh, 0,
826 CopyFromParent, CopyFromParent, CopyFromParent,
827 CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
828 XSetClassHint(dpy, win, &ch);
832 if ((xim = XOpenIM(dpy, NULL, NULL, NULL)) == NULL)
833 die("XOpenIM failed: could not open input device");
835 xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
836 XNClientWindow, win, XNFocusWindow, win, NULL);
838 XMapRaised(dpy, win);
840 XSelectInput(dpy, parentwin, FocusChangeMask | SubstructureNotifyMask);
841 if (XQueryTree(dpy, parentwin, &dw, &w, &dws, &du) && dws) {
842 for (i = 0; i < du && dws[i] != win; ++i)
843 XSelectInput(dpy, dws[i], FocusChangeMask);
848 drw_resize(drw, mw, mh);
855 fputs("usage: dmenu [-bfivP] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
856 " [-nb color] [-nf color] [-sb color] [-sf color]\n"
857 " [-nhb color] [-nhf color] [-shb color] [-shf color] [-w windowid]\n", stderr);
862 main(int argc, char *argv[])
864 XWindowAttributes wa;
867 for (i = 1; i < argc; i++)
868 /* these options take no arguments */
869 if (!strcmp(argv[i], "-v")) { /* prints version information */
870 puts("dmenu-"VERSION);
872 } else if (!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
874 else if (!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
876 else if (!strcmp(argv[i], "-F")) /* grabs keyboard before reading stdin */
878 else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
879 fstrncmp = strncasecmp;
881 } else if (!strcmp(argv[i], "-P")) /* is the input a password */
883 else if (i + 1 == argc)
885 /* these options take one argument */
886 else if (!strcmp(argv[i], "-l")) /* number of lines in vertical list */
887 lines = atoi(argv[++i]);
888 else if (!strcmp(argv[i], "-m"))
889 mon = atoi(argv[++i]);
890 else if (!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
892 else if (!strcmp(argv[i], "-fn")) /* font or font set */
893 fonts[0] = argv[++i];
894 else if (!strcmp(argv[i], "-nb")) /* normal background color */
895 colors[SchemeNorm][ColBg] = argv[++i];
896 else if (!strcmp(argv[i], "-nf")) /* normal foreground color */
897 colors[SchemeNorm][ColFg] = argv[++i];
898 else if (!strcmp(argv[i], "-sb")) /* selected background color */
899 colors[SchemeSel][ColBg] = argv[++i];
900 else if (!strcmp(argv[i], "-sf")) /* selected foreground color */
901 colors[SchemeSel][ColFg] = argv[++i];
902 else if (!strcmp(argv[i], "-nhb")) /* normal hi background color */
903 colors[SchemeNormHighlight][ColBg] = argv[++i];
904 else if (!strcmp(argv[i], "-nhf")) /* normal hi foreground color */
905 colors[SchemeNormHighlight][ColFg] = argv[++i];
906 else if (!strcmp(argv[i], "-shb")) /* selected hi background color */
907 colors[SchemeSelHighlight][ColBg] = argv[++i];
908 else if (!strcmp(argv[i], "-shf")) /* selected hi foreground color */
909 colors[SchemeSelHighlight][ColFg] = argv[++i];
910 else if (!strcmp(argv[i], "-w")) /* embedding window id */
915 if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
916 fputs("warning: no locale support\n", stderr);
917 if (!(dpy = XOpenDisplay(NULL)))
918 die("cannot open display");
919 screen = DefaultScreen(dpy);
920 root = RootWindow(dpy, screen);
921 if (!embed || !(parentwin = strtol(embed, NULL, 0)))
923 if (!XGetWindowAttributes(dpy, parentwin, &wa))
924 die("could not get embedding window attributes: 0x%lx",
926 drw = drw_create(dpy, screen, root, wa.width, wa.height);
927 if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
928 die("no fonts could be loaded.");
929 lrpad = drw->fonts->h;
932 if (pledge("stdio rpath", NULL) == -1)
936 if (fast && !isatty(0)) {
946 return 1; /* unreachable */