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>
18 #include <X11/Xresource.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, SchemeOut, SchemeLast }; /* color schemes */
34 struct item *left, *right;
38 static char text[BUFSIZ] = "";
40 static int bh, mw, mh;
41 static int inputw = 0, promptw;
42 static int lrpad; /* sum of left and right padding */
43 static int reject_no_match = 0;
45 static struct item *items = NULL;
46 static struct item *matches, *matchend;
47 static struct item *prev, *curr, *next, *sel;
48 static int mon = -1, screen;
50 static Atom clip, utf8;
52 static Window root, parentwin, win;
56 static Clr *scheme[SchemeLast];
58 /* Temporary arrays to allow overriding xresources values */
59 static char *colortemp[4];
60 static char *tempfonts;
64 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
65 static char *(*fstrstr)(const char *, const char *) = strstr;
68 appenditem(struct item *item, struct item **list, struct item **last)
71 (*last)->right = item;
88 n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">"));
89 /* calculate which items will begin the next page and previous page */
90 for (i = 0, next = curr; next; next = next->right)
91 if ((i += (lines > 0) ? bh : MIN(TEXTW(next->text), n)) > n)
93 for (i = 0, prev = curr; prev && prev->left; prev = prev->left)
94 if ((i += (lines > 0) ? bh : MIN(TEXTW(prev->left->text), n)) > n)
102 for (struct item *item = items; item && item->text; item++)
103 len = MAX(TEXTW(item->text), len);
112 XUngrabKey(dpy, AnyKey, AnyModifier, root);
113 for (i = 0; i < SchemeLast; i++)
121 cistrstr(const char *s, const char *sub)
125 for (len = strlen(sub); *s; s++)
126 if (!strncasecmp(s, sub, len))
132 drawitem(struct item *item, int x, int y, int w)
135 drw_setscheme(drw, scheme[SchemeSel]);
137 drw_setscheme(drw, scheme[SchemeOut]);
139 drw_setscheme(drw, scheme[SchemeNorm]);
141 return drw_text(drw, x, y, w, bh, lrpad / 2, item->text, 0);
151 drw_setscheme(drw, scheme[SchemeNorm]);
152 drw_rect(drw, 0, 0, mw, mh, 1, 1);
154 if (prompt && *prompt) {
155 drw_setscheme(drw, scheme[SchemeSel]);
156 x = drw_text(drw, x, 0, promptw, bh, lrpad / 2, prompt, 0);
158 /* draw input field */
159 w = (lines > 0 || !matches) ? mw - x : inputw;
160 drw_setscheme(drw, scheme[SchemeNorm]);
161 drw_text(drw, x, 0, w, bh, lrpad / 2, text, 0);
163 curpos = TEXTW(text) - TEXTW(&text[cursor]);
164 if ((curpos += lrpad / 2 - 1) < w) {
165 drw_setscheme(drw, scheme[SchemeNorm]);
166 drw_rect(drw, x + curpos, 2, 2, bh - 4, 1, 0);
170 /* draw vertical list */
171 for (item = curr; item != next; item = item->right)
172 drawitem(item, x, y += bh, mw - x);
173 } else if (matches) {
174 /* draw horizontal list */
178 drw_setscheme(drw, scheme[SchemeNorm]);
179 drw_text(drw, x, 0, w, bh, lrpad / 2, "<", 0);
182 for (item = curr; item != next; item = item->right)
183 x = drawitem(item, x, 0, MIN(TEXTW(item->text), mw - x - TEXTW(">")));
186 drw_setscheme(drw, scheme[SchemeNorm]);
187 drw_text(drw, mw - w, 0, w, bh, lrpad / 2, ">", 0);
190 drw_map(drw, win, 0, 0, mw, mh);
196 struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 };
200 for (i = 0; i < 100; ++i) {
201 XGetInputFocus(dpy, &focuswin, &revertwin);
204 XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
205 nanosleep(&ts, NULL);
207 die("cannot grab focus");
213 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
218 /* try to grab keyboard, we may have to wait for another process to ungrab */
219 for (i = 0; i < 1000; i++) {
220 if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync,
221 GrabModeAsync, CurrentTime) == GrabSuccess)
223 nanosleep(&ts, NULL);
225 die("cannot grab keyboard");
231 static char **tokv = NULL;
234 char buf[sizeof text], *s;
236 size_t len, textsize;
237 struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
240 /* separate input text into tokens to be matched individually */
241 for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
242 if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
243 die("cannot realloc %u bytes:", tokn * sizeof *tokv);
244 len = tokc ? strlen(tokv[0]) : 0;
246 matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
247 textsize = strlen(text) + 1;
248 for (item = items; item && item->text; item++) {
249 for (i = 0; i < tokc; i++)
250 if (!fstrstr(item->text, tokv[i]))
252 if (i != tokc) /* not all tokens match */
254 /* exact matches go first, then prefixes, then substrings */
255 if (!tokc || !fstrncmp(text, item->text, textsize))
256 appenditem(item, &matches, &matchend);
257 else if (!fstrncmp(tokv[0], item->text, len))
258 appenditem(item, &lprefix, &prefixend);
260 appenditem(item, &lsubstr, &substrend);
264 matchend->right = lprefix;
265 lprefix->left = matchend;
268 matchend = prefixend;
272 matchend->right = lsubstr;
273 lsubstr->left = matchend;
276 matchend = substrend;
278 curr = sel = matches;
283 insert(const char *str, ssize_t n)
285 if (strlen(text) + n > sizeof text - 1)
288 static char last[BUFSIZ] = "";
289 if(reject_no_match) {
290 /* store last text value in case we need to revert it */
291 memcpy(last, text, BUFSIZ);
294 /* move existing text out of the way, insert new text, and update cursor */
295 memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
297 memcpy(&text[cursor], str, n);
301 if(!matches && reject_no_match) {
302 /* revert to last text value if theres no match */
303 memcpy(text, last, BUFSIZ);
314 /* return location of next utf8 rune in the given direction (+1 or -1) */
315 for (n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc)
321 movewordedge(int dir)
323 if (dir < 0) { /* move cursor to the start of the word*/
324 while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
325 cursor = nextrune(-1);
326 while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
327 cursor = nextrune(-1);
328 } else { /* move cursor to the end of the word */
329 while (text[cursor] && strchr(worddelimiters, text[cursor]))
330 cursor = nextrune(+1);
331 while (text[cursor] && !strchr(worddelimiters, text[cursor]))
332 cursor = nextrune(+1);
337 keypress(XKeyEvent *ev)
344 len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
346 default: /* XLookupNone, XBufferOverflow */
355 if (ev->state & ControlMask) {
357 case XK_a: ksym = XK_Home; break;
358 case XK_b: ksym = XK_Left; break;
359 case XK_c: ksym = XK_Escape; break;
360 case XK_d: ksym = XK_Delete; break;
361 case XK_e: ksym = XK_End; break;
362 case XK_f: ksym = XK_Right; break;
363 case XK_g: ksym = XK_Escape; break;
364 case XK_h: ksym = XK_BackSpace; break;
365 case XK_i: ksym = XK_Tab; break;
366 case XK_j: /* fallthrough */
367 case XK_J: /* fallthrough */
368 case XK_m: /* fallthrough */
369 case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
370 case XK_n: ksym = XK_Down; break;
371 case XK_p: ksym = XK_Up; break;
373 case XK_k: /* delete right */
377 case XK_u: /* delete left */
378 insert(NULL, 0 - cursor);
380 case XK_w: /* delete word */
381 while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
382 insert(NULL, nextrune(-1) - cursor);
383 while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
384 insert(NULL, nextrune(-1) - cursor);
386 case XK_y: /* paste selection */
388 XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
389 utf8, utf8, win, CurrentTime);
406 } else if (ev->state & Mod1Mask) {
414 case XK_g: ksym = XK_Home; break;
415 case XK_G: ksym = XK_End; break;
416 case XK_h: ksym = XK_Up; break;
417 case XK_j: ksym = XK_Next; break;
418 case XK_k: ksym = XK_Prior; break;
419 case XK_l: ksym = XK_Down; break;
432 if (text[cursor] == '\0')
434 cursor = nextrune(+1);
439 insert(NULL, nextrune(-1) - cursor);
442 if (text[cursor] != '\0') {
443 cursor = strlen(text);
447 /* jump to end of list and position items in reverse */
452 while (next && (curr = curr->right))
461 if (sel == matches) {
465 sel = curr = matches;
469 if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
470 cursor = nextrune(-1);
477 if (sel && sel->left && (sel = sel->left)->right == curr) {
496 puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
497 if (!(ev->state & ControlMask)) {
505 if (text[cursor] != '\0') {
506 cursor = nextrune(+1);
513 if (sel && sel->right && (sel = sel->right) == next) {
521 strncpy(text, sel->text, sizeof text - 1);
522 text[sizeof text - 1] = '\0';
523 cursor = strlen(text);
540 /* we have been given the current selection, now insert it into input */
541 if (XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
542 utf8, &da, &di, &dl, &dl, (unsigned char **)&p)
544 insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
553 char buf[sizeof text], *p;
554 size_t i, imax = 0, size = 0;
555 unsigned int tmpmax = 0;
557 /* read each line from stdin and add it to the item list */
558 for (i = 0; fgets(buf, sizeof buf, stdin); i++) {
559 if (i + 1 >= size / sizeof *items)
560 if (!(items = realloc(items, (size += BUFSIZ))))
561 die("cannot realloc %u bytes:", size);
562 if ((p = strchr(buf, '\n')))
564 if (!(items[i].text = strdup(buf)))
565 die("cannot strdup %u bytes:", strlen(buf) + 1);
567 drw_font_getexts(drw->fonts, buf, strlen(buf), &tmpmax, NULL);
568 if (tmpmax > inputw) {
574 items[i].text = NULL;
575 inputw = items ? TEXTW(items[imax].text) : 0;
576 lines = MIN(lines, i);
584 while (!XNextEvent(dpy, &ev)) {
585 if (XFilterEvent(&ev, win))
589 if (ev.xdestroywindow.window != win)
594 if (ev.xexpose.count == 0)
595 drw_map(drw, win, 0, 0, mw, mh);
598 /* regrab focus from parent window */
599 if (ev.xfocus.window != win)
605 case SelectionNotify:
606 if (ev.xselection.property == utf8)
609 case VisibilityNotify:
610 if (ev.xvisibility.state != VisibilityUnobscured)
611 XRaiseWindow(dpy, win);
622 XSetWindowAttributes swa;
625 XWindowAttributes wa;
626 XClassHint ch = {"dmenu", "dmenu"};
628 XineramaScreenInfo *info;
630 int a, di, n, area = 0;
632 /* init appearance */
633 for (j = 0; j < SchemeLast; j++) {
634 scheme[j] = drw_scm_create(drw, (const char**)colors[j], 2);
636 for (j = 0; j < SchemeOut; ++j) {
637 for (i = 0; i < 2; ++i)
641 clip = XInternAtom(dpy, "CLIPBOARD", False);
642 utf8 = XInternAtom(dpy, "UTF8_STRING", False);
644 /* calculate menu geometry */
645 bh = drw->fonts->h + 2;
646 lines = MAX(lines, 0);
647 mh = (lines + 1) * bh;
648 promptw = (prompt && *prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
651 if (parentwin == root && (info = XineramaQueryScreens(dpy, &n))) {
652 XGetInputFocus(dpy, &w, &di);
653 if (mon >= 0 && mon < n)
655 else if (w != root && w != PointerRoot && w != None) {
656 /* find top-level window containing current input focus */
658 if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
660 } while (w != root && w != pw);
661 /* find xinerama screen with which the window intersects most */
662 if (XGetWindowAttributes(dpy, pw, &wa))
663 for (j = 0; j < n; j++)
664 if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
669 /* no focused window is on screen, so use pointer location instead */
670 if (mon < 0 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
671 for (i = 0; i < n; i++)
672 if (INTERSECT(x, y, 1, 1, info[i]))
676 mw = MIN(MAX(max_textw() + promptw, min_width), info[i].width);
677 x = info[i].x_org + ((info[i].width - mw) / 2);
678 y = info[i].y_org + ((info[i].height - mh) / 2);
681 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
689 if (!XGetWindowAttributes(dpy, parentwin, &wa))
690 die("could not get embedding window attributes: 0x%lx",
694 mw = MIN(MAX(max_textw() + promptw, min_width), wa.width);
695 x = (wa.width - mw) / 2;
696 y = (wa.height - mh) / 2;
699 y = topbar ? 0 : wa.height - mh;
703 inputw = MIN(inputw, mw/3);
706 /* create menu window */
707 swa.override_redirect = True;
708 swa.background_pixel = scheme[SchemeNorm][ColBg].pixel;
709 swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
710 win = XCreateWindow(dpy, parentwin, x, y, mw, mh, border_width,
711 CopyFromParent, CopyFromParent, CopyFromParent,
712 CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
713 + XSetWindowBorder(dpy, win, scheme[SchemeSel][ColBg].pixel);
714 XSetClassHint(dpy, win, &ch);
718 if ((xim = XOpenIM(dpy, NULL, NULL, NULL)) == NULL)
719 die("XOpenIM failed: could not open input device");
721 xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
722 XNClientWindow, win, XNFocusWindow, win, NULL);
724 XMapRaised(dpy, win);
726 XSelectInput(dpy, parentwin, FocusChangeMask | SubstructureNotifyMask);
727 if (XQueryTree(dpy, parentwin, &dw, &w, &dws, &du) && dws) {
728 for (i = 0; i < du && dws[i] != win; ++i)
729 XSelectInput(dpy, dws[i], FocusChangeMask);
734 drw_resize(drw, mw, mh);
741 fputs("usage: dmenu [-bfirv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
742 " [-nb color] [-nf color] [-sb color] [-sf color] [-w windowid]\n", stderr);
747 readxresources(void) {
751 if ((xrm = XResourceManagerString(drw->dpy))) {
753 XrmDatabase xdb = XrmGetStringDatabase(xrm);
756 if (XrmGetResource(xdb, "dmenu.font", "*", &type, &xval))
757 fonts[0] = strdup(xval.addr);
759 fonts[0] = strdup(fonts[0]);
760 if (XrmGetResource(xdb, "dmenu.background", "*", &type, &xval))
761 colors[SchemeNorm][ColBg] = strdup(xval.addr);
763 colors[SchemeNorm][ColBg] = strdup(colors[SchemeNorm][ColBg]);
764 if (XrmGetResource(xdb, "dmenu.foreground", "*", &type, &xval))
765 colors[SchemeNorm][ColFg] = strdup(xval.addr);
767 colors[SchemeNorm][ColFg] = strdup(colors[SchemeNorm][ColFg]);
768 if (XrmGetResource(xdb, "dmenu.selbackground", "*", &type, &xval))
769 colors[SchemeSel][ColBg] = strdup(xval.addr);
771 colors[SchemeSel][ColBg] = strdup(colors[SchemeSel][ColBg]);
772 if (XrmGetResource(xdb, "dmenu.selforeground", "*", &type, &xval))
773 colors[SchemeSel][ColFg] = strdup(xval.addr);
775 colors[SchemeSel][ColFg] = strdup(colors[SchemeSel][ColFg]);
777 XrmDestroyDatabase(xdb);
782 main(int argc, char *argv[])
784 XWindowAttributes wa;
787 for (i = 1; i < argc; i++)
788 /* these options take no arguments */
789 if (!strcmp(argv[i], "-v")) { /* prints version information */
790 puts("dmenu-"VERSION);
792 } else if (!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
794 else if (!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
796 else if (!strcmp(argv[i], "-c")) /* centers dmenu on screen */
798 else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
799 fstrncmp = strncasecmp;
801 } else if (!strcmp(argv[i], "-r")) /* reject input which results in no match */
803 else if (i + 1 == argc)
805 /* these options take one argument */
806 else if (!strcmp(argv[i], "-l")) /* number of lines in vertical list */
807 lines = atoi(argv[++i]);
808 else if (!strcmp(argv[i], "-m"))
809 mon = atoi(argv[++i]);
810 else if (!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
812 else if (!strcmp(argv[i], "-fn")) /* font or font set */
813 tempfonts = argv[++i];
814 else if (!strcmp(argv[i], "-nb")) /* normal background color */
815 colortemp[0] = argv[++i];
816 else if (!strcmp(argv[i], "-nf")) /* normal foreground color */
817 colortemp[1] = argv[++i];
818 else if (!strcmp(argv[i], "-sb")) /* selected background color */
819 colortemp[2] = argv[++i];
820 else if (!strcmp(argv[i], "-sf")) /* selected foreground color */
821 colortemp[3] = argv[++i];
822 else if (!strcmp(argv[i], "-w")) /* embedding window id */
827 if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
828 fputs("warning: no locale support\n", stderr);
829 if (!(dpy = XOpenDisplay(NULL)))
830 die("cannot open display");
831 screen = DefaultScreen(dpy);
832 root = RootWindow(dpy, screen);
833 if (!embed || !(parentwin = strtol(embed, NULL, 0)))
835 if (!XGetWindowAttributes(dpy, parentwin, &wa))
836 die("could not get embedding window attributes: 0x%lx",
838 drw = drw_create(dpy, screen, root, wa.width, wa.height);
840 /* Now we check whether to override xresources with commandline parameters */
842 fonts[0] = strdup(tempfonts);
844 colors[SchemeNorm][ColBg] = strdup(colortemp[0]);
846 colors[SchemeNorm][ColFg] = strdup(colortemp[1]);
848 colors[SchemeSel][ColBg] = strdup(colortemp[2]);
850 colors[SchemeSel][ColFg] = strdup(colortemp[3]);
852 if (!drw_fontset_create(drw, (const char**)fonts, LENGTH(fonts)))
853 die("no fonts could be loaded.");
856 lrpad = drw->fonts->h;
859 if (pledge("stdio rpath", NULL) == -1)
863 if (fast && !isatty(0)) {
873 return 1; /* unreachable */