1 /* See LICENSE file for copyright and license details. */
11 #include <X11/keysym.h>
13 #include <X11/Xutil.h>
15 #include <X11/extensions/Xinerama.h>
19 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
20 #define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH))
21 #define MIN(a, b) ((a) < (b) ? (a) : (b))
24 enum { ColFG, ColBG, ColLast };
29 unsigned long norm[ColLast];
30 unsigned long sel[ColLast];
40 } DC; /* draw context */
42 typedef struct Item Item;
45 Item *next; /* traverses all items */
46 Item *left, *right; /* traverses items matching current search pattern */
49 /* forward declarations */
50 static void appenditem(Item *i, Item **list, Item **last);
51 static void calcoffsets(void);
52 static char *cistrstr(const char *s, const char *sub);
53 static void cleanup(void);
54 static void drawmenu(void);
55 static void drawtext(const char *text, unsigned long col[ColLast]);
56 static void eprint(const char *errstr, ...);
57 static unsigned long getcolor(const char *colstr);
58 static Bool grabkeyboard(void);
59 static void initfont(const char *fontstr);
60 static void kpress(XKeyEvent * e);
61 static void match(char *pattern);
62 static void readstdin(void);
63 static void run(void);
64 static void setup(Bool topbar);
65 static int textnw(const char *text, unsigned int len);
66 static int textw(const char *text);
71 static char *maxname = NULL;
72 static char *prompt = NULL;
73 static char text[4096];
75 static int promptw = 0;
78 static unsigned int mw, mh;
79 static unsigned int numlockmask = 0;
80 static Bool running = True;
83 static Item *allitems = NULL; /* first of all items */
84 static Item *item = NULL; /* first of pattern matching items */
85 static Item *sel = NULL;
86 static Item *next = NULL;
87 static Item *prev = NULL;
88 static Item *curr = NULL;
89 static Window root, win;
90 static int (*fstrncmp)(const char *, const char *, size_t n) = strncmp;
91 static char *(*fstrstr)(const char *, const char *) = strstr;
94 appenditem(Item *i, Item **list, Item **last) {
111 w = promptw + cmdw + 2 * spaceitem;
112 for(next = curr; next; next=next->right) {
113 tw = textw(next->text);
120 w = promptw + cmdw + 2 * spaceitem;
121 for(prev = curr; prev && prev->left; prev=prev->left) {
122 tw = textw(prev->left->text);
132 cistrstr(const char *s, const char *sub) {
138 if((c = *sub++) != 0) {
143 if((csub = *s++) == 0)
146 while(tolower(csub) != c);
148 while(strncasecmp(s, sub, len) != 0);
159 itm = allitems->next;
160 free(allitems->text);
165 XFreeFontSet(dpy, dc.font.set);
167 XFreeFont(dpy, dc.font.xfont);
168 XFreePixmap(dpy, dc.drawable);
170 XDestroyWindow(dpy, win);
171 XUngrabKeyboard(dpy, CurrentTime);
182 drawtext(NULL, dc.norm);
186 drawtext(prompt, dc.sel);
193 drawtext(text[0] ? text : NULL, dc.norm);
197 drawtext((curr && curr->left) ? "<" : NULL, dc.norm);
199 /* determine maximum items */
200 for(i = curr; i != next; i=i->right) {
201 dc.w = textw(i->text);
204 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
207 dc.x = mw - spaceitem;
209 drawtext(next ? ">" : NULL, dc.norm);
211 XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, mw, mh, 0, 0);
216 drawtext(const char *text, unsigned long col[ColLast]) {
218 int i, x, y, h, len, olen;
219 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
221 XSetForeground(dpy, dc.gc, col[ColBG]);
222 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
226 h = dc.font.ascent + dc.font.descent;
227 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
229 /* shorten text if necessary */
230 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
233 memcpy(buf, text, len);
235 for(i = len; i && i > len - 3; buf[--i] = '.');
236 XSetForeground(dpy, dc.gc, col[ColFG]);
238 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
240 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
244 eprint(const char *errstr, ...) {
247 va_start(ap, errstr);
248 vfprintf(stderr, errstr, ap);
254 getcolor(const char *colstr) {
255 Colormap cmap = DefaultColormap(dpy, screen);
258 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
259 eprint("error, cannot allocate color '%s'\n", colstr);
267 for(len = 1000; len; len--) {
268 if(XGrabKeyboard(dpy, root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
277 initfont(const char *fontstr) {
278 char *def, **missing;
281 if(!fontstr || fontstr[0] == '\0')
282 eprint("error, cannot load font: '%s'\n", fontstr);
284 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
286 XFreeStringList(missing);
288 XFontSetExtents *font_extents;
289 XFontStruct **xfonts;
291 dc.font.ascent = dc.font.descent = 0;
292 font_extents = XExtentsOfFontSet(dc.font.set);
293 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
294 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
295 if(dc.font.ascent < (*xfonts)->ascent)
296 dc.font.ascent = (*xfonts)->ascent;
297 if(dc.font.descent < (*xfonts)->descent)
298 dc.font.descent = (*xfonts)->descent;
304 XFreeFont(dpy, dc.font.xfont);
305 dc.font.xfont = NULL;
306 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
307 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
308 eprint("error, cannot load font: '%s'\n", fontstr);
309 dc.font.ascent = dc.font.xfont->ascent;
310 dc.font.descent = dc.font.xfont->descent;
312 dc.font.height = dc.font.ascent + dc.font.descent;
316 kpress(XKeyEvent * e) {
324 num = XLookupString(e, buf, sizeof buf, &ksym, 0);
325 if(IsKeypadKey(ksym)) {
326 if(ksym == XK_KP_Enter)
328 else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
329 ksym = (ksym - XK_KP_0) + XK_0;
331 if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
332 || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
333 || IsPrivateKeypadKey(ksym))
335 /* first check if a control mask is omitted */
336 if(e->state & ControlMask) {
338 default: /* ignore other control sequences */
365 while(i >= 0 && text[i] == ' ')
367 while(i >= 0 && text[i] != ' ')
375 if(CLEANMASK(e->state) & Mod1Mask) {
400 if(num && !iscntrl((int) buf[0])) {
403 strncat(text, buf, sizeof text);
405 strncpy(text, buf, sizeof text);
422 while(sel && sel->right)
436 if(!(sel && sel->left))
439 if(sel->right == curr) {
457 if((e->state & ShiftMask) && *text)
458 fprintf(stdout, "%s", text);
460 fprintf(stdout, "%s", sel->text);
462 fprintf(stdout, "%s", text);
467 if(!(sel && sel->right))
478 strncpy(text, sel->text, sizeof text);
486 match(char *pattern) {
488 Item *i, *itemend, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
492 plen = strlen(pattern);
493 item = lexact = lprefix = lsubstr = itemend = exactend = prefixend = substrend = NULL;
494 for(i = allitems; i; i = i->next)
495 if(!fstrncmp(pattern, i->text, plen + 1))
496 appenditem(i, &lexact, &exactend);
497 else if(!fstrncmp(pattern, i->text, plen))
498 appenditem(i, &lprefix, &prefixend);
499 else if(fstrstr(i->text, pattern))
500 appenditem(i, &lsubstr, &substrend);
507 itemend->right = lprefix;
508 lprefix->left = itemend;
516 itemend->right = lsubstr;
517 lsubstr->left = itemend;
522 curr = prev = next = sel = item;
529 unsigned int len = 0, max = 0;
533 while(fgets(buf, sizeof buf, stdin)) {
535 if (buf[len - 1] == '\n')
537 if(!(p = strdup(buf)))
538 eprint("fatal: could not strdup() %u bytes\n", strlen(buf));
543 if((new = (Item *)malloc(sizeof(Item))) == NULL)
544 eprint("fatal: could not malloc() %u bytes\n", sizeof(Item));
545 new->next = new->left = new->right = NULL;
559 /* main event loop */
560 while(running && !XNextEvent(dpy, &ev))
562 default: /* ignore all crap */
568 if(ev.xexpose.count == 0)
579 XineramaScreenInfo *info = NULL;
581 XModifierKeymap *modmap;
582 XSetWindowAttributes wa;
584 /* init modifier map */
585 modmap = XGetModifierMapping(dpy);
586 for(i = 0; i < 8; i++)
587 for(j = 0; j < modmap->max_keypermod; j++) {
588 if(modmap->modifiermap[i * modmap->max_keypermod + j]
589 == XKeysymToKeycode(dpy, XK_Num_Lock))
590 numlockmask = (1 << i);
592 XFreeModifiermap(modmap);
595 dc.norm[ColBG] = getcolor(normbgcolor);
596 dc.norm[ColFG] = getcolor(normfgcolor);
597 dc.sel[ColBG] = getcolor(selbgcolor);
598 dc.sel[ColFG] = getcolor(selfgcolor);
602 wa.override_redirect = 1;
603 wa.background_pixmap = ParentRelative;
604 wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask;
606 /* menu window geometry */
607 mh = dc.font.height + 2;
609 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
615 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
616 for(i = 0; i < n; i++)
617 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
621 y = topbar ? info[i].y_org : info[i].y_org + info[i].height - mh;
629 y = topbar ? 0 : DisplayHeight(dpy, screen) - mh;
630 mw = DisplayWidth(dpy, screen);
633 win = XCreateWindow(dpy, root, x, y, mw, mh, 0,
634 DefaultDepth(dpy, screen), CopyFromParent,
635 DefaultVisual(dpy, screen),
636 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
639 dc.drawable = XCreatePixmap(dpy, root, mw, mh, DefaultDepth(dpy, screen));
640 dc.gc = XCreateGC(dpy, root, 0, 0);
641 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
643 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
645 cmdw = textw(maxname);
649 promptw = textw(prompt);
654 XMapRaised(dpy, win);
658 textnw(const char *text, unsigned int len) {
662 XmbTextExtents(dc.font.set, text, len, NULL, &r);
665 return XTextWidth(dc.font.xfont, text, len);
669 textw(const char *text) {
670 return textnw(text, strlen(text)) + dc.font.height;
674 main(int argc, char *argv[]) {
678 /* command line args */
679 for(i = 1; i < argc; i++)
680 if(!strcmp(argv[i], "-i")) {
681 fstrncmp = strncasecmp;
684 else if(!strcmp(argv[i], "-b"))
686 else if(!strcmp(argv[i], "-fn")) {
687 if(++i < argc) font = argv[i];
689 else if(!strcmp(argv[i], "-nb")) {
690 if(++i < argc) normbgcolor = argv[i];
692 else if(!strcmp(argv[i], "-nf")) {
693 if(++i < argc) normfgcolor = argv[i];
695 else if(!strcmp(argv[i], "-p")) {
696 if(++i < argc) prompt = argv[i];
698 else if(!strcmp(argv[i], "-sb")) {
699 if(++i < argc) selbgcolor = argv[i];
701 else if(!strcmp(argv[i], "-sf")) {
702 if(++i < argc) selfgcolor = argv[i];
704 else if(!strcmp(argv[i], "-v"))
705 eprint("dmenu-"VERSION", © 2006-2008 dmenu engineers, see LICENSE for details\n");
707 eprint("usage: dmenu [-i] [-b] [-fn <font>] [-nb <color>] [-nf <color>]\n"
708 " [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
709 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
710 fprintf(stderr, "warning: no locale support\n");
711 if(!(dpy = XOpenDisplay(0)))
712 eprint("dmenu: cannot open display\n");
713 screen = DefaultScreen(dpy);
714 root = RootWindow(dpy, screen);
716 if(isatty(STDIN_FILENO)) {
718 running = grabkeyboard();
720 else { /* prevent keypress loss */
721 running = grabkeyboard();