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
)
103 for (struct item
*item
= items
; item
&& item
->text
; item
++)
104 len
= MAX(TEXTW(item
->text
), len
);
113 XUngrabKey(dpy
, AnyKey
, AnyModifier
, root
);
114 for (i
= 0; i
< SchemeLast
; i
++)
116 for (i
= 0; items
&& items
[i
].text
; ++i
)
125 cistrstr(const char *h
, const char *n
)
133 for (i
= 0; n
[i
] && tolower((unsigned char)n
[i
]) ==
134 tolower((unsigned char)h
[i
]); ++i
)
143 drawitem(struct item
*item
, int x
, int y
, int w
)
146 drw_setscheme(drw
, scheme
[SchemeSel
]);
148 drw_setscheme(drw
, scheme
[SchemeOut
]);
150 drw_setscheme(drw
, scheme
[SchemeNorm
]);
152 return drw_text(drw
, x
, y
, w
, bh
, lrpad
/ 2, item
->text
, 0);
162 drw_setscheme(drw
, scheme
[SchemeNorm
]);
163 drw_rect(drw
, 0, 0, mw
, mh
, 1, 1);
165 if (prompt
&& *prompt
) {
166 drw_setscheme(drw
, scheme
[SchemeSel
]);
167 x
= drw_text(drw
, x
, 0, promptw
, bh
, lrpad
/ 2, prompt
, 0);
169 /* draw input field */
170 w
= (lines
> 0 || !matches
) ? mw
- x
: inputw
;
171 drw_setscheme(drw
, scheme
[SchemeNorm
]);
172 drw_text(drw
, x
, 0, w
, bh
, lrpad
/ 2, text
, 0);
174 curpos
= TEXTW(text
) - TEXTW(&text
[cursor
]);
175 if ((curpos
+= lrpad
/ 2 - 1) < w
) {
176 drw_setscheme(drw
, scheme
[SchemeNorm
]);
177 drw_rect(drw
, x
+ curpos
, 2, 2, bh
- 4, 1, 0);
181 /* draw vertical list */
182 for (item
= curr
; item
!= next
; item
= item
->right
)
183 drawitem(item
, x
, y
+= bh
, mw
- x
);
184 } else if (matches
) {
185 /* draw horizontal list */
189 drw_setscheme(drw
, scheme
[SchemeNorm
]);
190 drw_text(drw
, x
, 0, w
, bh
, lrpad
/ 2, "<", 0);
193 for (item
= curr
; item
!= next
; item
= item
->right
)
194 x
= drawitem(item
, x
, 0, textw_clamp(item
->text
, mw
- x
- TEXTW(">")));
197 drw_setscheme(drw
, scheme
[SchemeNorm
]);
198 drw_text(drw
, mw
- w
, 0, w
, bh
, lrpad
/ 2, ">", 0);
201 drw_map(drw
, win
, 0, 0, mw
, mh
);
207 struct timespec ts
= { .tv_sec
= 0, .tv_nsec
= 10000000 };
211 for (i
= 0; i
< 100; ++i
) {
212 XGetInputFocus(dpy
, &focuswin
, &revertwin
);
215 XSetInputFocus(dpy
, win
, RevertToParent
, CurrentTime
);
216 nanosleep(&ts
, NULL
);
218 die("cannot grab focus");
224 struct timespec ts
= { .tv_sec
= 0, .tv_nsec
= 1000000 };
229 /* try to grab keyboard, we may have to wait for another process to ungrab */
230 for (i
= 0; i
< 1000; i
++) {
231 if (XGrabKeyboard(dpy
, DefaultRootWindow(dpy
), True
, GrabModeAsync
,
232 GrabModeAsync
, CurrentTime
) == GrabSuccess
)
234 nanosleep(&ts
, NULL
);
236 die("cannot grab keyboard");
242 static char **tokv
= NULL
;
245 char buf
[sizeof text
], *s
;
247 size_t len
, textsize
;
248 struct item
*item
, *lprefix
, *lsubstr
, *prefixend
, *substrend
;
251 /* separate input text into tokens to be matched individually */
252 for (s
= strtok(buf
, " "); s
; tokv
[tokc
- 1] = s
, s
= strtok(NULL
, " "))
253 if (++tokc
> tokn
&& !(tokv
= realloc(tokv
, ++tokn
* sizeof *tokv
)))
254 die("cannot realloc %zu bytes:", tokn
* sizeof *tokv
);
255 len
= tokc
? strlen(tokv
[0]) : 0;
257 matches
= lprefix
= lsubstr
= matchend
= prefixend
= substrend
= NULL
;
258 textsize
= strlen(text
) + 1;
259 for (item
= items
; item
&& item
->text
; item
++) {
260 for (i
= 0; i
< tokc
; i
++)
261 if (!fstrstr(item
->text
, tokv
[i
]))
263 if (i
!= tokc
) /* not all tokens match */
265 /* exact matches go first, then prefixes, then substrings */
266 if (!tokc
|| !fstrncmp(text
, item
->text
, textsize
))
267 appenditem(item
, &matches
, &matchend
);
268 else if (!fstrncmp(tokv
[0], item
->text
, len
))
269 appenditem(item
, &lprefix
, &prefixend
);
271 appenditem(item
, &lsubstr
, &substrend
);
275 matchend
->right
= lprefix
;
276 lprefix
->left
= matchend
;
279 matchend
= prefixend
;
283 matchend
->right
= lsubstr
;
284 lsubstr
->left
= matchend
;
287 matchend
= substrend
;
289 curr
= sel
= matches
;
294 insert(const char *str
, ssize_t n
)
296 if (strlen(text
) + n
> sizeof text
- 1)
298 /* move existing text out of the way, insert new text, and update cursor */
299 memmove(&text
[cursor
+ n
], &text
[cursor
], sizeof text
- cursor
- MAX(n
, 0));
301 memcpy(&text
[cursor
], str
, n
);
311 /* return location of next utf8 rune in the given direction (+1 or -1) */
312 for (n
= cursor
+ inc
; n
+ inc
>= 0 && (text
[n
] & 0xc0) == 0x80; n
+= inc
)
318 movewordedge(int dir
)
320 if (dir
< 0) { /* move cursor to the start of the word*/
321 while (cursor
> 0 && strchr(worddelimiters
, text
[nextrune(-1)]))
322 cursor
= nextrune(-1);
323 while (cursor
> 0 && !strchr(worddelimiters
, text
[nextrune(-1)]))
324 cursor
= nextrune(-1);
325 } else { /* move cursor to the end of the word */
326 while (text
[cursor
] && strchr(worddelimiters
, text
[cursor
]))
327 cursor
= nextrune(+1);
328 while (text
[cursor
] && !strchr(worddelimiters
, text
[cursor
]))
329 cursor
= nextrune(+1);
334 keypress(XKeyEvent
*ev
)
341 len
= XmbLookupString(xic
, ev
, buf
, sizeof buf
, &ksym
, &status
);
343 default: /* XLookupNone, XBufferOverflow */
352 if (ev
->state
& ControlMask
) {
354 case XK_a
: ksym
= XK_Home
; break;
355 case XK_b
: ksym
= XK_Left
; break;
356 case XK_c
: ksym
= XK_Escape
; break;
357 case XK_d
: ksym
= XK_Delete
; break;
358 case XK_e
: ksym
= XK_End
; break;
359 case XK_f
: ksym
= XK_Right
; break;
360 case XK_g
: ksym
= XK_Escape
; break;
361 case XK_h
: ksym
= XK_BackSpace
; break;
362 case XK_i
: ksym
= XK_Tab
; break;
363 case XK_j
: /* fallthrough */
364 case XK_J
: /* fallthrough */
365 case XK_m
: /* fallthrough */
366 case XK_M
: ksym
= XK_Return
; ev
->state
&= ~ControlMask
; break;
367 case XK_n
: ksym
= XK_Down
; break;
368 case XK_p
: ksym
= XK_Up
; break;
370 case XK_k
: /* delete right */
374 case XK_u
: /* delete left */
375 insert(NULL
, 0 - cursor
);
377 case XK_w
: /* delete word */
378 while (cursor
> 0 && strchr(worddelimiters
, text
[nextrune(-1)]))
379 insert(NULL
, nextrune(-1) - cursor
);
380 while (cursor
> 0 && !strchr(worddelimiters
, text
[nextrune(-1)]))
381 insert(NULL
, nextrune(-1) - cursor
);
383 case XK_y
: /* paste selection */
385 XConvertSelection(dpy
, (ev
->state
& ShiftMask
) ? clip
: XA_PRIMARY
,
386 utf8
, utf8
, win
, CurrentTime
);
405 } else if (ev
->state
& Mod1Mask
) {
413 case XK_g
: ksym
= XK_Home
; break;
414 case XK_G
: ksym
= XK_End
; break;
415 case XK_h
: ksym
= XK_Up
; break;
416 case XK_j
: ksym
= XK_Next
; break;
417 case XK_k
: ksym
= XK_Prior
; break;
418 case XK_l
: ksym
= XK_Down
; break;
427 if (!iscntrl((unsigned char)*buf
))
432 if (text
[cursor
] == '\0')
434 cursor
= nextrune(+1);
439 insert(NULL
, nextrune(-1) - cursor
);
443 if (text
[cursor
] != '\0') {
444 cursor
= strlen(text
);
448 /* jump to end of list and position items in reverse */
453 while (next
&& (curr
= curr
->right
))
463 if (sel
== matches
) {
467 sel
= curr
= matches
;
472 if (cursor
> 0 && (!sel
|| !sel
->left
|| lines
> 0)) {
473 cursor
= nextrune(-1);
481 if (sel
&& sel
->left
&& (sel
= sel
->left
)->right
== curr
) {
502 puts((sel
&& !(ev
->state
& ShiftMask
)) ? sel
->text
: text
);
503 if (!(ev
->state
& ControlMask
)) {
512 if (text
[cursor
] != '\0') {
513 cursor
= nextrune(+1);
521 if (sel
&& sel
->right
&& (sel
= sel
->right
) == next
) {
529 strncpy(text
, sel
->text
, sizeof text
- 1);
530 text
[sizeof text
- 1] = '\0';
531 cursor
= strlen(text
);
548 /* we have been given the current selection, now insert it into input */
549 if (XGetWindowProperty(dpy
, win
, utf8
, 0, (sizeof text
/ 4) + 1, False
,
550 utf8
, &da
, &di
, &dl
, &dl
, (unsigned char **)&p
)
552 insert(p
, (q
= strchr(p
, '\n')) ? q
- p
: (ssize_t
)strlen(p
));
561 char buf
[sizeof text
], *p
;
564 /* read each line from stdin and add it to the item list */
565 for (i
= 0; fgets(buf
, sizeof buf
, stdin
); i
++) {
566 if (i
+ 1 >= size
/ sizeof *items
)
567 if (!(items
= realloc(items
, (size
+= BUFSIZ
))))
568 die("cannot realloc %zu bytes:", size
);
569 if ((p
= strchr(buf
, '\n')))
571 if (!(items
[i
].text
= strdup(buf
)))
572 die("cannot strdup %zu bytes:", strlen(buf
) + 1);
576 items
[i
].text
= NULL
;
577 lines
= MIN(lines
, i
);
585 while (!XNextEvent(dpy
, &ev
)) {
586 if (XFilterEvent(&ev
, win
))
590 if (ev
.xdestroywindow
.window
!= win
)
595 if (ev
.xexpose
.count
== 0)
596 drw_map(drw
, win
, 0, 0, mw
, mh
);
599 /* regrab focus from parent window */
600 if (ev
.xfocus
.window
!= win
)
606 case SelectionNotify
:
607 if (ev
.xselection
.property
== utf8
)
610 case VisibilityNotify
:
611 if (ev
.xvisibility
.state
!= VisibilityUnobscured
)
612 XRaiseWindow(dpy
, win
);
622 unsigned int du
, tmp
;
623 XSetWindowAttributes swa
;
626 XWindowAttributes wa
;
627 XClassHint ch
= {"dmenu", "dmenu"};
630 XineramaScreenInfo
*info
;
632 int a
, di
, n
, area
= 0;
634 /* init appearance */
635 for (j
= 0; j
< SchemeLast
; j
++)
636 scheme
[j
] = drw_scm_create(drw
, colors
[j
], 2);
638 clip
= XInternAtom(dpy
, "CLIPBOARD", False
);
639 utf8
= XInternAtom(dpy
, "UTF8_STRING", False
);
641 /* calculate menu geometry */
642 bh
= drw
->fonts
->h
+ 2;
643 lines
= MAX(lines
, 0);
644 mh
= (lines
+ 1) * bh
;
645 promptw
= (prompt
&& *prompt
) ? TEXTW(prompt
) - lrpad
/ 4 : 0;
648 if (parentwin
== root
&& (info
= XineramaQueryScreens(dpy
, &n
))) {
649 XGetInputFocus(dpy
, &w
, &di
);
650 if (mon
>= 0 && mon
< n
)
652 else if (w
!= root
&& w
!= PointerRoot
&& w
!= None
) {
653 /* find top-level window containing current input focus */
655 if (XQueryTree(dpy
, (pw
= w
), &dw
, &w
, &dws
, &du
) && dws
)
657 } while (w
!= root
&& w
!= pw
);
658 /* find xinerama screen with which the window intersects most */
659 if (XGetWindowAttributes(dpy
, pw
, &wa
))
660 for (j
= 0; j
< n
; j
++)
661 if ((a
= INTERSECT(wa
.x
, wa
.y
, wa
.width
, wa
.height
, info
[j
])) > area
) {
666 /* no focused window is on screen, so use pointer location instead */
667 if (mon
< 0 && !area
&& XQueryPointer(dpy
, root
, &dw
, &dw
, &x
, &y
, &di
, &di
, &du
))
668 for (i
= 0; i
< n
; i
++)
669 if (INTERSECT(x
, y
, 1, 1, info
[i
]) != 0)
673 mw
= MIN(MAX(max_textw() + promptw
, min_width
), info
[i
].width
);
674 x
= info
[i
].x_org
+ ((info
[i
].width
- mw
) / 2);
675 y
= info
[i
].y_org
+ ((info
[i
].height
- mh
) / 2);
678 y
= info
[i
].y_org
+ (topbar
? 0 : info
[i
].height
- mh
);
686 if (!XGetWindowAttributes(dpy
, parentwin
, &wa
))
687 die("could not get embedding window attributes: 0x%lx",
691 mw
= MIN(MAX(max_textw() + promptw
, min_width
), wa
.width
);
692 x
= (wa
.width
- mw
) / 2;
693 y
= (wa
.height
- mh
) / 2;
696 y
= topbar
? 0 : wa
.height
- mh
;
700 for (item
= items
; item
&& item
->text
; ++item
) {
701 if ((tmp
= textw_clamp(item
->text
, mw
/3)) > inputw
) {
702 if ((inputw
= tmp
) == mw
/3)
708 /* create menu window */
709 swa
.override_redirect
= True
;
710 swa
.background_pixel
= scheme
[SchemeNorm
][ColBg
].pixel
;
711 swa
.event_mask
= ExposureMask
| KeyPressMask
| VisibilityChangeMask
;
712 win
= XCreateWindow(dpy
, parentwin
, x
, y
, mw
, mh
, 0,
713 CopyFromParent
, CopyFromParent
, CopyFromParent
,
714 CWOverrideRedirect
| CWBackPixel
| CWEventMask
, &swa
);
715 XSetClassHint(dpy
, win
, &ch
);
719 if ((xim
= XOpenIM(dpy
, NULL
, NULL
, NULL
)) == NULL
)
720 die("XOpenIM failed: could not open input device");
722 xic
= XCreateIC(xim
, XNInputStyle
, XIMPreeditNothing
| XIMStatusNothing
,
723 XNClientWindow
, win
, XNFocusWindow
, win
, NULL
);
725 XMapRaised(dpy
, win
);
727 XSelectInput(dpy
, parentwin
, FocusChangeMask
| SubstructureNotifyMask
);
728 if (XQueryTree(dpy
, parentwin
, &dw
, &w
, &dws
, &du
) && dws
) {
729 for (i
= 0; i
< du
&& dws
[i
] != win
; ++i
)
730 XSelectInput(dpy
, dws
[i
], FocusChangeMask
);
735 drw_resize(drw
, mw
, mh
);
742 fputs("usage: dmenu [-bfiv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
743 " [-nb color] [-nf color] [-sb color] [-sf color] [-w windowid]\n", stderr
);
748 main(int argc
, char *argv
[])
750 XWindowAttributes wa
;
753 for (i
= 1; i
< argc
; i
++)
754 /* these options take no arguments */
755 if (!strcmp(argv
[i
], "-v")) { /* prints version information */
756 puts("dmenu-"VERSION
);
758 } else if (!strcmp(argv
[i
], "-b")) /* appears at the bottom of the screen */
760 else if (!strcmp(argv
[i
], "-f")) /* grabs keyboard before reading stdin */
762 else if (!strcmp(argv
[i
], "-c")) /* centers dmenu on screen */
764 else if (!strcmp(argv
[i
], "-i")) { /* case-insensitive item matching */
765 fstrncmp
= strncasecmp
;
767 } else if (i
+ 1 == argc
)
769 /* these options take one argument */
770 else if (!strcmp(argv
[i
], "-l")) /* number of lines in vertical list */
771 lines
= atoi(argv
[++i
]);
772 else if (!strcmp(argv
[i
], "-m"))
773 mon
= atoi(argv
[++i
]);
774 else if (!strcmp(argv
[i
], "-p")) /* adds prompt to left of input field */
776 else if (!strcmp(argv
[i
], "-fn")) /* font or font set */
777 fonts
[0] = argv
[++i
];
778 else if (!strcmp(argv
[i
], "-nb")) /* normal background color */
779 colors
[SchemeNorm
][ColBg
] = argv
[++i
];
780 else if (!strcmp(argv
[i
], "-nf")) /* normal foreground color */
781 colors
[SchemeNorm
][ColFg
] = argv
[++i
];
782 else if (!strcmp(argv
[i
], "-sb")) /* selected background color */
783 colors
[SchemeSel
][ColBg
] = argv
[++i
];
784 else if (!strcmp(argv
[i
], "-sf")) /* selected foreground color */
785 colors
[SchemeSel
][ColFg
] = argv
[++i
];
786 else if (!strcmp(argv
[i
], "-w")) /* embedding window id */
791 if (!setlocale(LC_CTYPE
, "") || !XSupportsLocale())
792 fputs("warning: no locale support\n", stderr
);
793 if (!(dpy
= XOpenDisplay(NULL
)))
794 die("cannot open display");
795 screen
= DefaultScreen(dpy
);
796 root
= RootWindow(dpy
, screen
);
797 if (!embed
|| !(parentwin
= strtol(embed
, NULL
, 0)))
799 if (!XGetWindowAttributes(dpy
, parentwin
, &wa
))
800 die("could not get embedding window attributes: 0x%lx",
802 drw
= drw_create(dpy
, screen
, root
, wa
.width
, wa
.height
);
803 if (!drw_fontset_create(drw
, fonts
, LENGTH(fonts
)))
804 die("no fonts could be loaded.");
805 lrpad
= drw
->fonts
->h
;
808 if (pledge("stdio rpath", NULL
) == -1)
812 if (fast
&& !isatty(0)) {
822 return 1; /* unreachable */