1 /* See LICENSE file for copyright and license details. */
12 #include <X11/Xatom.h>
13 #include <X11/Xutil.h>
15 #include <X11/extensions/Xinerama.h>
17 #include <X11/Xft/Xft.h>
23 #define INTERSECT(x,y,w,h,r) (MAX(0, MIN((x)+(w),(r).x_org+(r).width) - MAX((x),(r).x_org)) \
24 * MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
25 #define LENGTH(X) (sizeof X / sizeof X[0])
26 #define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad)
29 enum { SchemeNorm
, SchemeSel
, SchemeOut
, SchemeLast
}; /* color schemes */
33 struct item
*left
, *right
;
37 static char text
[BUFSIZ
] = "";
39 static int bh
, mw
, mh
;
40 static int inputw
= 0, promptw
;
41 static int lrpad
; /* sum of left and right padding */
43 static struct item
*items
= NULL
;
44 static struct item
*matches
, *matchend
;
45 static struct item
*prev
, *curr
, *next
, *sel
;
46 static int mon
= -1, screen
;
48 static Atom clip
, utf8
;
50 static Window root
, parentwin
, win
;
54 static Clr
*scheme
[SchemeLast
];
58 static int (*fstrncmp
)(const char *, const char *, size_t) = strncmp
;
59 static char *(*fstrstr
)(const char *, const char *) = strstr
;
62 textw_clamp(const char *str
, unsigned int n
)
64 unsigned int w
= drw_fontset_getwidth_clamp(drw
, str
, n
) + lrpad
;
69 appenditem(struct item
*item
, struct item
**list
, struct item
**last
)
72 (*last
)->right
= item
;
89 n
= mw
- (promptw
+ inputw
+ TEXTW("<") + TEXTW(">"));
90 /* calculate which items will begin the next page and previous page */
91 for (i
= 0, next
= curr
; next
; next
= next
->right
)
92 if ((i
+= (lines
> 0) ? bh
: textw_clamp(next
->text
, n
)) > n
)
94 for (i
= 0, prev
= curr
; prev
&& prev
->left
; prev
= prev
->left
)
95 if ((i
+= (lines
> 0) ? bh
: textw_clamp(prev
->left
->text
, n
)) > n
)
104 XUngrabKey(dpy
, AnyKey
, AnyModifier
, root
);
105 for (i
= 0; i
< SchemeLast
; i
++)
107 for (i
= 0; items
&& items
[i
].text
; ++i
)
116 cistrstr(const char *h
, const char *n
)
124 for (i
= 0; n
[i
] && tolower((unsigned char)n
[i
]) ==
125 tolower((unsigned char)h
[i
]); ++i
)
134 drawitem(struct item
*item
, int x
, int y
, int w
)
137 drw_setscheme(drw
, scheme
[SchemeSel
]);
139 drw_setscheme(drw
, scheme
[SchemeOut
]);
141 drw_setscheme(drw
, scheme
[SchemeNorm
]);
143 return drw_text(drw
, x
, y
, w
, bh
, lrpad
/ 2, item
->text
, 0);
153 drw_setscheme(drw
, scheme
[SchemeNorm
]);
154 drw_rect(drw
, 0, 0, mw
, mh
, 1, 1);
156 if (prompt
&& *prompt
) {
157 drw_setscheme(drw
, scheme
[SchemeSel
]);
158 x
= drw_text(drw
, x
, 0, promptw
, bh
, lrpad
/ 2, prompt
, 0);
160 /* draw input field */
161 w
= (lines
> 0 || !matches
) ? mw
- x
: inputw
;
162 drw_setscheme(drw
, scheme
[SchemeNorm
]);
163 drw_text(drw
, x
, 0, w
, bh
, lrpad
/ 2, text
, 0);
165 curpos
= TEXTW(text
) - TEXTW(&text
[cursor
]);
166 if ((curpos
+= lrpad
/ 2 - 1) < w
) {
167 drw_setscheme(drw
, scheme
[SchemeNorm
]);
168 drw_rect(drw
, x
+ curpos
, 2, 2, bh
- 4, 1, 0);
172 /* draw vertical list */
173 for (item
= curr
; item
!= next
; item
= item
->right
)
174 drawitem(item
, x
, y
+= bh
, mw
- x
);
175 } else if (matches
) {
176 /* draw horizontal list */
180 drw_setscheme(drw
, scheme
[SchemeNorm
]);
181 drw_text(drw
, x
, 0, w
, bh
, lrpad
/ 2, "<", 0);
184 for (item
= curr
; item
!= next
; item
= item
->right
)
185 x
= drawitem(item
, x
, 0, textw_clamp(item
->text
, mw
- x
- TEXTW(">")));
188 drw_setscheme(drw
, scheme
[SchemeNorm
]);
189 drw_text(drw
, mw
- w
, 0, w
, bh
, lrpad
/ 2, ">", 0);
192 drw_map(drw
, win
, 0, 0, mw
, mh
);
198 struct timespec ts
= { .tv_sec
= 0, .tv_nsec
= 10000000 };
202 for (i
= 0; i
< 100; ++i
) {
203 XGetInputFocus(dpy
, &focuswin
, &revertwin
);
206 XSetInputFocus(dpy
, win
, RevertToParent
, CurrentTime
);
207 nanosleep(&ts
, NULL
);
209 die("cannot grab focus");
215 struct timespec ts
= { .tv_sec
= 0, .tv_nsec
= 1000000 };
220 /* try to grab keyboard, we may have to wait for another process to ungrab */
221 for (i
= 0; i
< 1000; i
++) {
222 if (XGrabKeyboard(dpy
, DefaultRootWindow(dpy
), True
, GrabModeAsync
,
223 GrabModeAsync
, CurrentTime
) == GrabSuccess
)
225 nanosleep(&ts
, NULL
);
227 die("cannot grab keyboard");
233 static char **tokv
= NULL
;
236 char buf
[sizeof text
], *s
;
238 size_t len
, textsize
;
239 struct item
*item
, *lprefix
, *lsubstr
, *prefixend
, *substrend
;
242 /* separate input text into tokens to be matched individually */
243 for (s
= strtok(buf
, " "); s
; tokv
[tokc
- 1] = s
, s
= strtok(NULL
, " "))
244 if (++tokc
> tokn
&& !(tokv
= realloc(tokv
, ++tokn
* sizeof *tokv
)))
245 die("cannot realloc %zu bytes:", tokn
* sizeof *tokv
);
246 len
= tokc
? strlen(tokv
[0]) : 0;
248 matches
= lprefix
= lsubstr
= matchend
= prefixend
= substrend
= NULL
;
249 textsize
= strlen(text
) + 1;
250 for (item
= items
; item
&& item
->text
; item
++) {
251 for (i
= 0; i
< tokc
; i
++)
252 if (!fstrstr(item
->text
, tokv
[i
]))
254 if (i
!= tokc
) /* not all tokens match */
256 /* exact matches go first, then prefixes, then substrings */
257 if (!tokc
|| !fstrncmp(text
, item
->text
, textsize
))
258 appenditem(item
, &matches
, &matchend
);
259 else if (!fstrncmp(tokv
[0], item
->text
, len
))
260 appenditem(item
, &lprefix
, &prefixend
);
262 appenditem(item
, &lsubstr
, &substrend
);
266 matchend
->right
= lprefix
;
267 lprefix
->left
= matchend
;
270 matchend
= prefixend
;
274 matchend
->right
= lsubstr
;
275 lsubstr
->left
= matchend
;
278 matchend
= substrend
;
280 curr
= sel
= matches
;
285 insert(const char *str
, ssize_t n
)
287 if (strlen(text
) + n
> sizeof text
- 1)
289 /* move existing text out of the way, insert new text, and update cursor */
290 memmove(&text
[cursor
+ n
], &text
[cursor
], sizeof text
- cursor
- MAX(n
, 0));
292 memcpy(&text
[cursor
], str
, n
);
302 /* return location of next utf8 rune in the given direction (+1 or -1) */
303 for (n
= cursor
+ inc
; n
+ inc
>= 0 && (text
[n
] & 0xc0) == 0x80; n
+= inc
)
309 movewordedge(int dir
)
311 if (dir
< 0) { /* move cursor to the start of the word*/
312 while (cursor
> 0 && strchr(worddelimiters
, text
[nextrune(-1)]))
313 cursor
= nextrune(-1);
314 while (cursor
> 0 && !strchr(worddelimiters
, text
[nextrune(-1)]))
315 cursor
= nextrune(-1);
316 } else { /* move cursor to the end of the word */
317 while (text
[cursor
] && strchr(worddelimiters
, text
[cursor
]))
318 cursor
= nextrune(+1);
319 while (text
[cursor
] && !strchr(worddelimiters
, text
[cursor
]))
320 cursor
= nextrune(+1);
325 keypress(XKeyEvent
*ev
)
332 len
= XmbLookupString(xic
, ev
, buf
, sizeof buf
, &ksym
, &status
);
334 default: /* XLookupNone, XBufferOverflow */
343 if (ev
->state
& ControlMask
) {
345 case XK_a
: ksym
= XK_Home
; break;
346 case XK_b
: ksym
= XK_Left
; break;
347 case XK_c
: ksym
= XK_Escape
; break;
348 case XK_d
: ksym
= XK_Delete
; break;
349 case XK_e
: ksym
= XK_End
; break;
350 case XK_f
: ksym
= XK_Right
; break;
351 case XK_g
: ksym
= XK_Escape
; break;
352 case XK_h
: ksym
= XK_BackSpace
; break;
353 case XK_i
: ksym
= XK_Tab
; break;
354 case XK_j
: /* fallthrough */
355 case XK_J
: /* fallthrough */
356 case XK_m
: /* fallthrough */
357 case XK_M
: ksym
= XK_Return
; ev
->state
&= ~ControlMask
; break;
358 case XK_n
: ksym
= XK_Down
; break;
359 case XK_p
: ksym
= XK_Up
; break;
361 case XK_k
: /* delete right */
365 case XK_u
: /* delete left */
366 insert(NULL
, 0 - cursor
);
368 case XK_w
: /* delete word */
369 while (cursor
> 0 && strchr(worddelimiters
, text
[nextrune(-1)]))
370 insert(NULL
, nextrune(-1) - cursor
);
371 while (cursor
> 0 && !strchr(worddelimiters
, text
[nextrune(-1)]))
372 insert(NULL
, nextrune(-1) - cursor
);
374 case XK_y
: /* paste selection */
376 XConvertSelection(dpy
, (ev
->state
& ShiftMask
) ? clip
: XA_PRIMARY
,
377 utf8
, utf8
, win
, CurrentTime
);
396 } else if (ev
->state
& Mod1Mask
) {
404 case XK_g
: ksym
= XK_Home
; break;
405 case XK_G
: ksym
= XK_End
; break;
406 case XK_h
: ksym
= XK_Up
; break;
407 case XK_j
: ksym
= XK_Next
; break;
408 case XK_k
: ksym
= XK_Prior
; break;
409 case XK_l
: ksym
= XK_Down
; break;
418 if (!iscntrl((unsigned char)*buf
))
423 if (text
[cursor
] == '\0')
425 cursor
= nextrune(+1);
430 insert(NULL
, nextrune(-1) - cursor
);
434 if (text
[cursor
] != '\0') {
435 cursor
= strlen(text
);
439 /* jump to end of list and position items in reverse */
444 while (next
&& (curr
= curr
->right
))
454 if (sel
== matches
) {
458 sel
= curr
= matches
;
463 if (cursor
> 0 && (!sel
|| !sel
->left
|| lines
> 0)) {
464 cursor
= nextrune(-1);
472 if (sel
&& sel
->left
&& (sel
= sel
->left
)->right
== curr
) {
493 puts((sel
&& !(ev
->state
& ShiftMask
)) ? sel
->text
: text
);
494 if (!(ev
->state
& ControlMask
)) {
503 if (text
[cursor
] != '\0') {
504 cursor
= nextrune(+1);
512 if (sel
&& sel
->right
&& (sel
= sel
->right
) == next
) {
520 strncpy(text
, sel
->text
, sizeof text
- 1);
521 text
[sizeof text
- 1] = '\0';
522 cursor
= strlen(text
);
539 /* we have been given the current selection, now insert it into input */
540 if (XGetWindowProperty(dpy
, win
, utf8
, 0, (sizeof text
/ 4) + 1, False
,
541 utf8
, &da
, &di
, &dl
, &dl
, (unsigned char **)&p
)
543 insert(p
, (q
= strchr(p
, '\n')) ? q
- p
: (ssize_t
)strlen(p
));
552 char buf
[sizeof text
], *p
;
555 /* read each line from stdin and add it to the item list */
556 for (i
= 0; fgets(buf
, sizeof buf
, stdin
); i
++) {
557 if (i
+ 1 >= size
/ sizeof *items
)
558 if (!(items
= realloc(items
, (size
+= BUFSIZ
))))
559 die("cannot realloc %zu bytes:", size
);
560 if ((p
= strchr(buf
, '\n')))
562 if (!(items
[i
].text
= strdup(buf
)))
563 die("cannot strdup %zu bytes:", strlen(buf
) + 1);
567 items
[i
].text
= NULL
;
568 lines
= MIN(lines
, i
);
576 while (!XNextEvent(dpy
, &ev
)) {
577 if (XFilterEvent(&ev
, win
))
581 if (ev
.xdestroywindow
.window
!= win
)
586 if (ev
.xexpose
.count
== 0)
587 drw_map(drw
, win
, 0, 0, mw
, mh
);
590 /* regrab focus from parent window */
591 if (ev
.xfocus
.window
!= win
)
597 case SelectionNotify
:
598 if (ev
.xselection
.property
== utf8
)
601 case VisibilityNotify
:
602 if (ev
.xvisibility
.state
!= VisibilityUnobscured
)
603 XRaiseWindow(dpy
, win
);
614 XSetWindowAttributes swa
;
617 XWindowAttributes wa
;
618 XClassHint ch
= {"dmenu", "dmenu"};
620 XineramaScreenInfo
*info
;
622 int a
, di
, n
, area
= 0;
624 /* init appearance */
625 for (j
= 0; j
< SchemeLast
; j
++)
626 scheme
[j
] = drw_scm_create(drw
, colors
[j
], 2);
628 clip
= XInternAtom(dpy
, "CLIPBOARD", False
);
629 utf8
= XInternAtom(dpy
, "UTF8_STRING", False
);
631 /* calculate menu geometry */
632 bh
= drw
->fonts
->h
+ 2;
633 lines
= MAX(lines
, 0);
634 mh
= (lines
+ 1) * bh
;
637 if (parentwin
== root
&& (info
= XineramaQueryScreens(dpy
, &n
))) {
638 XGetInputFocus(dpy
, &w
, &di
);
639 if (mon
>= 0 && mon
< n
)
641 else if (w
!= root
&& w
!= PointerRoot
&& w
!= None
) {
642 /* find top-level window containing current input focus */
644 if (XQueryTree(dpy
, (pw
= w
), &dw
, &w
, &dws
, &du
) && dws
)
646 } while (w
!= root
&& w
!= pw
);
647 /* find xinerama screen with which the window intersects most */
648 if (XGetWindowAttributes(dpy
, pw
, &wa
))
649 for (j
= 0; j
< n
; j
++)
650 if ((a
= INTERSECT(wa
.x
, wa
.y
, wa
.width
, wa
.height
, info
[j
])) > area
) {
655 /* no focused window is on screen, so use pointer location instead */
656 if (mon
< 0 && !area
&& XQueryPointer(dpy
, root
, &dw
, &dw
, &x
, &y
, &di
, &di
, &du
))
657 for (i
= 0; i
< n
; i
++)
658 if (INTERSECT(x
, y
, 1, 1, info
[i
]) != 0)
662 y
= info
[i
].y_org
+ (topbar
? 0 : info
[i
].height
- mh
);
668 if (!XGetWindowAttributes(dpy
, parentwin
, &wa
))
669 die("could not get embedding window attributes: 0x%lx",
672 y
= topbar
? 0 : wa
.height
- mh
;
675 promptw
= (prompt
&& *prompt
) ? TEXTW(prompt
) - lrpad
/ 4 : 0;
676 inputw
= mw
/ 3; /* input width: ~33% of monitor width */
679 /* create menu window */
680 swa
.override_redirect
= True
;
681 swa
.background_pixel
= scheme
[SchemeNorm
][ColBg
].pixel
;
682 swa
.event_mask
= ExposureMask
| KeyPressMask
| VisibilityChangeMask
;
683 win
= XCreateWindow(dpy
, parentwin
, x
, y
, mw
, mh
, 0,
684 CopyFromParent
, CopyFromParent
, CopyFromParent
,
685 CWOverrideRedirect
| CWBackPixel
| CWEventMask
, &swa
);
686 XSetClassHint(dpy
, win
, &ch
);
690 if ((xim
= XOpenIM(dpy
, NULL
, NULL
, NULL
)) == NULL
)
691 die("XOpenIM failed: could not open input device");
693 xic
= XCreateIC(xim
, XNInputStyle
, XIMPreeditNothing
| XIMStatusNothing
,
694 XNClientWindow
, win
, XNFocusWindow
, win
, NULL
);
696 XMapRaised(dpy
, win
);
698 XSelectInput(dpy
, parentwin
, FocusChangeMask
| SubstructureNotifyMask
);
699 if (XQueryTree(dpy
, parentwin
, &dw
, &w
, &dws
, &du
) && dws
) {
700 for (i
= 0; i
< du
&& dws
[i
] != win
; ++i
)
701 XSelectInput(dpy
, dws
[i
], FocusChangeMask
);
706 drw_resize(drw
, mw
, mh
);
713 fputs("usage: dmenu [-bfiv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
714 " [-nb color] [-nf color] [-sb color] [-sf color] [-w windowid]\n", stderr
);
719 main(int argc
, char *argv
[])
721 XWindowAttributes wa
;
724 for (i
= 1; i
< argc
; i
++)
725 /* these options take no arguments */
726 if (!strcmp(argv
[i
], "-v")) { /* prints version information */
727 puts("dmenu-"VERSION
);
729 } else if (!strcmp(argv
[i
], "-b")) /* appears at the bottom of the screen */
731 else if (!strcmp(argv
[i
], "-f")) /* grabs keyboard before reading stdin */
733 else if (!strcmp(argv
[i
], "-i")) { /* case-insensitive item matching */
734 fstrncmp
= strncasecmp
;
736 } else if (i
+ 1 == argc
)
738 /* these options take one argument */
739 else if (!strcmp(argv
[i
], "-l")) /* number of lines in vertical list */
740 lines
= atoi(argv
[++i
]);
741 else if (!strcmp(argv
[i
], "-m"))
742 mon
= atoi(argv
[++i
]);
743 else if (!strcmp(argv
[i
], "-p")) /* adds prompt to left of input field */
745 else if (!strcmp(argv
[i
], "-fn")) /* font or font set */
746 fonts
[0] = argv
[++i
];
747 else if (!strcmp(argv
[i
], "-nb")) /* normal background color */
748 colors
[SchemeNorm
][ColBg
] = argv
[++i
];
749 else if (!strcmp(argv
[i
], "-nf")) /* normal foreground color */
750 colors
[SchemeNorm
][ColFg
] = argv
[++i
];
751 else if (!strcmp(argv
[i
], "-sb")) /* selected background color */
752 colors
[SchemeSel
][ColBg
] = argv
[++i
];
753 else if (!strcmp(argv
[i
], "-sf")) /* selected foreground color */
754 colors
[SchemeSel
][ColFg
] = argv
[++i
];
755 else if (!strcmp(argv
[i
], "-w")) /* embedding window id */
760 if (!setlocale(LC_CTYPE
, "") || !XSupportsLocale())
761 fputs("warning: no locale support\n", stderr
);
762 if (!(dpy
= XOpenDisplay(NULL
)))
763 die("cannot open display");
764 screen
= DefaultScreen(dpy
);
765 root
= RootWindow(dpy
, screen
);
766 if (!embed
|| !(parentwin
= strtol(embed
, NULL
, 0)))
768 if (!XGetWindowAttributes(dpy
, parentwin
, &wa
))
769 die("could not get embedding window attributes: 0x%lx",
771 drw
= drw_create(dpy
, screen
, root
, wa
.width
, wa
.height
);
772 if (!drw_fontset_create(drw
, fonts
, LENGTH(fonts
)))
773 die("no fonts could be loaded.");
774 lrpad
= drw
->fonts
->h
;
777 if (pledge("stdio rpath", NULL
) == -1)
781 if (fast
&& !isatty(0)) {
791 return 1; /* unreachable */