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)) {
394 memmove(text, text + cursor, sizeof text - cursor + 1);
401 while(i-- > 0 && text[i] == ' ');
402 while(i-- > 0 && text[i] != ' ');
403 memmove(text + i + 1, text + cursor, sizeof text - cursor + 1);
412 if(!(fp = popen("sselp", "r")))
413 eprint("dmenu: cannot popen sselp\n");
414 s = fgets(buf, sizeof buf, fp);
420 if(num && buf[num-1] == '\n')
427 num = MIN(num, sizeof text - cursor);
428 if(num && !iscntrl((int) buf[0])) {
429 memmove(text + cursor + num, text + cursor, sizeof text - cursor - num);
430 memcpy(text + cursor, buf, num);
438 for(i = 1; cursor - i > 0 && !IS_UTF8_1ST_CHAR(text[cursor - i]); i++);
439 memmove(text + cursor - i, text + cursor, sizeof text - cursor + i);
446 for(i = 1; cursor + i < len && !IS_UTF8_1ST_CHAR(text[cursor + i]); i++);
447 memmove(text + cursor, text + cursor + i, sizeof text - cursor);
459 while(sel && sel->right)
475 if(cursor > 0 && (!sel || !sel->left)) {
476 while(cursor-- > 0 && !IS_UTF8_1ST_CHAR(text[cursor]));
482 if(!sel || !sel->left)
485 if(sel->right == curr) {
503 if((e->state & ShiftMask) || !sel)
504 fprintf(stdout, "%s", text);
506 fprintf(stdout, "%s", sel->text);
512 while(cursor++ < len && !IS_UTF8_1ST_CHAR(text[cursor]));
518 if(!sel || !sel->right)
529 strncpy(text, sel->text, sizeof text);
530 cursor = strlen(text);
538 match(char *pattern) {
540 Item *i, *itemend, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
544 plen = strlen(pattern);
545 item = lexact = lprefix = lsubstr = itemend = exactend = prefixend = substrend = NULL;
546 for(i = allitems; i; i = i->next)
547 if(!fstrncmp(pattern, i->text, plen + 1))
548 appenditem(i, &lexact, &exactend);
549 else if(!fstrncmp(pattern, i->text, plen))
550 appenditem(i, &lprefix, &prefixend);
551 else if(fstrstr(i->text, pattern))
552 appenditem(i, &lsubstr, &substrend);
559 itemend->right = lprefix;
560 lprefix->left = itemend;
568 itemend->right = lsubstr;
569 lsubstr->left = itemend;
574 curr = prev = next = sel = item;
580 char *p, buf[sizeof text];
581 unsigned int len = 0, max = 0;
585 while(fgets(buf, sizeof buf, stdin)) {
587 if(buf[len-1] == '\n')
589 if(!(p = strdup(buf)))
590 eprint("dmenu: cannot strdup %u bytes\n", len);
591 if((max = MAX(max, len)) == len)
593 if(!(new = malloc(sizeof *new)))
594 eprint("dmenu: cannot malloc %u bytes\n", sizeof *new);
595 new->next = new->left = new->right = NULL;
609 /* main event loop */
610 while(running && !XNextEvent(dpy, &ev))
616 if(ev.xexpose.count == 0)
619 case VisibilityNotify:
620 if (ev.xvisibility.state != VisibilityUnobscured)
621 XRaiseWindow(dpy, win);
631 XineramaScreenInfo *info = NULL;
633 XModifierKeymap *modmap;
634 XSetWindowAttributes wa;
635 XWindowAttributes pwa;
637 /* init modifier map */
638 modmap = XGetModifierMapping(dpy);
639 for(i = 0; i < 8; i++)
640 for(j = 0; j < modmap->max_keypermod; j++) {
641 if(modmap->modifiermap[i * modmap->max_keypermod + j]
642 == XKeysymToKeycode(dpy, XK_Num_Lock))
643 numlockmask = (1 << i);
645 XFreeModifiermap(modmap);
648 dc.norm[ColBG] = getcolor(normbgcolor);
649 dc.norm[ColFG] = getcolor(normfgcolor);
650 dc.sel[ColBG] = getcolor(selbgcolor);
651 dc.sel[ColFG] = getcolor(selfgcolor);
655 wa.override_redirect = True;
656 wa.background_pixmap = ParentRelative;
657 wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask | VisibilityChangeMask;
659 /* menu window geometry */
660 mh = (dc.font.height + 2) * (lines + 1);
662 if(parent == RootWindow(dpy, screen) && XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
668 if(XQueryPointer(dpy, parent, &dummy, &dummy, &x, &y, &di, &di, &dui))
669 for(i = 0; i < n; i++)
670 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
674 y = topbar ? info[i].y_org : info[i].y_org + info[i].height - mh;
681 XGetWindowAttributes(dpy, parent, &pwa);
683 y = topbar ? 0 : pwa.height - mh;
687 win = XCreateWindow(dpy, parent, x, y, mw, mh, 0,
688 DefaultDepth(dpy, screen), CopyFromParent,
689 DefaultVisual(dpy, screen),
690 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
693 dc.drawable = XCreatePixmap(dpy, parent, mw, mh, DefaultDepth(dpy, screen));
694 dc.gc = XCreateGC(dpy, parent, 0, NULL);
695 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
697 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
699 cmdw = MIN(textw(maxname), mw / 3);
701 promptw = MIN(textw(prompt), mw / 5);
704 XMapRaised(dpy, win);
708 textnw(const char *text, unsigned int len) {
712 XmbTextExtents(dc.font.set, text, len, NULL, &r);
715 return XTextWidth(dc.font.xfont, text, len);
719 textw(const char *text) {
720 return textnw(text, strlen(text)) + dc.font.height;
724 main(int argc, char *argv[]) {
728 /* command line args */
729 for(i = 1; i < argc; i++)
730 if(!strcmp(argv[i], "-i")) {
731 fstrncmp = strncasecmp;
734 else if(!strcmp(argv[i], "-b"))
736 else if(!strcmp(argv[i], "-e")) {
737 if(++i < argc) parent = atoi(argv[i]);
739 else if(!strcmp(argv[i], "-l")) {
740 if(++i < argc) lines = atoi(argv[i]);
742 calcoffsets = calcoffsetsv;
744 else if(!strcmp(argv[i], "-fn")) {
745 if(++i < argc) font = argv[i];
747 else if(!strcmp(argv[i], "-nb")) {
748 if(++i < argc) normbgcolor = argv[i];
750 else if(!strcmp(argv[i], "-nf")) {
751 if(++i < argc) normfgcolor = argv[i];
753 else if(!strcmp(argv[i], "-p")) {
754 if(++i < argc) prompt = argv[i];
756 else if(!strcmp(argv[i], "-sb")) {
757 if(++i < argc) selbgcolor = argv[i];
759 else if(!strcmp(argv[i], "-sf")) {
760 if(++i < argc) selfgcolor = argv[i];
762 else if(!strcmp(argv[i], "-v"))
763 eprint("dmenu-"VERSION", © 2006-2010 dmenu engineers, see LICENSE for details\n");
765 eprint("usage: dmenu [-i] [-b] [-e <xid>] [-l <lines>] [-fn <font>] [-nb <color>]\n"
766 " [-nf <color>] [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
767 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
768 fprintf(stderr, "dmenu: warning: no locale support\n");
769 if(!(dpy = XOpenDisplay(NULL)))
770 eprint("dmenu: cannot open display\n");
771 screen = DefaultScreen(dpy);
773 parent = RootWindow(dpy, screen);
776 running = grabkeyboard();