Xinqi Bao's Git
3b2f3ec9ec88321f8390b8493bcfd4add8182083
1 /* See LICENSE file for copyright and license details. */
14 #include <X11/Xatom.h>
15 #include <X11/Xutil.h>
17 #include <X11/extensions/Xinerama.h>
19 #include <X11/Xft/Xft.h>
25 #define INTERSECT(x,y,w,h,r) (MAX(0, MIN((x)+(w),(r).x_org+(r).width) - MAX((x),(r).x_org)) \
26 * MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
27 #define LENGTH(X) (sizeof X / sizeof X[0])
28 #define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad)
31 enum { SchemeNorm
, SchemeSel
, SchemeOut
, SchemeLast
}; /* color schemes */
35 struct item
*left
, *right
;
39 static char text
[BUFSIZ
] = "";
41 static int bh
, mw
, mh
;
42 static int inputw
= 0, promptw
;
43 static int lrpad
; /* sum of left and right padding */
45 static struct item
*items
= NULL
;
46 static struct item
*matches
, *matchend
;
47 static struct item
*prev
, *curr
, *next
, *sel
;
48 static int mon
= -1, screen
;
50 static Atom clip
, utf8
;
52 static Window root
, parentwin
, win
;
56 static Clr
*scheme
[SchemeLast
];
60 static int (*fstrncmp
)(const char *, const char *, size_t) = strncmp
;
61 static char *(*fstrstr
)(const char *, const char *) = strstr
;
64 appenditem(struct item
*item
, struct item
**list
, struct item
**last
)
67 (*last
)->right
= item
;
84 n
= mw
- (promptw
+ inputw
+ TEXTW("<") + TEXTW(">"));
85 /* calculate which items will begin the next page and previous page */
86 for (i
= 0, next
= curr
; next
; next
= next
->right
)
87 if ((i
+= (lines
> 0) ? bh
: MIN(TEXTW(next
->text
), n
)) > n
)
89 for (i
= 0, prev
= curr
; prev
&& prev
->left
; prev
= prev
->left
)
90 if ((i
+= (lines
> 0) ? bh
: MIN(TEXTW(prev
->left
->text
), n
)) > n
)
99 XUngrabKey(dpy
, AnyKey
, AnyModifier
, root
);
100 for (i
= 0; i
< SchemeLast
; i
++)
108 cistrstr(const char *s
, const char *sub
)
112 for (len
= strlen(sub
); *s
; s
++)
113 if (!strncasecmp(s
, sub
, len
))
119 drawitem(struct item
*item
, int x
, int y
, int w
)
122 drw_setscheme(drw
, scheme
[SchemeSel
]);
124 drw_setscheme(drw
, scheme
[SchemeOut
]);
126 drw_setscheme(drw
, scheme
[SchemeNorm
]);
128 return drw_text(drw
, x
, y
, w
, bh
, lrpad
/ 2, item
->text
, 0);
138 drw_setscheme(drw
, scheme
[SchemeNorm
]);
139 drw_rect(drw
, 0, 0, mw
, mh
, 1, 1);
141 if (prompt
&& *prompt
) {
142 drw_setscheme(drw
, scheme
[SchemeSel
]);
143 x
= drw_text(drw
, x
, 0, promptw
, bh
, lrpad
/ 2, prompt
, 0);
145 /* draw input field */
146 w
= (lines
> 0 || !matches
) ? mw
- x
: inputw
;
147 drw_setscheme(drw
, scheme
[SchemeNorm
]);
148 drw_text(drw
, x
, 0, w
, bh
, lrpad
/ 2, text
, 0);
150 curpos
= TEXTW(text
) - TEXTW(&text
[cursor
]);
151 if ((curpos
+= lrpad
/ 2 - 1) < w
) {
152 drw_setscheme(drw
, scheme
[SchemeNorm
]);
153 drw_rect(drw
, x
+ curpos
, 2, 2, bh
- 4, 1, 0);
157 /* draw vertical list */
158 for (item
= curr
; item
!= next
; item
= item
->right
)
159 drawitem(item
, x
, y
+= bh
, mw
- x
);
160 } else if (matches
) {
161 /* draw horizontal list */
165 drw_setscheme(drw
, scheme
[SchemeNorm
]);
166 drw_text(drw
, x
, 0, w
, bh
, lrpad
/ 2, "<", 0);
169 for (item
= curr
; item
!= next
; item
= item
->right
)
170 x
= drawitem(item
, x
, 0, MIN(TEXTW(item
->text
), mw
- x
- TEXTW(">")));
173 drw_setscheme(drw
, scheme
[SchemeNorm
]);
174 drw_text(drw
, mw
- w
, 0, w
, bh
, lrpad
/ 2, ">", 0);
177 drw_map(drw
, win
, 0, 0, mw
, mh
);
183 struct timespec ts
= { .tv_sec
= 0, .tv_nsec
= 10000000 };
187 for (i
= 0; i
< 100; ++i
) {
188 XGetInputFocus(dpy
, &focuswin
, &revertwin
);
191 XSetInputFocus(dpy
, win
, RevertToParent
, CurrentTime
);
192 nanosleep(&ts
, NULL
);
194 die("cannot grab focus");
200 struct timespec ts
= { .tv_sec
= 0, .tv_nsec
= 1000000 };
205 /* try to grab keyboard, we may have to wait for another process to ungrab */
206 for (i
= 0; i
< 1000; i
++) {
207 if (XGrabKeyboard(dpy
, DefaultRootWindow(dpy
), True
, GrabModeAsync
,
208 GrabModeAsync
, CurrentTime
) == GrabSuccess
)
210 nanosleep(&ts
, NULL
);
212 die("cannot grab keyboard");
218 static char **tokv
= NULL
;
221 char buf
[sizeof text
], *s
;
223 size_t len
, textsize
;
224 struct item
*item
, *lprefix
, *lsubstr
, *prefixend
, *substrend
;
227 /* separate input text into tokens to be matched individually */
228 for (s
= strtok(buf
, " "); s
; tokv
[tokc
- 1] = s
, s
= strtok(NULL
, " "))
229 if (++tokc
> tokn
&& !(tokv
= realloc(tokv
, ++tokn
* sizeof *tokv
)))
230 die("cannot realloc %u bytes:", tokn
* sizeof *tokv
);
231 len
= tokc
? strlen(tokv
[0]) : 0;
233 matches
= lprefix
= lsubstr
= matchend
= prefixend
= substrend
= NULL
;
234 textsize
= strlen(text
) + 1;
235 for (item
= items
; item
&& item
->text
; item
++) {
236 for (i
= 0; i
< tokc
; i
++)
237 if (!fstrstr(item
->text
, tokv
[i
]))
239 if (i
!= tokc
) /* not all tokens match */
241 /* exact matches go first, then prefixes, then substrings */
242 if (!tokc
|| !fstrncmp(text
, item
->text
, textsize
))
243 appenditem(item
, &matches
, &matchend
);
244 else if (!fstrncmp(tokv
[0], item
->text
, len
))
245 appenditem(item
, &lprefix
, &prefixend
);
247 appenditem(item
, &lsubstr
, &substrend
);
251 matchend
->right
= lprefix
;
252 lprefix
->left
= matchend
;
255 matchend
= prefixend
;
259 matchend
->right
= lsubstr
;
260 lsubstr
->left
= matchend
;
263 matchend
= substrend
;
265 curr
= sel
= matches
;
270 insert(const char *str
, ssize_t n
)
272 if (strlen(text
) + n
> sizeof text
- 1)
274 /* move existing text out of the way, insert new text, and update cursor */
275 memmove(&text
[cursor
+ n
], &text
[cursor
], sizeof text
- cursor
- MAX(n
, 0));
277 memcpy(&text
[cursor
], str
, n
);
287 /* return location of next utf8 rune in the given direction (+1 or -1) */
288 for (n
= cursor
+ inc
; n
+ inc
>= 0 && (text
[n
] & 0xc0) == 0x80; n
+= inc
)
294 movewordedge(int dir
)
296 if (dir
< 0) { /* move cursor to the start of the word*/
297 while (cursor
> 0 && strchr(worddelimiters
, text
[nextrune(-1)]))
298 cursor
= nextrune(-1);
299 while (cursor
> 0 && !strchr(worddelimiters
, text
[nextrune(-1)]))
300 cursor
= nextrune(-1);
301 } else { /* move cursor to the end of the word */
302 while (text
[cursor
] && strchr(worddelimiters
, text
[cursor
]))
303 cursor
= nextrune(+1);
304 while (text
[cursor
] && !strchr(worddelimiters
, text
[cursor
]))
305 cursor
= nextrune(+1);
310 keypress(XKeyEvent
*ev
)
317 len
= XmbLookupString(xic
, ev
, buf
, sizeof buf
, &ksym
, &status
);
319 default: /* XLookupNone, XBufferOverflow */
328 if (ev
->state
& ControlMask
) {
330 case XK_a
: ksym
= XK_Home
; break;
331 case XK_b
: ksym
= XK_Left
; break;
332 case XK_c
: ksym
= XK_Escape
; break;
333 case XK_d
: ksym
= XK_Delete
; break;
334 case XK_e
: ksym
= XK_End
; break;
335 case XK_f
: ksym
= XK_Right
; break;
336 case XK_g
: ksym
= XK_Escape
; break;
337 case XK_h
: ksym
= XK_BackSpace
; break;
338 case XK_i
: ksym
= XK_Tab
; break;
339 case XK_j
: /* fallthrough */
340 case XK_J
: /* fallthrough */
341 case XK_m
: /* fallthrough */
342 case XK_M
: ksym
= XK_Return
; ev
->state
&= ~ControlMask
; break;
343 case XK_n
: ksym
= XK_Down
; break;
344 case XK_p
: ksym
= XK_Up
; break;
346 case XK_k
: /* delete right */
350 case XK_u
: /* delete left */
351 insert(NULL
, 0 - cursor
);
353 case XK_w
: /* delete word */
354 while (cursor
> 0 && strchr(worddelimiters
, text
[nextrune(-1)]))
355 insert(NULL
, nextrune(-1) - cursor
);
356 while (cursor
> 0 && !strchr(worddelimiters
, text
[nextrune(-1)]))
357 insert(NULL
, nextrune(-1) - cursor
);
359 case XK_y
: /* paste selection */
361 XConvertSelection(dpy
, (ev
->state
& ShiftMask
) ? clip
: XA_PRIMARY
,
362 utf8
, utf8
, win
, CurrentTime
);
379 } else if (ev
->state
& Mod1Mask
) {
387 case XK_g
: ksym
= XK_Home
; break;
388 case XK_G
: ksym
= XK_End
; break;
389 case XK_h
: ksym
= XK_Up
; break;
390 case XK_j
: ksym
= XK_Next
; break;
391 case XK_k
: ksym
= XK_Prior
; break;
392 case XK_l
: ksym
= XK_Down
; break;
405 if (text
[cursor
] == '\0')
407 cursor
= nextrune(+1);
412 insert(NULL
, nextrune(-1) - cursor
);
415 if (text
[cursor
] != '\0') {
416 cursor
= strlen(text
);
420 /* jump to end of list and position items in reverse */
425 while (next
&& (curr
= curr
->right
))
434 if (sel
== matches
) {
438 sel
= curr
= matches
;
442 if (cursor
> 0 && (!sel
|| !sel
->left
|| lines
> 0)) {
443 cursor
= nextrune(-1);
450 if (sel
&& sel
->left
&& (sel
= sel
->left
)->right
== curr
) {
469 puts((sel
&& !(ev
->state
& ShiftMask
)) ? sel
->text
: text
);
470 if (!(ev
->state
& ControlMask
)) {
478 if (text
[cursor
] != '\0') {
479 cursor
= nextrune(+1);
486 if (sel
&& sel
->right
&& (sel
= sel
->right
) == next
) {
494 strncpy(text
, sel
->text
, sizeof text
- 1);
495 text
[sizeof text
- 1] = '\0';
496 cursor
= strlen(text
);
513 /* we have been given the current selection, now insert it into input */
514 if (XGetWindowProperty(dpy
, win
, utf8
, 0, (sizeof text
/ 4) + 1, False
,
515 utf8
, &da
, &di
, &dl
, &dl
, (unsigned char **)&p
)
517 insert(p
, (q
= strchr(p
, '\n')) ? q
- p
: (ssize_t
)strlen(p
));
526 char buf
[sizeof text
], *p
;
527 size_t i
, imax
= 0, size
= 0;
528 unsigned int tmpmax
= 0;
530 /* read each line from stdin and add it to the item list */
531 for (i
= 0; fgets(buf
, sizeof buf
, stdin
); i
++) {
532 if (i
+ 1 >= size
/ sizeof *items
)
533 if (!(items
= realloc(items
, (size
+= BUFSIZ
))))
534 die("cannot realloc %u bytes:", size
);
535 if ((p
= strchr(buf
, '\n')))
537 if (!(items
[i
].text
= strdup(buf
)))
538 die("cannot strdup %u bytes:", strlen(buf
) + 1);
540 drw_font_getexts(drw
->fonts
, buf
, strlen(buf
), &tmpmax
, NULL
);
541 if (tmpmax
> inputw
) {
547 items
[i
].text
= NULL
;
548 inputw
= items
? TEXTW(items
[imax
].text
) : 0;
549 lines
= MIN(lines
, i
);
557 while (!XNextEvent(dpy
, &ev
)) {
558 if (XFilterEvent(&ev
, None
))
562 if (ev
.xexpose
.count
== 0)
563 drw_map(drw
, win
, 0, 0, mw
, mh
);
566 /* regrab focus from parent window */
567 if (ev
.xfocus
.window
!= win
)
573 case SelectionNotify
:
574 if (ev
.xselection
.property
== utf8
)
577 case VisibilityNotify
:
578 if (ev
.xvisibility
.state
!= VisibilityUnobscured
)
579 XRaiseWindow(dpy
, win
);
590 XSetWindowAttributes swa
;
593 XWindowAttributes wa
;
594 XClassHint ch
= {"dmenu", "dmenu"};
596 XineramaScreenInfo
*info
;
598 int a
, di
, n
, area
= 0;
600 /* init appearance */
601 for (j
= 0; j
< SchemeLast
; j
++)
602 scheme
[j
] = drw_scm_create(drw
, colors
[j
], 2);
604 clip
= XInternAtom(dpy
, "CLIPBOARD", False
);
605 utf8
= XInternAtom(dpy
, "UTF8_STRING", False
);
607 /* calculate menu geometry */
608 bh
= drw
->fonts
->h
+ 2;
609 lines
= MAX(lines
, 0);
610 mh
= (lines
+ 1) * bh
;
613 if (parentwin
== root
&& (info
= XineramaQueryScreens(dpy
, &n
))) {
614 XGetInputFocus(dpy
, &w
, &di
);
615 if (mon
>= 0 && mon
< n
)
617 else if (w
!= root
&& w
!= PointerRoot
&& w
!= None
) {
618 /* find top-level window containing current input focus */
620 if (XQueryTree(dpy
, (pw
= w
), &dw
, &w
, &dws
, &du
) && dws
)
622 } while (w
!= root
&& w
!= pw
);
623 /* find xinerama screen with which the window intersects most */
624 if (XGetWindowAttributes(dpy
, pw
, &wa
))
625 for (j
= 0; j
< n
; j
++)
626 if ((a
= INTERSECT(wa
.x
, wa
.y
, wa
.width
, wa
.height
, info
[j
])) > area
) {
631 /* no focused window is on screen, so use pointer location instead */
632 if (mon
< 0 && !area
&& XQueryPointer(dpy
, root
, &dw
, &dw
, &x
, &y
, &di
, &di
, &du
))
633 for (i
= 0; i
< n
; i
++)
634 if (INTERSECT(x
, y
, 1, 1, info
[i
]))
638 y
= info
[i
].y_org
+ (topbar
? 0 : info
[i
].height
- mh
);
644 if (!XGetWindowAttributes(dpy
, parentwin
, &wa
))
645 die("could not get embedding window attributes: 0x%lx",
648 y
= topbar
? 0 : wa
.height
- mh
;
651 promptw
= (prompt
&& *prompt
) ? TEXTW(prompt
) - lrpad
/ 4 : 0;
652 inputw
= MIN(inputw
, mw
/3);
655 /* create menu window */
656 swa
.override_redirect
= True
;
657 swa
.background_pixel
= scheme
[SchemeNorm
][ColBg
].pixel
;
658 swa
.event_mask
= ExposureMask
| KeyPressMask
| VisibilityChangeMask
;
659 win
= XCreateWindow(dpy
, parentwin
, x
, y
, mw
, mh
, 0,
660 CopyFromParent
, CopyFromParent
, CopyFromParent
,
661 CWOverrideRedirect
| CWBackPixel
| CWEventMask
, &swa
);
662 XSetClassHint(dpy
, win
, &ch
);
664 /* open input methods */
665 xim
= XOpenIM(dpy
, NULL
, NULL
, NULL
);
666 xic
= XCreateIC(xim
, XNInputStyle
, XIMPreeditNothing
| XIMStatusNothing
,
667 XNClientWindow
, win
, XNFocusWindow
, win
, NULL
);
669 XMapRaised(dpy
, win
);
670 XSetInputFocus(dpy
, win
, RevertToParent
, CurrentTime
);
672 XSelectInput(dpy
, parentwin
, FocusChangeMask
);
673 if (XQueryTree(dpy
, parentwin
, &dw
, &w
, &dws
, &du
) && dws
) {
674 for (i
= 0; i
< du
&& dws
[i
] != win
; ++i
)
675 XSelectInput(dpy
, dws
[i
], FocusChangeMask
);
680 drw_resize(drw
, mw
, mh
);
687 fputs("usage: dmenu [-bfiv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
688 " [-nb color] [-nf color] [-sb color] [-sf color] [-w windowid]\n", stderr
);
693 main(int argc
, char *argv
[])
695 XWindowAttributes wa
;
698 for (i
= 1; i
< argc
; i
++)
699 /* these options take no arguments */
700 if (!strcmp(argv
[i
], "-v")) { /* prints version information */
701 puts("dmenu-"VERSION
);
703 } else if (!strcmp(argv
[i
], "-b")) /* appears at the bottom of the screen */
705 else if (!strcmp(argv
[i
], "-f")) /* grabs keyboard before reading stdin */
707 else if (!strcmp(argv
[i
], "-i")) { /* case-insensitive item matching */
708 fstrncmp
= strncasecmp
;
710 } else if (i
+ 1 == argc
)
712 /* these options take one argument */
713 else if (!strcmp(argv
[i
], "-l")) /* number of lines in vertical list */
714 lines
= atoi(argv
[++i
]);
715 else if (!strcmp(argv
[i
], "-m"))
716 mon
= atoi(argv
[++i
]);
717 else if (!strcmp(argv
[i
], "-p")) /* adds prompt to left of input field */
719 else if (!strcmp(argv
[i
], "-fn")) /* font or font set */
720 fonts
[0] = argv
[++i
];
721 else if (!strcmp(argv
[i
], "-nb")) /* normal background color */
722 colors
[SchemeNorm
][ColBg
] = argv
[++i
];
723 else if (!strcmp(argv
[i
], "-nf")) /* normal foreground color */
724 colors
[SchemeNorm
][ColFg
] = argv
[++i
];
725 else if (!strcmp(argv
[i
], "-sb")) /* selected background color */
726 colors
[SchemeSel
][ColBg
] = argv
[++i
];
727 else if (!strcmp(argv
[i
], "-sf")) /* selected foreground color */
728 colors
[SchemeSel
][ColFg
] = argv
[++i
];
729 else if (!strcmp(argv
[i
], "-w")) /* embedding window id */
734 if (!setlocale(LC_CTYPE
, "") || !XSupportsLocale())
735 fputs("warning: no locale support\n", stderr
);
736 if (!XSetLocaleModifiers(""))
737 fputs("warning: no locale modifiers support\n", stderr
);
738 if (!(dpy
= XOpenDisplay(NULL
)))
739 die("cannot open display");
740 screen
= DefaultScreen(dpy
);
741 root
= RootWindow(dpy
, screen
);
742 if (!embed
|| !(parentwin
= strtol(embed
, NULL
, 0)))
744 if (!XGetWindowAttributes(dpy
, parentwin
, &wa
))
745 die("could not get embedding window attributes: 0x%lx",
747 drw
= drw_create(dpy
, screen
, root
, wa
.width
, wa
.height
);
748 if (!drw_fontset_create(drw
, fonts
, LENGTH(fonts
)))
749 die("no fonts could be loaded.");
750 lrpad
= drw
->fonts
->h
;
753 if (pledge("stdio rpath", NULL
) < 0)
767 return 1; /* unreachable */