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))
21 #define MAX(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 calcoffsetsh(void);
52 static void calcoffsetsv(void);
53 static char *cistrstr(const char *s, const char *sub);
54 static void cleanup(void);
55 static void drawcursor(void);
56 static void drawmenu(void);
57 static void drawmenuh(void);
58 static void drawmenuv(void);
59 static void drawtext(const char *text, unsigned long col[ColLast]);
60 static void eprint(const char *errstr, ...);
61 static unsigned long getcolor(const char *colstr);
62 static Bool grabkeyboard(void);
63 static void initfont(const char *fontstr);
64 static void kpress(XKeyEvent * e);
65 static void match(char *pattern);
66 static void readstdin(void);
67 static void run(void);
68 static void setup(Bool topbar);
69 static int textnw(const char *text, unsigned int len);
70 static int textw(const char *text);
75 static char *maxname = NULL;
76 static char *prompt = NULL;
77 static char text[4096];
79 static int promptw = 0;
81 static int cursor = 0;
83 static unsigned int mw, mh;
84 static unsigned int numlockmask = 0;
85 static Bool running = True;
88 static Item *allitems = NULL; /* first of all items */
89 static Item *item = NULL; /* first of pattern matching items */
90 static Item *sel = NULL;
91 static Item *next = NULL;
92 static Item *prev = NULL;
93 static Item *curr = NULL;
94 static Window root, win;
95 static int (*fstrncmp)(const char *, const char *, size_t n) = strncmp;
96 static char *(*fstrstr)(const char *, const char *) = strstr;
97 static Bool vlist = False;
98 static unsigned int lines = 5;
99 static void (*calcoffsets)(void) = calcoffsetsh;
102 appenditem(Item *i, Item **list, Item **last) {
119 w = promptw + cmdw + 2 * spaceitem;
120 for(next = curr; next; next=next->right) {
121 tw = textw(next->text);
128 w = promptw + cmdw + 2 * spaceitem;
129 for(prev = curr; prev && prev->left; prev=prev->left) {
130 tw = textw(prev->left->text);
141 static unsigned int w;
145 w = (dc.font.height + 2) * (lines + 1);
146 for(next = curr; next; next=next->right) {
147 w -= dc.font.height + 2;
151 w = (dc.font.height + 2) * (lines + 1);
152 for(prev = curr; prev && prev->left; prev=prev->left) {
153 w -= dc.font.height + 2;
160 cistrstr(const char *s, const char *sub) {
166 if((c = *sub++) != 0) {
171 if((csub = *s++) == 0)
174 while(tolower(csub) != c);
176 while(strncasecmp(s, sub, len) != 0);
187 itm = allitems->next;
188 free(allitems->text);
193 XFreeFontSet(dpy, dc.font.set);
195 XFreeFont(dpy, dc.font.xfont);
196 XFreePixmap(dpy, dc.drawable);
198 XDestroyWindow(dpy, win);
199 XUngrabKeyboard(dpy, CurrentTime);
204 XRectangle r = { dc.x, dc.y + 2, 1, dc.font.height - 2 };
206 r.x += textnw(text, cursor) + dc.font.height / 2;
208 XSetForeground(dpy, dc.gc, dc.norm[ColFG]);
209 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
218 drawtext(NULL, dc.norm);
222 drawtext(prompt, dc.sel);
229 drawtext(text[0] ? text : NULL, dc.norm);
238 XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, mw, mh, 0, 0);
247 drawtext((curr && curr->left) ? "<" : NULL, dc.norm);
249 /* determine maximum items */
250 for(i = curr; i != next; i=i->right) {
251 dc.w = MIN(textw(i->text), mw / 3);
252 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
255 dc.x = mw - spaceitem;
257 drawtext(next ? ">" : NULL, dc.norm);
266 dc.y += dc.font.height + 2;
267 /* determine maximum items */
268 for(i = curr; i != next; i=i->right) {
269 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
270 dc.y += dc.font.height + 2;
272 drawtext(NULL, dc.norm);
276 drawtext(const char *text, unsigned long col[ColLast]) {
278 int i, x, y, h, len, olen;
279 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
281 XSetForeground(dpy, dc.gc, col[ColBG]);
282 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
287 y = dc.y + ((h+2) / 2) - (h / 2) + dc.font.ascent;
289 /* shorten text if necessary */
290 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
293 memcpy(buf, text, len);
295 for(i = len; i && i > len - 3; buf[--i] = '.');
296 XSetForeground(dpy, dc.gc, col[ColFG]);
298 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
300 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
304 eprint(const char *errstr, ...) {
307 va_start(ap, errstr);
308 vfprintf(stderr, errstr, ap);
314 getcolor(const char *colstr) {
315 Colormap cmap = DefaultColormap(dpy, screen);
318 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
319 eprint("error, cannot allocate color '%s'\n", colstr);
327 for(len = 1000; len; len--) {
328 if(XGrabKeyboard(dpy, root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
337 initfont(const char *fontstr) {
338 char *def, **missing;
341 if(!fontstr || fontstr[0] == '\0')
342 eprint("error, cannot load font: '%s'\n", fontstr);
344 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
346 XFreeStringList(missing);
348 XFontSetExtents *font_extents;
349 XFontStruct **xfonts;
351 dc.font.ascent = dc.font.descent = 0;
352 font_extents = XExtentsOfFontSet(dc.font.set);
353 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
354 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
355 if(dc.font.ascent < (*xfonts)->ascent)
356 dc.font.ascent = (*xfonts)->ascent;
357 if(dc.font.descent < (*xfonts)->descent)
358 dc.font.descent = (*xfonts)->descent;
363 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
364 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
365 eprint("error, cannot load font: '%s'\n", fontstr);
366 dc.font.ascent = dc.font.xfont->ascent;
367 dc.font.descent = dc.font.xfont->descent;
369 dc.font.height = dc.font.ascent + dc.font.descent;
373 kpress(XKeyEvent * e) {
374 char buf[sizeof text];
381 num = XLookupString(e, buf, sizeof buf, &ksym, NULL);
382 if(IsKeypadKey(ksym)) {
383 if(ksym == XK_KP_Enter)
385 else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
386 ksym = (ksym - XK_KP_0) + XK_0;
388 if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
389 || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
390 || IsPrivateKeypadKey(ksym))
392 /* first check if a control mask is omitted */
393 if(e->state & ControlMask) {
395 default: /* ignore other control sequences */
422 while(i-- > 0 && text[i] == ' ');
423 while(i-- > 0 && text[i] != ' ');
424 memmove(text + i + 1, text + cursor, sizeof text - cursor);
431 if(CLEANMASK(e->state) & Mod1Mask) {
456 if(!(fp = (FILE*)popen("sselp", "r")))
457 eprint("dmenu: Could not popen sselp\n");
458 c = fgets(buf, sizeof buf, fp);
464 if(num && buf[num-1] == '\n')
471 num = MIN(num, sizeof text - cursor);
472 if(num && !iscntrl((int) buf[0])) {
473 memmove(text + cursor + num, text + cursor, sizeof text - cursor - num);
474 memcpy(text + cursor, buf, num);
481 memmove(text + cursor - 1, text + cursor, sizeof text - cursor + 1);
487 memmove(text + cursor, text + cursor + 1, sizeof text - cursor);
499 while(sel && sel->right)
516 if(sel && sel->left){
518 if(sel->right == curr) {
541 if((e->state & ShiftMask) || !sel)
542 fprintf(stdout, "%s", text);
544 fprintf(stdout, "%s", sel->text);
552 else if(sel && sel->right) {
565 strncpy(text, sel->text, sizeof text);
566 cursor = strlen(text);
574 match(char *pattern) {
576 Item *i, *itemend, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
580 plen = strlen(pattern);
581 item = lexact = lprefix = lsubstr = itemend = exactend = prefixend = substrend = NULL;
582 for(i = allitems; i; i = i->next)
583 if(!fstrncmp(pattern, i->text, plen + 1))
584 appenditem(i, &lexact, &exactend);
585 else if(!fstrncmp(pattern, i->text, plen))
586 appenditem(i, &lprefix, &prefixend);
587 else if(fstrstr(i->text, pattern))
588 appenditem(i, &lsubstr, &substrend);
595 itemend->right = lprefix;
596 lprefix->left = itemend;
604 itemend->right = lsubstr;
605 lsubstr->left = itemend;
610 curr = prev = next = sel = item;
617 unsigned int len = 0, max = 0;
621 while(fgets(buf, sizeof buf, stdin)) {
623 if(buf[len-1] == '\n')
625 if(!(p = strdup(buf)))
626 eprint("fatal: could not strdup() %u bytes\n", len);
631 if(!(new = (Item *)malloc(sizeof(Item))))
632 eprint("fatal: could not malloc() %u bytes\n", sizeof(Item));
633 new->next = new->left = new->right = NULL;
647 /* main event loop */
648 while(running && !XNextEvent(dpy, &ev))
650 default: /* ignore all crap */
656 if(ev.xexpose.count == 0)
667 XineramaScreenInfo *info = NULL;
669 XModifierKeymap *modmap;
670 XSetWindowAttributes wa;
672 /* init modifier map */
673 modmap = XGetModifierMapping(dpy);
674 for(i = 0; i < 8; i++)
675 for(j = 0; j < modmap->max_keypermod; j++) {
676 if(modmap->modifiermap[i * modmap->max_keypermod + j]
677 == XKeysymToKeycode(dpy, XK_Num_Lock))
678 numlockmask = (1 << i);
680 XFreeModifiermap(modmap);
683 dc.norm[ColBG] = getcolor(normbgcolor);
684 dc.norm[ColFG] = getcolor(normfgcolor);
685 dc.sel[ColBG] = getcolor(selbgcolor);
686 dc.sel[ColFG] = getcolor(selfgcolor);
690 wa.override_redirect = True;
691 wa.background_pixmap = ParentRelative;
692 wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask;
694 /* menu window geometry */
695 mh = dc.font.height + 2;
696 mh = vlist ? mh * (lines+1) : mh;
698 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
704 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
705 for(i = 0; i < n; i++)
706 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
710 y = topbar ? info[i].y_org : info[i].y_org + info[i].height - mh;
718 y = topbar ? 0 : DisplayHeight(dpy, screen) - mh;
719 mw = DisplayWidth(dpy, screen);
722 win = XCreateWindow(dpy, root, x, y, mw, mh, 0,
723 DefaultDepth(dpy, screen), CopyFromParent,
724 DefaultVisual(dpy, screen),
725 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
728 dc.drawable = XCreatePixmap(dpy, root, mw, mh, DefaultDepth(dpy, screen));
729 dc.gc = XCreateGC(dpy, root, 0, NULL);
730 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
732 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
734 cmdw = MIN(textw(maxname), mw / 3);
736 promptw = MIN(textw(prompt), mw / 5);
739 XMapRaised(dpy, win);
743 textnw(const char *text, unsigned int len) {
747 XmbTextExtents(dc.font.set, text, len, NULL, &r);
750 return XTextWidth(dc.font.xfont, text, len);
754 textw(const char *text) {
755 return textnw(text, strlen(text)) + dc.font.height;
759 main(int argc, char *argv[]) {
763 /* command line args */
764 for(i = 1; i < argc; i++)
765 if(!strcmp(argv[i], "-i")) {
766 fstrncmp = strncasecmp;
769 else if(!strcmp(argv[i], "-b"))
771 else if(!strcmp(argv[i], "-l")) {
773 calcoffsets = calcoffsetsv;
774 if(++i < argc) lines = atoi(argv[i]);
776 else if(!strcmp(argv[i], "-fn")) {
777 if(++i < argc) font = argv[i];
779 else if(!strcmp(argv[i], "-nb")) {
780 if(++i < argc) normbgcolor = argv[i];
782 else if(!strcmp(argv[i], "-nf")) {
783 if(++i < argc) normfgcolor = argv[i];
785 else if(!strcmp(argv[i], "-p")) {
786 if(++i < argc) prompt = argv[i];
788 else if(!strcmp(argv[i], "-sb")) {
789 if(++i < argc) selbgcolor = argv[i];
791 else if(!strcmp(argv[i], "-sf")) {
792 if(++i < argc) selfgcolor = argv[i];
794 else if(!strcmp(argv[i], "-v"))
795 eprint("dmenu-"VERSION", © 2006-2010 dmenu engineers, see LICENSE for details\n");
797 eprint("usage: dmenu [-i] [-b] [-l <lines>] [-fn <font>] [-nb <color>] [-nf <color>]\n"
798 " [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
799 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
800 fprintf(stderr, "warning: no locale support\n");
801 if(!(dpy = XOpenDisplay(NULL)))
802 eprint("dmenu: cannot open display\n");
803 screen = DefaultScreen(dpy);
804 root = RootWindow(dpy, screen);
806 if(isatty(STDIN_FILENO)) {
808 running = grabkeyboard();
810 else { /* prevent keypress loss */
811 running = grabkeyboard();