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))
22 #define IS_UTF8_1ST_CHAR(c) ((((c) & 0xc0) == 0xc0) || !((c) & 0x80))
25 enum { ColFG, ColBG, ColLast };
30 unsigned long norm[ColLast];
31 unsigned long sel[ColLast];
41 } DC; /* draw context */
43 typedef struct Item Item;
46 Item *next; /* traverses all items */
47 Item *left, *right; /* traverses items matching current search pattern */
50 /* forward declarations */
51 static void appenditem(Item *i, Item **list, Item **last);
52 static void calcoffsetsh(void);
53 static void calcoffsetsv(void);
54 static char *cistrstr(const char *s, const char *sub);
55 static void cleanup(void);
56 static void drawcursor(void);
57 static void drawmenu(void);
58 static void drawmenuh(void);
59 static void drawmenuv(void);
60 static void drawtext(const char *text, unsigned long col[ColLast]);
61 static void eprint(const char *errstr, ...);
62 static unsigned long getcolor(const char *colstr);
63 static Bool grabkeyboard(void);
64 static void initfont(const char *fontstr);
65 static void kpress(XKeyEvent * e);
66 static void match(char *pattern);
67 static void readstdin(void);
68 static void run(void);
69 static void setup(Bool topbar);
70 static int textnw(const char *text, unsigned int len);
71 static int textw(const char *text);
76 static char *maxname = NULL;
77 static char *prompt = NULL;
78 static char text[4096];
80 static int promptw = 0;
83 static unsigned int mw, mh;
84 static unsigned int cursor = 0;
85 static unsigned int numlockmask = 0;
86 static Bool running = True;
89 static Item *allitems = NULL; /* first of all items */
90 static Item *item = NULL; /* first of pattern matching items */
91 static Item *sel = NULL;
92 static Item *next = NULL;
93 static Item *prev = NULL;
94 static Item *curr = NULL;
95 static Window parent, win;
96 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
97 static char *(*fstrstr)(const char *, const char *) = strstr;
98 static unsigned int lines = 0;
99 static void (*calcoffsets)(void) = calcoffsetsh;
102 appenditem(Item *i, Item **list, Item **last) {
118 w = promptw + cmdw + 2 * spaceitem;
119 for(next = curr; next && w < mw; next=next->right)
120 w += MIN(textw(next->text), mw / 3);
121 w = promptw + cmdw + 2 * spaceitem;
122 for(prev = curr; prev && prev->left && w < mw; prev=prev->left)
123 w += MIN(textw(prev->left->text), mw / 3);
132 h = (dc.font.height + 2) * lines;
133 for(next = curr; next && h > 0; next = next->right)
134 h -= dc.font.height + 2;
135 h = (dc.font.height + 2) * lines;
136 for(prev = curr; prev && prev->left && h > 0; prev = prev->left)
137 h -= dc.font.height + 2;
141 cistrstr(const char *s, const char *sub) {
147 if((c = tolower(*sub++)) != '\0') {
151 if((csub = *s++) == '\0')
154 while(tolower(csub) != c);
156 while(strncasecmp(s, sub, len) != 0);
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);
176 XRectangle r = { dc.x, dc.y + 2, 1, dc.font.height - 2 };
178 r.x += textnw(text, cursor) + dc.font.height / 2;
180 XSetForeground(dpy, dc.gc, dc.norm[ColFG]);
181 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
190 drawtext(NULL, dc.norm);
194 drawtext(prompt, dc.sel);
199 if(cmdw && item && lines == 0)
201 drawtext(*text ? text : NULL, dc.norm);
209 XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, mw, mh, 0, 0);
219 drawtext(curr->left ? "<" : NULL, dc.norm);
221 for(i = curr; i != next; i=i->right) {
222 dc.w = MIN(textw(i->text), mw / 3);
223 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
228 drawtext(next ? ">" : NULL, dc.norm);
236 dc.h = dc.font.height + 2;
238 for(i = curr; i != next; i=i->right) {
239 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
243 drawtext(NULL, dc.norm);
247 drawtext(const char *text, unsigned long col[ColLast]) {
249 int i, x, y, h, len, olen;
250 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
252 XSetForeground(dpy, dc.gc, col[ColBG]);
253 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
258 y = dc.y + ((h+2) / 2) - (h / 2) + dc.font.ascent;
260 /* shorten text if necessary */
261 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
264 memcpy(buf, text, len);
266 for(i = len; i && i > len - 3; buf[--i] = '.');
267 XSetForeground(dpy, dc.gc, col[ColFG]);
269 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
271 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
275 eprint(const char *errstr, ...) {
278 va_start(ap, errstr);
279 vfprintf(stderr, errstr, ap);
285 getcolor(const char *colstr) {
286 Colormap cmap = DefaultColormap(dpy, screen);
289 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
290 eprint("dmenu: cannot allocate color '%s'\n", colstr);
298 for(len = 1000; len; len--) {
299 if(XGrabKeyboard(dpy, parent, True, GrabModeAsync, GrabModeAsync, CurrentTime)
308 initfont(const char *fontstr) {
309 char *def, **missing = NULL;
312 if(!fontstr || fontstr[0] == '\0')
313 eprint("dmenu: cannot load font: '%s'\n", fontstr);
314 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
316 XFreeStringList(missing);
318 XFontStruct **xfonts;
320 dc.font.ascent = dc.font.descent = 0;
321 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
322 for(i = 0; i < n; i++) {
323 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
324 dc.font.descent = MAX(dc.font.descent, (*xfonts)->descent);
329 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
330 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
331 eprint("dmenu: cannot load font: '%s'\n", fontstr);
332 dc.font.ascent = dc.font.xfont->ascent;
333 dc.font.descent = dc.font.xfont->descent;
335 dc.font.height = dc.font.ascent + dc.font.descent;
339 kpress(XKeyEvent * e) {
340 char buf[sizeof text];
346 num = XLookupString(e, buf, sizeof buf, &ksym, NULL);
347 if(ksym == XK_KP_Enter)
349 else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
350 ksym = (ksym - XK_KP_0) + XK_0;
351 else if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
352 || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
353 || IsPrivateKeypadKey(ksym))
355 /* first check if a control mask is omitted */
356 if(e->state & ControlMask) {
357 switch(tolower(ksym)) {
358 default: /* ignore other control sequences */
382 memmove(text, text + cursor, sizeof text - cursor + 1);
389 while(i-- > 0 && text[i] == ' ');
390 while(i-- > 0 && text[i] != ' ');
391 memmove(text + i + 1, text + cursor, sizeof text - cursor + 1);
398 if(CLEANMASK(e->state) & Mod1Mask) {
424 if(!(fp = popen("sselp", "r")))
425 eprint("dmenu: cannot popen sselp\n");
426 s = fgets(buf, sizeof buf, fp);
432 if(num && buf[num-1] == '\n')
439 num = MIN(num, sizeof text - cursor);
440 if(num && !iscntrl((int) buf[0])) {
441 memmove(text + cursor + num, text + cursor, sizeof text - cursor - num);
442 memcpy(text + cursor, buf, num);
450 for(i = 1; cursor - i > 0 && !IS_UTF8_1ST_CHAR(text[cursor - i]); i++);
451 memmove(text + cursor - i, text + cursor, sizeof text - cursor + i);
456 for(i = 1; cursor + i < len && !IS_UTF8_1ST_CHAR(text[cursor + i]); i++);
457 memmove(text + cursor, text + cursor + i, sizeof text - cursor);
469 while(sel && sel->right)
486 if(sel && sel->left){
488 if(sel->right == curr) {
494 while(cursor-- > 0 && !IS_UTF8_1ST_CHAR(text[cursor]));
511 if((e->state & ShiftMask) || !sel)
512 fprintf(stdout, "%s", text);
514 fprintf(stdout, "%s", sel->text);
521 while(cursor++ < len && !IS_UTF8_1ST_CHAR(text[cursor]));
522 else if(sel && sel->right) {
535 strncpy(text, sel->text, sizeof text);
536 cursor = strlen(text);
544 match(char *pattern) {
546 Item *i, *itemend, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
550 plen = strlen(pattern);
551 item = lexact = lprefix = lsubstr = itemend = exactend = prefixend = substrend = NULL;
552 for(i = allitems; i; i = i->next)
553 if(!fstrncmp(pattern, i->text, plen + 1))
554 appenditem(i, &lexact, &exactend);
555 else if(!fstrncmp(pattern, i->text, plen))
556 appenditem(i, &lprefix, &prefixend);
557 else if(fstrstr(i->text, pattern))
558 appenditem(i, &lsubstr, &substrend);
565 itemend->right = lprefix;
566 lprefix->left = itemend;
574 itemend->right = lsubstr;
575 lsubstr->left = itemend;
580 curr = prev = next = sel = item;
586 char *p, buf[sizeof text];
587 unsigned int len = 0, max = 0;
591 while(fgets(buf, sizeof buf, stdin)) {
593 if(buf[len-1] == '\n')
595 if(!(p = strdup(buf)))
596 eprint("dmenu: cannot strdup %u bytes\n", len);
597 if((max = MAX(max, len)) == len)
599 if(!(new = malloc(sizeof *new)))
600 eprint("dmenu: cannot malloc %u bytes\n", sizeof *new);
601 new->next = new->left = new->right = NULL;
615 /* main event loop */
616 while(running && !XNextEvent(dpy, &ev))
622 if(ev.xexpose.count == 0)
625 case VisibilityNotify:
626 if (ev.xvisibility.state != VisibilityUnobscured)
627 XRaiseWindow(dpy, win);
637 XineramaScreenInfo *info = NULL;
639 XModifierKeymap *modmap;
640 XSetWindowAttributes wa;
641 XWindowAttributes pwa;
643 /* init modifier map */
644 modmap = XGetModifierMapping(dpy);
645 for(i = 0; i < 8; i++)
646 for(j = 0; j < modmap->max_keypermod; j++) {
647 if(modmap->modifiermap[i * modmap->max_keypermod + j]
648 == XKeysymToKeycode(dpy, XK_Num_Lock))
649 numlockmask = (1 << i);
651 XFreeModifiermap(modmap);
654 dc.norm[ColBG] = getcolor(normbgcolor);
655 dc.norm[ColFG] = getcolor(normfgcolor);
656 dc.sel[ColBG] = getcolor(selbgcolor);
657 dc.sel[ColFG] = getcolor(selfgcolor);
661 wa.override_redirect = True;
662 wa.background_pixmap = ParentRelative;
663 wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask | VisibilityChangeMask;
665 /* menu window geometry */
666 mh = (dc.font.height + 2) * (lines + 1);
668 if(parent == RootWindow(dpy, screen) && XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
674 if(XQueryPointer(dpy, parent, &dummy, &dummy, &x, &y, &di, &di, &dui))
675 for(i = 0; i < n; i++)
676 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
680 y = topbar ? info[i].y_org : info[i].y_org + info[i].height - mh;
687 XGetWindowAttributes(dpy, parent, &pwa);
689 y = topbar ? 0 : pwa.height - mh;
693 win = XCreateWindow(dpy, parent, x, y, mw, mh, 0,
694 DefaultDepth(dpy, screen), CopyFromParent,
695 DefaultVisual(dpy, screen),
696 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
699 dc.drawable = XCreatePixmap(dpy, parent, mw, mh, DefaultDepth(dpy, screen));
700 dc.gc = XCreateGC(dpy, parent, 0, NULL);
701 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
703 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
705 cmdw = MIN(textw(maxname), mw / 3);
707 promptw = MIN(textw(prompt), mw / 5);
710 XMapRaised(dpy, win);
714 textnw(const char *text, unsigned int len) {
718 XmbTextExtents(dc.font.set, text, len, NULL, &r);
721 return XTextWidth(dc.font.xfont, text, len);
725 textw(const char *text) {
726 return textnw(text, strlen(text)) + dc.font.height;
730 main(int argc, char *argv[]) {
734 /* command line args */
735 for(i = 1; i < argc; i++)
736 if(!strcmp(argv[i], "-i")) {
737 fstrncmp = strncasecmp;
740 else if(!strcmp(argv[i], "-b"))
742 else if(!strcmp(argv[i], "-e")) {
743 if(++i < argc) parent = atoi(argv[i]);
745 else if(!strcmp(argv[i], "-l")) {
746 if(++i < argc) lines = atoi(argv[i]);
748 calcoffsets = calcoffsetsv;
750 else if(!strcmp(argv[i], "-fn")) {
751 if(++i < argc) font = argv[i];
753 else if(!strcmp(argv[i], "-nb")) {
754 if(++i < argc) normbgcolor = argv[i];
756 else if(!strcmp(argv[i], "-nf")) {
757 if(++i < argc) normfgcolor = argv[i];
759 else if(!strcmp(argv[i], "-p")) {
760 if(++i < argc) prompt = argv[i];
762 else if(!strcmp(argv[i], "-sb")) {
763 if(++i < argc) selbgcolor = argv[i];
765 else if(!strcmp(argv[i], "-sf")) {
766 if(++i < argc) selfgcolor = argv[i];
768 else if(!strcmp(argv[i], "-v"))
769 eprint("dmenu-"VERSION", © 2006-2010 dmenu engineers, see LICENSE for details\n");
771 eprint("usage: dmenu [-i] [-b] [-e <xid>] [-l <lines>] [-fn <font>] [-nb <color>]\n"
772 " [-nf <color>] [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
773 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
774 fprintf(stderr, "dmenu: warning: no locale support\n");
775 if(!(dpy = XOpenDisplay(NULL)))
776 eprint("dmenu: cannot open display\n");
777 screen = DefaultScreen(dpy);
779 parent = RootWindow(dpy, screen);
782 running = grabkeyboard();