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 parent, win;
95 static int (*fstrncmp)(const char *, const char *, size_t n) = strncmp;
96 static char *(*fstrstr)(const char *, const char *) = strstr;
97 static unsigned int lines = 0;
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 = MIN(textw(next->text), mw / 3);
125 w = promptw + cmdw + 2 * spaceitem;
126 for(prev = curr; prev && prev->left; prev=prev->left) {
127 tw = MIN(textw(prev->left->text), mw / 3);
136 static unsigned int h;
140 h = (dc.font.height + 2) * (lines + 1);
141 for(next = curr; next; next=next->right) {
142 h -= dc.font.height + 2;
146 h = (dc.font.height + 2) * (lines + 1);
147 for(prev = curr; prev && prev->left; prev=prev->left) {
148 h -= dc.font.height + 2;
155 cistrstr(const char *s, const char *sub) {
161 if((c = *sub++) != '\0') {
166 if((csub = *s++) == '\0')
169 while(tolower(csub) != c);
171 while(strncasecmp(s, sub, len) != 0);
182 itm = allitems->next;
183 free(allitems->text);
188 XFreeFontSet(dpy, dc.font.set);
190 XFreeFont(dpy, dc.font.xfont);
191 XFreePixmap(dpy, dc.drawable);
193 XDestroyWindow(dpy, win);
194 XUngrabKeyboard(dpy, CurrentTime);
199 XRectangle r = { dc.x, dc.y + 2, 1, dc.font.height - 2 };
201 r.x += textnw(text, cursor) + dc.font.height / 2;
203 XSetForeground(dpy, dc.gc, dc.norm[ColFG]);
204 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
213 drawtext(NULL, dc.norm);
217 drawtext(prompt, dc.sel);
222 if(cmdw && item && lines == 0)
224 drawtext(text[0] ? text : NULL, dc.norm);
232 XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, mw, mh, 0, 0);
242 drawtext(curr->left ? "<" : NULL, dc.norm);
244 /* determine maximum items */
245 for(i = curr; i != next; i=i->right) {
246 dc.w = MIN(textw(i->text), mw / 3);
247 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
250 dc.x = mw - spaceitem;
252 drawtext(next ? ">" : NULL, dc.norm);
261 dc.y += dc.font.height + 2;
262 /* determine maximum items */
263 for(i = curr; i != next; i=i->right) {
264 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
265 dc.y += dc.font.height + 2;
267 drawtext(NULL, dc.norm);
271 drawtext(const char *text, unsigned long col[ColLast]) {
273 int i, x, y, h, len, olen;
274 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
276 XSetForeground(dpy, dc.gc, col[ColBG]);
277 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
282 y = dc.y + ((h+2) / 2) - (h / 2) + dc.font.ascent;
284 /* shorten text if necessary */
285 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
288 memcpy(buf, text, len);
290 for(i = len; i && i > len - 3; buf[--i] = '.');
291 XSetForeground(dpy, dc.gc, col[ColFG]);
293 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
295 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
299 eprint(const char *errstr, ...) {
302 va_start(ap, errstr);
303 vfprintf(stderr, errstr, ap);
309 getcolor(const char *colstr) {
310 Colormap cmap = DefaultColormap(dpy, screen);
313 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
314 eprint("error, cannot allocate color '%s'\n", colstr);
322 for(len = 1000; len; len--) {
323 if(XGrabKeyboard(dpy, parent, True, GrabModeAsync, GrabModeAsync, CurrentTime)
332 initfont(const char *fontstr) {
333 char *def, **missing;
336 if(!fontstr || fontstr[0] == '\0')
337 eprint("error, cannot load font: '%s'\n", fontstr);
339 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
341 XFreeStringList(missing);
343 XFontSetExtents *font_extents;
344 XFontStruct **xfonts;
346 dc.font.ascent = dc.font.descent = 0;
347 font_extents = XExtentsOfFontSet(dc.font.set);
348 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
349 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
350 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
351 dc.font.descent = MAX(dc.font.descent, (*xfonts)->descent);
356 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
357 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
358 eprint("error, cannot load font: '%s'\n", fontstr);
359 dc.font.ascent = dc.font.xfont->ascent;
360 dc.font.descent = dc.font.xfont->descent;
362 dc.font.height = dc.font.ascent + dc.font.descent;
366 kpress(XKeyEvent * e) {
367 char buf[sizeof text];
374 num = XLookupString(e, buf, sizeof buf, &ksym, NULL);
375 if(IsKeypadKey(ksym)) {
376 if(ksym == XK_KP_Enter)
378 else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
379 ksym = (ksym - XK_KP_0) + XK_0;
381 if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
382 || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
383 || IsPrivateKeypadKey(ksym))
385 /* first check if a control mask is omitted */
386 if(e->state & ControlMask) {
388 default: /* ignore other control sequences */
416 memmove(text, text + cursor, sizeof text - cursor + 1);
424 while(i-- > 0 && text[i] == ' ');
425 while(i-- > 0 && text[i] != ' ');
426 memmove(text + i + 1, text + cursor, sizeof text - cursor + 1);
433 if(CLEANMASK(e->state) & Mod1Mask) {
458 if(!(fp = (FILE*)popen("sselp", "r")))
459 eprint("dmenu: Could not popen sselp\n");
460 s = fgets(buf, sizeof buf, fp);
466 if(num && buf[num-1] == '\n')
473 num = MIN(num, sizeof text - cursor);
474 if(num && !iscntrl((int) buf[0])) {
475 memmove(text + cursor + num, text + cursor, sizeof text - cursor - num);
476 memcpy(text + cursor, buf, num);
483 memmove(text + cursor - 1, text + cursor, sizeof text - cursor + 1);
489 memmove(text + cursor, text + cursor + 1, sizeof text - cursor);
501 while(sel && sel->right)
518 if(sel && sel->left){
520 if(sel->right == curr) {
543 if((e->state & ShiftMask) || !sel)
544 fprintf(stdout, "%s", text);
546 fprintf(stdout, "%s", sel->text);
554 else if(sel && sel->right) {
567 strncpy(text, sel->text, sizeof text);
568 cursor = strlen(text);
576 match(char *pattern) {
578 Item *i, *itemend, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
582 plen = strlen(pattern);
583 item = lexact = lprefix = lsubstr = itemend = exactend = prefixend = substrend = NULL;
584 for(i = allitems; i; i = i->next)
585 if(!fstrncmp(pattern, i->text, plen + 1))
586 appenditem(i, &lexact, &exactend);
587 else if(!fstrncmp(pattern, i->text, plen))
588 appenditem(i, &lprefix, &prefixend);
589 else if(fstrstr(i->text, pattern))
590 appenditem(i, &lsubstr, &substrend);
597 itemend->right = lprefix;
598 lprefix->left = itemend;
606 itemend->right = lsubstr;
607 lsubstr->left = itemend;
612 curr = prev = next = sel = item;
618 char *p, buf[sizeof text];
619 unsigned int len = 0, max = 0;
623 while(fgets(buf, sizeof buf, stdin)) {
625 if(buf[len-1] == '\n')
627 if(!(p = strdup(buf)))
628 eprint("fatal: could not strdup() %u bytes\n", len);
629 if(max < len || !maxname) {
633 if(!(new = (Item *)malloc(sizeof(Item))))
634 eprint("fatal: could not malloc() %u bytes\n", sizeof(Item));
635 new->next = new->left = new->right = NULL;
649 /* main event loop */
650 while(running && !XNextEvent(dpy, &ev))
652 default: /* ignore all crap */
658 if(ev.xexpose.count == 0)
661 case VisibilityNotify:
662 if (ev.xvisibility.state != VisibilityUnobscured)
663 XRaiseWindow(dpy, win);
673 XineramaScreenInfo *info = NULL;
675 XModifierKeymap *modmap;
676 XSetWindowAttributes wa;
677 XWindowAttributes pwa;
679 /* init modifier map */
680 modmap = XGetModifierMapping(dpy);
681 for(i = 0; i < 8; i++)
682 for(j = 0; j < modmap->max_keypermod; j++) {
683 if(modmap->modifiermap[i * modmap->max_keypermod + j]
684 == XKeysymToKeycode(dpy, XK_Num_Lock))
685 numlockmask = (1 << i);
687 XFreeModifiermap(modmap);
690 dc.norm[ColBG] = getcolor(normbgcolor);
691 dc.norm[ColFG] = getcolor(normfgcolor);
692 dc.sel[ColBG] = getcolor(selbgcolor);
693 dc.sel[ColFG] = getcolor(selfgcolor);
697 wa.override_redirect = True;
698 wa.background_pixmap = ParentRelative;
699 wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask | VisibilityChangeMask;
701 /* menu window geometry */
702 mh = (dc.font.height + 2) * (lines + 1);
704 if(parent == RootWindow(dpy, screen) && XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
710 if(XQueryPointer(dpy, parent, &dummy, &dummy, &x, &y, &di, &di, &dui))
711 for(i = 0; i < n; i++)
712 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
716 y = topbar ? info[i].y_org : info[i].y_org + info[i].height - mh;
723 XGetWindowAttributes(dpy, parent, &pwa);
725 y = topbar ? 0 : pwa.height - mh;
729 win = XCreateWindow(dpy, parent, x, y, mw, mh, 0,
730 DefaultDepth(dpy, screen), CopyFromParent,
731 DefaultVisual(dpy, screen),
732 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
735 dc.drawable = XCreatePixmap(dpy, parent, mw, mh, DefaultDepth(dpy, screen));
736 dc.gc = XCreateGC(dpy, parent, 0, NULL);
737 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
739 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
741 cmdw = MIN(textw(maxname), mw / 3);
743 promptw = MIN(textw(prompt), mw / 5);
746 XMapRaised(dpy, win);
750 textnw(const char *text, unsigned int len) {
754 XmbTextExtents(dc.font.set, text, len, NULL, &r);
757 return XTextWidth(dc.font.xfont, text, len);
761 textw(const char *text) {
762 return textnw(text, strlen(text)) + dc.font.height;
766 main(int argc, char *argv[]) {
770 /* command line args */
771 for(i = 1; i < argc; i++)
772 if(!strcmp(argv[i], "-i")) {
773 fstrncmp = strncasecmp;
776 else if(!strcmp(argv[i], "-b"))
778 else if(!strcmp(argv[i], "-e")) {
779 if(++i < argc) parent = atoi(argv[i]);
781 else if(!strcmp(argv[i], "-l")) {
782 calcoffsets = calcoffsetsv;
783 if(++i < argc) lines = atoi(argv[i]);
785 else if(!strcmp(argv[i], "-fn")) {
786 if(++i < argc) font = argv[i];
788 else if(!strcmp(argv[i], "-nb")) {
789 if(++i < argc) normbgcolor = argv[i];
791 else if(!strcmp(argv[i], "-nf")) {
792 if(++i < argc) normfgcolor = argv[i];
794 else if(!strcmp(argv[i], "-p")) {
795 if(++i < argc) prompt = argv[i];
797 else if(!strcmp(argv[i], "-sb")) {
798 if(++i < argc) selbgcolor = argv[i];
800 else if(!strcmp(argv[i], "-sf")) {
801 if(++i < argc) selfgcolor = argv[i];
803 else if(!strcmp(argv[i], "-v"))
804 eprint("dmenu-"VERSION", © 2006-2010 dmenu engineers, see LICENSE for details\n");
806 eprint("usage: dmenu [-i] [-b] [-e <xid>] [-l <lines>] [-fn <font>] [-nb <color>]\n"
807 " [-nf <color>] [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
808 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
809 fprintf(stderr, "warning: no locale support\n");
810 if(!(dpy = XOpenDisplay(NULL)))
811 eprint("dmenu: cannot open display\n");
812 screen = DefaultScreen(dpy);
814 parent = RootWindow(dpy, screen);
817 running = grabkeyboard();