1 /* See LICENSE file for copyright and license details. */
10 #include <X11/Xutil.h>
12 #include <X11/extensions/Xinerama.h>
16 #define INTERSECT(x,y,w,h,r) (MAX(0, MIN((x)+(w),(r).x_org+(r).width) - MAX((x),(r).x_org)) \
17 * MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
18 #define MIN(a,b) ((a) < (b) ? (a) : (b))
19 #define MAX(a,b) ((a) > (b) ? (a) : (b))
21 typedef struct Item Item;
28 static void appenditem(Item *item, Item **list, Item **last);
29 static void calcoffsets(void);
30 static char *cistrstr(const char *s, const char *sub);
31 static void drawmenu(void);
32 static void grabkeyboard(void);
33 static void insert(const char *str, ssize_t n);
34 static void keypress(XKeyEvent *ev);
35 static void match(void);
36 static size_t nextrune(int inc);
37 static void paste(void);
38 static void readstdin(void);
39 static void run(void);
40 static void setup(void);
41 static void usage(void);
43 static char text[BUFSIZ] = "";
44 static int bh, mw, mh;
45 static int inputw, promptw;
46 static size_t cursor = 0;
47 static const char *font = NULL;
48 static const char *prompt = NULL;
49 static const char *normbgcolor = "#222222";
50 static const char *normfgcolor = "#bbbbbb";
51 static const char *selbgcolor = "#005577";
52 static const char *selfgcolor = "#eeeeee";
53 static const char *outbgcolor = "#00ffff";
54 static const char *outfgcolor = "#000000";
55 static unsigned int lines = 0;
56 static unsigned long normcol[ColLast];
57 static unsigned long selcol[ColLast];
58 static unsigned long outcol[ColLast];
59 static Atom clip, utf8;
60 static Bool topbar = True;
62 static Item *items = NULL;
63 static Item *matches, *matchend;
64 static Item *prev, *curr, *next, *sel;
68 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
69 static char *(*fstrstr)(const char *, const char *) = strstr;
72 main(int argc, char *argv[]) {
76 for(i = 1; i < argc; i++)
77 /* these options take no arguments */
78 if(!strcmp(argv[i], "-v")) { /* prints version information */
79 puts("dmenu-"VERSION", © 2006-2012 dmenu engineers, see LICENSE for details");
82 else if(!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
84 else if(!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
86 else if(!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
87 fstrncmp = strncasecmp;
92 /* these options take one argument */
93 else if(!strcmp(argv[i], "-l")) /* number of lines in vertical list */
94 lines = atoi(argv[++i]);
95 else if(!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
97 else if(!strcmp(argv[i], "-fn")) /* font or font set */
99 else if(!strcmp(argv[i], "-nb")) /* normal background color */
100 normbgcolor = argv[++i];
101 else if(!strcmp(argv[i], "-nf")) /* normal foreground color */
102 normfgcolor = argv[++i];
103 else if(!strcmp(argv[i], "-sb")) /* selected background color */
104 selbgcolor = argv[++i];
105 else if(!strcmp(argv[i], "-sf")) /* selected foreground color */
106 selfgcolor = argv[++i];
124 return 1; /* unreachable */
128 appenditem(Item *item, Item **list, Item **last) {
130 (*last)->right = item;
146 n = mw - (promptw + inputw + textw(dc, "<") + textw(dc, ">"));
147 /* calculate which items will begin the next page and previous page */
148 for(i = 0, next = curr; next; next = next->right)
149 if((i += (lines > 0) ? bh : MIN(textw(dc, next->text), n)) > n)
151 for(i = 0, prev = curr; prev && prev->left; prev = prev->left)
152 if((i += (lines > 0) ? bh : MIN(textw(dc, prev->left->text), n)) > n)
157 cistrstr(const char *s, const char *sub) {
160 for(len = strlen(sub); *s; s++)
161 if(!strncasecmp(s, sub, len))
174 drawrect(dc, 0, 0, mw, mh, True, BG(dc, normcol));
176 if(prompt && *prompt) {
178 drawtext(dc, prompt, selcol);
181 /* draw input field */
182 dc->w = (lines > 0 || !matches) ? mw - dc->x : inputw;
183 drawtext(dc, text, normcol);
184 if((curpos = textnw(dc, text, cursor) + dc->h/2 - 2) < dc->w)
185 drawrect(dc, curpos, 2, 1, dc->h - 4, True, FG(dc, normcol));
188 /* draw vertical list */
190 for(item = curr; item != next; item = item->right) {
192 drawtext(dc, item->text, (item == sel) ? selcol :
193 (item->out) ? outcol : normcol);
197 /* draw horizontal list */
199 dc->w = textw(dc, "<");
201 drawtext(dc, "<", normcol);
202 for(item = curr; item != next; item = item->right) {
204 dc->w = MIN(textw(dc, item->text), mw - dc->x - textw(dc, ">"));
205 drawtext(dc, item->text, (item == sel) ? selcol :
206 (item->out) ? outcol : normcol);
208 dc->w = textw(dc, ">");
211 drawtext(dc, ">", normcol);
213 mapdc(dc, win, mw, mh);
220 /* try to grab keyboard, we may have to wait for another process to ungrab */
221 for(i = 0; i < 1000; i++) {
222 if(XGrabKeyboard(dc->dpy, DefaultRootWindow(dc->dpy), True,
223 GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
227 eprintf("cannot grab keyboard\n");
231 insert(const char *str, ssize_t n) {
232 if(strlen(text) + n > sizeof text - 1)
234 /* move existing text out of the way, insert new text, and update cursor */
235 memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
237 memcpy(&text[cursor], str, n);
243 keypress(XKeyEvent *ev) {
246 KeySym ksym = NoSymbol;
249 len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
250 if(status == XBufferOverflow)
252 if(ev->state & ControlMask)
254 case XK_a: ksym = XK_Home; break;
255 case XK_b: ksym = XK_Left; break;
256 case XK_c: ksym = XK_Escape; break;
257 case XK_d: ksym = XK_Delete; break;
258 case XK_e: ksym = XK_End; break;
259 case XK_f: ksym = XK_Right; break;
260 case XK_g: ksym = XK_Escape; break;
261 case XK_h: ksym = XK_BackSpace; break;
262 case XK_i: ksym = XK_Tab; break;
263 case XK_j: /* fallthrough */
264 case XK_J: ksym = XK_Return; break;
265 case XK_m: /* fallthrough */
266 case XK_M: ksym = XK_Return; break;
267 case XK_n: ksym = XK_Down; break;
268 case XK_p: ksym = XK_Up; break;
270 case XK_k: /* delete right */
274 case XK_u: /* delete left */
275 insert(NULL, 0 - cursor);
277 case XK_w: /* delete word */
278 while(cursor > 0 && text[nextrune(-1)] == ' ')
279 insert(NULL, nextrune(-1) - cursor);
280 while(cursor > 0 && text[nextrune(-1)] != ' ')
281 insert(NULL, nextrune(-1) - cursor);
283 case XK_y: /* paste selection */
284 XConvertSelection(dc->dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
285 utf8, utf8, win, CurrentTime);
293 else if(ev->state & Mod1Mask)
295 case XK_g: ksym = XK_Home; break;
296 case XK_G: ksym = XK_End; break;
297 case XK_h: ksym = XK_Up; break;
298 case XK_j: ksym = XK_Next; break;
299 case XK_k: ksym = XK_Prior; break;
300 case XK_l: ksym = XK_Down; break;
310 if(text[cursor] == '\0')
312 cursor = nextrune(+1);
317 insert(NULL, nextrune(-1) - cursor);
320 if(text[cursor] != '\0') {
321 cursor = strlen(text);
325 /* jump to end of list and position items in reverse */
330 while(next && (curr = curr->right))
342 sel = curr = matches;
346 if(cursor > 0 && (!sel || !sel->left || lines > 0)) {
347 cursor = nextrune(-1);
354 if(sel && sel->left && (sel = sel->left)->right == curr) {
373 puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
374 if(!(ev->state & ControlMask))
379 if(text[cursor] != '\0') {
380 cursor = nextrune(+1);
387 if(sel && sel->right && (sel = sel->right) == next) {
395 strncpy(text, sel->text, sizeof text);
396 cursor = strlen(text);
405 static char **tokv = NULL;
408 char buf[sizeof text], *s;
411 Item *item, *lprefix, *lsubstr, *prefixend, *substrend;
414 /* separate input text into tokens to be matched individually */
415 for(s = strtok(buf, " "); s; tokv[tokc-1] = s, s = strtok(NULL, " "))
416 if(++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
417 eprintf("cannot realloc %u bytes\n", tokn * sizeof *tokv);
418 len = tokc ? strlen(tokv[0]) : 0;
420 matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
421 for(item = items; item && item->text; item++) {
422 for(i = 0; i < tokc; i++)
423 if(!fstrstr(item->text, tokv[i]))
425 if(i != tokc) /* not all tokens match */
427 /* exact matches go first, then prefixes, then substrings */
428 if(!tokc || !fstrncmp(tokv[0], item->text, len+1))
429 appenditem(item, &matches, &matchend);
430 else if(!fstrncmp(tokv[0], item->text, len))
431 appenditem(item, &lprefix, &prefixend);
433 appenditem(item, &lsubstr, &substrend);
437 matchend->right = lprefix;
438 lprefix->left = matchend;
442 matchend = prefixend;
446 matchend->right = lsubstr;
447 lsubstr->left = matchend;
451 matchend = substrend;
453 curr = sel = matches;
461 /* return location of next utf8 rune in the given direction (+1 or -1) */
462 for(n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc);
473 /* we have been given the current selection, now insert it into input */
474 XGetWindowProperty(dc->dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
475 utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
476 insert(p, (q = strchr(p, '\n')) ? q-p : (ssize_t)strlen(p));
483 char buf[sizeof text], *p, *maxstr = NULL;
484 size_t i, max = 0, size = 0;
486 /* read each line from stdin and add it to the item list */
487 for(i = 0; fgets(buf, sizeof buf, stdin); i++) {
488 if(i+1 >= size / sizeof *items)
489 if(!(items = realloc(items, (size += BUFSIZ))))
490 eprintf("cannot realloc %u bytes:", size);
491 if((p = strchr(buf, '\n')))
493 if(!(items[i].text = strdup(buf)))
494 eprintf("cannot strdup %u bytes:", strlen(buf)+1);
495 items[i].out = False;
496 if(strlen(items[i].text) > max)
497 max = strlen(maxstr = items[i].text);
500 items[i].text = NULL;
501 inputw = maxstr ? textw(dc, maxstr) : 0;
502 lines = MIN(lines, i);
509 while(!XNextEvent(dc->dpy, &ev)) {
510 if(XFilterEvent(&ev, win))
514 if(ev.xexpose.count == 0)
515 mapdc(dc, win, mw, mh);
520 case SelectionNotify:
521 if(ev.xselection.property == utf8)
524 case VisibilityNotify:
525 if(ev.xvisibility.state != VisibilityUnobscured)
526 XRaiseWindow(dc->dpy, win);
534 int x, y, screen = DefaultScreen(dc->dpy);
535 Window root = RootWindow(dc->dpy, screen);
536 XSetWindowAttributes swa;
540 XineramaScreenInfo *info;
543 normcol[ColBG] = getcolor(dc, normbgcolor);
544 normcol[ColFG] = getcolor(dc, normfgcolor);
545 selcol[ColBG] = getcolor(dc, selbgcolor);
546 selcol[ColFG] = getcolor(dc, selfgcolor);
547 outcol[ColBG] = getcolor(dc, outbgcolor);
548 outcol[ColFG] = getcolor(dc, outfgcolor);
550 clip = XInternAtom(dc->dpy, "CLIPBOARD", False);
551 utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);
553 /* calculate menu geometry */
554 bh = dc->font.height + 2;
555 lines = MAX(lines, 0);
556 mh = (lines + 1) * bh;
558 if((info = XineramaQueryScreens(dc->dpy, &n))) {
559 int a, j, di, i = 0, area = 0;
561 Window w, pw, dw, *dws;
562 XWindowAttributes wa;
564 XGetInputFocus(dc->dpy, &w, &di);
565 if(w != root && w != PointerRoot && w != None) {
566 /* find top-level window containing current input focus */
568 if(XQueryTree(dc->dpy, (pw = w), &dw, &w, &dws, &du) && dws)
570 } while(w != root && w != pw);
571 /* find xinerama screen with which the window intersects most */
572 if(XGetWindowAttributes(dc->dpy, pw, &wa))
573 for(j = 0; j < n; j++)
574 if((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
579 /* no focused window is on screen, so use pointer location instead */
580 if(!area && XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
581 for(i = 0; i < n; i++)
582 if(INTERSECT(x, y, 1, 1, info[i]))
586 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
594 y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - mh;
595 mw = DisplayWidth(dc->dpy, screen);
597 promptw = (prompt && *prompt) ? textw(dc, prompt) : 0;
598 inputw = MIN(inputw, mw/3);
601 /* create menu window */
602 swa.override_redirect = True;
603 swa.background_pixel = normcol[ColBG];
604 swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
605 win = XCreateWindow(dc->dpy, root, x, y, mw, mh, 0,
606 DefaultDepth(dc->dpy, screen), CopyFromParent,
607 DefaultVisual(dc->dpy, screen),
608 CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
610 /* open input methods */
611 xim = XOpenIM(dc->dpy, NULL, NULL, NULL);
612 xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
613 XNClientWindow, win, XNFocusWindow, win, NULL);
615 XMapRaised(dc->dpy, win);
616 resizedc(dc, mw, mh);
622 fputs("usage: dmenu [-b] [-f] [-i] [-l lines] [-p prompt] [-fn font]\n"
623 " [-nb color] [-nf color] [-sb color] [-sf color] [-v]\n", stderr);