Xinqi Bao's Git
eca67acadb6d176f5389ee0e6eb1cd085322bad0
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 appenditem(struct item
*item
, struct item
**list
, struct item
**last
)
65 (*last
)->right
= item
;
82 n
= mw
- (promptw
+ inputw
+ TEXTW("<") + TEXTW(">"));
83 /* calculate which items will begin the next page and previous page */
84 for (i
= 0, next
= curr
; next
; next
= next
->right
)
85 if ((i
+= (lines
> 0) ? bh
: MIN(TEXTW(next
->text
), n
)) > n
)
87 for (i
= 0, prev
= curr
; prev
&& prev
->left
; prev
= prev
->left
)
88 if ((i
+= (lines
> 0) ? bh
: MIN(TEXTW(prev
->left
->text
), n
)) > n
)
97 XUngrabKey(dpy
, AnyKey
, AnyModifier
, root
);
98 for (i
= 0; i
< SchemeLast
; i
++)
106 cistrstr(const char *h
, const char *n
)
114 for (i
= 0; n
[i
] && tolower((unsigned char)n
[i
]) ==
115 tolower((unsigned char)h
[i
]); ++i
)
124 drawitem(struct item
*item
, int x
, int y
, int w
)
127 drw_setscheme(drw
, scheme
[SchemeSel
]);
129 drw_setscheme(drw
, scheme
[SchemeOut
]);
131 drw_setscheme(drw
, scheme
[SchemeNorm
]);
133 return drw_text(drw
, x
, y
, w
, bh
, lrpad
/ 2, item
->text
, 0);
143 drw_setscheme(drw
, scheme
[SchemeNorm
]);
144 drw_rect(drw
, 0, 0, mw
, mh
, 1, 1);
146 if (prompt
&& *prompt
) {
147 drw_setscheme(drw
, scheme
[SchemeSel
]);
148 x
= drw_text(drw
, x
, 0, promptw
, bh
, lrpad
/ 2, prompt
, 0);
150 /* draw input field */
151 w
= (lines
> 0 || !matches
) ? mw
- x
: inputw
;
152 drw_setscheme(drw
, scheme
[SchemeNorm
]);
153 drw_text(drw
, x
, 0, w
, bh
, lrpad
/ 2, text
, 0);
155 curpos
= TEXTW(text
) - TEXTW(&text
[cursor
]);
156 if ((curpos
+= lrpad
/ 2 - 1) < w
) {
157 drw_setscheme(drw
, scheme
[SchemeNorm
]);
158 drw_rect(drw
, x
+ curpos
, 2, 2, bh
- 4, 1, 0);
162 /* draw vertical list */
163 for (item
= curr
; item
!= next
; item
= item
->right
)
164 drawitem(item
, x
, y
+= bh
, mw
- x
);
165 } else if (matches
) {
166 /* draw horizontal list */
170 drw_setscheme(drw
, scheme
[SchemeNorm
]);
171 drw_text(drw
, x
, 0, w
, bh
, lrpad
/ 2, "<", 0);
174 for (item
= curr
; item
!= next
; item
= item
->right
)
175 x
= drawitem(item
, x
, 0, MIN(TEXTW(item
->text
), mw
- x
- TEXTW(">")));
178 drw_setscheme(drw
, scheme
[SchemeNorm
]);
179 drw_text(drw
, mw
- w
, 0, w
, bh
, lrpad
/ 2, ">", 0);
182 drw_map(drw
, win
, 0, 0, mw
, mh
);
188 struct timespec ts
= { .tv_sec
= 0, .tv_nsec
= 10000000 };
192 for (i
= 0; i
< 100; ++i
) {
193 XGetInputFocus(dpy
, &focuswin
, &revertwin
);
196 XSetInputFocus(dpy
, win
, RevertToParent
, CurrentTime
);
197 nanosleep(&ts
, NULL
);
199 die("cannot grab focus");
205 struct timespec ts
= { .tv_sec
= 0, .tv_nsec
= 1000000 };
210 /* try to grab keyboard, we may have to wait for another process to ungrab */
211 for (i
= 0; i
< 1000; i
++) {
212 if (XGrabKeyboard(dpy
, DefaultRootWindow(dpy
), True
, GrabModeAsync
,
213 GrabModeAsync
, CurrentTime
) == GrabSuccess
)
215 nanosleep(&ts
, NULL
);
217 die("cannot grab keyboard");
223 static char **tokv
= NULL
;
226 char buf
[sizeof text
], *s
;
228 size_t len
, textsize
;
229 struct item
*item
, *lprefix
, *lsubstr
, *prefixend
, *substrend
;
232 /* separate input text into tokens to be matched individually */
233 for (s
= strtok(buf
, " "); s
; tokv
[tokc
- 1] = s
, s
= strtok(NULL
, " "))
234 if (++tokc
> tokn
&& !(tokv
= realloc(tokv
, ++tokn
* sizeof *tokv
)))
235 die("cannot realloc %u bytes:", tokn
* sizeof *tokv
);
236 len
= tokc
? strlen(tokv
[0]) : 0;
238 matches
= lprefix
= lsubstr
= matchend
= prefixend
= substrend
= NULL
;
239 textsize
= strlen(text
) + 1;
240 for (item
= items
; item
&& item
->text
; item
++) {
241 for (i
= 0; i
< tokc
; i
++)
242 if (!fstrstr(item
->text
, tokv
[i
]))
244 if (i
!= tokc
) /* not all tokens match */
246 /* exact matches go first, then prefixes, then substrings */
247 if (!tokc
|| !fstrncmp(text
, item
->text
, textsize
))
248 appenditem(item
, &matches
, &matchend
);
249 else if (!fstrncmp(tokv
[0], item
->text
, len
))
250 appenditem(item
, &lprefix
, &prefixend
);
252 appenditem(item
, &lsubstr
, &substrend
);
256 matchend
->right
= lprefix
;
257 lprefix
->left
= matchend
;
260 matchend
= prefixend
;
264 matchend
->right
= lsubstr
;
265 lsubstr
->left
= matchend
;
268 matchend
= substrend
;
270 curr
= sel
= matches
;
275 insert(const char *str
, ssize_t n
)
277 if (strlen(text
) + n
> sizeof text
- 1)
279 /* move existing text out of the way, insert new text, and update cursor */
280 memmove(&text
[cursor
+ n
], &text
[cursor
], sizeof text
- cursor
- MAX(n
, 0));
282 memcpy(&text
[cursor
], str
, n
);
292 /* return location of next utf8 rune in the given direction (+1 or -1) */
293 for (n
= cursor
+ inc
; n
+ inc
>= 0 && (text
[n
] & 0xc0) == 0x80; n
+= inc
)
299 movewordedge(int dir
)
301 if (dir
< 0) { /* move cursor to the start of the word*/
302 while (cursor
> 0 && strchr(worddelimiters
, text
[nextrune(-1)]))
303 cursor
= nextrune(-1);
304 while (cursor
> 0 && !strchr(worddelimiters
, text
[nextrune(-1)]))
305 cursor
= nextrune(-1);
306 } else { /* move cursor to the end of the word */
307 while (text
[cursor
] && strchr(worddelimiters
, text
[cursor
]))
308 cursor
= nextrune(+1);
309 while (text
[cursor
] && !strchr(worddelimiters
, text
[cursor
]))
310 cursor
= nextrune(+1);
315 keypress(XKeyEvent
*ev
)
322 len
= XmbLookupString(xic
, ev
, buf
, sizeof buf
, &ksym
, &status
);
324 default: /* XLookupNone, XBufferOverflow */
333 if (ev
->state
& ControlMask
) {
335 case XK_a
: ksym
= XK_Home
; break;
336 case XK_b
: ksym
= XK_Left
; break;
337 case XK_c
: ksym
= XK_Escape
; break;
338 case XK_d
: ksym
= XK_Delete
; break;
339 case XK_e
: ksym
= XK_End
; break;
340 case XK_f
: ksym
= XK_Right
; break;
341 case XK_g
: ksym
= XK_Escape
; break;
342 case XK_h
: ksym
= XK_BackSpace
; break;
343 case XK_i
: ksym
= XK_Tab
; break;
344 case XK_j
: /* fallthrough */
345 case XK_J
: /* fallthrough */
346 case XK_m
: /* fallthrough */
347 case XK_M
: ksym
= XK_Return
; ev
->state
&= ~ControlMask
; break;
348 case XK_n
: ksym
= XK_Down
; break;
349 case XK_p
: ksym
= XK_Up
; break;
351 case XK_k
: /* delete right */
355 case XK_u
: /* delete left */
356 insert(NULL
, 0 - cursor
);
358 case XK_w
: /* delete word */
359 while (cursor
> 0 && strchr(worddelimiters
, text
[nextrune(-1)]))
360 insert(NULL
, nextrune(-1) - cursor
);
361 while (cursor
> 0 && !strchr(worddelimiters
, text
[nextrune(-1)]))
362 insert(NULL
, nextrune(-1) - cursor
);
364 case XK_y
: /* paste selection */
366 XConvertSelection(dpy
, (ev
->state
& ShiftMask
) ? clip
: XA_PRIMARY
,
367 utf8
, utf8
, win
, CurrentTime
);
386 } else if (ev
->state
& Mod1Mask
) {
394 case XK_g
: ksym
= XK_Home
; break;
395 case XK_G
: ksym
= XK_End
; break;
396 case XK_h
: ksym
= XK_Up
; break;
397 case XK_j
: ksym
= XK_Next
; break;
398 case XK_k
: ksym
= XK_Prior
; break;
399 case XK_l
: ksym
= XK_Down
; break;
413 if (text
[cursor
] == '\0')
415 cursor
= nextrune(+1);
420 insert(NULL
, nextrune(-1) - cursor
);
424 if (text
[cursor
] != '\0') {
425 cursor
= strlen(text
);
429 /* jump to end of list and position items in reverse */
434 while (next
&& (curr
= curr
->right
))
444 if (sel
== matches
) {
448 sel
= curr
= matches
;
453 if (cursor
> 0 && (!sel
|| !sel
->left
|| lines
> 0)) {
454 cursor
= nextrune(-1);
462 if (sel
&& sel
->left
&& (sel
= sel
->left
)->right
== curr
) {
483 puts((sel
&& !(ev
->state
& ShiftMask
)) ? sel
->text
: text
);
484 if (!(ev
->state
& ControlMask
)) {
493 if (text
[cursor
] != '\0') {
494 cursor
= nextrune(+1);
502 if (sel
&& sel
->right
&& (sel
= sel
->right
) == next
) {
510 strncpy(text
, sel
->text
, sizeof text
- 1);
511 text
[sizeof text
- 1] = '\0';
512 cursor
= strlen(text
);
529 /* we have been given the current selection, now insert it into input */
530 if (XGetWindowProperty(dpy
, win
, utf8
, 0, (sizeof text
/ 4) + 1, False
,
531 utf8
, &da
, &di
, &dl
, &dl
, (unsigned char **)&p
)
533 insert(p
, (q
= strchr(p
, '\n')) ? q
- p
: (ssize_t
)strlen(p
));
542 char buf
[sizeof text
], *p
;
543 size_t i
, imax
= 0, size
= 0;
544 unsigned int tmpmax
= 0;
546 /* read each line from stdin and add it to the item list */
547 for (i
= 0; fgets(buf
, sizeof buf
, stdin
); i
++) {
548 if (i
+ 1 >= size
/ sizeof *items
)
549 if (!(items
= realloc(items
, (size
+= BUFSIZ
))))
550 die("cannot realloc %u bytes:", size
);
551 if ((p
= strchr(buf
, '\n')))
553 if (!(items
[i
].text
= strdup(buf
)))
554 die("cannot strdup %u bytes:", strlen(buf
) + 1);
556 drw_font_getexts(drw
->fonts
, buf
, strlen(buf
), &tmpmax
, NULL
);
557 if (tmpmax
> inputw
) {
563 items
[i
].text
= NULL
;
564 inputw
= items
? TEXTW(items
[imax
].text
) : 0;
565 lines
= MIN(lines
, i
);
573 while (!XNextEvent(dpy
, &ev
)) {
574 if (XFilterEvent(&ev
, win
))
578 if (ev
.xdestroywindow
.window
!= win
)
583 if (ev
.xexpose
.count
== 0)
584 drw_map(drw
, win
, 0, 0, mw
, mh
);
587 /* regrab focus from parent window */
588 if (ev
.xfocus
.window
!= win
)
594 case SelectionNotify
:
595 if (ev
.xselection
.property
== utf8
)
598 case VisibilityNotify
:
599 if (ev
.xvisibility
.state
!= VisibilityUnobscured
)
600 XRaiseWindow(dpy
, win
);
611 XSetWindowAttributes swa
;
614 XWindowAttributes wa
;
615 XClassHint ch
= {"dmenu", "dmenu"};
617 XineramaScreenInfo
*info
;
619 int a
, di
, n
, area
= 0;
621 /* init appearance */
622 for (j
= 0; j
< SchemeLast
; j
++)
623 scheme
[j
] = drw_scm_create(drw
, colors
[j
], 2);
625 clip
= XInternAtom(dpy
, "CLIPBOARD", False
);
626 utf8
= XInternAtom(dpy
, "UTF8_STRING", False
);
628 /* calculate menu geometry */
629 bh
= drw
->fonts
->h
+ 2;
630 lines
= MAX(lines
, 0);
631 mh
= (lines
+ 1) * bh
;
634 if (parentwin
== root
&& (info
= XineramaQueryScreens(dpy
, &n
))) {
635 XGetInputFocus(dpy
, &w
, &di
);
636 if (mon
>= 0 && mon
< n
)
638 else if (w
!= root
&& w
!= PointerRoot
&& w
!= None
) {
639 /* find top-level window containing current input focus */
641 if (XQueryTree(dpy
, (pw
= w
), &dw
, &w
, &dws
, &du
) && dws
)
643 } while (w
!= root
&& w
!= pw
);
644 /* find xinerama screen with which the window intersects most */
645 if (XGetWindowAttributes(dpy
, pw
, &wa
))
646 for (j
= 0; j
< n
; j
++)
647 if ((a
= INTERSECT(wa
.x
, wa
.y
, wa
.width
, wa
.height
, info
[j
])) > area
) {
652 /* no focused window is on screen, so use pointer location instead */
653 if (mon
< 0 && !area
&& XQueryPointer(dpy
, root
, &dw
, &dw
, &x
, &y
, &di
, &di
, &du
))
654 for (i
= 0; i
< n
; i
++)
655 if (INTERSECT(x
, y
, 1, 1, info
[i
]) != 0)
659 y
= info
[i
].y_org
+ (topbar
? 0 : info
[i
].height
- mh
);
665 if (!XGetWindowAttributes(dpy
, parentwin
, &wa
))
666 die("could not get embedding window attributes: 0x%lx",
669 y
= topbar
? 0 : wa
.height
- mh
;
672 promptw
= (prompt
&& *prompt
) ? TEXTW(prompt
) - lrpad
/ 4 : 0;
673 inputw
= MIN(inputw
, mw
/3);
676 /* create menu window */
677 swa
.override_redirect
= True
;
678 swa
.background_pixel
= scheme
[SchemeNorm
][ColBg
].pixel
;
679 swa
.event_mask
= ExposureMask
| KeyPressMask
| VisibilityChangeMask
;
680 win
= XCreateWindow(dpy
, parentwin
, x
, y
, mw
, mh
, 0,
681 CopyFromParent
, CopyFromParent
, CopyFromParent
,
682 CWOverrideRedirect
| CWBackPixel
| CWEventMask
, &swa
);
683 XSetClassHint(dpy
, win
, &ch
);
687 if ((xim
= XOpenIM(dpy
, NULL
, NULL
, NULL
)) == NULL
)
688 die("XOpenIM failed: could not open input device");
690 xic
= XCreateIC(xim
, XNInputStyle
, XIMPreeditNothing
| XIMStatusNothing
,
691 XNClientWindow
, win
, XNFocusWindow
, win
, NULL
);
693 XMapRaised(dpy
, win
);
695 XSelectInput(dpy
, parentwin
, FocusChangeMask
| SubstructureNotifyMask
);
696 if (XQueryTree(dpy
, parentwin
, &dw
, &w
, &dws
, &du
) && dws
) {
697 for (i
= 0; i
< du
&& dws
[i
] != win
; ++i
)
698 XSelectInput(dpy
, dws
[i
], FocusChangeMask
);
703 drw_resize(drw
, mw
, mh
);
710 fputs("usage: dmenu [-bfiv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
711 " [-nb color] [-nf color] [-sb color] [-sf color] [-w windowid]\n", stderr
);
716 main(int argc
, char *argv
[])
718 XWindowAttributes wa
;
721 for (i
= 1; i
< argc
; i
++)
722 /* these options take no arguments */
723 if (!strcmp(argv
[i
], "-v")) { /* prints version information */
724 puts("dmenu-"VERSION
);
726 } else if (!strcmp(argv
[i
], "-b")) /* appears at the bottom of the screen */
728 else if (!strcmp(argv
[i
], "-f")) /* grabs keyboard before reading stdin */
730 else if (!strcmp(argv
[i
], "-i")) { /* case-insensitive item matching */
731 fstrncmp
= strncasecmp
;
733 } else if (i
+ 1 == argc
)
735 /* these options take one argument */
736 else if (!strcmp(argv
[i
], "-l")) /* number of lines in vertical list */
737 lines
= atoi(argv
[++i
]);
738 else if (!strcmp(argv
[i
], "-m"))
739 mon
= atoi(argv
[++i
]);
740 else if (!strcmp(argv
[i
], "-p")) /* adds prompt to left of input field */
742 else if (!strcmp(argv
[i
], "-fn")) /* font or font set */
743 fonts
[0] = argv
[++i
];
744 else if (!strcmp(argv
[i
], "-nb")) /* normal background color */
745 colors
[SchemeNorm
][ColBg
] = argv
[++i
];
746 else if (!strcmp(argv
[i
], "-nf")) /* normal foreground color */
747 colors
[SchemeNorm
][ColFg
] = argv
[++i
];
748 else if (!strcmp(argv
[i
], "-sb")) /* selected background color */
749 colors
[SchemeSel
][ColBg
] = argv
[++i
];
750 else if (!strcmp(argv
[i
], "-sf")) /* selected foreground color */
751 colors
[SchemeSel
][ColFg
] = argv
[++i
];
752 else if (!strcmp(argv
[i
], "-w")) /* embedding window id */
757 if (!setlocale(LC_CTYPE
, "") || !XSupportsLocale())
758 fputs("warning: no locale support\n", stderr
);
759 if (!(dpy
= XOpenDisplay(NULL
)))
760 die("cannot open display");
761 screen
= DefaultScreen(dpy
);
762 root
= RootWindow(dpy
, screen
);
763 if (!embed
|| !(parentwin
= strtol(embed
, NULL
, 0)))
765 if (!XGetWindowAttributes(dpy
, parentwin
, &wa
))
766 die("could not get embedding window attributes: 0x%lx",
768 drw
= drw_create(dpy
, screen
, root
, wa
.width
, wa
.height
);
769 if (!drw_fontset_create(drw
, fonts
, LENGTH(fonts
)))
770 die("no fonts could be loaded.");
771 lrpad
= drw
->fonts
->h
;
774 if (pledge("stdio rpath", NULL
) == -1)
778 if (fast
&& !isatty(0)) {
788 return 1; /* unreachable */