1 /* See LICENSE file for copyright and license details. */
10 #include <X11/Xatom.h>
11 #include <X11/Xutil.h>
13 #include <X11/extensions/Xinerama.h>
15 #include <X11/Xft/Xft.h>
21 #define INTERSECT(x,y,w,h,r) (MAX(0, MIN((x)+(w),(r).x_org+(r).width) - MAX((x),(r).x_org)) \
22 * MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
23 #define LENGTH(X) (sizeof X / sizeof X[0])
24 #define TEXTNW(X,N) (drw_font_getexts_width(drw->fonts[0], (X), (N)))
25 #define TEXTW(X) (drw_text(drw, 0, 0, 0, 0, (X), 0) + drw->fonts[0]->h)
28 enum { SchemeNorm, SchemeSel, SchemeOut, SchemeLast }; /* color schemes */
30 typedef struct Item Item;
37 static void appenditem(Item *item, Item **list, Item **last);
38 static void calcoffsets(void);
39 static char *cistrstr(const char *s, const char *sub);
40 static void cleanup(void);
41 static void drawmenu(void);
42 static void grabkeyboard(void);
43 static void insert(const char *str, ssize_t n);
44 static void keypress(XKeyEvent *ev);
45 static void match(void);
46 static size_t nextrune(int inc);
47 static void paste(void);
48 static void readstdin(void);
49 static void run(void);
50 static void setup(void);
51 static void usage(void);
53 static char text[BUFSIZ] = "";
54 static int bh, mw, mh;
55 static int inputw, promptw;
56 static size_t cursor = 0;
57 static Atom clip, utf8;
58 static Item *items = NULL;
59 static Item *matches, *matchend;
60 static Item *prev, *curr, *next, *sel;
65 static ClrScheme scheme[SchemeLast];
70 static int sw, sh; /* X display screen geometry width, height */
74 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
75 static char *(*fstrstr)(const char *, const char *) = strstr;
78 main(int argc, char *argv[]) {
82 for(i = 1; i < argc; i++)
83 /* these options take no arguments */
84 if(!strcmp(argv[i], "-v")) { /* prints version information */
85 puts("dmenu-"VERSION", © 2006-2015 dmenu engineers, see LICENSE for details");
88 else if(!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
90 else if(!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
92 else if(!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
93 fstrncmp = strncasecmp;
98 /* these options take one argument */
99 else if(!strcmp(argv[i], "-l")) /* number of lines in vertical list */
100 lines = atoi(argv[++i]);
101 else if(!strcmp(argv[i], "-m"))
102 mon = atoi(argv[++i]);
103 else if(!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
105 else if(!strcmp(argv[i], "-fn")) /* font or font set */
106 fonts[0] = argv[++i];
107 else if(!strcmp(argv[i], "-nb")) /* normal background color */
108 normbgcolor = argv[++i];
109 else if(!strcmp(argv[i], "-nf")) /* normal foreground color */
110 normfgcolor = argv[++i];
111 else if(!strcmp(argv[i], "-sb")) /* selected background color */
112 selbgcolor = argv[++i];
113 else if(!strcmp(argv[i], "-sf")) /* selected foreground color */
114 selfgcolor = argv[++i];
118 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
119 fputs("warning: no locale support\n", stderr);
120 if(!(dpy = XOpenDisplay(NULL)))
121 die("dwm: cannot open display\n");
122 screen = DefaultScreen(dpy);
123 root = RootWindow(dpy, screen);
124 sw = DisplayWidth(dpy, screen);
125 sh = DisplayHeight(dpy, screen);
126 drw = drw_create(dpy, screen, root, sw, sh);
127 drw_load_fonts(drw, fonts, LENGTH(fonts));
129 die("No fonts could be loaded.\n");
130 drw_setscheme(drw, &scheme[SchemeNorm]);
143 return 1; /* unreachable */
147 appenditem(Item *item, Item **list, Item **last) {
149 (*last)->right = item;
165 n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">"));
166 /* calculate which items will begin the next page and previous page */
167 for(i = 0, next = curr; next; next = next->right)
168 if((i += (lines > 0) ? bh : MIN(TEXTW(next->text), n)) > n)
170 for(i = 0, prev = curr; prev && prev->left; prev = prev->left)
171 if((i += (lines > 0) ? bh : MIN(TEXTW(prev->left->text), n)) > n)
177 XUngrabKey(dpy, AnyKey, AnyModifier, root);
178 drw_clr_free(scheme[SchemeNorm].bg);
179 drw_clr_free(scheme[SchemeNorm].fg);
180 drw_clr_free(scheme[SchemeSel].fg);
181 drw_clr_free(scheme[SchemeSel].bg);
182 drw_clr_free(scheme[SchemeOut].fg);
183 drw_clr_free(scheme[SchemeOut].bg);
190 cistrstr(const char *s, const char *sub) {
193 for(len = strlen(sub); *s; s++)
194 if(!strncasecmp(s, sub, len))
203 int x = 0, y = 0, h = bh, w;
205 drw_setscheme(drw, &scheme[SchemeNorm]);
206 drw_rect(drw, 0, 0, mw, mh, True, 1, 1);
208 if(prompt && *prompt) {
209 drw_setscheme(drw, &scheme[SchemeSel]);
210 drw_text(drw, x, 0, promptw, bh, prompt, 1);
213 /* draw input field */
214 w = (lines > 0 || !matches) ? mw - x : inputw;
215 drw_setscheme(drw, &scheme[SchemeNorm]);
216 drw_text(drw, x, 0, w, bh, text, 0);
218 if((curpos = TEXTNW(text, cursor) + bh/2 - 2) < w) {
219 drw_setscheme(drw, &scheme[SchemeNorm]);
220 drw_rect(drw, x + curpos + 2, 2, 1, bh - 4, 1, 1, 0);
224 /* draw vertical list */
226 for(item = curr; item != next; item = item->right) {
229 drw_setscheme(drw, &scheme[SchemeSel]);
231 drw_setscheme(drw, &scheme[SchemeOut]);
233 drw_setscheme(drw, &scheme[SchemeNorm]);
235 drw_text(drw, x, y, w, bh, item->text, 0);
239 /* draw horizontal list */
243 drw_setscheme(drw, &scheme[SchemeNorm]);
244 drw_text(drw, x, 0, w, bh, "<", 0);
246 for(item = curr; item != next; item = item->right) {
248 w = MIN(TEXTW(item->text), mw - x - TEXTW(">"));
251 drw_setscheme(drw, &scheme[SchemeSel]);
253 drw_setscheme(drw, &scheme[SchemeOut]);
255 drw_setscheme(drw, &scheme[SchemeNorm]);
256 drw_text(drw, x, 0, w, bh, item->text, 0);
261 drw_setscheme(drw, &scheme[SchemeNorm]);
262 drw_text(drw, x, 0, w, bh, ">", 0);
265 drw_map(drw, win, 0, 0, mw, mh);
272 /* try to grab keyboard, we may have to wait for another process to ungrab */
273 for(i = 0; i < 1000; i++) {
274 if(XGrabKeyboard(dpy, DefaultRootWindow(dpy), True,
275 GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
279 die("cannot grab keyboard\n");
283 insert(const char *str, ssize_t n) {
284 if(strlen(text) + n > sizeof text - 1)
286 /* move existing text out of the way, insert new text, and update cursor */
287 memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
289 memcpy(&text[cursor], str, n);
295 keypress(XKeyEvent *ev) {
298 KeySym ksym = NoSymbol;
301 len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
302 if(status == XBufferOverflow)
304 if(ev->state & ControlMask)
306 case XK_a: ksym = XK_Home; break;
307 case XK_b: ksym = XK_Left; break;
308 case XK_c: ksym = XK_Escape; break;
309 case XK_d: ksym = XK_Delete; break;
310 case XK_e: ksym = XK_End; break;
311 case XK_f: ksym = XK_Right; break;
312 case XK_g: ksym = XK_Escape; break;
313 case XK_h: ksym = XK_BackSpace; break;
314 case XK_i: ksym = XK_Tab; break;
315 case XK_j: /* fallthrough */
316 case XK_J: /* fallthrough */
317 case XK_m: /* fallthrough */
318 case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
319 case XK_n: ksym = XK_Down; break;
320 case XK_p: ksym = XK_Up; break;
322 case XK_k: /* delete right */
326 case XK_u: /* delete left */
327 insert(NULL, 0 - cursor);
329 case XK_w: /* delete word */
330 while(cursor > 0 && text[nextrune(-1)] == ' ')
331 insert(NULL, nextrune(-1) - cursor);
332 while(cursor > 0 && text[nextrune(-1)] != ' ')
333 insert(NULL, nextrune(-1) - cursor);
335 case XK_y: /* paste selection */
336 XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
337 utf8, utf8, win, CurrentTime);
348 else if(ev->state & Mod1Mask)
350 case XK_g: ksym = XK_Home; break;
351 case XK_G: ksym = XK_End; break;
352 case XK_h: ksym = XK_Up; break;
353 case XK_j: ksym = XK_Next; break;
354 case XK_k: ksym = XK_Prior; break;
355 case XK_l: ksym = XK_Down; break;
365 if(text[cursor] == '\0')
367 cursor = nextrune(+1);
372 insert(NULL, nextrune(-1) - cursor);
375 if(text[cursor] != '\0') {
376 cursor = strlen(text);
380 /* jump to end of list and position items in reverse */
385 while(next && (curr = curr->right))
398 sel = curr = matches;
402 if(cursor > 0 && (!sel || !sel->left || lines > 0)) {
403 cursor = nextrune(-1);
410 if(sel && sel->left && (sel = sel->left)->right == curr) {
429 puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
430 if(!(ev->state & ControlMask)) {
438 if(text[cursor] != '\0') {
439 cursor = nextrune(+1);
446 if(sel && sel->right && (sel = sel->right) == next) {
454 strncpy(text, sel->text, sizeof text - 1);
455 text[sizeof text - 1] = '\0';
456 cursor = strlen(text);
465 static char **tokv = NULL;
468 char buf[sizeof text], *s;
471 Item *item, *lprefix, *lsubstr, *prefixend, *substrend;
474 /* separate input text into tokens to be matched individually */
475 for(s = strtok(buf, " "); s; tokv[tokc-1] = s, s = strtok(NULL, " "))
476 if(++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
477 die("cannot realloc %u bytes\n", tokn * sizeof *tokv);
478 len = tokc ? strlen(tokv[0]) : 0;
480 matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
481 for(item = items; item && item->text; item++) {
482 for(i = 0; i < tokc; i++)
483 if(!fstrstr(item->text, tokv[i]))
485 if(i != tokc) /* not all tokens match */
487 /* exact matches go first, then prefixes, then substrings */
488 if(!tokc || !fstrncmp(tokv[0], item->text, len+1))
489 appenditem(item, &matches, &matchend);
490 else if(!fstrncmp(tokv[0], item->text, len))
491 appenditem(item, &lprefix, &prefixend);
493 appenditem(item, &lsubstr, &substrend);
497 matchend->right = lprefix;
498 lprefix->left = matchend;
502 matchend = prefixend;
506 matchend->right = lsubstr;
507 lsubstr->left = matchend;
511 matchend = substrend;
513 curr = sel = matches;
521 /* return location of next utf8 rune in the given direction (+1 or -1) */
522 for(n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc);
533 /* we have been given the current selection, now insert it into input */
534 XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
535 utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
536 insert(p, (q = strchr(p, '\n')) ? q-p : (ssize_t)strlen(p));
543 char buf[sizeof text], *p, *maxstr = NULL;
544 size_t i, max = 0, size = 0;
546 /* read each line from stdin and add it to the item list */
547 for(i = 0; fgets(buf, sizeof buf, stdin); i++) {
548 if(i+1 >= size / sizeof *items)
549 if(!(items = realloc(items, (size += BUFSIZ))))
550 die("cannot realloc %u bytes:", size);
551 if((p = strchr(buf, '\n')))
553 if(!(items[i].text = strdup(buf)))
554 die("cannot strdup %u bytes:", strlen(buf)+1);
555 items[i].out = False;
556 if(strlen(items[i].text) > max)
557 max = strlen(maxstr = items[i].text);
560 items[i].text = NULL;
561 inputw = maxstr ? TEXTW(maxstr) : 0;
562 lines = MIN(lines, i);
569 while(!XNextEvent(dpy, &ev)) {
570 if(XFilterEvent(&ev, win))
574 if(ev.xexpose.count == 0)
575 drw_map(drw, win, 0, 0, mw, mh);
580 case SelectionNotify:
581 if(ev.xselection.property == utf8)
584 case VisibilityNotify:
585 if(ev.xvisibility.state != VisibilityUnobscured)
586 XRaiseWindow(dpy, win);
595 XSetWindowAttributes swa;
598 XineramaScreenInfo *info;
599 Window w, pw, dw, *dws;
600 XWindowAttributes wa;
601 int a, j, di, n, i = 0, area = 0;
605 /* init appearance */
606 scheme[SchemeNorm].bg = drw_clr_create(drw, normbgcolor);
607 scheme[SchemeNorm].fg = drw_clr_create(drw, normfgcolor);
608 scheme[SchemeSel].bg = drw_clr_create(drw, selbgcolor);
609 scheme[SchemeSel].fg = drw_clr_create(drw, selfgcolor);
610 scheme[SchemeOut].bg = drw_clr_create(drw, outbgcolor);
611 scheme[SchemeOut].fg = drw_clr_create(drw, outfgcolor);
613 clip = XInternAtom(dpy, "CLIPBOARD", False);
614 utf8 = XInternAtom(dpy, "UTF8_STRING", False);
616 /* calculate menu geometry */
617 bh = drw->fonts[0]->h + 2;
618 lines = MAX(lines, 0);
619 mh = (lines + 1) * bh;
621 if((info = XineramaQueryScreens(dpy, &n))) {
622 XGetInputFocus(dpy, &w, &di);
623 if(mon != -1 && mon < n)
625 if(!i && w != root && w != PointerRoot && w != None) {
626 /* find top-level window containing current input focus */
628 if(XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
630 } while(w != root && w != pw);
631 /* find xinerama screen with which the window intersects most */
632 if(XGetWindowAttributes(dpy, pw, &wa))
633 for(j = 0; j < n; j++)
634 if((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
639 /* no focused window is on screen, so use pointer location instead */
640 if(mon == -1 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
641 for(i = 0; i < n; i++)
642 if(INTERSECT(x, y, 1, 1, info[i]))
646 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
654 y = topbar ? 0 : sh - mh;
657 promptw = (prompt && *prompt) ? TEXTW(prompt) : 0;
658 inputw = MIN(inputw, mw/3);
661 /* create menu window */
662 swa.override_redirect = True;
663 swa.background_pixel = scheme[SchemeNorm].bg->pix;
664 swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
665 win = XCreateWindow(dpy, root, x, y, mw, mh, 0,
666 DefaultDepth(dpy, screen), CopyFromParent,
667 DefaultVisual(dpy, screen),
668 CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
670 /* open input methods */
671 xim = XOpenIM(dpy, NULL, NULL, NULL);
672 xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
673 XNClientWindow, win, XNFocusWindow, win, NULL);
675 XMapRaised(dpy, win);
676 drw_resize(drw, mw, mh);
682 fputs("usage: dmenu [-b] [-f] [-i] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
683 " [-nb color] [-nf color] [-sb color] [-sf color] [-v]\n", stderr);