Xinqi Bao's Git
d764658ba9859638a516629cac0b1785f90679da
1 /* See LICENSE file for copyright and license details. */
11 #include <X11/Xatom.h>
12 #include <X11/Xutil.h>
14 #include <X11/extensions/Xinerama.h>
16 #include <X11/Xft/Xft.h>
22 #define INTERSECT(x,y,w,h,r) (MAX(0, MIN((x)+(w),(r).x_org+(r).width) - MAX((x),(r).x_org)) \
23 * MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
24 #define LENGTH(X) (sizeof X / sizeof X[0])
25 #define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad)
28 enum { SchemeNorm
, SchemeSel
, SchemeOut
, SchemeLast
}; /* color schemes */
32 struct item
*left
, *right
;
36 static char text
[BUFSIZ
] = "";
38 static int bh
, mw
, mh
;
39 static int inputw
= 0, promptw
;
40 static int lrpad
; /* sum of left and right padding */
42 static struct item
*items
= NULL
;
43 static struct item
*matches
, *matchend
;
44 static struct item
*prev
, *curr
, *next
, *sel
;
45 static int mon
= -1, screen
;
47 static Atom clip
, utf8
;
49 static Window root
, parentwin
, win
;
53 static Clr
*scheme
[SchemeLast
];
57 static int (*fstrncmp
)(const char *, const char *, size_t) = strncmp
;
58 static char *(*fstrstr
)(const char *, const char *) = strstr
;
61 appenditem(struct item
*item
, struct item
**list
, struct item
**last
)
64 (*last
)->right
= item
;
81 n
= mw
- (promptw
+ inputw
+ TEXTW("<") + TEXTW(">"));
82 /* calculate which items will begin the next page and previous page */
83 for (i
= 0, next
= curr
; next
; next
= next
->right
)
84 if ((i
+= (lines
> 0) ? bh
: MIN(TEXTW(next
->text
), n
)) > n
)
86 for (i
= 0, prev
= curr
; prev
&& prev
->left
; prev
= prev
->left
)
87 if ((i
+= (lines
> 0) ? bh
: MIN(TEXTW(prev
->left
->text
), n
)) > n
)
96 XUngrabKey(dpy
, AnyKey
, AnyModifier
, root
);
97 for (i
= 0; i
< SchemeLast
; i
++)
105 cistrstr(const char *s
, const char *sub
)
109 for (len
= strlen(sub
); *s
; s
++)
110 if (!strncasecmp(s
, sub
, len
))
116 drawitem(struct item
*item
, int x
, int y
, int w
)
119 drw_setscheme(drw
, scheme
[SchemeSel
]);
121 drw_setscheme(drw
, scheme
[SchemeOut
]);
123 drw_setscheme(drw
, scheme
[SchemeNorm
]);
125 return drw_text(drw
, x
, y
, w
, bh
, lrpad
/ 2, item
->text
, 0);
135 drw_setscheme(drw
, scheme
[SchemeNorm
]);
136 drw_rect(drw
, 0, 0, mw
, mh
, 1, 1);
138 if (prompt
&& *prompt
) {
139 drw_setscheme(drw
, scheme
[SchemeSel
]);
140 x
= drw_text(drw
, x
, 0, promptw
, bh
, lrpad
/ 2, prompt
, 0);
142 /* draw input field */
143 w
= (lines
> 0 || !matches
) ? mw
- x
: inputw
;
144 drw_setscheme(drw
, scheme
[SchemeNorm
]);
145 drw_text(drw
, x
, 0, w
, bh
, lrpad
/ 2, text
, 0);
147 curpos
= TEXTW(text
) - TEXTW(&text
[cursor
]);
148 if ((curpos
+= lrpad
/ 2 - 1) < w
) {
149 drw_setscheme(drw
, scheme
[SchemeNorm
]);
150 drw_rect(drw
, x
+ curpos
, 2, 2, bh
- 4, 1, 0);
154 /* draw vertical list */
155 for (item
= curr
; item
!= next
; item
= item
->right
)
156 drawitem(item
, x
, y
+= bh
, mw
- x
);
157 } else if (matches
) {
158 /* draw horizontal list */
162 drw_setscheme(drw
, scheme
[SchemeNorm
]);
163 drw_text(drw
, x
, 0, w
, bh
, lrpad
/ 2, "<", 0);
166 for (item
= curr
; item
!= next
; item
= item
->right
)
167 x
= drawitem(item
, x
, 0, MIN(TEXTW(item
->text
), mw
- x
- TEXTW(">")));
170 drw_setscheme(drw
, scheme
[SchemeNorm
]);
171 drw_text(drw
, mw
- w
, 0, w
, bh
, lrpad
/ 2, ">", 0);
174 drw_map(drw
, win
, 0, 0, mw
, mh
);
180 struct timespec ts
= { .tv_sec
= 0, .tv_nsec
= 10000000 };
184 for (i
= 0; i
< 100; ++i
) {
185 XGetInputFocus(dpy
, &focuswin
, &revertwin
);
188 XSetInputFocus(dpy
, win
, RevertToParent
, CurrentTime
);
189 nanosleep(&ts
, NULL
);
191 die("cannot grab focus");
197 struct timespec ts
= { .tv_sec
= 0, .tv_nsec
= 1000000 };
202 /* try to grab keyboard, we may have to wait for another process to ungrab */
203 for (i
= 0; i
< 1000; i
++) {
204 if (XGrabKeyboard(dpy
, DefaultRootWindow(dpy
), True
, GrabModeAsync
,
205 GrabModeAsync
, CurrentTime
) == GrabSuccess
)
207 nanosleep(&ts
, NULL
);
209 die("cannot grab keyboard");
215 static char **tokv
= NULL
;
218 char buf
[sizeof text
], *s
;
220 size_t len
, textsize
;
221 struct item
*item
, *lprefix
, *lsubstr
, *prefixend
, *substrend
;
224 /* separate input text into tokens to be matched individually */
225 for (s
= strtok(buf
, " "); s
; tokv
[tokc
- 1] = s
, s
= strtok(NULL
, " "))
226 if (++tokc
> tokn
&& !(tokv
= realloc(tokv
, ++tokn
* sizeof *tokv
)))
227 die("cannot realloc %u bytes:", tokn
* sizeof *tokv
);
228 len
= tokc
? strlen(tokv
[0]) : 0;
230 matches
= lprefix
= lsubstr
= matchend
= prefixend
= substrend
= NULL
;
231 textsize
= strlen(text
) + 1;
232 for (item
= items
; item
&& item
->text
; item
++) {
233 for (i
= 0; i
< tokc
; i
++)
234 if (!fstrstr(item
->text
, tokv
[i
]))
236 if (i
!= tokc
) /* not all tokens match */
238 /* exact matches go first, then prefixes, then substrings */
239 if (!tokc
|| !fstrncmp(text
, item
->text
, textsize
))
240 appenditem(item
, &matches
, &matchend
);
241 else if (!fstrncmp(tokv
[0], item
->text
, len
))
242 appenditem(item
, &lprefix
, &prefixend
);
244 appenditem(item
, &lsubstr
, &substrend
);
248 matchend
->right
= lprefix
;
249 lprefix
->left
= matchend
;
252 matchend
= prefixend
;
256 matchend
->right
= lsubstr
;
257 lsubstr
->left
= matchend
;
260 matchend
= substrend
;
262 curr
= sel
= matches
;
267 insert(const char *str
, ssize_t n
)
269 if (strlen(text
) + n
> sizeof text
- 1)
271 /* move existing text out of the way, insert new text, and update cursor */
272 memmove(&text
[cursor
+ n
], &text
[cursor
], sizeof text
- cursor
- MAX(n
, 0));
274 memcpy(&text
[cursor
], str
, n
);
284 /* return location of next utf8 rune in the given direction (+1 or -1) */
285 for (n
= cursor
+ inc
; n
+ inc
>= 0 && (text
[n
] & 0xc0) == 0x80; n
+= inc
)
291 movewordedge(int dir
)
293 if (dir
< 0) { /* move cursor to the start of the word*/
294 while (cursor
> 0 && strchr(worddelimiters
, text
[nextrune(-1)]))
295 cursor
= nextrune(-1);
296 while (cursor
> 0 && !strchr(worddelimiters
, text
[nextrune(-1)]))
297 cursor
= nextrune(-1);
298 } else { /* move cursor to the end of the word */
299 while (text
[cursor
] && strchr(worddelimiters
, text
[cursor
]))
300 cursor
= nextrune(+1);
301 while (text
[cursor
] && !strchr(worddelimiters
, text
[cursor
]))
302 cursor
= nextrune(+1);
307 keypress(XKeyEvent
*ev
)
314 len
= XmbLookupString(xic
, ev
, buf
, sizeof buf
, &ksym
, &status
);
316 default: /* XLookupNone, XBufferOverflow */
325 if (ev
->state
& ControlMask
) {
327 case XK_a
: ksym
= XK_Home
; break;
328 case XK_b
: ksym
= XK_Left
; break;
329 case XK_c
: ksym
= XK_Escape
; break;
330 case XK_d
: ksym
= XK_Delete
; break;
331 case XK_e
: ksym
= XK_End
; break;
332 case XK_f
: ksym
= XK_Right
; break;
333 case XK_g
: ksym
= XK_Escape
; break;
334 case XK_h
: ksym
= XK_BackSpace
; break;
335 case XK_i
: ksym
= XK_Tab
; break;
336 case XK_j
: /* fallthrough */
337 case XK_J
: /* fallthrough */
338 case XK_m
: /* fallthrough */
339 case XK_M
: ksym
= XK_Return
; ev
->state
&= ~ControlMask
; break;
340 case XK_n
: ksym
= XK_Down
; break;
341 case XK_p
: ksym
= XK_Up
; break;
343 case XK_k
: /* delete right */
347 case XK_u
: /* delete left */
348 insert(NULL
, 0 - cursor
);
350 case XK_w
: /* delete word */
351 while (cursor
> 0 && strchr(worddelimiters
, text
[nextrune(-1)]))
352 insert(NULL
, nextrune(-1) - cursor
);
353 while (cursor
> 0 && !strchr(worddelimiters
, text
[nextrune(-1)]))
354 insert(NULL
, nextrune(-1) - cursor
);
356 case XK_y
: /* paste selection */
358 XConvertSelection(dpy
, (ev
->state
& ShiftMask
) ? clip
: XA_PRIMARY
,
359 utf8
, utf8
, win
, CurrentTime
);
376 } else if (ev
->state
& Mod1Mask
) {
384 case XK_g
: ksym
= XK_Home
; break;
385 case XK_G
: ksym
= XK_End
; break;
386 case XK_h
: ksym
= XK_Up
; break;
387 case XK_j
: ksym
= XK_Next
; break;
388 case XK_k
: ksym
= XK_Prior
; break;
389 case XK_l
: ksym
= XK_Down
; break;
402 if (text
[cursor
] == '\0')
404 cursor
= nextrune(+1);
409 insert(NULL
, nextrune(-1) - cursor
);
412 if (text
[cursor
] != '\0') {
413 cursor
= strlen(text
);
417 /* jump to end of list and position items in reverse */
422 while (next
&& (curr
= curr
->right
))
431 if (sel
== matches
) {
435 sel
= curr
= matches
;
439 if (cursor
> 0 && (!sel
|| !sel
->left
|| lines
> 0)) {
440 cursor
= nextrune(-1);
447 if (sel
&& sel
->left
&& (sel
= sel
->left
)->right
== curr
) {
466 puts((sel
&& !(ev
->state
& ShiftMask
)) ? sel
->text
: text
);
467 if (!(ev
->state
& ControlMask
)) {
475 if (text
[cursor
] != '\0') {
476 cursor
= nextrune(+1);
483 if (sel
&& sel
->right
&& (sel
= sel
->right
) == next
) {
491 strncpy(text
, sel
->text
, sizeof text
- 1);
492 text
[sizeof text
- 1] = '\0';
493 cursor
= strlen(text
);
510 /* we have been given the current selection, now insert it into input */
511 if (XGetWindowProperty(dpy
, win
, utf8
, 0, (sizeof text
/ 4) + 1, False
,
512 utf8
, &da
, &di
, &dl
, &dl
, (unsigned char **)&p
)
514 insert(p
, (q
= strchr(p
, '\n')) ? q
- p
: (ssize_t
)strlen(p
));
523 char buf
[sizeof text
], *p
;
524 size_t i
, imax
= 0, size
= 0;
525 unsigned int tmpmax
= 0;
527 /* read each line from stdin and add it to the item list */
528 for (i
= 0; fgets(buf
, sizeof buf
, stdin
); i
++) {
529 if (i
+ 1 >= size
/ sizeof *items
)
530 if (!(items
= realloc(items
, (size
+= BUFSIZ
))))
531 die("cannot realloc %u bytes:", size
);
532 if ((p
= strchr(buf
, '\n')))
534 if (!(items
[i
].text
= strdup(buf
)))
535 die("cannot strdup %u bytes:", strlen(buf
) + 1);
537 drw_font_getexts(drw
->fonts
, buf
, strlen(buf
), &tmpmax
, NULL
);
538 if (tmpmax
> inputw
) {
544 items
[i
].text
= NULL
;
545 inputw
= items
? TEXTW(items
[imax
].text
) : 0;
546 lines
= MIN(lines
, i
);
554 while (!XNextEvent(dpy
, &ev
)) {
555 if (XFilterEvent(&ev
, None
))
559 if (ev
.xexpose
.count
== 0)
560 drw_map(drw
, win
, 0, 0, mw
, mh
);
563 /* regrab focus from parent window */
564 if (ev
.xfocus
.window
!= win
)
570 case SelectionNotify
:
571 if (ev
.xselection
.property
== utf8
)
574 case VisibilityNotify
:
575 if (ev
.xvisibility
.state
!= VisibilityUnobscured
)
576 XRaiseWindow(dpy
, win
);
587 XSetWindowAttributes swa
;
590 XWindowAttributes wa
;
591 XClassHint ch
= {"dmenu", "dmenu"};
593 XineramaScreenInfo
*info
;
595 int a
, di
, n
, area
= 0;
597 /* init appearance */
598 for (j
= 0; j
< SchemeLast
; j
++)
599 scheme
[j
] = drw_scm_create(drw
, colors
[j
], 2);
601 clip
= XInternAtom(dpy
, "CLIPBOARD", False
);
602 utf8
= XInternAtom(dpy
, "UTF8_STRING", False
);
604 /* calculate menu geometry */
605 bh
= drw
->fonts
->h
+ 2;
606 lines
= MAX(lines
, 0);
607 mh
= (lines
+ 1) * bh
;
610 if (parentwin
== root
&& (info
= XineramaQueryScreens(dpy
, &n
))) {
611 XGetInputFocus(dpy
, &w
, &di
);
612 if (mon
>= 0 && mon
< n
)
614 else if (w
!= root
&& w
!= PointerRoot
&& w
!= None
) {
615 /* find top-level window containing current input focus */
617 if (XQueryTree(dpy
, (pw
= w
), &dw
, &w
, &dws
, &du
) && dws
)
619 } while (w
!= root
&& w
!= pw
);
620 /* find xinerama screen with which the window intersects most */
621 if (XGetWindowAttributes(dpy
, pw
, &wa
))
622 for (j
= 0; j
< n
; j
++)
623 if ((a
= INTERSECT(wa
.x
, wa
.y
, wa
.width
, wa
.height
, info
[j
])) > area
) {
628 /* no focused window is on screen, so use pointer location instead */
629 if (mon
< 0 && !area
&& XQueryPointer(dpy
, root
, &dw
, &dw
, &x
, &y
, &di
, &di
, &du
))
630 for (i
= 0; i
< n
; i
++)
631 if (INTERSECT(x
, y
, 1, 1, info
[i
]))
635 y
= info
[i
].y_org
+ (topbar
? 0 : info
[i
].height
- mh
);
641 if (!XGetWindowAttributes(dpy
, parentwin
, &wa
))
642 die("could not get embedding window attributes: 0x%lx",
645 y
= topbar
? 0 : wa
.height
- mh
;
648 promptw
= (prompt
&& *prompt
) ? TEXTW(prompt
) - lrpad
/ 4 : 0;
649 inputw
= MIN(inputw
, mw
/3);
652 /* create menu window */
653 swa
.override_redirect
= True
;
654 swa
.background_pixel
= scheme
[SchemeNorm
][ColBg
].pixel
;
655 swa
.event_mask
= ExposureMask
| KeyPressMask
| VisibilityChangeMask
;
656 win
= XCreateWindow(dpy
, parentwin
, x
, y
, mw
, mh
, 0,
657 CopyFromParent
, CopyFromParent
, CopyFromParent
,
658 CWOverrideRedirect
| CWBackPixel
| CWEventMask
, &swa
);
659 XSetClassHint(dpy
, win
, &ch
);
661 /* open input methods */
662 xim
= XOpenIM(dpy
, NULL
, NULL
, NULL
);
663 xic
= XCreateIC(xim
, XNInputStyle
, XIMPreeditNothing
| XIMStatusNothing
,
664 XNClientWindow
, win
, XNFocusWindow
, win
, NULL
);
666 XMapRaised(dpy
, win
);
667 XSetInputFocus(dpy
, win
, RevertToParent
, CurrentTime
);
669 XSelectInput(dpy
, parentwin
, FocusChangeMask
);
670 if (XQueryTree(dpy
, parentwin
, &dw
, &w
, &dws
, &du
) && dws
) {
671 for (i
= 0; i
< du
&& dws
[i
] != win
; ++i
)
672 XSelectInput(dpy
, dws
[i
], FocusChangeMask
);
677 drw_resize(drw
, mw
, mh
);
684 fputs("usage: dmenu [-bfiv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
685 " [-nb color] [-nf color] [-sb color] [-sf color] [-w windowid]\n", stderr
);
690 main(int argc
, char *argv
[])
692 XWindowAttributes wa
;
695 for (i
= 1; i
< argc
; i
++)
696 /* these options take no arguments */
697 if (!strcmp(argv
[i
], "-v")) { /* prints version information */
698 puts("dmenu-"VERSION
);
700 } else if (!strcmp(argv
[i
], "-b")) /* appears at the bottom of the screen */
702 else if (!strcmp(argv
[i
], "-f")) /* grabs keyboard before reading stdin */
704 else if (!strcmp(argv
[i
], "-i")) { /* case-insensitive item matching */
705 fstrncmp
= strncasecmp
;
707 } else if (i
+ 1 == argc
)
709 /* these options take one argument */
710 else if (!strcmp(argv
[i
], "-l")) /* number of lines in vertical list */
711 lines
= atoi(argv
[++i
]);
712 else if (!strcmp(argv
[i
], "-m"))
713 mon
= atoi(argv
[++i
]);
714 else if (!strcmp(argv
[i
], "-p")) /* adds prompt to left of input field */
716 else if (!strcmp(argv
[i
], "-fn")) /* font or font set */
717 fonts
[0] = argv
[++i
];
718 else if (!strcmp(argv
[i
], "-nb")) /* normal background color */
719 colors
[SchemeNorm
][ColBg
] = argv
[++i
];
720 else if (!strcmp(argv
[i
], "-nf")) /* normal foreground color */
721 colors
[SchemeNorm
][ColFg
] = argv
[++i
];
722 else if (!strcmp(argv
[i
], "-sb")) /* selected background color */
723 colors
[SchemeSel
][ColBg
] = argv
[++i
];
724 else if (!strcmp(argv
[i
], "-sf")) /* selected foreground color */
725 colors
[SchemeSel
][ColFg
] = argv
[++i
];
726 else if (!strcmp(argv
[i
], "-w")) /* embedding window id */
731 if (!setlocale(LC_CTYPE
, "") || !XSupportsLocale())
732 fputs("warning: no locale support\n", stderr
);
733 if (!XSetLocaleModifiers(""))
734 fputs("warning: no locale modifiers support\n", stderr
);
735 if (!(dpy
= XOpenDisplay(NULL
)))
736 die("cannot open display");
737 screen
= DefaultScreen(dpy
);
738 root
= RootWindow(dpy
, screen
);
739 if (!embed
|| !(parentwin
= strtol(embed
, NULL
, 0)))
741 if (!XGetWindowAttributes(dpy
, parentwin
, &wa
))
742 die("could not get embedding window attributes: 0x%lx",
744 drw
= drw_create(dpy
, screen
, root
, wa
.width
, wa
.height
);
745 if (!drw_fontset_create(drw
, fonts
, LENGTH(fonts
)))
746 die("no fonts could be loaded.");
747 lrpad
= drw
->fonts
->h
;
759 return 1; /* unreachable */