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 unsigned long normcol[ColLast];
48 static unsigned long selcol[ColLast];
49 static unsigned long outcol[ColLast];
50 static Atom clip, utf8;
52 static Item *items = NULL;
53 static Item *matches, *matchend;
54 static Item *prev, *curr, *next, *sel;
61 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
62 static char *(*fstrstr)(const char *, const char *) = strstr;
65 main(int argc, char *argv[]) {
69 for(i = 1; i < argc; i++)
70 /* these options take no arguments */
71 if(!strcmp(argv[i], "-v")) { /* prints version information */
72 puts("dmenu-"VERSION", © 2006-2012 dmenu engineers, see LICENSE for details");
75 else if(!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
77 else if(!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
79 else if(!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
80 fstrncmp = strncasecmp;
85 /* these options take one argument */
86 else if(!strcmp(argv[i], "-l")) /* number of lines in vertical list */
87 lines = atoi(argv[++i]);
88 else if(!strcmp(argv[i], "-m"))
89 mon = atoi(argv[++i]);
90 else if(!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
92 else if(!strcmp(argv[i], "-fn")) /* font or font set */
94 else if(!strcmp(argv[i], "-nb")) /* normal background color */
95 normbgcolor = argv[++i];
96 else if(!strcmp(argv[i], "-nf")) /* normal foreground color */
97 normfgcolor = argv[++i];
98 else if(!strcmp(argv[i], "-sb")) /* selected background color */
99 selbgcolor = argv[++i];
100 else if(!strcmp(argv[i], "-sf")) /* selected foreground color */
101 selfgcolor = argv[++i];
119 return 1; /* unreachable */
123 appenditem(Item *item, Item **list, Item **last) {
125 (*last)->right = item;
141 n = mw - (promptw + inputw + textw(dc, "<") + textw(dc, ">"));
142 /* calculate which items will begin the next page and previous page */
143 for(i = 0, next = curr; next; next = next->right)
144 if((i += (lines > 0) ? bh : MIN(textw(dc, next->text), n)) > n)
146 for(i = 0, prev = curr; prev && prev->left; prev = prev->left)
147 if((i += (lines > 0) ? bh : MIN(textw(dc, prev->left->text), n)) > n)
152 cistrstr(const char *s, const char *sub) {
155 for(len = strlen(sub); *s; s++)
156 if(!strncasecmp(s, sub, len))
169 drawrect(dc, 0, 0, mw, mh, True, BG(dc, normcol));
171 if(prompt && *prompt) {
173 drawtext(dc, prompt, selcol);
176 /* draw input field */
177 dc->w = (lines > 0 || !matches) ? mw - dc->x : inputw;
178 drawtext(dc, text, normcol);
179 if((curpos = textnw(dc, text, cursor) + dc->h/2 - 2) < dc->w)
180 drawrect(dc, curpos, 2, 1, dc->h - 4, True, FG(dc, normcol));
183 /* draw vertical list */
185 for(item = curr; item != next; item = item->right) {
187 drawtext(dc, item->text, (item == sel) ? selcol :
188 (item->out) ? outcol : normcol);
192 /* draw horizontal list */
194 dc->w = textw(dc, "<");
196 drawtext(dc, "<", normcol);
197 for(item = curr; item != next; item = item->right) {
199 dc->w = MIN(textw(dc, item->text), mw - dc->x - textw(dc, ">"));
200 drawtext(dc, item->text, (item == sel) ? selcol :
201 (item->out) ? outcol : normcol);
203 dc->w = textw(dc, ">");
206 drawtext(dc, ">", normcol);
208 mapdc(dc, win, mw, mh);
215 /* try to grab keyboard, we may have to wait for another process to ungrab */
216 for(i = 0; i < 1000; i++) {
217 if(XGrabKeyboard(dc->dpy, DefaultRootWindow(dc->dpy), True,
218 GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
222 eprintf("cannot grab keyboard\n");
226 insert(const char *str, ssize_t n) {
227 if(strlen(text) + n > sizeof text - 1)
229 /* move existing text out of the way, insert new text, and update cursor */
230 memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
232 memcpy(&text[cursor], str, n);
238 keypress(XKeyEvent *ev) {
241 KeySym ksym = NoSymbol;
244 len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
245 if(status == XBufferOverflow)
247 if(ev->state & ControlMask)
249 case XK_a: ksym = XK_Home; break;
250 case XK_b: ksym = XK_Left; break;
251 case XK_c: ksym = XK_Escape; break;
252 case XK_d: ksym = XK_Delete; break;
253 case XK_e: ksym = XK_End; break;
254 case XK_f: ksym = XK_Right; break;
255 case XK_g: ksym = XK_Escape; break;
256 case XK_h: ksym = XK_BackSpace; break;
257 case XK_i: ksym = XK_Tab; break;
258 case XK_j: /* fallthrough */
259 case XK_J: ksym = XK_Return; break;
260 case XK_m: /* fallthrough */
261 case XK_M: ksym = XK_Return; break;
262 case XK_n: ksym = XK_Down; break;
263 case XK_p: ksym = XK_Up; break;
265 case XK_k: /* delete right */
269 case XK_u: /* delete left */
270 insert(NULL, 0 - cursor);
272 case XK_w: /* delete word */
273 while(cursor > 0 && text[nextrune(-1)] == ' ')
274 insert(NULL, nextrune(-1) - cursor);
275 while(cursor > 0 && text[nextrune(-1)] != ' ')
276 insert(NULL, nextrune(-1) - cursor);
278 case XK_y: /* paste selection */
279 XConvertSelection(dc->dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
280 utf8, utf8, win, CurrentTime);
290 else if(ev->state & Mod1Mask)
292 case XK_g: ksym = XK_Home; break;
293 case XK_G: ksym = XK_End; break;
294 case XK_h: ksym = XK_Up; break;
295 case XK_j: ksym = XK_Next; break;
296 case XK_k: ksym = XK_Prior; break;
297 case XK_l: ksym = XK_Down; break;
307 if(text[cursor] == '\0')
309 cursor = nextrune(+1);
314 insert(NULL, nextrune(-1) - cursor);
317 if(text[cursor] != '\0') {
318 cursor = strlen(text);
322 /* jump to end of list and position items in reverse */
327 while(next && (curr = curr->right))
339 sel = curr = matches;
343 if(cursor > 0 && (!sel || !sel->left || lines > 0)) {
344 cursor = nextrune(-1);
351 if(sel && sel->left && (sel = sel->left)->right == curr) {
370 puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
371 if(!(ev->state & ControlMask))
376 if(text[cursor] != '\0') {
377 cursor = nextrune(+1);
384 if(sel && sel->right && (sel = sel->right) == next) {
392 strncpy(text, sel->text, sizeof text - 1);
393 text[sizeof text - 1] = '\0';
394 cursor = strlen(text);
403 static char **tokv = NULL;
406 char buf[sizeof text], *s;
409 Item *item, *lprefix, *lsubstr, *prefixend, *substrend;
412 /* separate input text into tokens to be matched individually */
413 for(s = strtok(buf, " "); s; tokv[tokc-1] = s, s = strtok(NULL, " "))
414 if(++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
415 eprintf("cannot realloc %u bytes\n", tokn * sizeof *tokv);
416 len = tokc ? strlen(tokv[0]) : 0;
418 matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
419 for(item = items; item && item->text; item++) {
420 for(i = 0; i < tokc; i++)
421 if(!fstrstr(item->text, tokv[i]))
423 if(i != tokc) /* not all tokens match */
425 /* exact matches go first, then prefixes, then substrings */
426 if(!tokc || !fstrncmp(tokv[0], item->text, len+1))
427 appenditem(item, &matches, &matchend);
428 else if(!fstrncmp(tokv[0], item->text, len))
429 appenditem(item, &lprefix, &prefixend);
431 appenditem(item, &lsubstr, &substrend);
435 matchend->right = lprefix;
436 lprefix->left = matchend;
440 matchend = prefixend;
444 matchend->right = lsubstr;
445 lsubstr->left = matchend;
449 matchend = substrend;
451 curr = sel = matches;
459 /* return location of next utf8 rune in the given direction (+1 or -1) */
460 for(n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc);
471 /* we have been given the current selection, now insert it into input */
472 XGetWindowProperty(dc->dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
473 utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
474 insert(p, (q = strchr(p, '\n')) ? q-p : (ssize_t)strlen(p));
481 char buf[sizeof text], *p, *maxstr = NULL;
482 size_t i, max = 0, size = 0;
484 /* read each line from stdin and add it to the item list */
485 for(i = 0; fgets(buf, sizeof buf, stdin); i++) {
486 if(i+1 >= size / sizeof *items)
487 if(!(items = realloc(items, (size += BUFSIZ))))
488 eprintf("cannot realloc %u bytes:", size);
489 if((p = strchr(buf, '\n')))
491 if(!(items[i].text = strdup(buf)))
492 eprintf("cannot strdup %u bytes:", strlen(buf)+1);
493 items[i].out = False;
494 if(strlen(items[i].text) > max)
495 max = strlen(maxstr = items[i].text);
498 items[i].text = NULL;
499 inputw = maxstr ? textw(dc, maxstr) : 0;
500 lines = MIN(lines, i);
507 while(!XNextEvent(dc->dpy, &ev)) {
508 if(XFilterEvent(&ev, win))
512 if(ev.xexpose.count == 0)
513 mapdc(dc, win, mw, mh);
518 case SelectionNotify:
519 if(ev.xselection.property == utf8)
522 case VisibilityNotify:
523 if(ev.xvisibility.state != VisibilityUnobscured)
524 XRaiseWindow(dc->dpy, win);
532 int x, y, screen = DefaultScreen(dc->dpy);
533 Window root = RootWindow(dc->dpy, screen);
534 XSetWindowAttributes swa;
538 XineramaScreenInfo *info;
541 normcol[ColBG] = getcolor(dc, normbgcolor);
542 normcol[ColFG] = getcolor(dc, normfgcolor);
543 selcol[ColBG] = getcolor(dc, selbgcolor);
544 selcol[ColFG] = getcolor(dc, selfgcolor);
545 outcol[ColBG] = getcolor(dc, outbgcolor);
546 outcol[ColFG] = getcolor(dc, outfgcolor);
548 clip = XInternAtom(dc->dpy, "CLIPBOARD", False);
549 utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);
551 /* calculate menu geometry */
552 bh = dc->font.height + 2;
553 lines = MAX(lines, 0);
554 mh = (lines + 1) * bh;
556 if((info = XineramaQueryScreens(dc->dpy, &n))) {
557 int a, j, di, i = 0, area = 0;
559 Window w, pw, dw, *dws;
560 XWindowAttributes wa;
562 XGetInputFocus(dc->dpy, &w, &di);
563 if(mon != -1 && mon < n)
565 if(!i && 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(mon == -1 && !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] [-m monitor]\n"
623 " [-nb color] [-nf color] [-sb color] [-sf color] [-v]\n", stderr);