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;
82 static int cursor = 0;
84 static unsigned int mw, mh;
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 */
386 memmove(text, text + cursor, sizeof text - cursor + 1);
394 while(i-- > 0 && text[i] == ' ');
395 while(i-- > 0 && text[i] != ' ');
396 memmove(text + i + 1, text + cursor, sizeof text - cursor + 1);
403 if(CLEANMASK(e->state) & Mod1Mask) {
429 if(!(fp = popen("sselp", "r")))
430 eprint("dmenu: cannot popen sselp\n");
431 s = fgets(buf, sizeof buf, fp);
437 if(num && buf[num-1] == '\n')
444 num = MIN(num, sizeof text - cursor);
445 if(num && !iscntrl((int) buf[0])) {
446 memmove(text + cursor + num, text + cursor, sizeof text - cursor - num);
447 memcpy(text + cursor, buf, num);
454 for(i = 1; cursor - i > 0 && !IS_UTF8_1ST_CHAR(text[cursor - i]); i++);
455 memmove(text + cursor - i, text + cursor, sizeof text - cursor + i);
461 for(i = 1; cursor + i < len && !IS_UTF8_1ST_CHAR(text[cursor + i]); i++);
462 memmove(text + cursor, text + cursor + i, sizeof text - cursor);
474 while(sel && sel->right)
491 if(sel && sel->left){
493 if(sel->right == curr) {
499 while(cursor-- > 0 && !IS_UTF8_1ST_CHAR(text[cursor]));
516 if((e->state & ShiftMask) || !sel)
517 fprintf(stdout, "%s", text);
519 fprintf(stdout, "%s", sel->text);
526 while(cursor++ < len && !IS_UTF8_1ST_CHAR(text[cursor]));
527 else if(sel && sel->right) {
540 strncpy(text, sel->text, sizeof text);
541 cursor = strlen(text);
549 match(char *pattern) {
551 Item *i, *itemend, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
555 plen = strlen(pattern);
556 item = lexact = lprefix = lsubstr = itemend = exactend = prefixend = substrend = NULL;
557 for(i = allitems; i; i = i->next)
558 if(!fstrncmp(pattern, i->text, plen + 1))
559 appenditem(i, &lexact, &exactend);
560 else if(!fstrncmp(pattern, i->text, plen))
561 appenditem(i, &lprefix, &prefixend);
562 else if(fstrstr(i->text, pattern))
563 appenditem(i, &lsubstr, &substrend);
570 itemend->right = lprefix;
571 lprefix->left = itemend;
579 itemend->right = lsubstr;
580 lsubstr->left = itemend;
585 curr = prev = next = sel = item;
591 char *p, buf[sizeof text];
592 unsigned int len = 0, max = 0;
596 while(fgets(buf, sizeof buf, stdin)) {
598 if(buf[len-1] == '\n')
600 if(!(p = strdup(buf)))
601 eprint("dmenu: cannot strdup %u bytes\n", len);
602 if((max = MAX(max, len)) == len)
604 if(!(new = malloc(sizeof *new)))
605 eprint("dmenu: cannot malloc %u bytes\n", sizeof *new);
606 new->next = new->left = new->right = NULL;
620 /* main event loop */
621 while(running && !XNextEvent(dpy, &ev))
627 if(ev.xexpose.count == 0)
630 case VisibilityNotify:
631 if (ev.xvisibility.state != VisibilityUnobscured)
632 XRaiseWindow(dpy, win);
642 XineramaScreenInfo *info = NULL;
644 XModifierKeymap *modmap;
645 XSetWindowAttributes wa;
646 XWindowAttributes pwa;
648 /* init modifier map */
649 modmap = XGetModifierMapping(dpy);
650 for(i = 0; i < 8; i++)
651 for(j = 0; j < modmap->max_keypermod; j++) {
652 if(modmap->modifiermap[i * modmap->max_keypermod + j]
653 == XKeysymToKeycode(dpy, XK_Num_Lock))
654 numlockmask = (1 << i);
656 XFreeModifiermap(modmap);
659 dc.norm[ColBG] = getcolor(normbgcolor);
660 dc.norm[ColFG] = getcolor(normfgcolor);
661 dc.sel[ColBG] = getcolor(selbgcolor);
662 dc.sel[ColFG] = getcolor(selfgcolor);
666 wa.override_redirect = True;
667 wa.background_pixmap = ParentRelative;
668 wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask | VisibilityChangeMask;
670 /* menu window geometry */
671 mh = (dc.font.height + 2) * (lines + 1);
673 if(parent == RootWindow(dpy, screen) && XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
679 if(XQueryPointer(dpy, parent, &dummy, &dummy, &x, &y, &di, &di, &dui))
680 for(i = 0; i < n; i++)
681 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
685 y = topbar ? info[i].y_org : info[i].y_org + info[i].height - mh;
692 XGetWindowAttributes(dpy, parent, &pwa);
694 y = topbar ? 0 : pwa.height - mh;
698 win = XCreateWindow(dpy, parent, x, y, mw, mh, 0,
699 DefaultDepth(dpy, screen), CopyFromParent,
700 DefaultVisual(dpy, screen),
701 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
704 dc.drawable = XCreatePixmap(dpy, parent, mw, mh, DefaultDepth(dpy, screen));
705 dc.gc = XCreateGC(dpy, parent, 0, NULL);
706 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
708 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
710 cmdw = MIN(textw(maxname), mw / 3);
712 promptw = MIN(textw(prompt), mw / 5);
715 XMapRaised(dpy, win);
719 textnw(const char *text, unsigned int len) {
723 XmbTextExtents(dc.font.set, text, len, NULL, &r);
726 return XTextWidth(dc.font.xfont, text, len);
730 textw(const char *text) {
731 return textnw(text, strlen(text)) + dc.font.height;
735 main(int argc, char *argv[]) {
739 /* command line args */
740 for(i = 1; i < argc; i++)
741 if(!strcmp(argv[i], "-i")) {
742 fstrncmp = strncasecmp;
745 else if(!strcmp(argv[i], "-b"))
747 else if(!strcmp(argv[i], "-e")) {
748 if(++i < argc) parent = atoi(argv[i]);
750 else if(!strcmp(argv[i], "-l")) {
751 if(++i < argc) lines = atoi(argv[i]);
753 calcoffsets = calcoffsetsv;
755 else if(!strcmp(argv[i], "-fn")) {
756 if(++i < argc) font = argv[i];
758 else if(!strcmp(argv[i], "-nb")) {
759 if(++i < argc) normbgcolor = argv[i];
761 else if(!strcmp(argv[i], "-nf")) {
762 if(++i < argc) normfgcolor = argv[i];
764 else if(!strcmp(argv[i], "-p")) {
765 if(++i < argc) prompt = argv[i];
767 else if(!strcmp(argv[i], "-sb")) {
768 if(++i < argc) selbgcolor = argv[i];
770 else if(!strcmp(argv[i], "-sf")) {
771 if(++i < argc) selfgcolor = argv[i];
773 else if(!strcmp(argv[i], "-v"))
774 eprint("dmenu-"VERSION", © 2006-2010 dmenu engineers, see LICENSE for details\n");
776 eprint("usage: dmenu [-i] [-b] [-e <xid>] [-l <lines>] [-fn <font>] [-nb <color>]\n"
777 " [-nf <color>] [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
778 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
779 fprintf(stderr, "dmenu: warning: no locale support\n");
780 if(!(dpy = XOpenDisplay(NULL)))
781 eprint("dmenu: cannot open display\n");
782 screen = DefaultScreen(dpy);
784 parent = RootWindow(dpy, screen);
787 running = grabkeyboard();