Xinqi Bao's Git
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
++)
113 cistrstr(const char *h
, const char *n
)
121 for (i
= 0; n
[i
] && tolower((unsigned char)n
[i
]) ==
122 tolower((unsigned char)h
[i
]); ++i
)
131 drawitem(struct item
*item
, int x
, int y
, int w
)
134 drw_setscheme(drw
, scheme
[SchemeSel
]);
136 drw_setscheme(drw
, scheme
[SchemeOut
]);
138 drw_setscheme(drw
, scheme
[SchemeNorm
]);
140 return drw_text(drw
, x
, y
, w
, bh
, lrpad
/ 2, item
->text
, 0);
150 drw_setscheme(drw
, scheme
[SchemeNorm
]);
151 drw_rect(drw
, 0, 0, mw
, mh
, 1, 1);
153 if (prompt
&& *prompt
) {
154 drw_setscheme(drw
, scheme
[SchemeSel
]);
155 x
= drw_text(drw
, x
, 0, promptw
, bh
, lrpad
/ 2, prompt
, 0);
157 /* draw input field */
158 w
= (lines
> 0 || !matches
) ? mw
- x
: inputw
;
159 drw_setscheme(drw
, scheme
[SchemeNorm
]);
160 drw_text(drw
, x
, 0, w
, bh
, lrpad
/ 2, text
, 0);
162 curpos
= TEXTW(text
) - TEXTW(&text
[cursor
]);
163 if ((curpos
+= lrpad
/ 2 - 1) < w
) {
164 drw_setscheme(drw
, scheme
[SchemeNorm
]);
165 drw_rect(drw
, x
+ curpos
, 2, 2, bh
- 4, 1, 0);
169 /* draw vertical list */
170 for (item
= curr
; item
!= next
; item
= item
->right
)
171 drawitem(item
, x
, y
+= bh
, mw
- x
);
172 } else if (matches
) {
173 /* draw horizontal list */
177 drw_setscheme(drw
, scheme
[SchemeNorm
]);
178 drw_text(drw
, x
, 0, w
, bh
, lrpad
/ 2, "<", 0);
181 for (item
= curr
; item
!= next
; item
= item
->right
)
182 x
= drawitem(item
, x
, 0, textw_clamp(item
->text
, mw
- x
- TEXTW(">")));
185 drw_setscheme(drw
, scheme
[SchemeNorm
]);
186 drw_text(drw
, mw
- w
, 0, w
, bh
, lrpad
/ 2, ">", 0);
189 drw_map(drw
, win
, 0, 0, mw
, mh
);
195 struct timespec ts
= { .tv_sec
= 0, .tv_nsec
= 10000000 };
199 for (i
= 0; i
< 100; ++i
) {
200 XGetInputFocus(dpy
, &focuswin
, &revertwin
);
203 XSetInputFocus(dpy
, win
, RevertToParent
, CurrentTime
);
204 nanosleep(&ts
, NULL
);
206 die("cannot grab focus");
212 struct timespec ts
= { .tv_sec
= 0, .tv_nsec
= 1000000 };
217 /* try to grab keyboard, we may have to wait for another process to ungrab */
218 for (i
= 0; i
< 1000; i
++) {
219 if (XGrabKeyboard(dpy
, DefaultRootWindow(dpy
), True
, GrabModeAsync
,
220 GrabModeAsync
, CurrentTime
) == GrabSuccess
)
222 nanosleep(&ts
, NULL
);
224 die("cannot grab keyboard");
230 static char **tokv
= NULL
;
233 char buf
[sizeof text
], *s
;
235 size_t len
, textsize
;
236 struct item
*item
, *lprefix
, *lsubstr
, *prefixend
, *substrend
;
239 /* separate input text into tokens to be matched individually */
240 for (s
= strtok(buf
, " "); s
; tokv
[tokc
- 1] = s
, s
= strtok(NULL
, " "))
241 if (++tokc
> tokn
&& !(tokv
= realloc(tokv
, ++tokn
* sizeof *tokv
)))
242 die("cannot realloc %u bytes:", tokn
* sizeof *tokv
);
243 len
= tokc
? strlen(tokv
[0]) : 0;
245 matches
= lprefix
= lsubstr
= matchend
= prefixend
= substrend
= NULL
;
246 textsize
= strlen(text
) + 1;
247 for (item
= items
; item
&& item
->text
; item
++) {
248 for (i
= 0; i
< tokc
; i
++)
249 if (!fstrstr(item
->text
, tokv
[i
]))
251 if (i
!= tokc
) /* not all tokens match */
253 /* exact matches go first, then prefixes, then substrings */
254 if (!tokc
|| !fstrncmp(text
, item
->text
, textsize
))
255 appenditem(item
, &matches
, &matchend
);
256 else if (!fstrncmp(tokv
[0], item
->text
, len
))
257 appenditem(item
, &lprefix
, &prefixend
);
259 appenditem(item
, &lsubstr
, &substrend
);
263 matchend
->right
= lprefix
;
264 lprefix
->left
= matchend
;
267 matchend
= prefixend
;
271 matchend
->right
= lsubstr
;
272 lsubstr
->left
= matchend
;
275 matchend
= substrend
;
277 curr
= sel
= matches
;
282 insert(const char *str
, ssize_t n
)
284 if (strlen(text
) + n
> sizeof text
- 1)
286 /* move existing text out of the way, insert new text, and update cursor */
287 memmove(&text
[cursor
+ n
], &text
[cursor
], sizeof text
- cursor
- MAX(n
, 0));
289 memcpy(&text
[cursor
], str
, n
);
299 /* return location of next utf8 rune in the given direction (+1 or -1) */
300 for (n
= cursor
+ inc
; n
+ inc
>= 0 && (text
[n
] & 0xc0) == 0x80; n
+= inc
)
306 movewordedge(int dir
)
308 if (dir
< 0) { /* move cursor to the start of the word*/
309 while (cursor
> 0 && strchr(worddelimiters
, text
[nextrune(-1)]))
310 cursor
= nextrune(-1);
311 while (cursor
> 0 && !strchr(worddelimiters
, text
[nextrune(-1)]))
312 cursor
= nextrune(-1);
313 } else { /* move cursor to the end of the word */
314 while (text
[cursor
] && strchr(worddelimiters
, text
[cursor
]))
315 cursor
= nextrune(+1);
316 while (text
[cursor
] && !strchr(worddelimiters
, text
[cursor
]))
317 cursor
= nextrune(+1);
322 keypress(XKeyEvent
*ev
)
329 len
= XmbLookupString(xic
, ev
, buf
, sizeof buf
, &ksym
, &status
);
331 default: /* XLookupNone, XBufferOverflow */
340 if (ev
->state
& ControlMask
) {
342 case XK_a
: ksym
= XK_Home
; break;
343 case XK_b
: ksym
= XK_Left
; break;
344 case XK_c
: ksym
= XK_Escape
; break;
345 case XK_d
: ksym
= XK_Delete
; break;
346 case XK_e
: ksym
= XK_End
; break;
347 case XK_f
: ksym
= XK_Right
; break;
348 case XK_g
: ksym
= XK_Escape
; break;
349 case XK_h
: ksym
= XK_BackSpace
; break;
350 case XK_i
: ksym
= XK_Tab
; break;
351 case XK_j
: /* fallthrough */
352 case XK_J
: /* fallthrough */
353 case XK_m
: /* fallthrough */
354 case XK_M
: ksym
= XK_Return
; ev
->state
&= ~ControlMask
; break;
355 case XK_n
: ksym
= XK_Down
; break;
356 case XK_p
: ksym
= XK_Up
; break;
358 case XK_k
: /* delete right */
362 case XK_u
: /* delete left */
363 insert(NULL
, 0 - cursor
);
365 case XK_w
: /* delete word */
366 while (cursor
> 0 && strchr(worddelimiters
, text
[nextrune(-1)]))
367 insert(NULL
, nextrune(-1) - cursor
);
368 while (cursor
> 0 && !strchr(worddelimiters
, text
[nextrune(-1)]))
369 insert(NULL
, nextrune(-1) - cursor
);
371 case XK_y
: /* paste selection */
373 XConvertSelection(dpy
, (ev
->state
& ShiftMask
) ? clip
: XA_PRIMARY
,
374 utf8
, utf8
, win
, CurrentTime
);
393 } else if (ev
->state
& Mod1Mask
) {
401 case XK_g
: ksym
= XK_Home
; break;
402 case XK_G
: ksym
= XK_End
; break;
403 case XK_h
: ksym
= XK_Up
; break;
404 case XK_j
: ksym
= XK_Next
; break;
405 case XK_k
: ksym
= XK_Prior
; break;
406 case XK_l
: ksym
= XK_Down
; break;
420 if (text
[cursor
] == '\0')
422 cursor
= nextrune(+1);
427 insert(NULL
, nextrune(-1) - cursor
);
431 if (text
[cursor
] != '\0') {
432 cursor
= strlen(text
);
436 /* jump to end of list and position items in reverse */
441 while (next
&& (curr
= curr
->right
))
451 if (sel
== matches
) {
455 sel
= curr
= matches
;
460 if (cursor
> 0 && (!sel
|| !sel
->left
|| lines
> 0)) {
461 cursor
= nextrune(-1);
469 if (sel
&& sel
->left
&& (sel
= sel
->left
)->right
== curr
) {
490 puts((sel
&& !(ev
->state
& ShiftMask
)) ? sel
->text
: text
);
491 if (!(ev
->state
& ControlMask
)) {
500 if (text
[cursor
] != '\0') {
501 cursor
= nextrune(+1);
509 if (sel
&& sel
->right
&& (sel
= sel
->right
) == next
) {
517 strncpy(text
, sel
->text
, sizeof text
- 1);
518 text
[sizeof text
- 1] = '\0';
519 cursor
= strlen(text
);
536 /* we have been given the current selection, now insert it into input */
537 if (XGetWindowProperty(dpy
, win
, utf8
, 0, (sizeof text
/ 4) + 1, False
,
538 utf8
, &da
, &di
, &dl
, &dl
, (unsigned char **)&p
)
540 insert(p
, (q
= strchr(p
, '\n')) ? q
- p
: (ssize_t
)strlen(p
));
549 char buf
[sizeof text
], *p
;
550 size_t i
, imax
= 0, size
= 0;
551 unsigned int tmpmax
= 0;
553 /* read each line from stdin and add it to the item list */
554 for (i
= 0; fgets(buf
, sizeof buf
, stdin
); i
++) {
555 if (i
+ 1 >= size
/ sizeof *items
)
556 if (!(items
= realloc(items
, (size
+= BUFSIZ
))))
557 die("cannot realloc %u bytes:", size
);
558 if ((p
= strchr(buf
, '\n')))
560 if (!(items
[i
].text
= strdup(buf
)))
561 die("cannot strdup %u bytes:", strlen(buf
) + 1);
563 drw_font_getexts(drw
->fonts
, buf
, strlen(buf
), &tmpmax
, NULL
);
564 if (tmpmax
> inputw
) {
570 items
[i
].text
= NULL
;
571 inputw
= items
? TEXTW(items
[imax
].text
) : 0;
572 lines
= MIN(lines
, i
);
580 while (!XNextEvent(dpy
, &ev
)) {
581 if (XFilterEvent(&ev
, win
))
585 if (ev
.xdestroywindow
.window
!= win
)
590 if (ev
.xexpose
.count
== 0)
591 drw_map(drw
, win
, 0, 0, mw
, mh
);
594 /* regrab focus from parent window */
595 if (ev
.xfocus
.window
!= win
)
601 case SelectionNotify
:
602 if (ev
.xselection
.property
== utf8
)
605 case VisibilityNotify
:
606 if (ev
.xvisibility
.state
!= VisibilityUnobscured
)
607 XRaiseWindow(dpy
, win
);
618 XSetWindowAttributes swa
;
621 XWindowAttributes wa
;
622 XClassHint ch
= {"dmenu", "dmenu"};
624 XineramaScreenInfo
*info
;
626 int a
, di
, n
, area
= 0;
628 /* init appearance */
629 for (j
= 0; j
< SchemeLast
; j
++)
630 scheme
[j
] = drw_scm_create(drw
, colors
[j
], 2);
632 clip
= XInternAtom(dpy
, "CLIPBOARD", False
);
633 utf8
= XInternAtom(dpy
, "UTF8_STRING", False
);
635 /* calculate menu geometry */
636 bh
= drw
->fonts
->h
+ 2;
637 lines
= MAX(lines
, 0);
638 mh
= (lines
+ 1) * bh
;
641 if (parentwin
== root
&& (info
= XineramaQueryScreens(dpy
, &n
))) {
642 XGetInputFocus(dpy
, &w
, &di
);
643 if (mon
>= 0 && mon
< n
)
645 else if (w
!= root
&& w
!= PointerRoot
&& w
!= None
) {
646 /* find top-level window containing current input focus */
648 if (XQueryTree(dpy
, (pw
= w
), &dw
, &w
, &dws
, &du
) && dws
)
650 } while (w
!= root
&& w
!= pw
);
651 /* find xinerama screen with which the window intersects most */
652 if (XGetWindowAttributes(dpy
, pw
, &wa
))
653 for (j
= 0; j
< n
; j
++)
654 if ((a
= INTERSECT(wa
.x
, wa
.y
, wa
.width
, wa
.height
, info
[j
])) > area
) {
659 /* no focused window is on screen, so use pointer location instead */
660 if (mon
< 0 && !area
&& XQueryPointer(dpy
, root
, &dw
, &dw
, &x
, &y
, &di
, &di
, &du
))
661 for (i
= 0; i
< n
; i
++)
662 if (INTERSECT(x
, y
, 1, 1, info
[i
]) != 0)
666 y
= info
[i
].y_org
+ (topbar
? 0 : info
[i
].height
- mh
);
672 if (!XGetWindowAttributes(dpy
, parentwin
, &wa
))
673 die("could not get embedding window attributes: 0x%lx",
676 y
= topbar
? 0 : wa
.height
- mh
;
679 promptw
= (prompt
&& *prompt
) ? TEXTW(prompt
) - lrpad
/ 4 : 0;
680 inputw
= MIN(inputw
, mw
/3);
683 /* create menu window */
684 swa
.override_redirect
= True
;
685 swa
.background_pixel
= scheme
[SchemeNorm
][ColBg
].pixel
;
686 swa
.event_mask
= ExposureMask
| KeyPressMask
| VisibilityChangeMask
;
687 win
= XCreateWindow(dpy
, parentwin
, x
, y
, mw
, mh
, 0,
688 CopyFromParent
, CopyFromParent
, CopyFromParent
,
689 CWOverrideRedirect
| CWBackPixel
| CWEventMask
, &swa
);
690 XSetClassHint(dpy
, win
, &ch
);
694 if ((xim
= XOpenIM(dpy
, NULL
, NULL
, NULL
)) == NULL
)
695 die("XOpenIM failed: could not open input device");
697 xic
= XCreateIC(xim
, XNInputStyle
, XIMPreeditNothing
| XIMStatusNothing
,
698 XNClientWindow
, win
, XNFocusWindow
, win
, NULL
);
700 XMapRaised(dpy
, win
);
702 XSelectInput(dpy
, parentwin
, FocusChangeMask
| SubstructureNotifyMask
);
703 if (XQueryTree(dpy
, parentwin
, &dw
, &w
, &dws
, &du
) && dws
) {
704 for (i
= 0; i
< du
&& dws
[i
] != win
; ++i
)
705 XSelectInput(dpy
, dws
[i
], FocusChangeMask
);
710 drw_resize(drw
, mw
, mh
);
717 fputs("usage: dmenu [-bfiv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
718 " [-nb color] [-nf color] [-sb color] [-sf color] [-w windowid]\n", stderr
);
723 main(int argc
, char *argv
[])
725 XWindowAttributes wa
;
728 for (i
= 1; i
< argc
; i
++)
729 /* these options take no arguments */
730 if (!strcmp(argv
[i
], "-v")) { /* prints version information */
731 puts("dmenu-"VERSION
);
733 } else if (!strcmp(argv
[i
], "-b")) /* appears at the bottom of the screen */
735 else if (!strcmp(argv
[i
], "-f")) /* grabs keyboard before reading stdin */
737 else if (!strcmp(argv
[i
], "-i")) { /* case-insensitive item matching */
738 fstrncmp
= strncasecmp
;
740 } else if (i
+ 1 == argc
)
742 /* these options take one argument */
743 else if (!strcmp(argv
[i
], "-l")) /* number of lines in vertical list */
744 lines
= atoi(argv
[++i
]);
745 else if (!strcmp(argv
[i
], "-m"))
746 mon
= atoi(argv
[++i
]);
747 else if (!strcmp(argv
[i
], "-p")) /* adds prompt to left of input field */
749 else if (!strcmp(argv
[i
], "-fn")) /* font or font set */
750 fonts
[0] = argv
[++i
];
751 else if (!strcmp(argv
[i
], "-nb")) /* normal background color */
752 colors
[SchemeNorm
][ColBg
] = argv
[++i
];
753 else if (!strcmp(argv
[i
], "-nf")) /* normal foreground color */
754 colors
[SchemeNorm
][ColFg
] = argv
[++i
];
755 else if (!strcmp(argv
[i
], "-sb")) /* selected background color */
756 colors
[SchemeSel
][ColBg
] = argv
[++i
];
757 else if (!strcmp(argv
[i
], "-sf")) /* selected foreground color */
758 colors
[SchemeSel
][ColFg
] = argv
[++i
];
759 else if (!strcmp(argv
[i
], "-w")) /* embedding window id */
764 if (!setlocale(LC_CTYPE
, "") || !XSupportsLocale())
765 fputs("warning: no locale support\n", stderr
);
766 if (!(dpy
= XOpenDisplay(NULL
)))
767 die("cannot open display");
768 screen
= DefaultScreen(dpy
);
769 root
= RootWindow(dpy
, screen
);
770 if (!embed
|| !(parentwin
= strtol(embed
, NULL
, 0)))
772 if (!XGetWindowAttributes(dpy
, parentwin
, &wa
))
773 die("could not get embedding window attributes: 0x%lx",
775 drw
= drw_create(dpy
, screen
, root
, wa
.width
, wa
.height
);
776 if (!drw_fontset_create(drw
, fonts
, LENGTH(fonts
)))
777 die("no fonts could be loaded.");
778 lrpad
= drw
->fonts
->h
;
781 if (pledge("stdio rpath", NULL
) == -1)
785 if (fast
&& !isatty(0)) {
795 return 1; /* unreachable */