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) {
358 default: /* ignore other control sequences */
390 memmove(text, text + cursor, sizeof text - cursor + 1);
398 while(i-- > 0 && text[i] == ' ');
399 while(i-- > 0 && text[i] != ' ');
400 memmove(text + i + 1, text + cursor, sizeof text - cursor + 1);
407 if(CLEANMASK(e->state) & Mod1Mask) {
433 if(!(fp = popen("sselp", "r")))
434 eprint("dmenu: cannot popen sselp\n");
435 s = fgets(buf, sizeof buf, fp);
441 if(num && buf[num-1] == '\n')
448 num = MIN(num, sizeof text - cursor);
449 if(num && !iscntrl((int) buf[0])) {
450 memmove(text + cursor + num, text + cursor, sizeof text - cursor - num);
451 memcpy(text + cursor, buf, num);
459 for(i = 1; cursor - i > 0 && !IS_UTF8_1ST_CHAR(text[cursor - i]); i++);
460 memmove(text + cursor - i, text + cursor, sizeof text - cursor + i);
465 for(i = 1; cursor + i < len && !IS_UTF8_1ST_CHAR(text[cursor + i]); i++);
466 memmove(text + cursor, text + cursor + i, sizeof text - cursor);
478 while(sel && sel->right)
495 if(sel && sel->left){
497 if(sel->right == curr) {
503 while(cursor-- > 0 && !IS_UTF8_1ST_CHAR(text[cursor]));
520 if((e->state & ShiftMask) || !sel)
521 fprintf(stdout, "%s", text);
523 fprintf(stdout, "%s", sel->text);
530 while(cursor++ < len && !IS_UTF8_1ST_CHAR(text[cursor]));
531 else if(sel && sel->right) {
544 strncpy(text, sel->text, sizeof text);
545 cursor = strlen(text);
553 match(char *pattern) {
555 Item *i, *itemend, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
559 plen = strlen(pattern);
560 item = lexact = lprefix = lsubstr = itemend = exactend = prefixend = substrend = NULL;
561 for(i = allitems; i; i = i->next)
562 if(!fstrncmp(pattern, i->text, plen + 1))
563 appenditem(i, &lexact, &exactend);
564 else if(!fstrncmp(pattern, i->text, plen))
565 appenditem(i, &lprefix, &prefixend);
566 else if(fstrstr(i->text, pattern))
567 appenditem(i, &lsubstr, &substrend);
574 itemend->right = lprefix;
575 lprefix->left = itemend;
583 itemend->right = lsubstr;
584 lsubstr->left = itemend;
589 curr = prev = next = sel = item;
595 char *p, buf[sizeof text];
596 unsigned int len = 0, max = 0;
600 while(fgets(buf, sizeof buf, stdin)) {
602 if(buf[len-1] == '\n')
604 if(!(p = strdup(buf)))
605 eprint("dmenu: cannot strdup %u bytes\n", len);
606 if((max = MAX(max, len)) == len)
608 if(!(new = malloc(sizeof *new)))
609 eprint("dmenu: cannot malloc %u bytes\n", sizeof *new);
610 new->next = new->left = new->right = NULL;
624 /* main event loop */
625 while(running && !XNextEvent(dpy, &ev))
631 if(ev.xexpose.count == 0)
634 case VisibilityNotify:
635 if (ev.xvisibility.state != VisibilityUnobscured)
636 XRaiseWindow(dpy, win);
646 XineramaScreenInfo *info = NULL;
648 XModifierKeymap *modmap;
649 XSetWindowAttributes wa;
650 XWindowAttributes pwa;
652 /* init modifier map */
653 modmap = XGetModifierMapping(dpy);
654 for(i = 0; i < 8; i++)
655 for(j = 0; j < modmap->max_keypermod; j++) {
656 if(modmap->modifiermap[i * modmap->max_keypermod + j]
657 == XKeysymToKeycode(dpy, XK_Num_Lock))
658 numlockmask = (1 << i);
660 XFreeModifiermap(modmap);
663 dc.norm[ColBG] = getcolor(normbgcolor);
664 dc.norm[ColFG] = getcolor(normfgcolor);
665 dc.sel[ColBG] = getcolor(selbgcolor);
666 dc.sel[ColFG] = getcolor(selfgcolor);
670 wa.override_redirect = True;
671 wa.background_pixmap = ParentRelative;
672 wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask | VisibilityChangeMask;
674 /* menu window geometry */
675 mh = (dc.font.height + 2) * (lines + 1);
677 if(parent == RootWindow(dpy, screen) && XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
683 if(XQueryPointer(dpy, parent, &dummy, &dummy, &x, &y, &di, &di, &dui))
684 for(i = 0; i < n; i++)
685 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
689 y = topbar ? info[i].y_org : info[i].y_org + info[i].height - mh;
696 XGetWindowAttributes(dpy, parent, &pwa);
698 y = topbar ? 0 : pwa.height - mh;
702 win = XCreateWindow(dpy, parent, x, y, mw, mh, 0,
703 DefaultDepth(dpy, screen), CopyFromParent,
704 DefaultVisual(dpy, screen),
705 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
708 dc.drawable = XCreatePixmap(dpy, parent, mw, mh, DefaultDepth(dpy, screen));
709 dc.gc = XCreateGC(dpy, parent, 0, NULL);
710 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
712 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
714 cmdw = MIN(textw(maxname), mw / 3);
716 promptw = MIN(textw(prompt), mw / 5);
719 XMapRaised(dpy, win);
723 textnw(const char *text, unsigned int len) {
727 XmbTextExtents(dc.font.set, text, len, NULL, &r);
730 return XTextWidth(dc.font.xfont, text, len);
734 textw(const char *text) {
735 return textnw(text, strlen(text)) + dc.font.height;
739 main(int argc, char *argv[]) {
743 /* command line args */
744 for(i = 1; i < argc; i++)
745 if(!strcmp(argv[i], "-i")) {
746 fstrncmp = strncasecmp;
749 else if(!strcmp(argv[i], "-b"))
751 else if(!strcmp(argv[i], "-e")) {
752 if(++i < argc) parent = atoi(argv[i]);
754 else if(!strcmp(argv[i], "-l")) {
755 if(++i < argc) lines = atoi(argv[i]);
757 calcoffsets = calcoffsetsv;
759 else if(!strcmp(argv[i], "-fn")) {
760 if(++i < argc) font = argv[i];
762 else if(!strcmp(argv[i], "-nb")) {
763 if(++i < argc) normbgcolor = argv[i];
765 else if(!strcmp(argv[i], "-nf")) {
766 if(++i < argc) normfgcolor = argv[i];
768 else if(!strcmp(argv[i], "-p")) {
769 if(++i < argc) prompt = argv[i];
771 else if(!strcmp(argv[i], "-sb")) {
772 if(++i < argc) selbgcolor = argv[i];
774 else if(!strcmp(argv[i], "-sf")) {
775 if(++i < argc) selfgcolor = argv[i];
777 else if(!strcmp(argv[i], "-v"))
778 eprint("dmenu-"VERSION", © 2006-2010 dmenu engineers, see LICENSE for details\n");
780 eprint("usage: dmenu [-i] [-b] [-e <xid>] [-l <lines>] [-fn <font>] [-nb <color>]\n"
781 " [-nf <color>] [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
782 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
783 fprintf(stderr, "dmenu: warning: no locale support\n");
784 if(!(dpy = XOpenDisplay(NULL)))
785 eprint("dmenu: cannot open display\n");
786 screen = DefaultScreen(dpy);
788 parent = RootWindow(dpy, screen);
791 running = grabkeyboard();