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 for(i = curr; i != next; i=i->right) {
245 dc.w = MIN(textw(i->text), mw / 3);
246 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
251 drawtext(next ? ">" : NULL, dc.norm);
259 dc.y += dc.font.height + 2;
260 for(i = curr; i != next; i=i->right) {
261 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
262 dc.y += dc.font.height + 2;
264 drawtext(NULL, dc.norm);
268 drawtext(const char *text, unsigned long col[ColLast]) {
270 int i, x, y, h, len, olen;
271 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
273 XSetForeground(dpy, dc.gc, col[ColBG]);
274 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
279 y = dc.y + ((h+2) / 2) - (h / 2) + dc.font.ascent;
281 /* shorten text if necessary */
282 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
285 memcpy(buf, text, len);
287 for(i = len; i && i > len - 3; buf[--i] = '.');
288 XSetForeground(dpy, dc.gc, col[ColFG]);
290 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
292 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
296 eprint(const char *errstr, ...) {
299 va_start(ap, errstr);
300 vfprintf(stderr, errstr, ap);
306 getcolor(const char *colstr) {
307 Colormap cmap = DefaultColormap(dpy, screen);
310 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
311 eprint("error, cannot allocate color '%s'\n", colstr);
319 for(len = 1000; len; len--) {
320 if(XGrabKeyboard(dpy, parent, True, GrabModeAsync, GrabModeAsync, CurrentTime)
329 initfont(const char *fontstr) {
330 char *def, **missing;
333 if(!fontstr || fontstr[0] == '\0')
334 eprint("error, cannot load font: '%s'\n", fontstr);
336 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
338 XFreeStringList(missing);
340 XFontStruct **xfonts;
342 dc.font.ascent = dc.font.descent = 0;
343 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
344 for(i = 0; i < n; i++) {
345 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
346 dc.font.descent = MAX(dc.font.descent, (*xfonts)->descent);
351 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
352 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
353 eprint("error, cannot load font: '%s'\n", fontstr);
354 dc.font.ascent = dc.font.xfont->ascent;
355 dc.font.descent = dc.font.xfont->descent;
357 dc.font.height = dc.font.ascent + dc.font.descent;
361 kpress(XKeyEvent * e) {
362 char buf[sizeof text];
369 num = XLookupString(e, buf, sizeof buf, &ksym, NULL);
370 if(IsKeypadKey(ksym)) {
371 if(ksym == XK_KP_Enter)
373 else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
374 ksym = (ksym - XK_KP_0) + XK_0;
376 if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
377 || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
378 || IsPrivateKeypadKey(ksym))
380 /* first check if a control mask is omitted */
381 if(e->state & ControlMask) {
383 default: /* ignore other control sequences */
411 memmove(text, text + cursor, sizeof text - cursor + 1);
419 while(i-- > 0 && text[i] == ' ');
420 while(i-- > 0 && text[i] != ' ');
421 memmove(text + i + 1, text + cursor, sizeof text - cursor + 1);
428 if(CLEANMASK(e->state) & Mod1Mask) {
453 if(!(fp = (FILE*)popen("sselp", "r")))
454 eprint("dmenu: Could not popen sselp\n");
455 s = fgets(buf, sizeof buf, fp);
461 if(num && buf[num-1] == '\n')
468 num = MIN(num, sizeof text - cursor);
469 if(num && !iscntrl((int) buf[0])) {
470 memmove(text + cursor + num, text + cursor, sizeof text - cursor - num);
471 memcpy(text + cursor, buf, num);
478 memmove(text + cursor - 1, text + cursor, sizeof text - cursor + 1);
484 memmove(text + cursor, text + cursor + 1, sizeof text - cursor);
496 while(sel && sel->right)
513 if(sel && sel->left){
515 if(sel->right == curr) {
538 if((e->state & ShiftMask) || !sel)
539 fprintf(stdout, "%s", text);
541 fprintf(stdout, "%s", sel->text);
549 else if(sel && sel->right) {
562 strncpy(text, sel->text, sizeof text);
563 cursor = strlen(text);
571 match(char *pattern) {
573 Item *i, *itemend, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
577 plen = strlen(pattern);
578 item = lexact = lprefix = lsubstr = itemend = exactend = prefixend = substrend = NULL;
579 for(i = allitems; i; i = i->next)
580 if(!fstrncmp(pattern, i->text, plen + 1))
581 appenditem(i, &lexact, &exactend);
582 else if(!fstrncmp(pattern, i->text, plen))
583 appenditem(i, &lprefix, &prefixend);
584 else if(fstrstr(i->text, pattern))
585 appenditem(i, &lsubstr, &substrend);
592 itemend->right = lprefix;
593 lprefix->left = itemend;
601 itemend->right = lsubstr;
602 lsubstr->left = itemend;
607 curr = prev = next = sel = item;
613 char *p, buf[sizeof text];
614 unsigned int len = 0, max = 0;
618 while(fgets(buf, sizeof buf, stdin)) {
620 if(buf[len-1] == '\n')
622 if(!(p = strdup(buf)))
623 eprint("fatal: could not strdup() %u bytes\n", len);
624 if(max < len || !maxname) {
628 if(!(new = (Item *)malloc(sizeof(Item))))
629 eprint("fatal: could not malloc() %u bytes\n", sizeof(Item));
630 new->next = new->left = new->right = NULL;
644 /* main event loop */
645 while(running && !XNextEvent(dpy, &ev))
647 default: /* ignore all crap */
653 if(ev.xexpose.count == 0)
656 case VisibilityNotify:
657 if (ev.xvisibility.state != VisibilityUnobscured)
658 XRaiseWindow(dpy, win);
668 XineramaScreenInfo *info = NULL;
670 XModifierKeymap *modmap;
671 XSetWindowAttributes wa;
672 XWindowAttributes pwa;
674 /* init modifier map */
675 modmap = XGetModifierMapping(dpy);
676 for(i = 0; i < 8; i++)
677 for(j = 0; j < modmap->max_keypermod; j++) {
678 if(modmap->modifiermap[i * modmap->max_keypermod + j]
679 == XKeysymToKeycode(dpy, XK_Num_Lock))
680 numlockmask = (1 << i);
682 XFreeModifiermap(modmap);
685 dc.norm[ColBG] = getcolor(normbgcolor);
686 dc.norm[ColFG] = getcolor(normfgcolor);
687 dc.sel[ColBG] = getcolor(selbgcolor);
688 dc.sel[ColFG] = getcolor(selfgcolor);
692 wa.override_redirect = True;
693 wa.background_pixmap = ParentRelative;
694 wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask | VisibilityChangeMask;
696 /* menu window geometry */
697 mh = (dc.font.height + 2) * (lines + 1);
699 if(parent == RootWindow(dpy, screen) && XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
705 if(XQueryPointer(dpy, parent, &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;
718 XGetWindowAttributes(dpy, parent, &pwa);
720 y = topbar ? 0 : pwa.height - mh;
724 win = XCreateWindow(dpy, parent, x, y, mw, mh, 0,
725 DefaultDepth(dpy, screen), CopyFromParent,
726 DefaultVisual(dpy, screen),
727 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
730 dc.drawable = XCreatePixmap(dpy, parent, mw, mh, DefaultDepth(dpy, screen));
731 dc.gc = XCreateGC(dpy, parent, 0, NULL);
732 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
734 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
736 cmdw = MIN(textw(maxname), mw / 3);
738 promptw = MIN(textw(prompt), mw / 5);
741 XMapRaised(dpy, win);
745 textnw(const char *text, unsigned int len) {
749 XmbTextExtents(dc.font.set, text, len, NULL, &r);
752 return XTextWidth(dc.font.xfont, text, len);
756 textw(const char *text) {
757 return textnw(text, strlen(text)) + dc.font.height;
761 main(int argc, char *argv[]) {
765 /* command line args */
766 for(i = 1; i < argc; i++)
767 if(!strcmp(argv[i], "-i")) {
768 fstrncmp = strncasecmp;
771 else if(!strcmp(argv[i], "-b"))
773 else if(!strcmp(argv[i], "-e")) {
774 if(++i < argc) parent = atoi(argv[i]);
776 else if(!strcmp(argv[i], "-l")) {
777 calcoffsets = calcoffsetsv;
778 if(++i < argc) lines = atoi(argv[i]);
780 else if(!strcmp(argv[i], "-fn")) {
781 if(++i < argc) font = argv[i];
783 else if(!strcmp(argv[i], "-nb")) {
784 if(++i < argc) normbgcolor = argv[i];
786 else if(!strcmp(argv[i], "-nf")) {
787 if(++i < argc) normfgcolor = argv[i];
789 else if(!strcmp(argv[i], "-p")) {
790 if(++i < argc) prompt = argv[i];
792 else if(!strcmp(argv[i], "-sb")) {
793 if(++i < argc) selbgcolor = argv[i];
795 else if(!strcmp(argv[i], "-sf")) {
796 if(++i < argc) selfgcolor = argv[i];
798 else if(!strcmp(argv[i], "-v"))
799 eprint("dmenu-"VERSION", © 2006-2010 dmenu engineers, see LICENSE for details\n");
801 eprint("usage: dmenu [-i] [-b] [-e <xid>] [-l <lines>] [-fn <font>] [-nb <color>]\n"
802 " [-nf <color>] [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
803 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
804 fprintf(stderr, "warning: no locale support\n");
805 if(!(dpy = XOpenDisplay(NULL)))
806 eprint("dmenu: cannot open display\n");
807 screen = DefaultScreen(dpy);
809 parent = RootWindow(dpy, screen);
812 running = grabkeyboard();