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 n) = 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 = *sub++) != '\0') {
152 if((csub = *s++) == '\0')
155 while(tolower(csub) != c);
157 while(strncasecmp(s, sub, len) != 0);
166 XFreeFontSet(dpy, dc.font.set);
168 XFreeFont(dpy, dc.font.xfont);
169 XFreePixmap(dpy, dc.drawable);
171 XDestroyWindow(dpy, win);
172 XUngrabKeyboard(dpy, CurrentTime);
177 XRectangle r = { dc.x, dc.y + 2, 1, dc.font.height - 2 };
179 r.x += textnw(text, cursor) + dc.font.height / 2;
181 XSetForeground(dpy, dc.gc, dc.norm[ColFG]);
182 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
191 drawtext(NULL, dc.norm);
195 drawtext(prompt, dc.sel);
200 if(cmdw && item && lines == 0)
202 drawtext(text[0] ? text : NULL, dc.norm);
210 XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, mw, mh, 0, 0);
220 drawtext(curr->left ? "<" : NULL, dc.norm);
222 for(i = curr; i != next; i=i->right) {
223 dc.w = MIN(textw(i->text), mw / 3);
224 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
229 drawtext(next ? ">" : NULL, dc.norm);
237 dc.h = dc.font.height + 2;
239 for(i = curr; i != next; i=i->right) {
240 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
244 drawtext(NULL, dc.norm);
248 drawtext(const char *text, unsigned long col[ColLast]) {
250 int i, x, y, h, len, olen;
251 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
253 XSetForeground(dpy, dc.gc, col[ColBG]);
254 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
259 y = dc.y + ((h+2) / 2) - (h / 2) + dc.font.ascent;
261 /* shorten text if necessary */
262 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
265 memcpy(buf, text, len);
267 for(i = len; i && i > len - 3; buf[--i] = '.');
268 XSetForeground(dpy, dc.gc, col[ColFG]);
270 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
272 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
276 eprint(const char *errstr, ...) {
279 va_start(ap, errstr);
280 vfprintf(stderr, errstr, ap);
286 getcolor(const char *colstr) {
287 Colormap cmap = DefaultColormap(dpy, screen);
290 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
291 eprint("dmenu: cannot allocate color '%s'\n", colstr);
299 for(len = 1000; len; len--) {
300 if(XGrabKeyboard(dpy, parent, True, GrabModeAsync, GrabModeAsync, CurrentTime)
309 initfont(const char *fontstr) {
310 char *def, **missing = NULL;
313 if(!fontstr || fontstr[0] == '\0')
314 eprint("dmenu: cannot load font: '%s'\n", fontstr);
315 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
317 XFreeStringList(missing);
319 XFontStruct **xfonts;
321 dc.font.ascent = dc.font.descent = 0;
322 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
323 for(i = 0; i < n; i++) {
324 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
325 dc.font.descent = MAX(dc.font.descent, (*xfonts)->descent);
330 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
331 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
332 eprint("dmenu: cannot load font: '%s'\n", fontstr);
333 dc.font.ascent = dc.font.xfont->ascent;
334 dc.font.descent = dc.font.xfont->descent;
336 dc.font.height = dc.font.ascent + dc.font.descent;
340 kpress(XKeyEvent * e) {
341 char buf[sizeof text];
347 num = XLookupString(e, buf, sizeof buf, &ksym, NULL);
348 if(IsKeypadKey(ksym)) {
349 if(ksym == XK_KP_Enter)
351 else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
352 ksym = (ksym - XK_KP_0) + XK_0;
354 if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
355 || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
356 || IsPrivateKeypadKey(ksym))
358 /* first check if a control mask is omitted */
359 if(e->state & ControlMask) {
361 default: /* ignore other control sequences */
389 memmove(text, text + cursor, sizeof text - cursor + 1);
397 while(i-- > 0 && text[i] == ' ');
398 while(i-- > 0 && text[i] != ' ');
399 memmove(text + i + 1, text + cursor, sizeof text - cursor + 1);
406 if(CLEANMASK(e->state) & Mod1Mask) {
431 if(!(fp = popen("sselp", "r")))
432 eprint("dmenu: cannot popen sselp\n");
433 s = fgets(buf, sizeof buf, fp);
439 if(num && buf[num-1] == '\n')
446 num = MIN(num, sizeof text - cursor);
447 if(num && !iscntrl((int) buf[0])) {
448 memmove(text + cursor + num, text + cursor, sizeof text - cursor - num);
449 memcpy(text + cursor, buf, num);
456 for(i = 1; cursor - i > 0 && !IS_UTF8_1ST_CHAR(text[cursor - i]); i++);
457 memmove(text + cursor - i, text + cursor, sizeof text - cursor + i);
463 for(i = 1; cursor + i < len && !IS_UTF8_1ST_CHAR(text[cursor + i]); i++);
464 memmove(text + cursor, text + cursor + i, sizeof text - cursor);
476 while(sel && sel->right)
493 if(sel && sel->left){
495 if(sel->right == curr) {
500 else if(cursor > 0) {
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);
532 } while(cursor < len && !IS_UTF8_1ST_CHAR(text[cursor]));
533 } else if(sel && sel->right) {
546 strncpy(text, sel->text, sizeof text);
547 cursor = strlen(text);
555 match(char *pattern) {
557 Item *i, *itemend, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
561 plen = strlen(pattern);
562 item = lexact = lprefix = lsubstr = itemend = exactend = prefixend = substrend = NULL;
563 for(i = allitems; i; i = i->next)
564 if(!fstrncmp(pattern, i->text, plen + 1))
565 appenditem(i, &lexact, &exactend);
566 else if(!fstrncmp(pattern, i->text, plen))
567 appenditem(i, &lprefix, &prefixend);
568 else if(fstrstr(i->text, pattern))
569 appenditem(i, &lsubstr, &substrend);
576 itemend->right = lprefix;
577 lprefix->left = itemend;
585 itemend->right = lsubstr;
586 lsubstr->left = itemend;
591 curr = prev = next = sel = item;
597 char *p, buf[sizeof text];
598 unsigned int len = 0, max = 0;
602 while(fgets(buf, sizeof buf, stdin)) {
604 if(buf[len-1] == '\n')
606 if(!(p = strdup(buf)))
607 eprint("dmenu: cannot strdup %u bytes\n", len);
608 if(max < len || !maxname) {
612 if(!(new = malloc(sizeof *new)))
613 eprint("dmenu: cannot malloc %u bytes\n", sizeof *new);
614 new->next = new->left = new->right = NULL;
628 /* main event loop */
629 while(running && !XNextEvent(dpy, &ev))
631 default: /* ignore all crap */
637 if(ev.xexpose.count == 0)
640 case VisibilityNotify:
641 if (ev.xvisibility.state != VisibilityUnobscured)
642 XRaiseWindow(dpy, win);
652 XineramaScreenInfo *info = NULL;
654 XModifierKeymap *modmap;
655 XSetWindowAttributes wa;
656 XWindowAttributes pwa;
658 /* init modifier map */
659 modmap = XGetModifierMapping(dpy);
660 for(i = 0; i < 8; i++)
661 for(j = 0; j < modmap->max_keypermod; j++) {
662 if(modmap->modifiermap[i * modmap->max_keypermod + j]
663 == XKeysymToKeycode(dpy, XK_Num_Lock))
664 numlockmask = (1 << i);
666 XFreeModifiermap(modmap);
669 dc.norm[ColBG] = getcolor(normbgcolor);
670 dc.norm[ColFG] = getcolor(normfgcolor);
671 dc.sel[ColBG] = getcolor(selbgcolor);
672 dc.sel[ColFG] = getcolor(selfgcolor);
676 wa.override_redirect = True;
677 wa.background_pixmap = ParentRelative;
678 wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask | VisibilityChangeMask;
680 /* menu window geometry */
681 mh = (dc.font.height + 2) * (lines + 1);
683 if(parent == RootWindow(dpy, screen) && XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
689 if(XQueryPointer(dpy, parent, &dummy, &dummy, &x, &y, &di, &di, &dui))
690 for(i = 0; i < n; i++)
691 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
695 y = topbar ? info[i].y_org : info[i].y_org + info[i].height - mh;
702 XGetWindowAttributes(dpy, parent, &pwa);
704 y = topbar ? 0 : pwa.height - mh;
708 win = XCreateWindow(dpy, parent, x, y, mw, mh, 0,
709 DefaultDepth(dpy, screen), CopyFromParent,
710 DefaultVisual(dpy, screen),
711 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
714 dc.drawable = XCreatePixmap(dpy, parent, mw, mh, DefaultDepth(dpy, screen));
715 dc.gc = XCreateGC(dpy, parent, 0, NULL);
716 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
718 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
720 cmdw = MIN(textw(maxname), mw / 3);
722 promptw = MIN(textw(prompt), mw / 5);
725 XMapRaised(dpy, win);
729 textnw(const char *text, unsigned int len) {
733 XmbTextExtents(dc.font.set, text, len, NULL, &r);
736 return XTextWidth(dc.font.xfont, text, len);
740 textw(const char *text) {
741 return textnw(text, strlen(text)) + dc.font.height;
745 main(int argc, char *argv[]) {
749 /* command line args */
750 for(i = 1; i < argc; i++)
751 if(!strcmp(argv[i], "-i")) {
752 fstrncmp = strncasecmp;
755 else if(!strcmp(argv[i], "-b"))
757 else if(!strcmp(argv[i], "-e")) {
758 if(++i < argc) parent = atoi(argv[i]);
760 else if(!strcmp(argv[i], "-l")) {
761 if(++i < argc) lines = atoi(argv[i]);
763 calcoffsets = calcoffsetsv;
765 else if(!strcmp(argv[i], "-fn")) {
766 if(++i < argc) font = argv[i];
768 else if(!strcmp(argv[i], "-nb")) {
769 if(++i < argc) normbgcolor = argv[i];
771 else if(!strcmp(argv[i], "-nf")) {
772 if(++i < argc) normfgcolor = argv[i];
774 else if(!strcmp(argv[i], "-p")) {
775 if(++i < argc) prompt = argv[i];
777 else if(!strcmp(argv[i], "-sb")) {
778 if(++i < argc) selbgcolor = argv[i];
780 else if(!strcmp(argv[i], "-sf")) {
781 if(++i < argc) selfgcolor = argv[i];
783 else if(!strcmp(argv[i], "-v"))
784 eprint("dmenu-"VERSION", © 2006-2010 dmenu engineers, see LICENSE for details\n");
786 eprint("usage: dmenu [-i] [-b] [-e <xid>] [-l <lines>] [-fn <font>] [-nb <color>]\n"
787 " [-nf <color>] [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
788 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
789 fprintf(stderr, "dmenu: warning: no locale support\n");
790 if(!(dpy = XOpenDisplay(NULL)))
791 eprint("dmenu: cannot open display\n");
792 screen = DefaultScreen(dpy);
794 parent = RootWindow(dpy, screen);
797 running = grabkeyboard();