1 /* See LICENSE file for copyright and license details. */
10 #include <X11/keysym.h>
12 #include <X11/Xutil.h>
14 #include <X11/extensions/Xinerama.h>
18 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
19 #define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH))
20 #define MIN(a, b) ((a) < (b) ? (a) : (b))
23 enum { ColFG, ColBG, ColLast };
28 unsigned long norm[ColLast];
29 unsigned long sel[ColLast];
39 } DC; /* draw context */
41 typedef struct Item Item;
44 Item *next; /* traverses all items */
45 Item *left, *right; /* traverses items matching current search pattern */
48 /* forward declarations */
49 static void appenditem(Item *i, Item **list, Item **last);
50 static void calcoffsets(void);
51 static char *cistrstr(const char *s, const char *sub);
52 static void cleanup(void);
53 static void drawmenu(void);
54 static void drawtext(const char *text, unsigned long col[ColLast]);
55 static void eprint(const char *errstr, ...);
56 static unsigned long getcolor(const char *colstr);
57 static Bool grabkeyboard(void);
58 static void initfont(const char *fontstr);
59 static void kpress(XKeyEvent * e);
60 static void match(char *pattern);
61 static void readstdin(void);
62 static void run(void);
63 static void setup(Bool topbar);
64 static int textnw(const char *text, unsigned int len);
65 static int textw(const char *text);
70 static char *maxname = NULL;
71 static char *prompt = NULL;
72 static char text[4096];
74 static int promptw = 0;
77 static unsigned int mw, mh;
78 static unsigned int numlockmask = 0;
79 static Bool running = True;
82 static Item *allitems = NULL; /* first of all items */
83 static Item *item = NULL; /* first of pattern matching items */
84 static Item *sel = NULL;
85 static Item *next = NULL;
86 static Item *prev = NULL;
87 static Item *curr = NULL;
88 static Window root, win;
89 static int (*fstrncmp)(const char *, const char *, size_t n) = strncmp;
90 static char *(*fstrstr)(const char *, const char *) = strstr;
93 appenditem(Item *i, Item **list, Item **last) {
110 w = promptw + cmdw + 2 * spaceitem;
111 for(next = curr; next; next=next->right) {
112 tw = textw(next->text);
119 w = promptw + cmdw + 2 * spaceitem;
120 for(prev = curr; prev && prev->left; prev=prev->left) {
121 tw = textw(prev->left->text);
131 cistrstr(const char *s, const char *sub) {
137 if((c = *sub++) != 0) {
142 if((csub = *s++) == 0)
145 while(tolower(csub) != c);
147 while(strncasecmp(s, sub, len) != 0);
158 itm = allitems->next;
159 free(allitems->text);
164 XFreeFontSet(dpy, dc.font.set);
166 XFreeFont(dpy, dc.font.xfont);
167 XFreePixmap(dpy, dc.drawable);
169 XDestroyWindow(dpy, win);
170 XUngrabKeyboard(dpy, CurrentTime);
181 drawtext(NULL, dc.norm);
185 drawtext(prompt, dc.sel);
192 drawtext(text[0] ? text : NULL, dc.norm);
196 drawtext((curr && curr->left) ? "<" : NULL, dc.norm);
198 /* determine maximum items */
199 for(i = curr; i != next; i=i->right) {
200 dc.w = textw(i->text);
203 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
206 dc.x = mw - spaceitem;
208 drawtext(next ? ">" : NULL, dc.norm);
210 XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, mw, mh, 0, 0);
215 drawtext(const char *text, unsigned long col[ColLast]) {
217 int i, x, y, h, len, olen;
218 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
220 XSetForeground(dpy, dc.gc, col[ColBG]);
221 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
225 h = dc.font.ascent + dc.font.descent;
226 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
228 /* shorten text if necessary */
229 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
232 memcpy(buf, text, len);
234 for(i = len; i && i > len - 3; buf[--i] = '.');
235 XSetForeground(dpy, dc.gc, col[ColFG]);
237 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
239 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
243 eprint(const char *errstr, ...) {
246 va_start(ap, errstr);
247 vfprintf(stderr, errstr, ap);
253 getcolor(const char *colstr) {
254 Colormap cmap = DefaultColormap(dpy, screen);
257 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
258 eprint("error, cannot allocate color '%s'\n", colstr);
266 for(len = 1000; len; len--) {
267 if(XGrabKeyboard(dpy, root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
276 initfont(const char *fontstr) {
277 char *def, **missing;
280 if(!fontstr || fontstr[0] == '\0')
281 eprint("error, cannot load font: '%s'\n", fontstr);
283 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
285 XFreeStringList(missing);
287 XFontSetExtents *font_extents;
288 XFontStruct **xfonts;
290 dc.font.ascent = dc.font.descent = 0;
291 font_extents = XExtentsOfFontSet(dc.font.set);
292 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
293 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
294 if(dc.font.ascent < (*xfonts)->ascent)
295 dc.font.ascent = (*xfonts)->ascent;
296 if(dc.font.descent < (*xfonts)->descent)
297 dc.font.descent = (*xfonts)->descent;
302 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
303 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
304 eprint("error, cannot load font: '%s'\n", fontstr);
305 dc.font.ascent = dc.font.xfont->ascent;
306 dc.font.descent = dc.font.xfont->descent;
308 dc.font.height = dc.font.ascent + dc.font.descent;
312 kpress(XKeyEvent * e) {
320 num = XLookupString(e, buf, sizeof buf, &ksym, NULL);
321 if(IsKeypadKey(ksym)) {
322 if(ksym == XK_KP_Enter)
324 else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
325 ksym = (ksym - XK_KP_0) + XK_0;
327 if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
328 || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
329 || IsPrivateKeypadKey(ksym))
331 /* first check if a control mask is omitted */
332 if(e->state & ControlMask) {
334 default: /* ignore other control sequences */
361 while(i >= 0 && text[i] == ' ')
363 while(i >= 0 && text[i] != ' ')
371 if(CLEANMASK(e->state) & Mod1Mask) {
396 if(num && !iscntrl((int) buf[0])) {
398 strncpy(text + len, buf, sizeof text - len);
415 while(sel && sel->right)
429 if(!(sel && sel->left))
432 if(sel->right == curr) {
450 if((e->state & ShiftMask) && *text)
451 fprintf(stdout, "%s", text);
453 fprintf(stdout, "%s", sel->text);
455 fprintf(stdout, "%s", text);
460 if(!(sel && sel->right))
471 strncpy(text, sel->text, sizeof text);
479 match(char *pattern) {
481 Item *i, *itemend, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
485 plen = strlen(pattern);
486 item = lexact = lprefix = lsubstr = itemend = exactend = prefixend = substrend = NULL;
487 for(i = allitems; i; i = i->next)
488 if(!fstrncmp(pattern, i->text, plen + 1))
489 appenditem(i, &lexact, &exactend);
490 else if(!fstrncmp(pattern, i->text, plen))
491 appenditem(i, &lprefix, &prefixend);
492 else if(fstrstr(i->text, pattern))
493 appenditem(i, &lsubstr, &substrend);
500 itemend->right = lprefix;
501 lprefix->left = itemend;
509 itemend->right = lsubstr;
510 lsubstr->left = itemend;
515 curr = prev = next = sel = item;
522 unsigned int len = 0, max = 0;
526 while(fgets(buf, sizeof buf, stdin)) {
528 if (buf[len - 1] == '\n')
530 if(!(p = strdup(buf)))
531 eprint("fatal: could not strdup() %u bytes\n", strlen(buf));
536 if(!(new = (Item *)malloc(sizeof(Item))))
537 eprint("fatal: could not malloc() %u bytes\n", sizeof(Item));
538 new->next = new->left = new->right = NULL;
552 /* main event loop */
553 while(running && !XNextEvent(dpy, &ev))
555 default: /* ignore all crap */
561 if(ev.xexpose.count == 0)
572 XineramaScreenInfo *info = NULL;
574 XModifierKeymap *modmap;
575 XSetWindowAttributes wa;
577 /* init modifier map */
578 modmap = XGetModifierMapping(dpy);
579 for(i = 0; i < 8; i++)
580 for(j = 0; j < modmap->max_keypermod; j++) {
581 if(modmap->modifiermap[i * modmap->max_keypermod + j]
582 == XKeysymToKeycode(dpy, XK_Num_Lock))
583 numlockmask = (1 << i);
585 XFreeModifiermap(modmap);
588 dc.norm[ColBG] = getcolor(normbgcolor);
589 dc.norm[ColFG] = getcolor(normfgcolor);
590 dc.sel[ColBG] = getcolor(selbgcolor);
591 dc.sel[ColFG] = getcolor(selfgcolor);
595 wa.override_redirect = True;
596 wa.background_pixmap = ParentRelative;
597 wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask;
599 /* menu window geometry */
600 mh = dc.font.height + 2;
602 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
608 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
609 for(i = 0; i < n; i++)
610 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
614 y = topbar ? info[i].y_org : info[i].y_org + info[i].height - mh;
622 y = topbar ? 0 : DisplayHeight(dpy, screen) - mh;
623 mw = DisplayWidth(dpy, screen);
626 win = XCreateWindow(dpy, root, x, y, mw, mh, 0,
627 DefaultDepth(dpy, screen), CopyFromParent,
628 DefaultVisual(dpy, screen),
629 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
632 dc.drawable = XCreatePixmap(dpy, root, mw, mh, DefaultDepth(dpy, screen));
633 dc.gc = XCreateGC(dpy, root, 0, NULL);
634 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
636 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
638 cmdw = textw(maxname);
642 promptw = textw(prompt);
647 XMapRaised(dpy, win);
651 textnw(const char *text, unsigned int len) {
655 XmbTextExtents(dc.font.set, text, len, NULL, &r);
658 return XTextWidth(dc.font.xfont, text, len);
662 textw(const char *text) {
663 return textnw(text, strlen(text)) + dc.font.height;
667 main(int argc, char *argv[]) {
671 /* command line args */
672 for(i = 1; i < argc; i++)
673 if(!strcmp(argv[i], "-i")) {
674 fstrncmp = strncasecmp;
677 else if(!strcmp(argv[i], "-b"))
679 else if(!strcmp(argv[i], "-fn")) {
680 if(++i < argc) font = argv[i];
682 else if(!strcmp(argv[i], "-nb")) {
683 if(++i < argc) normbgcolor = argv[i];
685 else if(!strcmp(argv[i], "-nf")) {
686 if(++i < argc) normfgcolor = argv[i];
688 else if(!strcmp(argv[i], "-p")) {
689 if(++i < argc) prompt = argv[i];
691 else if(!strcmp(argv[i], "-sb")) {
692 if(++i < argc) selbgcolor = argv[i];
694 else if(!strcmp(argv[i], "-sf")) {
695 if(++i < argc) selfgcolor = argv[i];
697 else if(!strcmp(argv[i], "-v"))
698 eprint("dmenu-"VERSION", © 2006-2008 dmenu engineers, see LICENSE for details\n");
700 eprint("usage: dmenu [-i] [-b] [-fn <font>] [-nb <color>] [-nf <color>]\n"
701 " [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
702 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
703 fprintf(stderr, "warning: no locale support\n");
704 if(!(dpy = XOpenDisplay(NULL)))
705 eprint("dmenu: cannot open display\n");
706 screen = DefaultScreen(dpy);
707 root = RootWindow(dpy, screen);
709 if(isatty(STDIN_FILENO)) {
711 running = grabkeyboard();
713 else { /* prevent keypress loss */
714 running = grabkeyboard();