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) {
119 w = promptw + cmdw + 2 * spaceitem;
120 for(next = curr; next; next=next->right) {
121 tw = MIN(textw(next->text), mw / 3);
126 w = promptw + cmdw + 2 * spaceitem;
127 for(prev = curr; prev && prev->left; prev=prev->left) {
128 tw = MIN(textw(prev->left->text), mw / 3);
137 static unsigned int h;
141 h = (dc.font.height + 2) * (lines + 1);
142 for(next = curr; next; next=next->right) {
143 h -= dc.font.height + 2;
147 h = (dc.font.height + 2) * (lines + 1);
148 for(prev = curr; prev && prev->left; prev=prev->left) {
149 h -= dc.font.height + 2;
156 cistrstr(const char *s, const char *sub) {
162 if((c = *sub++) != '\0') {
167 if((csub = *s++) == '\0')
170 while(tolower(csub) != c);
172 while(strncasecmp(s, sub, len) != 0);
183 itm = allitems->next;
184 free(allitems->text);
189 XFreeFontSet(dpy, dc.font.set);
191 XFreeFont(dpy, dc.font.xfont);
192 XFreePixmap(dpy, dc.drawable);
194 XDestroyWindow(dpy, win);
195 XUngrabKeyboard(dpy, CurrentTime);
200 XRectangle r = { dc.x, dc.y + 2, 1, dc.font.height - 2 };
202 r.x += textnw(text, cursor) + dc.font.height / 2;
204 XSetForeground(dpy, dc.gc, dc.norm[ColFG]);
205 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
214 drawtext(NULL, dc.norm);
218 drawtext(prompt, dc.sel);
223 if(cmdw && item && lines == 0)
225 drawtext(text[0] ? text : NULL, dc.norm);
233 XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, mw, mh, 0, 0);
243 drawtext(curr->left ? "<" : NULL, dc.norm);
245 for(i = curr; i != next; i=i->right) {
246 dc.w = MIN(textw(i->text), mw / 3);
247 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
252 drawtext(next ? ">" : NULL, dc.norm);
260 dc.y += dc.font.height + 2;
261 for(i = curr; i != next; i=i->right) {
262 drawtext(i->text, (sel == i) ? dc.sel : dc.norm);
263 dc.y += dc.font.height + 2;
265 drawtext(NULL, dc.norm);
269 drawtext(const char *text, unsigned long col[ColLast]) {
271 int i, x, y, h, len, olen;
272 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
274 XSetForeground(dpy, dc.gc, col[ColBG]);
275 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
280 y = dc.y + ((h+2) / 2) - (h / 2) + dc.font.ascent;
282 /* shorten text if necessary */
283 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
286 memcpy(buf, text, len);
288 for(i = len; i && i > len - 3; buf[--i] = '.');
289 XSetForeground(dpy, dc.gc, col[ColFG]);
291 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
293 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
297 eprint(const char *errstr, ...) {
300 va_start(ap, errstr);
301 vfprintf(stderr, errstr, ap);
307 getcolor(const char *colstr) {
308 Colormap cmap = DefaultColormap(dpy, screen);
311 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
312 eprint("error, cannot allocate color '%s'\n", colstr);
320 for(len = 1000; len; len--) {
321 if(XGrabKeyboard(dpy, parent, True, GrabModeAsync, GrabModeAsync, CurrentTime)
330 initfont(const char *fontstr) {
331 char *def, **missing;
334 if(!fontstr || fontstr[0] == '\0')
335 eprint("error, cannot load font: '%s'\n", fontstr);
337 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
339 XFreeStringList(missing);
341 XFontStruct **xfonts;
343 dc.font.ascent = dc.font.descent = 0;
344 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
345 for(i = 0; i < n; i++) {
346 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
347 dc.font.descent = MAX(dc.font.descent, (*xfonts)->descent);
352 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
353 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
354 eprint("error, cannot load font: '%s'\n", fontstr);
355 dc.font.ascent = dc.font.xfont->ascent;
356 dc.font.descent = dc.font.xfont->descent;
358 dc.font.height = dc.font.ascent + dc.font.descent;
362 kpress(XKeyEvent * e) {
363 char buf[sizeof text];
370 num = XLookupString(e, buf, sizeof buf, &ksym, NULL);
371 if(IsKeypadKey(ksym)) {
372 if(ksym == XK_KP_Enter)
374 else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
375 ksym = (ksym - XK_KP_0) + XK_0;
377 if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
378 || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
379 || IsPrivateKeypadKey(ksym))
381 /* first check if a control mask is omitted */
382 if(e->state & ControlMask) {
384 default: /* ignore other control sequences */
412 memmove(text, text + cursor, sizeof text - cursor + 1);
420 while(i-- > 0 && text[i] == ' ');
421 while(i-- > 0 && text[i] != ' ');
422 memmove(text + i + 1, text + cursor, sizeof text - cursor + 1);
429 if(CLEANMASK(e->state) & Mod1Mask) {
454 if(!(fp = (FILE*)popen("sselp", "r")))
455 eprint("dmenu: Could not popen sselp\n");
456 s = fgets(buf, sizeof buf, fp);
462 if(num && buf[num-1] == '\n')
469 num = MIN(num, sizeof text - cursor);
470 if(num && !iscntrl((int) buf[0])) {
471 memmove(text + cursor + num, text + cursor, sizeof text - cursor - num);
472 memcpy(text + cursor, buf, num);
480 while(cursor > off && !IS_UTF8_1ST_CHAR(text[cursor - off]))
482 memmove(text + cursor - off, text + cursor, sizeof text - cursor + off);
489 while(cursor + off < sizeof text - 1 && !IS_UTF8_1ST_CHAR(text[cursor + off]))
491 memmove(text + cursor, text + cursor + off, sizeof text - cursor);
503 while(sel && sel->right)
520 if(sel && sel->left){
522 if(sel->right == curr) {
527 else if(cursor > 0) {
530 } while(cursor > 0 && !IS_UTF8_1ST_CHAR(text[cursor]));
547 if((e->state & ShiftMask) || !sel)
548 fprintf(stdout, "%s", text);
550 fprintf(stdout, "%s", sel->text);
559 } while(cursor < len && !IS_UTF8_1ST_CHAR(text[cursor]));
560 } else if(sel && sel->right) {
573 strncpy(text, sel->text, sizeof text);
574 cursor = strlen(text);
582 match(char *pattern) {
584 Item *i, *itemend, *lexact, *lprefix, *lsubstr, *exactend, *prefixend, *substrend;
588 plen = strlen(pattern);
589 item = lexact = lprefix = lsubstr = itemend = exactend = prefixend = substrend = NULL;
590 for(i = allitems; i; i = i->next)
591 if(!fstrncmp(pattern, i->text, plen + 1))
592 appenditem(i, &lexact, &exactend);
593 else if(!fstrncmp(pattern, i->text, plen))
594 appenditem(i, &lprefix, &prefixend);
595 else if(fstrstr(i->text, pattern))
596 appenditem(i, &lsubstr, &substrend);
603 itemend->right = lprefix;
604 lprefix->left = itemend;
612 itemend->right = lsubstr;
613 lsubstr->left = itemend;
618 curr = prev = next = sel = item;
624 char *p, buf[sizeof text];
625 unsigned int len = 0, max = 0;
629 while(fgets(buf, sizeof buf, stdin)) {
631 if(buf[len-1] == '\n')
633 if(!(p = strdup(buf)))
634 eprint("fatal: could not strdup() %u bytes\n", len);
635 if(max < len || !maxname) {
639 if(!(new = (Item *)malloc(sizeof(Item))))
640 eprint("fatal: could not malloc() %u bytes\n", sizeof(Item));
641 new->next = new->left = new->right = NULL;
655 /* main event loop */
656 while(running && !XNextEvent(dpy, &ev))
658 default: /* ignore all crap */
664 if(ev.xexpose.count == 0)
667 case VisibilityNotify:
668 if (ev.xvisibility.state != VisibilityUnobscured)
669 XRaiseWindow(dpy, win);
679 XineramaScreenInfo *info = NULL;
681 XModifierKeymap *modmap;
682 XSetWindowAttributes wa;
683 XWindowAttributes pwa;
685 /* init modifier map */
686 modmap = XGetModifierMapping(dpy);
687 for(i = 0; i < 8; i++)
688 for(j = 0; j < modmap->max_keypermod; j++) {
689 if(modmap->modifiermap[i * modmap->max_keypermod + j]
690 == XKeysymToKeycode(dpy, XK_Num_Lock))
691 numlockmask = (1 << i);
693 XFreeModifiermap(modmap);
696 dc.norm[ColBG] = getcolor(normbgcolor);
697 dc.norm[ColFG] = getcolor(normfgcolor);
698 dc.sel[ColBG] = getcolor(selbgcolor);
699 dc.sel[ColFG] = getcolor(selfgcolor);
703 wa.override_redirect = True;
704 wa.background_pixmap = ParentRelative;
705 wa.event_mask = ExposureMask | ButtonPressMask | KeyPressMask | VisibilityChangeMask;
707 /* menu window geometry */
708 mh = (dc.font.height + 2) * (lines + 1);
710 if(parent == RootWindow(dpy, screen) && XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
716 if(XQueryPointer(dpy, parent, &dummy, &dummy, &x, &y, &di, &di, &dui))
717 for(i = 0; i < n; i++)
718 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
722 y = topbar ? info[i].y_org : info[i].y_org + info[i].height - mh;
729 XGetWindowAttributes(dpy, parent, &pwa);
731 y = topbar ? 0 : pwa.height - mh;
735 win = XCreateWindow(dpy, parent, x, y, mw, mh, 0,
736 DefaultDepth(dpy, screen), CopyFromParent,
737 DefaultVisual(dpy, screen),
738 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
741 dc.drawable = XCreatePixmap(dpy, parent, mw, mh, DefaultDepth(dpy, screen));
742 dc.gc = XCreateGC(dpy, parent, 0, NULL);
743 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
745 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
747 cmdw = MIN(textw(maxname), mw / 3);
749 promptw = MIN(textw(prompt), mw / 5);
752 XMapRaised(dpy, win);
756 textnw(const char *text, unsigned int len) {
760 XmbTextExtents(dc.font.set, text, len, NULL, &r);
763 return XTextWidth(dc.font.xfont, text, len);
767 textw(const char *text) {
768 return textnw(text, strlen(text)) + dc.font.height;
772 main(int argc, char *argv[]) {
776 /* command line args */
777 for(i = 1; i < argc; i++)
778 if(!strcmp(argv[i], "-i")) {
779 fstrncmp = strncasecmp;
782 else if(!strcmp(argv[i], "-b"))
784 else if(!strcmp(argv[i], "-e")) {
785 if(++i < argc) parent = atoi(argv[i]);
787 else if(!strcmp(argv[i], "-l")) {
788 calcoffsets = calcoffsetsv;
789 if(++i < argc) lines = atoi(argv[i]);
791 else if(!strcmp(argv[i], "-fn")) {
792 if(++i < argc) font = argv[i];
794 else if(!strcmp(argv[i], "-nb")) {
795 if(++i < argc) normbgcolor = argv[i];
797 else if(!strcmp(argv[i], "-nf")) {
798 if(++i < argc) normfgcolor = argv[i];
800 else if(!strcmp(argv[i], "-p")) {
801 if(++i < argc) prompt = argv[i];
803 else if(!strcmp(argv[i], "-sb")) {
804 if(++i < argc) selbgcolor = argv[i];
806 else if(!strcmp(argv[i], "-sf")) {
807 if(++i < argc) selfgcolor = argv[i];
809 else if(!strcmp(argv[i], "-v"))
810 eprint("dmenu-"VERSION", © 2006-2010 dmenu engineers, see LICENSE for details\n");
812 eprint("usage: dmenu [-i] [-b] [-e <xid>] [-l <lines>] [-fn <font>] [-nb <color>]\n"
813 " [-nf <color>] [-p <prompt>] [-sb <color>] [-sf <color>] [-v]\n");
814 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
815 fprintf(stderr, "warning: no locale support\n");
816 if(!(dpy = XOpenDisplay(NULL)))
817 eprint("dmenu: cannot open display\n");
818 screen = DefaultScreen(dpy);
820 parent = RootWindow(dpy, screen);
823 running = grabkeyboard();