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)
30 enum { SchemeNorm, SchemeSel, SchemeNormHighlight, SchemeSelHighlight,
31 SchemeOut, SchemeLast }; /* color schemes */
36 struct item *left, *right;
41 static char text[BUFSIZ] = "";
43 static int bh, mw, mh;
44 static int inputw = 0, promptw;
45 static int lrpad; /* sum of left and right padding */
47 static struct item *items = NULL;
48 static struct item *matches, *matchend;
49 static struct item *prev, *curr, *next, *sel;
50 static int mon = -1, screen;
52 static Atom clip, utf8;
54 static Window root, parentwin, win;
58 static Clr *scheme[SchemeLast];
62 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
63 static char *(*fstrstr)(const char *, const char *) = strstr;
66 appenditem(struct item *item, struct item **list, struct item **last)
69 (*last)->right = item;
86 n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">"));
87 /* calculate which items will begin the next page and previous page */
88 for (i = 0, next = curr; next; next = next->right)
89 if ((i += (lines > 0) ? bh : MIN(TEXTW(next->text), n)) > n)
91 for (i = 0, prev = curr; prev && prev->left; prev = prev->left)
92 if ((i += (lines > 0) ? bh : MIN(TEXTW(prev->left->text), n)) > n)
101 XUngrabKey(dpy, AnyKey, AnyModifier, root);
102 for (i = 0; i < SchemeLast; i++)
110 cistrstr(const char *s, const char *sub)
114 for (len = strlen(sub); *s; s++)
115 if (!strncasecmp(s, sub, len))
121 drawhighlights(struct item *item, int x, int y, int maxw)
127 if (!(strlen(item->text) && strlen(text)))
130 drw_setscheme(drw, scheme[item == sel
132 : SchemeNormHighlight]);
133 for (i = 0, highlight = item->text; *highlight && text[i];) {
134 if (*highlight == text[i]) {
135 /* get indentation */
138 indent = TEXTW(item->text);
141 /* highlight character */
146 x + indent - (lrpad / 2),
148 MIN(maxw - indent, TEXTW(highlight) - lrpad),
160 drawitem(struct item *item, int x, int y, int w)
164 drw_setscheme(drw, scheme[SchemeSel]);
166 drw_setscheme(drw, scheme[SchemeOut]);
168 drw_setscheme(drw, scheme[SchemeNorm]);
170 r = drw_text(drw, x, y, w, bh, lrpad / 2, item->text, 0);
171 drawhighlights(item, x, y, w);
182 drw_setscheme(drw, scheme[SchemeNorm]);
183 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);
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);
194 curpos = TEXTW(text) - TEXTW(&text[cursor]);
195 if ((curpos += lrpad / 2 - 1) < w) {
196 drw_setscheme(drw, scheme[SchemeNorm]);
197 drw_rect(drw, x + curpos, 2, 2, bh - 4, 1, 0);
201 /* draw vertical list */
202 for (item = curr; item != next; item = item->right)
203 drawitem(item, x, y += bh, mw - x);
204 } else if (matches) {
205 /* draw horizontal list */
209 drw_setscheme(drw, scheme[SchemeNorm]);
210 drw_text(drw, x, 0, w, bh, lrpad / 2, "<", 0);
213 for (item = curr; item != next; item = item->right)
214 x = drawitem(item, x, 0, MIN(TEXTW(item->text), mw - x - TEXTW(">")));
217 drw_setscheme(drw, scheme[SchemeNorm]);
218 drw_text(drw, mw - w, 0, w, bh, lrpad / 2, ">", 0);
221 drw_map(drw, win, 0, 0, mw, mh);
227 struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 };
231 for (i = 0; i < 100; ++i) {
232 XGetInputFocus(dpy, &focuswin, &revertwin);
235 XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
236 nanosleep(&ts, NULL);
238 die("cannot grab focus");
244 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
249 /* try to grab keyboard, we may have to wait for another process to ungrab */
250 for (i = 0; i < 1000; i++) {
251 if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync,
252 GrabModeAsync, CurrentTime) == GrabSuccess)
254 nanosleep(&ts, NULL);
256 die("cannot grab keyboard");
260 compare_distance(const void *a, const void *b)
262 struct item *da = *(struct item **) a;
263 struct item *db = *(struct item **) b;
270 return da->distance == db->distance ? 0 : da->distance < db->distance ? -1 : 1;
276 /* bang - we have so much memory */
278 struct item **fuzzymatches = NULL;
280 int number_of_matches = 0, i, pidx, sidx, eidx;
281 int text_len = strlen(text), itext_len;
283 matches = matchend = NULL;
285 /* walk through all items */
286 for (it = items; it && it->text; it++) {
288 itext_len = strlen(it->text);
289 pidx = 0; /* pointer */
290 sidx = eidx = -1; /* start of match, end of match */
291 /* walk through item text */
292 for (i = 0; i < itext_len && (c = it->text[i]); i++) {
293 /* fuzzy match pattern */
294 if (!fstrncmp(&text[pidx], &c, 1)) {
298 if (pidx == text_len) {
304 /* build list of matches */
306 /* compute distance */
307 /* add penalty if match starts late (log(sidx+2))
308 * add penalty for long a match without many matching characters */
309 it->distance = log(sidx + 2) + (double)(eidx - sidx - text_len);
310 /* fprintf(stderr, "distance %s %f\n", it->text, it->distance); */
311 appenditem(it, &matches, &matchend);
315 appenditem(it, &matches, &matchend);
319 if (number_of_matches) {
320 /* initialize array with matches */
321 if (!(fuzzymatches = realloc(fuzzymatches, number_of_matches * sizeof(struct item*))))
322 die("cannot realloc %u bytes:", number_of_matches * sizeof(struct item*));
323 for (i = 0, it = matches; it && i < number_of_matches; i++, it = it->right) {
324 fuzzymatches[i] = it;
326 /* sort matches according to distance */
327 qsort(fuzzymatches, number_of_matches, sizeof(struct item*), compare_distance);
328 /* rebuild list of matches */
329 matches = matchend = NULL;
330 for (i = 0, it = fuzzymatches[i]; i < number_of_matches && it && \
331 it->text; i++, it = fuzzymatches[i]) {
332 appenditem(it, &matches, &matchend);
336 curr = sel = matches;
347 static char **tokv = NULL;
350 char buf[sizeof text], *s;
352 size_t len, textsize;
353 struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
356 /* separate input text into tokens to be matched individually */
357 for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
358 if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
359 die("cannot realloc %u bytes:", tokn * sizeof *tokv);
360 len = tokc ? strlen(tokv[0]) : 0;
362 matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
363 textsize = strlen(text) + 1;
364 for (item = items; item && item->text; item++) {
365 for (i = 0; i < tokc; i++)
366 if (!fstrstr(item->text, tokv[i]))
368 if (i != tokc) /* not all tokens match */
370 /* exact matches go first, then prefixes, then substrings */
371 if (!tokc || !fstrncmp(text, item->text, textsize))
372 appenditem(item, &matches, &matchend);
373 else if (!fstrncmp(tokv[0], item->text, len))
374 appenditem(item, &lprefix, &prefixend);
376 appenditem(item, &lsubstr, &substrend);
380 matchend->right = lprefix;
381 lprefix->left = matchend;
384 matchend = prefixend;
388 matchend->right = lsubstr;
389 lsubstr->left = matchend;
392 matchend = substrend;
394 curr = sel = matches;
399 insert(const char *str, ssize_t n)
401 if (strlen(text) + n > sizeof text - 1)
403 /* move existing text out of the way, insert new text, and update cursor */
404 memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
406 memcpy(&text[cursor], str, n);
416 /* return location of next utf8 rune in the given direction (+1 or -1) */
417 for (n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc)
423 movewordedge(int dir)
425 if (dir < 0) { /* move cursor to the start of the word*/
426 while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
427 cursor = nextrune(-1);
428 while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
429 cursor = nextrune(-1);
430 } else { /* move cursor to the end of the word */
431 while (text[cursor] && strchr(worddelimiters, text[cursor]))
432 cursor = nextrune(+1);
433 while (text[cursor] && !strchr(worddelimiters, text[cursor]))
434 cursor = nextrune(+1);
439 keypress(XKeyEvent *ev)
446 len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
448 default: /* XLookupNone, XBufferOverflow */
457 if (ev->state & ControlMask) {
459 case XK_a: ksym = XK_Home; break;
460 case XK_b: ksym = XK_Left; break;
461 case XK_c: ksym = XK_Escape; break;
462 case XK_d: ksym = XK_Delete; break;
463 case XK_e: ksym = XK_End; break;
464 case XK_f: ksym = XK_Right; break;
465 case XK_g: ksym = XK_Escape; break;
466 case XK_h: ksym = XK_BackSpace; break;
467 case XK_i: ksym = XK_Tab; break;
468 case XK_j: /* fallthrough */
469 case XK_J: /* fallthrough */
470 case XK_m: /* fallthrough */
471 case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
472 case XK_n: ksym = XK_Down; break;
473 case XK_p: ksym = XK_Up; break;
475 case XK_k: /* delete right */
479 case XK_u: /* delete left */
480 insert(NULL, 0 - cursor);
482 case XK_w: /* delete word */
483 while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
484 insert(NULL, nextrune(-1) - cursor);
485 while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
486 insert(NULL, nextrune(-1) - cursor);
488 case XK_y: /* paste selection */
490 XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
491 utf8, utf8, win, CurrentTime);
508 } else if (ev->state & Mod1Mask) {
516 case XK_g: ksym = XK_Home; break;
517 case XK_G: ksym = XK_End; break;
518 case XK_h: ksym = XK_Up; break;
519 case XK_j: ksym = XK_Next; break;
520 case XK_k: ksym = XK_Prior; break;
521 case XK_l: ksym = XK_Down; break;
534 if (text[cursor] == '\0')
536 cursor = nextrune(+1);
541 insert(NULL, nextrune(-1) - cursor);
544 if (text[cursor] != '\0') {
545 cursor = strlen(text);
549 /* jump to end of list and position items in reverse */
554 while (next && (curr = curr->right))
563 if (sel == matches) {
567 sel = curr = matches;
571 if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
572 cursor = nextrune(-1);
579 if (sel && sel->left && (sel = sel->left)->right == curr) {
598 puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
599 if (!(ev->state & ControlMask)) {
607 if (text[cursor] != '\0') {
608 cursor = nextrune(+1);
615 if (sel && sel->right && (sel = sel->right) == next) {
623 strncpy(text, sel->text, sizeof text - 1);
624 text[sizeof text - 1] = '\0';
625 cursor = strlen(text);
642 /* we have been given the current selection, now insert it into input */
643 if (XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
644 utf8, &da, &di, &dl, &dl, (unsigned char **)&p)
646 insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
655 char buf[sizeof text], *p;
656 size_t i, imax = 0, size = 0;
657 unsigned int tmpmax = 0;
659 /* read each line from stdin and add it to the item list */
660 for (i = 0; fgets(buf, sizeof buf, stdin); i++) {
661 if (i + 1 >= size / sizeof *items)
662 if (!(items = realloc(items, (size += BUFSIZ))))
663 die("cannot realloc %u bytes:", size);
664 if ((p = strchr(buf, '\n')))
666 if (!(items[i].text = strdup(buf)))
667 die("cannot strdup %u bytes:", strlen(buf) + 1);
669 drw_font_getexts(drw->fonts, buf, strlen(buf), &tmpmax, NULL);
670 if (tmpmax > inputw) {
676 items[i].text = NULL;
677 inputw = items ? TEXTW(items[imax].text) : 0;
678 lines = MIN(lines, i);
686 while (!XNextEvent(dpy, &ev)) {
687 if (XFilterEvent(&ev, win))
691 if (ev.xdestroywindow.window != win)
696 if (ev.xexpose.count == 0)
697 drw_map(drw, win, 0, 0, mw, mh);
700 /* regrab focus from parent window */
701 if (ev.xfocus.window != win)
707 case SelectionNotify:
708 if (ev.xselection.property == utf8)
711 case VisibilityNotify:
712 if (ev.xvisibility.state != VisibilityUnobscured)
713 XRaiseWindow(dpy, win);
724 XSetWindowAttributes swa;
727 XWindowAttributes wa;
728 XClassHint ch = {"dmenu", "dmenu"};
730 XineramaScreenInfo *info;
732 int a, di, n, area = 0;
734 /* init appearance */
735 for (j = 0; j < SchemeLast; j++)
736 scheme[j] = drw_scm_create(drw, colors[j], 2);
738 clip = XInternAtom(dpy, "CLIPBOARD", False);
739 utf8 = XInternAtom(dpy, "UTF8_STRING", False);
741 /* calculate menu geometry */
742 bh = drw->fonts->h + 2;
743 lines = MAX(lines, 0);
744 mh = (lines + 1) * bh;
747 if (parentwin == root && (info = XineramaQueryScreens(dpy, &n))) {
748 XGetInputFocus(dpy, &w, &di);
749 if (mon >= 0 && mon < n)
751 else if (w != root && w != PointerRoot && w != None) {
752 /* find top-level window containing current input focus */
754 if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
756 } while (w != root && w != pw);
757 /* find xinerama screen with which the window intersects most */
758 if (XGetWindowAttributes(dpy, pw, &wa))
759 for (j = 0; j < n; j++)
760 if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
765 /* no focused window is on screen, so use pointer location instead */
766 if (mon < 0 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
767 for (i = 0; i < n; i++)
768 if (INTERSECT(x, y, 1, 1, info[i]))
772 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
778 if (!XGetWindowAttributes(dpy, parentwin, &wa))
779 die("could not get embedding window attributes: 0x%lx",
782 y = topbar ? 0 : wa.height - mh;
785 promptw = (prompt && *prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
786 inputw = MIN(inputw, mw/3);
789 /* create menu window */
790 swa.override_redirect = True;
791 swa.background_pixel = scheme[SchemeNorm][ColBg].pixel;
792 swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
793 win = XCreateWindow(dpy, parentwin, x, y, mw, mh, 0,
794 CopyFromParent, CopyFromParent, CopyFromParent,
795 CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
796 XSetClassHint(dpy, win, &ch);
800 if ((xim = XOpenIM(dpy, NULL, NULL, NULL)) == NULL)
801 die("XOpenIM failed: could not open input device");
803 xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
804 XNClientWindow, win, XNFocusWindow, win, NULL);
806 XMapRaised(dpy, win);
808 XSelectInput(dpy, parentwin, FocusChangeMask | SubstructureNotifyMask);
809 if (XQueryTree(dpy, parentwin, &dw, &w, &dws, &du) && dws) {
810 for (i = 0; i < du && dws[i] != win; ++i)
811 XSelectInput(dpy, dws[i], FocusChangeMask);
816 drw_resize(drw, mw, mh);
823 fputs("usage: dmenu [-bfiv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
824 " [-nb color] [-nf color] [-sb color] [-sf color]\n"
825 " [-nhb color] [-nhf color] [-shb color] [-shf color] [-w windowid]\n", stderr);
830 main(int argc, char *argv[])
832 XWindowAttributes wa;
835 for (i = 1; i < argc; i++)
836 /* these options take no arguments */
837 if (!strcmp(argv[i], "-v")) { /* prints version information */
838 puts("dmenu-"VERSION);
840 } else if (!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
842 else if (!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
844 else if (!strcmp(argv[i], "-F")) /* grabs keyboard before reading stdin */
846 else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
847 fstrncmp = strncasecmp;
849 } else if (i + 1 == argc)
851 /* these options take one argument */
852 else if (!strcmp(argv[i], "-l")) /* number of lines in vertical list */
853 lines = atoi(argv[++i]);
854 else if (!strcmp(argv[i], "-m"))
855 mon = atoi(argv[++i]);
856 else if (!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
858 else if (!strcmp(argv[i], "-fn")) /* font or font set */
859 fonts[0] = argv[++i];
860 else if (!strcmp(argv[i], "-nb")) /* normal background color */
861 colors[SchemeNorm][ColBg] = argv[++i];
862 else if (!strcmp(argv[i], "-nf")) /* normal foreground color */
863 colors[SchemeNorm][ColFg] = argv[++i];
864 else if (!strcmp(argv[i], "-sb")) /* selected background color */
865 colors[SchemeSel][ColBg] = argv[++i];
866 else if (!strcmp(argv[i], "-sf")) /* selected foreground color */
867 colors[SchemeSel][ColFg] = argv[++i];
868 else if (!strcmp(argv[i], "-nhb")) /* normal hi background color */
869 colors[SchemeNormHighlight][ColBg] = argv[++i];
870 else if (!strcmp(argv[i], "-nhf")) /* normal hi foreground color */
871 colors[SchemeNormHighlight][ColFg] = argv[++i];
872 else if (!strcmp(argv[i], "-shb")) /* selected hi background color */
873 colors[SchemeSelHighlight][ColBg] = argv[++i];
874 else if (!strcmp(argv[i], "-shf")) /* selected hi foreground color */
875 colors[SchemeSelHighlight][ColFg] = argv[++i];
876 else if (!strcmp(argv[i], "-w")) /* embedding window id */
881 if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
882 fputs("warning: no locale support\n", stderr);
883 if (!(dpy = XOpenDisplay(NULL)))
884 die("cannot open display");
885 screen = DefaultScreen(dpy);
886 root = RootWindow(dpy, screen);
887 if (!embed || !(parentwin = strtol(embed, NULL, 0)))
889 if (!XGetWindowAttributes(dpy, parentwin, &wa))
890 die("could not get embedding window attributes: 0x%lx",
892 drw = drw_create(dpy, screen, root, wa.width, wa.height);
893 if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
894 die("no fonts could be loaded.");
895 lrpad = drw->fonts->h;
898 if (pledge("stdio rpath", NULL) == -1)
902 if (fast && !isatty(0)) {
912 return 1; /* unreachable */