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 drawmenu(void);
56 static void drawmenuh(void);
57 static void drawmenuv(void);
58 static void drawtext(const char *text, unsigned long col[ColLast]);
59 static void eprint(const char *errstr, ...);
60 static unsigned long getcolor(const char *colstr);
61 static Bool grabkeyboard(void);
62 static void initfont(const char *fontstr);
63 static void kpress(XKeyEvent * e);
64 static void match(char *pattern);
65 static void readstdin(void);
66 static void run(void);
67 static void setup(Bool topbar);
68 static int textnw(const char *text, unsigned int len);
69 static int textw(const char *text);
74 static char *maxname = NULL;
75 static char *prompt = NULL;
76 static char text[4096];
78 static int promptw = 0;
80 static int cursor = 0;
82 static unsigned int mw, mh;
83 static unsigned int numlockmask = 0;
84 static Bool running = True;
87 static Item *allitems = NULL; /* first of all items */
88 static Item *item = NULL; /* first of pattern matching items */
89 static Item *sel = NULL;
90 static Item *next = NULL;
91 static Item *prev = NULL;
92 static Item *curr = NULL;
93 static Window root, win;
94 static int (*fstrncmp)(const char *, const char *, size_t n) = strncmp;
95 static char *(*fstrstr)(const char *, const char *) = strstr;
96 static Bool vlist = False;
97 static unsigned int lines = 5;
98 static void (*calcoffsets)(void) = calcoffsetsh;
101 appenditem(Item *i, Item **list, Item **last) {
118 w = promptw + cmdw + 2 * spaceitem;
119 for(next = curr; next; next=next->right) {
120 tw = textw(next->text);
127 w = promptw + cmdw + 2 * spaceitem;
128 for(prev = curr; prev && prev->left; prev=prev->left) {
129 tw = textw(prev->left->text);
140 static unsigned int w;
144 w = (dc.font.height + 2) * (lines + 1);
145 for(next = curr; next; next=next->right) {
146 w -= dc.font.height + 2;
150 w = (dc.font.height + 2) * (lines + 1);
151 for(prev = curr; prev && prev->left; prev=prev->left) {
152 w -= dc.font.height + 2;
159 cistrstr(const char *s, const char *sub) {
165 if((c = *sub++) != 0) {
170 if((csub = *s++) == 0)
173 while(tolower(csub) != c);
175 while(strncasecmp(s, sub, len) != 0);
186 itm = allitems->next;
187 free(allitems->text);
192 XFreeFontSet(dpy, dc.font.set);
194 XFreeFont(dpy, dc.font.xfont);
195 XFreePixmap(dpy, dc.drawable);
197 XDestroyWindow(dpy, win);
198 XUngrabKeyboard(dpy, CurrentTime);
203 XRectangle r = { dc.x, dc.y + 2, 1, dc.font.height - 2 };
205 r.x += textnw(text, cursor) + dc.font.height / 2;
207 XSetForeground(dpy, dc.gc, dc.norm[ColFG]);
208 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
217 drawtext(NULL, dc.norm);
221 drawtext(prompt, dc.sel);
228 drawtext(text[0] ? text : NULL, dc.norm);
237 XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, mw, mh, 0, 0);
246 drawtext((curr && curr->left) ? "<" : NULL, dc.norm);
248 /* determine maximum items */
249 for(i = curr; i != next; i=i->right) {
250 dc.w = textw(i->text);
253 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
256 dc.x = mw - spaceitem;
258 drawtext(next ? ">" : NULL, dc.norm);
267 dc.y += dc.font.height + 2;
268 /* determine maximum items */
269 for(i = curr; i != next; i=i->right) {
270 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
271 dc.y += dc.font.height + 2;
273 drawtext(NULL, dc.norm);
277 drawtext(const char *text, unsigned long col[ColLast]) {
279 int i, x, y, h, len, olen;
280 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
282 XSetForeground(dpy, dc.gc, col[ColBG]);
283 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
288 y = dc.y + ((h+2) / 2) - (h / 2) + dc.font.ascent;
290 /* shorten text if necessary */
291 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
294 memcpy(buf, text, len);
296 for(i = len; i && i > len - 3; buf[--i] = '.');
297 XSetForeground(dpy, dc.gc, col[ColFG]);
299 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
301 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
305 eprint(const char *errstr, ...) {
308 va_start(ap, errstr);
309 vfprintf(stderr, errstr, ap);
315 getcolor(const char *colstr) {
316 Colormap cmap = DefaultColormap(dpy, screen);
319 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
320 eprint("error, cannot allocate color '%s'\n", colstr);
328 for(len = 1000; len; len--) {
329 if(XGrabKeyboard(dpy, root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
338 initfont(const char *fontstr) {
339 char *def, **missing;
342 if(!fontstr || fontstr[0] == '\0')
343 eprint("error, cannot load font: '%s'\n", fontstr);
345 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
347 XFreeStringList(missing);
349 XFontSetExtents *font_extents;
350 XFontStruct **xfonts;
352 dc.font.ascent = dc.font.descent = 0;
353 font_extents = XExtentsOfFontSet(dc.font.set);
354 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
355 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
356 if(dc.font.ascent < (*xfonts)->ascent)
357 dc.font.ascent = (*xfonts)->ascent;
358 if(dc.font.descent < (*xfonts)->descent)
359 dc.font.descent = (*xfonts)->descent;
364 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
365 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
366 eprint("error, cannot load font: '%s'\n", fontstr);
367 dc.font.ascent = dc.font.xfont->ascent;
368 dc.font.descent = dc.font.xfont->descent;
370 dc.font.height = dc.font.ascent + dc.font.descent;
374 kpress(XKeyEvent * e) {
382 num = XLookupString(e, buf, sizeof buf, &ksym, NULL);
383 if(IsKeypadKey(ksym)) {
384 if(ksym == XK_KP_Enter)
386 else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
387 ksym = (ksym - XK_KP_0) + XK_0;
389 if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
390 || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
391 || IsPrivateKeypadKey(ksym))
393 /* first check if a control mask is omitted */
394 if(e->state & ControlMask) {
396 default: /* ignore other control sequences */
423 while(i >= 0 && text[i] == ' ')
425 while(i >= 0 && text[i] != ' ')
433 if(CLEANMASK(e->state) & Mod1Mask) {
458 if(!(fp = (FILE*)popen("sselp", "r")))
459 eprint("dmenu: Could not popen sselp\n");
460 c = fgets(text + len, sizeof(text) - len, fp);
466 if(len && text[len-1] == '\n')
475 if(num && !iscntrl((int) buf[0])) {
477 memmove(text + cursor + num, text + cursor, sizeof text - cursor);
478 strncpy(text + cursor, buf, sizeof text - cursor);
485 memmove(text + cursor + -1, text + cursor, sizeof text - cursor);
497 while(sel && sel->right)
512 if(sel && sel->left){
514 if(sel->right == curr) {
537 if((e->state & ShiftMask) && *text)
538 fprintf(stdout, "%s", text);
540 fprintf(stdout, "%s", sel->text);
542 fprintf(stdout, "%s", text);
550 else if(sel && sel->right) {
563 strncpy(text, sel->text, sizeof text);
564 cursor = strlen(text);
569 cursor = MIN(cursor, len);
570 cursor = MAX(cursor, 0);
575 match(char *pattern) {
577 Item *i, *itemend, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
581 plen = strlen(pattern);
582 item = lexact = lprefix = lsubstr = itemend = exactend = prefixend = substrend = NULL;
583 for(i = allitems; i; i = i->next)
584 if(!fstrncmp(pattern, i->text, plen + 1))
585 appenditem(i, &lexact, &exactend);
586 else if(!fstrncmp(pattern, i->text, plen))
587 appenditem(i, &lprefix, &prefixend);
588 else if(fstrstr(i->text, pattern))
589 appenditem(i, &lsubstr, &substrend);
596 itemend->right = lprefix;
597 lprefix->left = itemend;
605 itemend->right = lsubstr;
606 lsubstr->left = itemend;
611 curr = prev = next = sel = item;
618 unsigned int len = 0, max = 0;
622 while(fgets(buf, sizeof buf, stdin)) {
624 if (buf[len - 1] == '\n')
626 if(!(p = strdup(buf)))
627 eprint("fatal: could not strdup() %u bytes\n", strlen(buf));
632 if(!(new = (Item *)malloc(sizeof(Item))))
633 eprint("fatal: could not malloc() %u bytes\n", sizeof(Item));
634 new->next = new->left = new->right = NULL;
648 /* main event loop */
649 while(running && !XNextEvent(dpy, &ev))
651 default: /* ignore all crap */
657 if(ev.xexpose.count == 0)
668 XineramaScreenInfo *info = NULL;
670 XModifierKeymap *modmap;
671 XSetWindowAttributes wa;
673 /* init modifier map */
674 modmap = XGetModifierMapping(dpy);
675 for(i = 0; i < 8; i++)
676 for(j = 0; j < modmap->max_keypermod; j++) {
677 if(modmap->modifiermap[i * modmap->max_keypermod + j]
678 == XKeysymToKeycode(dpy, XK_Num_Lock))
679 numlockmask = (1 << i);
681 XFreeModifiermap(modmap);
684 dc.norm[ColBG] = getcolor(normbgcolor);
685 dc.norm[ColFG] = getcolor(normfgcolor);
686 dc.sel[ColBG] = getcolor(selbgcolor);
687 dc.sel[ColFG] = getcolor(selfgcolor);
691 wa.override_redirect = True;
692 wa.background_pixmap = ParentRelative;
693 wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask;
695 /* menu window geometry */
696 mh = dc.font.height + 2;
697 mh = vlist ? mh * (lines+1) : mh;
699 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
705 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
706 for(i = 0; i < n; i++)
707 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
711 y = topbar ? info[i].y_org : info[i].y_org + info[i].height - mh;
719 y = topbar ? 0 : DisplayHeight(dpy, screen) - mh;
720 mw = DisplayWidth(dpy, screen);
723 win = XCreateWindow(dpy, root, x, y, mw, mh, 0,
724 DefaultDepth(dpy, screen), CopyFromParent,
725 DefaultVisual(dpy, screen),
726 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
729 dc.drawable = XCreatePixmap(dpy, root, mw, mh, DefaultDepth(dpy, screen));
730 dc.gc = XCreateGC(dpy, root, 0, NULL);
731 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
733 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
735 cmdw = textw(maxname);
739 promptw = textw(prompt);
744 XMapRaised(dpy, win);
748 textnw(const char *text, unsigned int len) {
752 XmbTextExtents(dc.font.set, text, len, NULL, &r);
755 return XTextWidth(dc.font.xfont, text, len);
759 textw(const char *text) {
760 return textnw(text, strlen(text)) + dc.font.height;
764 main(int argc, char *argv[]) {
768 /* command line args */
769 for(i = 1; i < argc; i++)
770 if(!strcmp(argv[i], "-i")) {
771 fstrncmp = strncasecmp;
774 else if(!strcmp(argv[i], "-b"))
776 else if(!strcmp(argv[i], "-l")) {
778 calcoffsets = calcoffsetsv;
779 if(++i < argc) lines = atoi(argv[i]);
781 else if(!strcmp(argv[i], "-fn")) {
782 if(++i < argc) font = argv[i];
784 else if(!strcmp(argv[i], "-nb")) {
785 if(++i < argc) normbgcolor = argv[i];
787 else if(!strcmp(argv[i], "-nf")) {
788 if(++i < argc) normfgcolor = argv[i];
790 else if(!strcmp(argv[i], "-p")) {
791 if(++i < argc) prompt = argv[i];
793 else if(!strcmp(argv[i], "-sb")) {
794 if(++i < argc) selbgcolor = argv[i];
796 else if(!strcmp(argv[i], "-sf")) {
797 if(++i < argc) selfgcolor = argv[i];
799 else if(!strcmp(argv[i], "-v"))
800 eprint("dmenu-"VERSION", © 2006-2009 dmenu engineers, see LICENSE for details\n");
802 eprint("usage: dmenu [-i] [-b] [-l <lines>] [-fn <font>] [-nb <color>] [-nf <color>]\n"
803 " [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
804 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
805 fprintf(stderr, "warning: no locale support\n");
806 if(!(dpy = XOpenDisplay(NULL)))
807 eprint("dmenu: cannot open display\n");
808 screen = DefaultScreen(dpy);
809 root = RootWindow(dpy, screen);
811 if(isatty(STDIN_FILENO)) {
813 running = grabkeyboard();
815 else { /* prevent keypress loss */
816 running = grabkeyboard();