1 /* See LICENSE file for copyright and license details. */
12 #include <X11/Xatom.h>
13 #include <X11/Xutil.h>
15 #include <X11/extensions/Xinerama.h>
17 #include <X11/Xft/Xft.h>
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)
29 enum { SchemeNorm, SchemeSel, SchemeOut, SchemeLast }; /* color schemes */
33 struct item *left, *right;
37 static char text[BUFSIZ] = "";
39 static int bh, mw, mh;
40 static int inputw = 0, promptw;
41 static int lrpad; /* sum of left and right padding */
43 static struct item *items = NULL;
44 static struct item *matches, *matchend;
45 static struct item *prev, *curr, *next, *sel;
46 static int mon = -1, screen;
48 static Atom clip, utf8;
50 static Window root, parentwin, win;
54 static Clr *scheme[SchemeLast];
58 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
59 static char *(*fstrstr)(const char *, const char *) = strstr;
62 appenditem(struct item *item, struct item **list, struct item **last)
65 (*last)->right = item;
82 n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">"));
83 /* calculate which items will begin the next page and previous page */
84 for (i = 0, next = curr; next; next = next->right)
85 if ((i += (lines > 0) ? bh : MIN(TEXTW(next->text), n)) > n)
87 for (i = 0, prev = curr; prev && prev->left; prev = prev->left)
88 if ((i += (lines > 0) ? bh : MIN(TEXTW(prev->left->text), n)) > n)
97 XUngrabKey(dpy, AnyKey, AnyModifier, root);
98 for (i = 0; i < SchemeLast; i++)
106 cistrstr(const char *s, const char *sub)
110 for (len = strlen(sub); *s; s++)
111 if (!strncasecmp(s, sub, len))
117 drawitem(struct item *item, int x, int y, int w)
120 drw_setscheme(drw, scheme[SchemeSel]);
122 drw_setscheme(drw, scheme[SchemeOut]);
124 drw_setscheme(drw, scheme[SchemeNorm]);
126 return drw_text(drw, x, y, w, bh, lrpad / 2, item->text, 0);
136 drw_setscheme(drw, scheme[SchemeNorm]);
137 drw_rect(drw, 0, 0, mw, mh, 1, 1);
139 if (prompt && *prompt) {
140 drw_setscheme(drw, scheme[SchemeSel]);
141 x = drw_text(drw, x, 0, promptw, bh, lrpad / 2, prompt, 0);
143 /* draw input field */
144 w = (lines > 0 || !matches) ? mw - x : inputw;
145 drw_setscheme(drw, scheme[SchemeNorm]);
146 drw_text(drw, x, 0, w, bh, lrpad / 2, text, 0);
148 curpos = TEXTW(text) - TEXTW(&text[cursor]);
149 if ((curpos += lrpad / 2 - 1) < w) {
150 drw_setscheme(drw, scheme[SchemeNorm]);
151 drw_rect(drw, x + curpos, 2, 2, bh - 4, 1, 0);
155 /* draw vertical list */
156 for (item = curr; item != next; item = item->right)
157 drawitem(item, x, y += bh, mw - x);
158 } else if (matches) {
159 /* draw horizontal list */
163 drw_setscheme(drw, scheme[SchemeNorm]);
164 drw_text(drw, x, 0, w, bh, lrpad / 2, "<", 0);
167 for (item = curr; item != next; item = item->right)
168 x = drawitem(item, x, 0, MIN(TEXTW(item->text), mw - x - TEXTW(">")));
171 drw_setscheme(drw, scheme[SchemeNorm]);
172 drw_text(drw, mw - w, 0, w, bh, lrpad / 2, ">", 0);
175 drw_map(drw, win, 0, 0, mw, mh);
181 struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 };
185 for (i = 0; i < 100; ++i) {
186 XGetInputFocus(dpy, &focuswin, &revertwin);
189 XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
190 nanosleep(&ts, NULL);
192 die("cannot grab focus");
198 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
203 /* try to grab keyboard, we may have to wait for another process to ungrab */
204 for (i = 0; i < 1000; i++) {
205 if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync,
206 GrabModeAsync, CurrentTime) == GrabSuccess)
208 nanosleep(&ts, NULL);
210 die("cannot grab keyboard");
216 static char **tokv = NULL;
219 char buf[sizeof text], *s;
221 size_t len, textsize;
222 struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
225 /* separate input text into tokens to be matched individually */
226 for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
227 if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
228 die("cannot realloc %u bytes:", tokn * sizeof *tokv);
229 len = tokc ? strlen(tokv[0]) : 0;
231 matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
232 textsize = strlen(text) + 1;
233 for (item = items; item && item->text; item++) {
234 for (i = 0; i < tokc; i++)
235 if (!fstrstr(item->text, tokv[i]))
237 if (i != tokc) /* not all tokens match */
239 /* exact matches go first, then prefixes, then substrings */
240 if (!tokc || !fstrncmp(text, item->text, textsize))
241 appenditem(item, &matches, &matchend);
242 else if (!fstrncmp(tokv[0], item->text, len))
243 appenditem(item, &lprefix, &prefixend);
245 appenditem(item, &lsubstr, &substrend);
249 matchend->right = lprefix;
250 lprefix->left = matchend;
253 matchend = prefixend;
257 matchend->right = lsubstr;
258 lsubstr->left = matchend;
261 matchend = substrend;
263 curr = sel = matches;
268 insert(const char *str, ssize_t n)
270 if (strlen(text) + n > sizeof text - 1)
272 /* move existing text out of the way, insert new text, and update cursor */
273 memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
275 memcpy(&text[cursor], str, n);
285 /* return location of next utf8 rune in the given direction (+1 or -1) */
286 for (n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc)
292 movewordedge(int dir)
294 if (dir < 0) { /* move cursor to the start of the word*/
295 while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
296 cursor = nextrune(-1);
297 while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
298 cursor = nextrune(-1);
299 } else { /* move cursor to the end of the word */
300 while (text[cursor] && strchr(worddelimiters, text[cursor]))
301 cursor = nextrune(+1);
302 while (text[cursor] && !strchr(worddelimiters, text[cursor]))
303 cursor = nextrune(+1);
308 keypress(XKeyEvent *ev)
315 len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
317 default: /* XLookupNone, XBufferOverflow */
326 if (ev->state & ControlMask) {
328 case XK_a: ksym = XK_Home; break;
329 case XK_b: ksym = XK_Left; break;
330 case XK_c: ksym = XK_Escape; break;
331 case XK_d: ksym = XK_Delete; break;
332 case XK_e: ksym = XK_End; break;
333 case XK_f: ksym = XK_Right; break;
334 case XK_g: ksym = XK_Escape; break;
335 case XK_h: ksym = XK_BackSpace; break;
336 case XK_i: ksym = XK_Tab; break;
337 case XK_j: /* fallthrough */
338 case XK_J: /* fallthrough */
339 case XK_m: /* fallthrough */
340 case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
341 case XK_n: ksym = XK_Down; break;
342 case XK_p: ksym = XK_Up; break;
344 case XK_k: /* delete right */
348 case XK_u: /* delete left */
349 insert(NULL, 0 - cursor);
351 case XK_w: /* delete word */
352 while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
353 insert(NULL, nextrune(-1) - cursor);
354 while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
355 insert(NULL, nextrune(-1) - cursor);
357 case XK_y: /* paste selection */
359 XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
360 utf8, utf8, win, CurrentTime);
377 } else if (ev->state & Mod1Mask) {
385 case XK_g: ksym = XK_Home; break;
386 case XK_G: ksym = XK_End; break;
387 case XK_h: ksym = XK_Up; break;
388 case XK_j: ksym = XK_Next; break;
389 case XK_k: ksym = XK_Prior; break;
390 case XK_l: ksym = XK_Down; break;
403 if (text[cursor] == '\0')
405 cursor = nextrune(+1);
410 insert(NULL, nextrune(-1) - cursor);
413 if (text[cursor] != '\0') {
414 cursor = strlen(text);
418 /* jump to end of list and position items in reverse */
423 while (next && (curr = curr->right))
432 if (sel == matches) {
436 sel = curr = matches;
440 if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
441 cursor = nextrune(-1);
448 if (sel && sel->left && (sel = sel->left)->right == curr) {
467 puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
468 if (!(ev->state & ControlMask)) {
476 if (text[cursor] != '\0') {
477 cursor = nextrune(+1);
484 if (sel && sel->right && (sel = sel->right) == next) {
492 strncpy(text, sel->text, sizeof text - 1);
493 text[sizeof text - 1] = '\0';
494 cursor = strlen(text);
511 /* we have been given the current selection, now insert it into input */
512 if (XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
513 utf8, &da, &di, &dl, &dl, (unsigned char **)&p)
515 insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
524 char buf[sizeof text], *p;
525 size_t i, imax = 0, size = 0;
526 unsigned int tmpmax = 0;
528 /* read each line from stdin and add it to the item list */
529 for (i = 0; fgets(buf, sizeof buf, stdin); i++) {
530 if (i + 1 >= size / sizeof *items)
531 if (!(items = realloc(items, (size += BUFSIZ))))
532 die("cannot realloc %u bytes:", size);
533 if ((p = strchr(buf, '\n')))
535 if (!(items[i].text = strdup(buf)))
536 die("cannot strdup %u bytes:", strlen(buf) + 1);
538 drw_font_getexts(drw->fonts, buf, strlen(buf), &tmpmax, NULL);
539 if (tmpmax > inputw) {
545 items[i].text = NULL;
546 inputw = items ? TEXTW(items[imax].text) : 0;
547 lines = MIN(lines, i);
555 while (!XNextEvent(dpy, &ev)) {
556 if (XFilterEvent(&ev, None))
560 if (ev.xdestroywindow.window != win)
565 if (ev.xexpose.count == 0)
566 drw_map(drw, win, 0, 0, mw, mh);
569 /* regrab focus from parent window */
570 if (ev.xfocus.window != win)
576 case SelectionNotify:
577 if (ev.xselection.property == utf8)
580 case VisibilityNotify:
581 if (ev.xvisibility.state != VisibilityUnobscured)
582 XRaiseWindow(dpy, win);
593 XSetWindowAttributes swa;
596 XWindowAttributes wa;
597 XClassHint ch = {"dmenu", "dmenu"};
599 XineramaScreenInfo *info;
601 int a, di, n, area = 0;
603 /* init appearance */
604 for (j = 0; j < SchemeLast; j++)
605 scheme[j] = drw_scm_create(drw, colors[j], 2);
607 clip = XInternAtom(dpy, "CLIPBOARD", False);
608 utf8 = XInternAtom(dpy, "UTF8_STRING", False);
610 /* calculate menu geometry */
611 bh = drw->fonts->h + 2;
612 lines = MAX(lines, 0);
613 mh = (lines + 1) * bh;
616 if (parentwin == root && (info = XineramaQueryScreens(dpy, &n))) {
617 XGetInputFocus(dpy, &w, &di);
618 if (mon >= 0 && mon < n)
620 else if (w != root && w != PointerRoot && w != None) {
621 /* find top-level window containing current input focus */
623 if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
625 } while (w != root && w != pw);
626 /* find xinerama screen with which the window intersects most */
627 if (XGetWindowAttributes(dpy, pw, &wa))
628 for (j = 0; j < n; j++)
629 if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
634 /* no focused window is on screen, so use pointer location instead */
635 if (mon < 0 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
636 for (i = 0; i < n; i++)
637 if (INTERSECT(x, y, 1, 1, info[i]))
641 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
647 if (!XGetWindowAttributes(dpy, parentwin, &wa))
648 die("could not get embedding window attributes: 0x%lx",
651 y = topbar ? 0 : wa.height - mh;
654 promptw = (prompt && *prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
655 inputw = MIN(inputw, mw/3);
658 /* create menu window */
659 swa.override_redirect = True;
660 swa.background_pixel = scheme[SchemeNorm][ColBg].pixel;
661 swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
662 win = XCreateWindow(dpy, parentwin, x, y, mw, mh, 0,
663 CopyFromParent, CopyFromParent, CopyFromParent,
664 CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
665 XSetClassHint(dpy, win, &ch);
669 if ((xim = XOpenIM(dpy, NULL, NULL, NULL)) == NULL) {
670 XSetLocaleModifiers("@im=local");
671 if ((xim = XOpenIM(dpy, NULL, NULL, NULL)) == NULL) {
672 XSetLocaleModifiers("@im=");
673 if ((xim = XOpenIM(dpy, NULL, NULL, NULL)) == NULL)
674 die("XOpenIM failed: could not open input device");
678 xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
679 XNClientWindow, win, XNFocusWindow, win, NULL);
681 XMapRaised(dpy, win);
682 XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
684 XSelectInput(dpy, parentwin, FocusChangeMask | SubstructureNotifyMask);
685 if (XQueryTree(dpy, parentwin, &dw, &w, &dws, &du) && dws) {
686 for (i = 0; i < du && dws[i] != win; ++i)
687 XSelectInput(dpy, dws[i], FocusChangeMask);
692 drw_resize(drw, mw, mh);
699 fputs("usage: dmenu [-bfiv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
700 " [-nb color] [-nf color] [-sb color] [-sf color] [-w windowid]\n", stderr);
705 main(int argc, char *argv[])
707 XWindowAttributes wa;
710 for (i = 1; i < argc; i++)
711 /* these options take no arguments */
712 if (!strcmp(argv[i], "-v")) { /* prints version information */
713 puts("dmenu-"VERSION);
715 } else if (!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
717 else if (!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
719 else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
720 fstrncmp = strncasecmp;
722 } else if (i + 1 == argc)
724 /* these options take one argument */
725 else if (!strcmp(argv[i], "-l")) /* number of lines in vertical list */
726 lines = atoi(argv[++i]);
727 else if (!strcmp(argv[i], "-m"))
728 mon = atoi(argv[++i]);
729 else if (!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
731 else if (!strcmp(argv[i], "-fn")) /* font or font set */
732 fonts[0] = argv[++i];
733 else if (!strcmp(argv[i], "-nb")) /* normal background color */
734 colors[SchemeNorm][ColBg] = argv[++i];
735 else if (!strcmp(argv[i], "-nf")) /* normal foreground color */
736 colors[SchemeNorm][ColFg] = argv[++i];
737 else if (!strcmp(argv[i], "-sb")) /* selected background color */
738 colors[SchemeSel][ColBg] = argv[++i];
739 else if (!strcmp(argv[i], "-sf")) /* selected foreground color */
740 colors[SchemeSel][ColFg] = argv[++i];
741 else if (!strcmp(argv[i], "-w")) /* embedding window id */
746 if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
747 fputs("warning: no locale support\n", stderr);
748 if (!XSetLocaleModifiers(""))
749 fputs("warning: no locale modifiers support\n", stderr);
750 if (!(dpy = XOpenDisplay(NULL)))
751 die("cannot open display");
752 screen = DefaultScreen(dpy);
753 root = RootWindow(dpy, screen);
754 if (!embed || !(parentwin = strtol(embed, NULL, 0)))
756 if (!XGetWindowAttributes(dpy, parentwin, &wa))
757 die("could not get embedding window attributes: 0x%lx",
759 drw = drw_create(dpy, screen, root, wa.width, wa.height);
760 if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
761 die("no fonts could be loaded.");
762 lrpad = drw->fonts->h;
765 if (pledge("stdio rpath", NULL) == -1)
769 if (fast && !isatty(0)) {
779 return 1; /* unreachable */