Xinqi Bao's Git
15737caa23b925ca5b36781fd7dcac69cddb31b1
1 /* See LICENSE file for copyright and license details. */
12 #include <X11/Xatom.h>
13 #include <X11/Xproto.h>
14 #include <X11/Xutil.h>
16 #include <X11/extensions/Xinerama.h>
18 #include <X11/Xft/Xft.h>
24 #define INTERSECT(x,y,w,h,r) (MAX(0, MIN((x)+(w),(r).x_org+(r).width) - MAX((x),(r).x_org)) \
25 * MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
26 #define LENGTH(X) (sizeof X / sizeof X[0])
27 #define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad)
32 enum { SchemeNorm
, SchemeSel
, SchemeOut
, SchemeLast
}; /* color schemes */
36 struct item
*left
, *right
;
40 static char text
[BUFSIZ
] = "";
42 static int bh
, mw
, mh
;
43 static int inputw
= 0, promptw
;
44 static int lrpad
; /* sum of left and right padding */
46 static struct item
*items
= NULL
;
47 static struct item
*matches
, *matchend
;
48 static struct item
*prev
, *curr
, *next
, *sel
;
49 static int mon
= -1, screen
;
51 static Atom clip
, utf8
;
53 static Window root
, parentwin
, win
;
57 static Clr
*scheme
[SchemeLast
];
59 static int useargb
= 0;
60 static Visual
*visual
;
66 static int (*fstrncmp
)(const char *, const char *, size_t) = strncmp
;
67 static char *(*fstrstr
)(const char *, const char *) = strstr
;
68 static void xinitvisual();
71 textw_clamp(const char *str
, unsigned int n
)
73 unsigned int w
= drw_fontset_getwidth_clamp(drw
, str
, n
) + lrpad
;
78 appenditem(struct item
*item
, struct item
**list
, struct item
**last
)
81 (*last
)->right
= item
;
98 n
= mw
- (promptw
+ inputw
+ TEXTW("<") + TEXTW(">"));
99 /* calculate which items will begin the next page and previous page */
100 for (i
= 0, next
= curr
; next
; next
= next
->right
)
101 if ((i
+= (lines
> 0) ? bh
: textw_clamp(next
->text
, n
)) > n
)
103 for (i
= 0, prev
= curr
; prev
&& prev
->left
; prev
= prev
->left
)
104 if ((i
+= (lines
> 0) ? bh
: textw_clamp(prev
->left
->text
, n
)) > n
)
112 for (struct item
*item
= items
; item
&& item
->text
; item
++)
113 len
= MAX(TEXTW(item
->text
), len
);
122 XUngrabKey(dpy
, AnyKey
, AnyModifier
, root
);
123 for (i
= 0; i
< SchemeLast
; i
++)
125 for (i
= 0; items
&& items
[i
].text
; ++i
)
134 cistrstr(const char *h
, const char *n
)
142 for (i
= 0; n
[i
] && tolower((unsigned char)n
[i
]) ==
143 tolower((unsigned char)h
[i
]); ++i
)
152 drawitem(struct item
*item
, int x
, int y
, int w
)
155 drw_setscheme(drw
, scheme
[SchemeSel
]);
157 drw_setscheme(drw
, scheme
[SchemeOut
]);
159 drw_setscheme(drw
, scheme
[SchemeNorm
]);
161 return drw_text(drw
, x
, y
, w
, bh
, lrpad
/ 2, item
->text
, 0);
171 drw_setscheme(drw
, scheme
[SchemeNorm
]);
172 drw_rect(drw
, 0, 0, mw
, mh
, 1, 1);
174 if (prompt
&& *prompt
) {
175 drw_setscheme(drw
, scheme
[SchemeSel
]);
176 x
= drw_text(drw
, x
, 0, promptw
, bh
, lrpad
/ 2, prompt
, 0);
178 /* draw input field */
179 w
= (lines
> 0 || !matches
) ? mw
- x
: inputw
;
180 drw_setscheme(drw
, scheme
[SchemeNorm
]);
181 drw_text(drw
, x
, 0, w
, bh
, lrpad
/ 2, text
, 0);
183 curpos
= TEXTW(text
) - TEXTW(&text
[cursor
]);
184 if ((curpos
+= lrpad
/ 2 - 1) < w
) {
185 drw_setscheme(drw
, scheme
[SchemeNorm
]);
186 drw_rect(drw
, x
+ curpos
, 2, 2, bh
- 4, 1, 0);
190 /* draw vertical list */
191 for (item
= curr
; item
!= next
; item
= item
->right
)
192 drawitem(item
, x
, y
+= bh
, mw
- x
);
193 } else if (matches
) {
194 /* draw horizontal list */
198 drw_setscheme(drw
, scheme
[SchemeNorm
]);
199 drw_text(drw
, x
, 0, w
, bh
, lrpad
/ 2, "<", 0);
202 for (item
= curr
; item
!= next
; item
= item
->right
)
203 x
= drawitem(item
, x
, 0, textw_clamp(item
->text
, mw
- x
- TEXTW(">")));
206 drw_setscheme(drw
, scheme
[SchemeNorm
]);
207 drw_text(drw
, mw
- w
, 0, w
, bh
, lrpad
/ 2, ">", 0);
210 drw_map(drw
, win
, 0, 0, mw
, mh
);
216 struct timespec ts
= { .tv_sec
= 0, .tv_nsec
= 10000000 };
220 for (i
= 0; i
< 100; ++i
) {
221 XGetInputFocus(dpy
, &focuswin
, &revertwin
);
224 XSetInputFocus(dpy
, win
, RevertToParent
, CurrentTime
);
225 nanosleep(&ts
, NULL
);
227 die("cannot grab focus");
233 struct timespec ts
= { .tv_sec
= 0, .tv_nsec
= 1000000 };
238 /* try to grab keyboard, we may have to wait for another process to ungrab */
239 for (i
= 0; i
< 1000; i
++) {
240 if (XGrabKeyboard(dpy
, DefaultRootWindow(dpy
), True
, GrabModeAsync
,
241 GrabModeAsync
, CurrentTime
) == GrabSuccess
)
243 nanosleep(&ts
, NULL
);
245 die("cannot grab keyboard");
251 static char **tokv
= NULL
;
254 char buf
[sizeof text
], *s
;
256 size_t len
, textsize
;
257 struct item
*item
, *lprefix
, *lsubstr
, *prefixend
, *substrend
;
260 /* separate input text into tokens to be matched individually */
261 for (s
= strtok(buf
, " "); s
; tokv
[tokc
- 1] = s
, s
= strtok(NULL
, " "))
262 if (++tokc
> tokn
&& !(tokv
= realloc(tokv
, ++tokn
* sizeof *tokv
)))
263 die("cannot realloc %zu bytes:", tokn
* sizeof *tokv
);
264 len
= tokc
? strlen(tokv
[0]) : 0;
266 matches
= lprefix
= lsubstr
= matchend
= prefixend
= substrend
= NULL
;
267 textsize
= strlen(text
) + 1;
268 for (item
= items
; item
&& item
->text
; item
++) {
269 for (i
= 0; i
< tokc
; i
++)
270 if (!fstrstr(item
->text
, tokv
[i
]))
272 if (i
!= tokc
) /* not all tokens match */
274 /* exact matches go first, then prefixes, then substrings */
275 if (!tokc
|| !fstrncmp(text
, item
->text
, textsize
))
276 appenditem(item
, &matches
, &matchend
);
277 else if (!fstrncmp(tokv
[0], item
->text
, len
))
278 appenditem(item
, &lprefix
, &prefixend
);
280 appenditem(item
, &lsubstr
, &substrend
);
284 matchend
->right
= lprefix
;
285 lprefix
->left
= matchend
;
288 matchend
= prefixend
;
292 matchend
->right
= lsubstr
;
293 lsubstr
->left
= matchend
;
296 matchend
= substrend
;
298 curr
= sel
= matches
;
303 insert(const char *str
, ssize_t n
)
305 if (strlen(text
) + n
> sizeof text
- 1)
307 /* move existing text out of the way, insert new text, and update cursor */
308 memmove(&text
[cursor
+ n
], &text
[cursor
], sizeof text
- cursor
- MAX(n
, 0));
310 memcpy(&text
[cursor
], str
, n
);
320 /* return location of next utf8 rune in the given direction (+1 or -1) */
321 for (n
= cursor
+ inc
; n
+ inc
>= 0 && (text
[n
] & 0xc0) == 0x80; n
+= inc
)
327 movewordedge(int dir
)
329 if (dir
< 0) { /* move cursor to the start of the word*/
330 while (cursor
> 0 && strchr(worddelimiters
, text
[nextrune(-1)]))
331 cursor
= nextrune(-1);
332 while (cursor
> 0 && !strchr(worddelimiters
, text
[nextrune(-1)]))
333 cursor
= nextrune(-1);
334 } else { /* move cursor to the end of the word */
335 while (text
[cursor
] && strchr(worddelimiters
, text
[cursor
]))
336 cursor
= nextrune(+1);
337 while (text
[cursor
] && !strchr(worddelimiters
, text
[cursor
]))
338 cursor
= nextrune(+1);
343 keypress(XKeyEvent
*ev
)
350 len
= XmbLookupString(xic
, ev
, buf
, sizeof buf
, &ksym
, &status
);
352 default: /* XLookupNone, XBufferOverflow */
361 if (ev
->state
& ControlMask
) {
363 case XK_a
: ksym
= XK_Home
; break;
364 case XK_b
: ksym
= XK_Left
; break;
365 case XK_c
: ksym
= XK_Escape
; break;
366 case XK_d
: ksym
= XK_Delete
; break;
367 case XK_e
: ksym
= XK_End
; break;
368 case XK_f
: ksym
= XK_Right
; break;
369 case XK_g
: ksym
= XK_Escape
; break;
370 case XK_h
: ksym
= XK_BackSpace
; break;
371 case XK_i
: ksym
= XK_Tab
; break;
372 case XK_j
: /* fallthrough */
373 case XK_J
: /* fallthrough */
374 case XK_m
: /* fallthrough */
375 case XK_M
: ksym
= XK_Return
; ev
->state
&= ~ControlMask
; break;
376 case XK_n
: ksym
= XK_Down
; break;
377 case XK_p
: ksym
= XK_Up
; break;
379 case XK_k
: /* delete right */
383 case XK_u
: /* delete left */
384 insert(NULL
, 0 - cursor
);
386 case XK_w
: /* delete word */
387 while (cursor
> 0 && strchr(worddelimiters
, text
[nextrune(-1)]))
388 insert(NULL
, nextrune(-1) - cursor
);
389 while (cursor
> 0 && !strchr(worddelimiters
, text
[nextrune(-1)]))
390 insert(NULL
, nextrune(-1) - cursor
);
392 case XK_y
: /* paste selection */
394 XConvertSelection(dpy
, (ev
->state
& ShiftMask
) ? clip
: XA_PRIMARY
,
395 utf8
, utf8
, win
, CurrentTime
);
414 } else if (ev
->state
& Mod1Mask
) {
422 case XK_g
: ksym
= XK_Home
; break;
423 case XK_G
: ksym
= XK_End
; break;
424 case XK_h
: ksym
= XK_Up
; break;
425 case XK_j
: ksym
= XK_Next
; break;
426 case XK_k
: ksym
= XK_Prior
; break;
427 case XK_l
: ksym
= XK_Down
; break;
436 if (!iscntrl((unsigned char)*buf
))
441 if (text
[cursor
] == '\0')
443 cursor
= nextrune(+1);
448 insert(NULL
, nextrune(-1) - cursor
);
452 if (text
[cursor
] != '\0') {
453 cursor
= strlen(text
);
457 /* jump to end of list and position items in reverse */
462 while (next
&& (curr
= curr
->right
))
472 if (sel
== matches
) {
476 sel
= curr
= matches
;
481 if (cursor
> 0 && (!sel
|| !sel
->left
|| lines
> 0)) {
482 cursor
= nextrune(-1);
490 if (sel
&& sel
->left
&& (sel
= sel
->left
)->right
== curr
) {
511 puts((sel
&& !(ev
->state
& ShiftMask
)) ? sel
->text
: text
);
512 if (!(ev
->state
& ControlMask
)) {
521 if (text
[cursor
] != '\0') {
522 cursor
= nextrune(+1);
530 if (sel
&& sel
->right
&& (sel
= sel
->right
) == next
) {
538 strncpy(text
, sel
->text
, sizeof text
- 1);
539 text
[sizeof text
- 1] = '\0';
540 cursor
= strlen(text
);
557 /* we have been given the current selection, now insert it into input */
558 if (XGetWindowProperty(dpy
, win
, utf8
, 0, (sizeof text
/ 4) + 1, False
,
559 utf8
, &da
, &di
, &dl
, &dl
, (unsigned char **)&p
)
561 insert(p
, (q
= strchr(p
, '\n')) ? q
- p
: (ssize_t
)strlen(p
));
570 char buf
[sizeof text
], *p
;
573 /* read each line from stdin and add it to the item list */
574 for (i
= 0; fgets(buf
, sizeof buf
, stdin
); i
++) {
575 if (i
+ 1 >= size
/ sizeof *items
)
576 if (!(items
= realloc(items
, (size
+= BUFSIZ
))))
577 die("cannot realloc %zu bytes:", size
);
578 if ((p
= strchr(buf
, '\n')))
580 if (!(items
[i
].text
= strdup(buf
)))
581 die("cannot strdup %zu bytes:", strlen(buf
) + 1);
585 items
[i
].text
= NULL
;
586 lines
= MIN(lines
, i
);
594 while (!XNextEvent(dpy
, &ev
)) {
595 if (XFilterEvent(&ev
, win
))
599 if (ev
.xdestroywindow
.window
!= win
)
604 if (ev
.xexpose
.count
== 0)
605 drw_map(drw
, win
, 0, 0, mw
, mh
);
608 /* regrab focus from parent window */
609 if (ev
.xfocus
.window
!= win
)
615 case SelectionNotify
:
616 if (ev
.xselection
.property
== utf8
)
619 case VisibilityNotify
:
620 if (ev
.xvisibility
.state
!= VisibilityUnobscured
)
621 XRaiseWindow(dpy
, win
);
631 unsigned int du
, tmp
;
632 XSetWindowAttributes swa
;
635 XWindowAttributes wa
;
636 XClassHint ch
= {"dmenu", "dmenu"};
639 XineramaScreenInfo
*info
;
641 int a
, di
, n
, area
= 0;
643 /* init appearance */
644 for (j
= 0; j
< SchemeLast
; j
++)
645 scheme
[j
] = drw_scm_create(drw
, colors
[j
], alphas
[j
], 2);
647 clip
= XInternAtom(dpy
, "CLIPBOARD", False
);
648 utf8
= XInternAtom(dpy
, "UTF8_STRING", False
);
650 /* calculate menu geometry */
651 bh
= drw
->fonts
->h
+ 2;
652 lines
= MAX(lines
, 0);
653 mh
= (lines
+ 1) * bh
;
654 promptw
= (prompt
&& *prompt
) ? TEXTW(prompt
) - lrpad
/ 4 : 0;
657 if (parentwin
== root
&& (info
= XineramaQueryScreens(dpy
, &n
))) {
658 XGetInputFocus(dpy
, &w
, &di
);
659 if (mon
>= 0 && mon
< n
)
661 else if (w
!= root
&& w
!= PointerRoot
&& w
!= None
) {
662 /* find top-level window containing current input focus */
664 if (XQueryTree(dpy
, (pw
= w
), &dw
, &w
, &dws
, &du
) && dws
)
666 } while (w
!= root
&& w
!= pw
);
667 /* find xinerama screen with which the window intersects most */
668 if (XGetWindowAttributes(dpy
, pw
, &wa
))
669 for (j
= 0; j
< n
; j
++)
670 if ((a
= INTERSECT(wa
.x
, wa
.y
, wa
.width
, wa
.height
, info
[j
])) > area
) {
675 /* no focused window is on screen, so use pointer location instead */
676 if (mon
< 0 && !area
&& XQueryPointer(dpy
, root
, &dw
, &dw
, &x
, &y
, &di
, &di
, &du
))
677 for (i
= 0; i
< n
; i
++)
678 if (INTERSECT(x
, y
, 1, 1, info
[i
]) != 0)
682 mw
= MIN(MAX(max_textw() + promptw
, min_width
), info
[i
].width
);
683 x
= info
[i
].x_org
+ ((info
[i
].width
- mw
) / 2);
684 y
= info
[i
].y_org
+ ((info
[i
].height
- mh
) / 2);
687 y
= info
[i
].y_org
+ (topbar
? 0 : info
[i
].height
- mh
);
695 if (!XGetWindowAttributes(dpy
, parentwin
, &wa
))
696 die("could not get embedding window attributes: 0x%lx",
700 mw
= MIN(MAX(max_textw() + promptw
, min_width
), wa
.width
);
701 x
= (wa
.width
- mw
) / 2;
702 y
= (wa
.height
- mh
) / 2;
705 y
= topbar
? 0 : wa
.height
- mh
;
709 for (item
= items
; item
&& item
->text
; ++item
) {
710 if ((tmp
= textw_clamp(item
->text
, mw
/3)) > inputw
) {
711 if ((inputw
= tmp
) == mw
/3)
717 /* create menu window */
718 swa
.override_redirect
= True
;
719 swa
.background_pixel
= 0;
720 swa
.border_pixel
= 0;
722 swa
.event_mask
= ExposureMask
| KeyPressMask
| VisibilityChangeMask
;
723 win
= XCreateWindow(dpy
, parentwin
, x
, y
, mw
, mh
, 0,
724 depth
, CopyFromParent
, visual
,
725 CWOverrideRedirect
| CWBackPixel
| CWBorderPixel
| CWColormap
| CWEventMask
, &swa
);
726 XSetClassHint(dpy
, win
, &ch
);
730 if ((xim
= XOpenIM(dpy
, NULL
, NULL
, NULL
)) == NULL
)
731 die("XOpenIM failed: could not open input device");
733 xic
= XCreateIC(xim
, XNInputStyle
, XIMPreeditNothing
| XIMStatusNothing
,
734 XNClientWindow
, win
, XNFocusWindow
, win
, NULL
);
736 XMapRaised(dpy
, win
);
738 XSelectInput(dpy
, parentwin
, FocusChangeMask
| SubstructureNotifyMask
);
739 if (XQueryTree(dpy
, parentwin
, &dw
, &w
, &dws
, &du
) && dws
) {
740 for (i
= 0; i
< du
&& dws
[i
] != win
; ++i
)
741 XSelectInput(dpy
, dws
[i
], FocusChangeMask
);
746 drw_resize(drw
, mw
, mh
);
753 fputs("usage: dmenu [-bfiv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
754 " [-nb color] [-nf color] [-sb color] [-sf color] [-w windowid]\n", stderr
);
759 main(int argc
, char *argv
[])
761 XWindowAttributes wa
;
764 for (i
= 1; i
< argc
; i
++)
765 /* these options take no arguments */
766 if (!strcmp(argv
[i
], "-v")) { /* prints version information */
767 puts("dmenu-"VERSION
);
769 } else if (!strcmp(argv
[i
], "-b")) /* appears at the bottom of the screen */
771 else if (!strcmp(argv
[i
], "-f")) /* grabs keyboard before reading stdin */
773 else if (!strcmp(argv
[i
], "-c")) /* centers dmenu on screen */
775 else if (!strcmp(argv
[i
], "-i")) { /* case-insensitive item matching */
776 fstrncmp
= strncasecmp
;
778 } else if (i
+ 1 == argc
)
780 /* these options take one argument */
781 else if (!strcmp(argv
[i
], "-l")) /* number of lines in vertical list */
782 lines
= atoi(argv
[++i
]);
783 else if (!strcmp(argv
[i
], "-m"))
784 mon
= atoi(argv
[++i
]);
785 else if (!strcmp(argv
[i
], "-p")) /* adds prompt to left of input field */
787 else if (!strcmp(argv
[i
], "-fn")) /* font or font set */
788 fonts
[0] = argv
[++i
];
789 else if (!strcmp(argv
[i
], "-nb")) /* normal background color */
790 colors
[SchemeNorm
][ColBg
] = argv
[++i
];
791 else if (!strcmp(argv
[i
], "-nf")) /* normal foreground color */
792 colors
[SchemeNorm
][ColFg
] = argv
[++i
];
793 else if (!strcmp(argv
[i
], "-sb")) /* selected background color */
794 colors
[SchemeSel
][ColBg
] = argv
[++i
];
795 else if (!strcmp(argv
[i
], "-sf")) /* selected foreground color */
796 colors
[SchemeSel
][ColFg
] = argv
[++i
];
797 else if (!strcmp(argv
[i
], "-w")) /* embedding window id */
802 if (!setlocale(LC_CTYPE
, "") || !XSupportsLocale())
803 fputs("warning: no locale support\n", stderr
);
804 if (!(dpy
= XOpenDisplay(NULL
)))
805 die("cannot open display");
806 screen
= DefaultScreen(dpy
);
807 root
= RootWindow(dpy
, screen
);
808 if (!embed
|| !(parentwin
= strtol(embed
, NULL
, 0)))
810 if (!XGetWindowAttributes(dpy
, parentwin
, &wa
))
811 die("could not get embedding window attributes: 0x%lx",
814 drw
= drw_create(dpy
, screen
, root
, wa
.width
, wa
.height
, visual
, depth
, cmap
);
815 if (!drw_fontset_create(drw
, fonts
, LENGTH(fonts
)))
816 die("no fonts could be loaded.");
817 lrpad
= drw
->fonts
->h
;
820 if (pledge("stdio rpath", NULL
) == -1)
824 if (fast
&& !isatty(0)) {
834 return 1; /* unreachable */
841 XRenderPictFormat
*fmt
;
850 long masks
= VisualScreenMask
| VisualDepthMask
| VisualClassMask
;
852 infos
= XGetVisualInfo(dpy
, masks
, &tpl
, &nitems
);
854 for(i
= 0; i
< nitems
; i
++) {
855 fmt
= XRenderFindVisualFormat(dpy
, infos
[i
].visual
);
856 if (fmt
->type
== PictTypeDirect
&& fmt
->direct
.alphaMask
) {
857 visual
= infos
[i
].visual
;
858 depth
= infos
[i
].depth
;
859 cmap
= XCreateColormap(dpy
, root
, visual
, AllocNone
);
868 visual
= DefaultVisual(dpy
, screen
);
869 depth
= DefaultDepth(dpy
, screen
);
870 cmap
= DefaultColormap(dpy
, screen
);