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))
22 enum { ColFG, ColBG, ColLast };
25 typedef unsigned int uint;
26 typedef unsigned long ulong;
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, ulong col[ColLast]);
56 static void eprint(const char *errstr, ...);
57 static ulong 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, uint 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;
79 static uint 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, ulong col[ColLast]) {
218 static char buf[256];
220 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
222 XSetForeground(dpy, dc.gc, col[ColBG]);
223 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
227 olen = len = strlen(text);
228 if(len >= sizeof buf)
229 len = sizeof buf - 1;
230 memcpy(buf, text, len);
232 h = dc.font.ascent + dc.font.descent;
233 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
235 /* shorten text if necessary */
236 while(len && (w = textnw(buf, len)) > dc.w - h)
247 return; /* too long */
248 XSetForeground(dpy, dc.gc, col[ColFG]);
250 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
252 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
256 eprint(const char *errstr, ...) {
259 va_start(ap, errstr);
260 vfprintf(stderr, errstr, ap);
266 getcolor(const char *colstr) {
267 Colormap cmap = DefaultColormap(dpy, screen);
270 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
271 eprint("error, cannot allocate color '%s'\n", colstr);
279 for(len = 1000; len; len--) {
280 if(XGrabKeyboard(dpy, root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
289 initfont(const char *fontstr) {
290 char *def, **missing;
293 if(!fontstr || fontstr[0] == '\0')
294 eprint("error, cannot load font: '%s'\n", fontstr);
297 XFreeFontSet(dpy, dc.font.set);
298 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
300 XFreeStringList(missing);
302 XFontSetExtents *font_extents;
303 XFontStruct **xfonts;
305 dc.font.ascent = dc.font.descent = 0;
306 font_extents = XExtentsOfFontSet(dc.font.set);
307 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
308 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
309 if(dc.font.ascent < (*xfonts)->ascent)
310 dc.font.ascent = (*xfonts)->ascent;
311 if(dc.font.descent < (*xfonts)->descent)
312 dc.font.descent = (*xfonts)->descent;
318 XFreeFont(dpy, dc.font.xfont);
319 dc.font.xfont = NULL;
320 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
321 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
322 eprint("error, cannot load font: '%s'\n", fontstr);
323 dc.font.ascent = dc.font.xfont->ascent;
324 dc.font.descent = dc.font.xfont->descent;
326 dc.font.height = dc.font.ascent + dc.font.descent;
330 kpress(XKeyEvent * e) {
338 num = XLookupString(e, buf, sizeof buf, &ksym, 0);
339 if(IsKeypadKey(ksym)) {
340 if(ksym == XK_KP_Enter)
342 else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
343 ksym = (ksym - XK_KP_0) + XK_0;
345 if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
346 || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
347 || IsPrivateKeypadKey(ksym))
349 /* first check if a control mask is omitted */
350 if(e->state & ControlMask) {
352 default: /* ignore other control sequences */
379 while(i >= 0 && text[i] == ' ')
381 while(i >= 0 && text[i] != ' ')
389 if(CLEANMASK(e->state) & Mod1Mask) {
414 if(num && !iscntrl((int) buf[0])) {
417 strncat(text, buf, sizeof text);
419 strncpy(text, buf, sizeof text);
436 while(sel && sel->right)
450 if(!(sel && sel->left))
453 if(sel->right == curr) {
471 if((e->state & ShiftMask) && *text)
472 fprintf(stdout, "%s", text);
474 fprintf(stdout, "%s", sel->text);
476 fprintf(stdout, "%s", text);
481 if(!(sel && sel->right))
492 strncpy(text, sel->text, sizeof text);
500 match(char *pattern) {
502 Item *i, *itemend, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
506 plen = strlen(pattern);
507 item = lexact = lprefix = lsubstr = itemend = exactend = prefixend = substrend = NULL;
508 for(i = allitems; i; i = i->next)
509 if(!fstrncmp(pattern, i->text, plen + 1))
510 appenditem(i, &lexact, &exactend);
511 else if(!fstrncmp(pattern, i->text, plen))
512 appenditem(i, &lprefix, &prefixend);
513 else if(fstrstr(i->text, pattern))
514 appenditem(i, &lsubstr, &substrend);
521 itemend->right = lprefix;
522 lprefix->left = itemend;
530 itemend->right = lsubstr;
531 lsubstr->left = itemend;
536 curr = prev = next = sel = item;
543 uint len = 0, max = 0;
547 while(fgets(buf, sizeof buf, stdin)) {
549 if (buf[len - 1] == '\n')
551 if(!(p = strdup(buf)))
552 eprint("fatal: could not strdup() %u bytes\n", strlen(buf));
557 if((new = (Item *)malloc(sizeof(Item))) == NULL)
558 eprint("fatal: could not malloc() %u bytes\n", sizeof(Item));
559 new->next = new->left = new->right = NULL;
573 /* main event loop */
574 while(running && !XNextEvent(dpy, &ev))
576 default: /* ignore all crap */
582 if(ev.xexpose.count == 0)
591 XModifierKeymap *modmap;
592 XSetWindowAttributes wa;
594 XineramaScreenInfo *info = NULL;
597 /* init modifier map */
598 modmap = XGetModifierMapping(dpy);
599 for(i = 0; i < 8; i++)
600 for(j = 0; j < modmap->max_keypermod; j++) {
601 if(modmap->modifiermap[i * modmap->max_keypermod + j]
602 == XKeysymToKeycode(dpy, XK_Num_Lock))
603 numlockmask = (1 << i);
605 XFreeModifiermap(modmap);
608 dc.norm[ColBG] = getcolor(normbgcolor);
609 dc.norm[ColFG] = getcolor(normfgcolor);
610 dc.sel[ColBG] = getcolor(selbgcolor);
611 dc.sel[ColFG] = getcolor(selfgcolor);
615 wa.override_redirect = 1;
616 wa.background_pixmap = ParentRelative;
617 wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask;
619 /* menu window geometry */
620 mh = dc.font.height + 2;
622 if(XineramaIsActive(dpy)) {
623 info = XineramaQueryScreens(dpy, &i);
624 x = info[xidx].x_org;
625 y = topbar ? info[xidx].y_org : info[xidx].y_org + info[xidx].height - mh;
626 mw = info[xidx].width;
633 y = topbar ? 0 : DisplayHeight(dpy, screen) - mh;
634 mw = DisplayWidth(dpy, screen);
637 win = XCreateWindow(dpy, root, x, y, mw, mh, 0,
638 DefaultDepth(dpy, screen), CopyFromParent,
639 DefaultVisual(dpy, screen),
640 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
643 dc.drawable = XCreatePixmap(dpy, root, mw, mh, DefaultDepth(dpy, screen));
644 dc.gc = XCreateGC(dpy, root, 0, 0);
645 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
647 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
649 cmdw = textw(maxname);
653 promptw = textw(prompt);
658 XMapRaised(dpy, win);
662 textnw(const char *text, uint len) {
666 XmbTextExtents(dc.font.set, text, len, NULL, &r);
669 return XTextWidth(dc.font.xfont, text, len);
673 textw(const char *text) {
674 return textnw(text, strlen(text)) + dc.font.height;
678 main(int argc, char *argv[]) {
682 /* command line args */
683 for(i = 1; i < argc; i++)
684 if(!strcmp(argv[i], "-i")) {
685 fstrncmp = strncasecmp;
688 else if(!strcmp(argv[i], "-b"))
690 else if(!strcmp(argv[i], "-fn")) {
691 if(++i < argc) font = argv[i];
693 else if(!strcmp(argv[i], "-nb")) {
694 if(++i < argc) normbgcolor = argv[i];
696 else if(!strcmp(argv[i], "-nf")) {
697 if(++i < argc) normfgcolor = argv[i];
699 else if(!strcmp(argv[i], "-p")) {
700 if(++i < argc) prompt = argv[i];
702 else if(!strcmp(argv[i], "-sb")) {
703 if(++i < argc) selbgcolor = argv[i];
705 else if(!strcmp(argv[i], "-sf")) {
706 if(++i < argc) selfgcolor = argv[i];
708 else if(!strcmp(argv[i], "-v"))
709 eprint("dmenu-"VERSION", © 2006-2008 dmenu engineers, see LICENSE for details\n");
711 eprint("usage: dmenu [-i] [-b] [-fn <font>] [-nb <color>] [-nf <color>]\n"
712 " [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
713 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
714 fprintf(stderr, "warning: no locale support\n");
715 if(!(dpy = XOpenDisplay(0)))
716 eprint("dmenu: cannot open display\n");
717 screen = DefaultScreen(dpy);
718 root = RootWindow(dpy, screen);
720 if(isatty(STDIN_FILENO)) {
722 running = grabkeyboard();
724 else { /* prevent keypress loss */
725 running = grabkeyboard();