1 /* See LICENSE file for copyright and license details. */
12 #include <X11/Xatom.h>
13 #include <X11/Xproto.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
34 enum { SchemeNorm, SchemeSel, SchemeOut, SchemeLast }; /* color schemes */
38 struct item *left, *right;
42 static char numbers[NUMBERSBUFSIZE] = "";
43 static char text[BUFSIZ] = "";
45 static int bh, mw, mh;
46 static int inputw = 0, promptw;
47 static int lrpad; /* sum of left and right padding */
49 static struct item *items = NULL;
50 static struct item *matches, *matchend;
51 static struct item *prev, *curr, *next, *sel;
52 static int mon = -1, screen;
54 static Atom clip, utf8;
56 static Window root, parentwin, win;
60 static Clr *scheme[SchemeLast];
62 static int useargb = 0;
63 static Visual *visual;
69 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
70 static char *(*fstrstr)(const char *, const char *) = strstr;
71 static void xinitvisual();
74 appenditem(struct item *item, struct item **list, struct item **last)
77 (*last)->right = item;
94 n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">"));
95 /* calculate which items will begin the next page and previous page */
96 for (i = 0, next = curr; next; next = next->right)
97 if ((i += (lines > 0) ? bh : MIN(TEXTW(next->text), n)) > n)
99 for (i = 0, prev = curr; prev && prev->left; prev = prev->left)
100 if ((i += (lines > 0) ? bh : MIN(TEXTW(prev->left->text), n)) > n)
108 for (struct item *item = items; item && item->text; item++)
109 len = MAX(TEXTW(item->text), len);
118 XUngrabKey(dpy, AnyKey, AnyModifier, root);
119 for (i = 0; i < SchemeLast; i++)
127 cistrstr(const char *h, const char *n)
135 for (i = 0; n[i] && tolower((unsigned char)n[i]) ==
136 tolower((unsigned char)h[i]); ++i)
145 drawitem(struct item *item, int x, int y, int w)
148 drw_setscheme(drw, scheme[SchemeSel]);
150 drw_setscheme(drw, scheme[SchemeOut]);
152 drw_setscheme(drw, scheme[SchemeNorm]);
154 return drw_text(drw, x, y, w, bh, lrpad / 2, item->text, 0);
160 unsigned int numer = 0, denom = 0;
164 for (item = matchend; item && item->left; item = item->left)
167 for (item = items; item && item->text; item++)
169 snprintf(numbers, NUMBERSBUFSIZE, "%d/%d", numer, denom);
179 drw_setscheme(drw, scheme[SchemeNorm]);
180 drw_rect(drw, 0, 0, mw, mh, 1, 1);
182 if (prompt && *prompt) {
183 drw_setscheme(drw, scheme[SchemeSel]);
184 x = drw_text(drw, x, 0, promptw, bh, lrpad / 2, prompt, 0);
186 /* draw input field */
187 w = (lines > 0 || !matches) ? mw - x : inputw;
188 drw_setscheme(drw, scheme[SchemeNorm]);
189 drw_text(drw, x, 0, w, bh, lrpad / 2, text, 0);
191 curpos = TEXTW(text) - TEXTW(&text[cursor]);
192 if ((curpos += lrpad / 2 - 1) < w) {
193 drw_setscheme(drw, scheme[SchemeNorm]);
194 drw_rect(drw, x + curpos, 2, 2, bh - 4, 1, 0);
197 recalculatenumbers();
199 /* draw vertical list */
200 for (item = curr; item != next; item = item->right)
201 drawitem(item, x, y += bh, mw - x);
202 } else if (matches) {
203 /* draw horizontal list */
207 drw_setscheme(drw, scheme[SchemeNorm]);
208 drw_text(drw, x, 0, w, bh, lrpad / 2, "<", 0);
211 for (item = curr; item != next; item = item->right)
212 x = drawitem(item, x, 0, MIN(TEXTW(item->text), mw - x - TEXTW(">") - TEXTW(numbers)));
215 drw_setscheme(drw, scheme[SchemeNorm]);
216 drw_text(drw, mw - w - TEXTW(numbers), 0, w, bh, lrpad / 2, ">", 0);
219 drw_setscheme(drw, scheme[SchemeNorm]);
220 drw_text(drw, mw - TEXTW(numbers), 0, TEXTW(numbers), bh, lrpad / 2, numbers, 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");
262 static char **tokv = NULL;
265 char buf[sizeof text], *s;
267 size_t len, textsize;
268 struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
271 /* separate input text into tokens to be matched individually */
272 for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
273 if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
274 die("cannot realloc %u bytes:", tokn * sizeof *tokv);
275 len = tokc ? strlen(tokv[0]) : 0;
277 matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
278 textsize = strlen(text) + 1;
279 for (item = items; item && item->text; item++) {
280 for (i = 0; i < tokc; i++)
281 if (!fstrstr(item->text, tokv[i]))
283 if (i != tokc) /* not all tokens match */
285 /* exact matches go first, then prefixes, then substrings */
286 if (!tokc || !fstrncmp(text, item->text, textsize))
287 appenditem(item, &matches, &matchend);
288 else if (!fstrncmp(tokv[0], item->text, len))
289 appenditem(item, &lprefix, &prefixend);
291 appenditem(item, &lsubstr, &substrend);
295 matchend->right = lprefix;
296 lprefix->left = matchend;
299 matchend = prefixend;
303 matchend->right = lsubstr;
304 lsubstr->left = matchend;
307 matchend = substrend;
309 curr = sel = matches;
314 insert(const char *str, ssize_t n)
316 if (strlen(text) + n > sizeof text - 1)
318 /* move existing text out of the way, insert new text, and update cursor */
319 memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
321 memcpy(&text[cursor], str, n);
331 /* return location of next utf8 rune in the given direction (+1 or -1) */
332 for (n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc)
338 movewordedge(int dir)
340 if (dir < 0) { /* move cursor to the start of the word*/
341 while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
342 cursor = nextrune(-1);
343 while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
344 cursor = nextrune(-1);
345 } else { /* move cursor to the end of the word */
346 while (text[cursor] && strchr(worddelimiters, text[cursor]))
347 cursor = nextrune(+1);
348 while (text[cursor] && !strchr(worddelimiters, text[cursor]))
349 cursor = nextrune(+1);
354 keypress(XKeyEvent *ev)
361 len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
363 default: /* XLookupNone, XBufferOverflow */
372 if (ev->state & ControlMask) {
374 case XK_a: ksym = XK_Home; break;
375 case XK_b: ksym = XK_Left; break;
376 case XK_c: ksym = XK_Escape; break;
377 case XK_d: ksym = XK_Delete; break;
378 case XK_e: ksym = XK_End; break;
379 case XK_f: ksym = XK_Right; break;
380 case XK_g: ksym = XK_Escape; break;
381 case XK_h: ksym = XK_BackSpace; break;
382 case XK_i: ksym = XK_Tab; break;
383 case XK_j: /* fallthrough */
384 case XK_J: /* fallthrough */
385 case XK_m: /* fallthrough */
386 case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
387 case XK_n: ksym = XK_Down; break;
388 case XK_p: ksym = XK_Up; break;
390 case XK_k: /* delete right */
394 case XK_u: /* delete left */
395 insert(NULL, 0 - cursor);
397 case XK_w: /* delete word */
398 while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
399 insert(NULL, nextrune(-1) - cursor);
400 while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
401 insert(NULL, nextrune(-1) - cursor);
403 case XK_y: /* paste selection */
405 XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
406 utf8, utf8, win, CurrentTime);
425 } else if (ev->state & Mod1Mask) {
433 case XK_g: ksym = XK_Home; break;
434 case XK_G: ksym = XK_End; break;
435 case XK_h: ksym = XK_Up; break;
436 case XK_j: ksym = XK_Next; break;
437 case XK_k: ksym = XK_Prior; break;
438 case XK_l: ksym = XK_Down; break;
452 if (text[cursor] == '\0')
454 cursor = nextrune(+1);
459 insert(NULL, nextrune(-1) - cursor);
463 if (text[cursor] != '\0') {
464 cursor = strlen(text);
468 /* jump to end of list and position items in reverse */
473 while (next && (curr = curr->right))
483 if (sel == matches) {
487 sel = curr = matches;
492 if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
493 cursor = nextrune(-1);
501 if (sel && sel->left && (sel = sel->left)->right == curr) {
522 puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
523 if (!(ev->state & ControlMask)) {
532 if (text[cursor] != '\0') {
533 cursor = nextrune(+1);
541 if (sel && sel->right && (sel = sel->right) == next) {
549 strncpy(text, sel->text, sizeof text - 1);
550 text[sizeof text - 1] = '\0';
551 cursor = strlen(text);
568 /* we have been given the current selection, now insert it into input */
569 if (XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
570 utf8, &da, &di, &dl, &dl, (unsigned char **)&p)
572 insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
581 char buf[sizeof text], *p;
582 size_t i, imax = 0, size = 0;
583 unsigned int tmpmax = 0;
585 /* read each line from stdin and add it to the item list */
586 for (i = 0; fgets(buf, sizeof buf, stdin); i++) {
587 if (i + 1 >= size / sizeof *items)
588 if (!(items = realloc(items, (size += BUFSIZ))))
589 die("cannot realloc %u bytes:", size);
590 if ((p = strchr(buf, '\n')))
592 if (!(items[i].text = strdup(buf)))
593 die("cannot strdup %u bytes:", strlen(buf) + 1);
595 drw_font_getexts(drw->fonts, buf, strlen(buf), &tmpmax, NULL);
596 if (tmpmax > inputw) {
602 items[i].text = NULL;
603 inputw = items ? TEXTW(items[imax].text) : 0;
604 lines = MIN(lines, i);
612 while (!XNextEvent(dpy, &ev)) {
613 if (XFilterEvent(&ev, win))
617 if (ev.xdestroywindow.window != win)
622 if (ev.xexpose.count == 0)
623 drw_map(drw, win, 0, 0, mw, mh);
626 /* regrab focus from parent window */
627 if (ev.xfocus.window != win)
633 case SelectionNotify:
634 if (ev.xselection.property == utf8)
637 case VisibilityNotify:
638 if (ev.xvisibility.state != VisibilityUnobscured)
639 XRaiseWindow(dpy, win);
650 XSetWindowAttributes swa;
653 XWindowAttributes wa;
654 XClassHint ch = {"dmenu", "dmenu"};
656 XineramaScreenInfo *info;
658 int a, di, n, area = 0;
660 /* init appearance */
661 for (j = 0; j < SchemeLast; j++)
662 scheme[j] = drw_scm_create(drw, colors[j], alphas[i], 2);
664 clip = XInternAtom(dpy, "CLIPBOARD", False);
665 utf8 = XInternAtom(dpy, "UTF8_STRING", False);
667 /* calculate menu geometry */
668 bh = drw->fonts->h + 2;
669 lines = MAX(lines, 0);
670 mh = (lines + 1) * bh;
671 promptw = (prompt && *prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
674 if (parentwin == root && (info = XineramaQueryScreens(dpy, &n))) {
675 XGetInputFocus(dpy, &w, &di);
676 if (mon >= 0 && mon < n)
678 else if (w != root && w != PointerRoot && w != None) {
679 /* find top-level window containing current input focus */
681 if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
683 } while (w != root && w != pw);
684 /* find xinerama screen with which the window intersects most */
685 if (XGetWindowAttributes(dpy, pw, &wa))
686 for (j = 0; j < n; j++)
687 if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
692 /* no focused window is on screen, so use pointer location instead */
693 if (mon < 0 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
694 for (i = 0; i < n; i++)
695 if (INTERSECT(x, y, 1, 1, info[i]) != 0)
699 mw = MIN(MAX(max_textw() + promptw, min_width), info[i].width);
700 x = info[i].x_org + ((info[i].width - mw) / 2);
701 y = info[i].y_org + ((info[i].height - mh) / 2);
704 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
711 if (!XGetWindowAttributes(dpy, parentwin, &wa))
712 die("could not get embedding window attributes: 0x%lx",
716 mw = MIN(MAX(max_textw() + promptw, min_width), wa.width);
717 x = (wa.width - mw) / 2;
718 y = (wa.height - mh) / 2;
721 y = topbar ? 0 : wa.height - mh;
725 inputw = MIN(inputw, mw/3);
728 /* create menu window */
729 swa.override_redirect = True;
730 swa.background_pixel = 0;
731 swa.border_pixel = 0;
733 swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
734 win = XCreateWindow(dpy, parentwin, x, y, mw, mh, CWBorderWidth,
735 depth, CopyFromParent, visual,
736 CWOverrideRedirect | CWBackPixel | CWBorderPixel | CWColormap | CWEventMask, &swa);
737 XSetClassHint(dpy, win, &ch);
741 if ((xim = XOpenIM(dpy, NULL, NULL, NULL)) == NULL)
742 die("XOpenIM failed: could not open input device");
744 xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
745 XNClientWindow, win, XNFocusWindow, win, NULL);
747 XMapRaised(dpy, win);
749 XSelectInput(dpy, parentwin, FocusChangeMask | SubstructureNotifyMask);
750 if (XQueryTree(dpy, parentwin, &dw, &w, &dws, &du) && dws) {
751 for (i = 0; i < du && dws[i] != win; ++i)
752 XSelectInput(dpy, dws[i], FocusChangeMask);
757 drw_resize(drw, mw, mh);
764 fputs("usage: dmenu [-bfiv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
765 " [-nb color] [-nf color] [-sb color] [-sf color] [-w windowid]\n", stderr);
770 main(int argc, char *argv[])
772 XWindowAttributes wa;
775 for (i = 1; i < argc; i++)
776 /* these options take no arguments */
777 if (!strcmp(argv[i], "-v")) { /* prints version information */
778 puts("dmenu-"VERSION);
780 } else if (!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
782 else if (!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
784 else if (!strcmp(argv[i], "-c")) /* centers dmenu on screen */
786 else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
787 fstrncmp = strncasecmp;
789 } else if (i + 1 == argc)
791 /* these options take one argument */
792 else if (!strcmp(argv[i], "-l")) /* number of lines in vertical list */
793 lines = atoi(argv[++i]);
794 else if (!strcmp(argv[i], "-m"))
795 mon = atoi(argv[++i]);
796 else if (!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
798 else if (!strcmp(argv[i], "-fn")) /* font or font set */
799 fonts[0] = argv[++i];
800 else if (!strcmp(argv[i], "-nb")) /* normal background color */
801 colors[SchemeNorm][ColBg] = argv[++i];
802 else if (!strcmp(argv[i], "-nf")) /* normal foreground color */
803 colors[SchemeNorm][ColFg] = argv[++i];
804 else if (!strcmp(argv[i], "-sb")) /* selected background color */
805 colors[SchemeSel][ColBg] = argv[++i];
806 else if (!strcmp(argv[i], "-sf")) /* selected foreground color */
807 colors[SchemeSel][ColFg] = argv[++i];
808 else if (!strcmp(argv[i], "-w")) /* embedding window id */
813 if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
814 fputs("warning: no locale support\n", stderr);
815 if (!(dpy = XOpenDisplay(NULL)))
816 die("cannot open display");
817 screen = DefaultScreen(dpy);
818 root = RootWindow(dpy, screen);
819 if (!embed || !(parentwin = strtol(embed, NULL, 0)))
821 if (!XGetWindowAttributes(dpy, parentwin, &wa))
822 die("could not get embedding window attributes: 0x%lx",
825 drw = drw_create(dpy, screen, root, wa.width, wa.height, visual, depth, cmap);
826 if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
827 die("no fonts could be loaded.");
828 lrpad = drw->fonts->h;
831 if (pledge("stdio rpath", NULL) == -1)
835 if (fast && !isatty(0)) {
845 return 1; /* unreachable */
852 XRenderPictFormat *fmt;
861 long masks = VisualScreenMask | VisualDepthMask | VisualClassMask;
863 infos = XGetVisualInfo(dpy, masks, &tpl, &nitems);
865 for(i = 0; i < nitems; i ++) {
866 fmt = XRenderFindVisualFormat(dpy, infos[i].visual);
867 if (fmt->type == PictTypeDirect && fmt->direct.alphaMask) {
868 visual = infos[i].visual;
869 depth = infos[i].depth;
870 cmap = XCreateColormap(dpy, root, visual, AllocNone);
879 visual = DefaultVisual(dpy, screen);
880 depth = DefaultDepth(dpy, screen);
881 cmap = DefaultColormap(dpy, screen);