Xinqi Bao's Git

b19148632adb7f63b4706822f623d616f3f19e10
[dmenu.git] / dmenu.c
1 /* See LICENSE file for copyright and license details. */
2 #include <ctype.h>
3 #include <locale.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <strings.h>
8 #include <time.h>
9
10 #include <X11/Xlib.h>
11 #include <X11/Xatom.h>
12 #include <X11/Xutil.h>
13 #ifdef XINERAMA
14 #include <X11/extensions/Xinerama.h>
15 #endif
16 #include <X11/Xft/Xft.h>
17
18 #include "drw.h"
19 #include "util.h"
20
21 /* macros */
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)
26
27 /* enums */
28 enum { SchemeNorm, SchemeSel, SchemeOut, SchemeLast }; /* color schemes */
29
30 struct item {
31 char *text;
32 struct item *left, *right;
33 int out;
34 };
35
36 static char text[BUFSIZ] = "";
37 static int bh, mw, mh;
38 static int sw, sh; /* X display screen geometry width, height */
39 static int inputw = 0, promptw;
40 static int lrpad; /* sum of left and right padding */
41 static size_t cursor;
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;
46
47 static Atom clip, utf8;
48 static Display *dpy;
49 static Window root, win;
50 static XIC xic;
51
52 static Drw *drw;
53 static Clr *scheme[SchemeLast];
54
55 #include "config.h"
56
57 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
58 static char *(*fstrstr)(const char *, const char *) = strstr;
59
60 static void
61 appenditem(struct item *item, struct item **list, struct item **last)
62 {
63 if (*last)
64 (*last)->right = item;
65 else
66 *list = item;
67
68 item->left = *last;
69 item->right = NULL;
70 *last = item;
71 }
72
73 static void
74 calcoffsets(void)
75 {
76 int i, n;
77
78 if (lines > 0)
79 n = lines * bh;
80 else
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)
85 break;
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)
88 break;
89 }
90
91 static void
92 cleanup(void)
93 {
94 size_t i;
95
96 XUngrabKey(dpy, AnyKey, AnyModifier, root);
97 for (i = 0; i < SchemeLast; i++)
98 free(scheme[i]);
99 drw_free(drw);
100 XSync(dpy, False);
101 XCloseDisplay(dpy);
102 }
103
104 static char *
105 cistrstr(const char *s, const char *sub)
106 {
107 size_t len;
108
109 for (len = strlen(sub); *s; s++)
110 if (!strncasecmp(s, sub, len))
111 return (char *)s;
112 return NULL;
113 }
114
115 static int
116 drawitem(struct item *item, int x, int y, int w)
117 {
118 if (item == sel)
119 drw_setscheme(drw, scheme[SchemeSel]);
120 else if (item->out)
121 drw_setscheme(drw, scheme[SchemeOut]);
122 else
123 drw_setscheme(drw, scheme[SchemeNorm]);
124
125 return drw_text(drw, x, y, w, bh, lrpad / 2, item->text, 0);
126 }
127
128 static void
129 drawmenu(void)
130 {
131 unsigned int curpos;
132 struct item *item;
133 int x = 0, y = 0, w, inputscheme;
134
135 drw_setscheme(drw, scheme[SchemeNorm]);
136 drw_rect(drw, 0, 0, mw, mh, 1, 1);
137
138 if (prompt && *prompt) {
139 drw_setscheme(drw, scheme[SchemeSel]);
140 x = drw_text(drw, x, 0, promptw, bh, lrpad / 2, prompt, 0);
141 x += 2;
142 }
143 /* draw input field */
144 w = (lines > 0 || !matches) ? mw - x : inputw;
145 if (matches && !strcmp(text, curr->text))
146 inputscheme = SchemeSel;
147 else
148 inputscheme = SchemeNorm;
149 drw_setscheme(drw, scheme[inputscheme]);
150
151 drw_text(drw, x, 0, w, bh, lrpad / 2, text, 0);
152
153 drw_font_getexts(drw->fonts, text, cursor, &curpos, NULL);
154 if ((curpos += lrpad / 2 - 1) < w) {
155 drw_setscheme(drw, scheme[inputscheme]);
156 drw_rect(drw, x + curpos, 2, 2, bh - 4, 1, 0);
157 }
158
159 if (inputscheme == SchemeSel)
160 goto drawmap;
161
162 if (lines > 0) {
163 /* draw vertical list */
164 for (item = curr; item != next; item = item->right)
165 drawitem(item, x, y += bh, mw - x);
166 } else if (matches) {
167 /* draw horizontal list */
168 x += inputw;
169 w = TEXTW("<");
170 if (curr->left) {
171 drw_setscheme(drw, scheme[SchemeNorm]);
172 drw_text(drw, x, 0, w, bh, lrpad / 2, "<", 0);
173 }
174 x += w;
175 for (item = curr; item != next; item = item->right)
176 x = drawitem(item, x, 0, MIN(TEXTW(item->text), mw - x - TEXTW(">")));
177 if (next) {
178 w = TEXTW(">");
179 drw_setscheme(drw, scheme[SchemeNorm]);
180 drw_text(drw, mw - w, 0, w, bh, lrpad / 2, ">", 0);
181 }
182 }
183 drawmap:
184 drw_map(drw, win, 0, 0, mw, mh);
185 }
186
187 static void
188 grabkeyboard(void)
189 {
190 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
191 int i;
192
193 /* try to grab keyboard, we may have to wait for another process to ungrab */
194 for (i = 0; i < 1000; i++) {
195 if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync,
196 GrabModeAsync, CurrentTime) == GrabSuccess)
197 return;
198 nanosleep(&ts, NULL);
199 }
200 die("cannot grab keyboard\n");
201 }
202
203 static void
204 match(void)
205 {
206 static char **tokv = NULL;
207 static int tokn = 0;
208
209 char buf[sizeof text], *s;
210 int i, tokc = 0;
211 size_t len, textsize;
212 struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
213
214 strcpy(buf, text);
215 /* separate input text into tokens to be matched individually */
216 for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
217 if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
218 die("cannot realloc %u bytes\n", tokn * sizeof *tokv);
219 len = tokc ? strlen(tokv[0]) : 0;
220
221 matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
222 textsize = strlen(text);
223 for (item = items; item && item->text; item++) {
224 for (i = 0; i < tokc; i++)
225 if (!fstrstr(item->text, tokv[i]))
226 break;
227 if (i != tokc) /* not all tokens match */
228 continue;
229 /* exact matches go first, then prefixes, then substrings */
230 if (!tokc || !fstrncmp(text, item->text, textsize))
231 appenditem(item, &matches, &matchend);
232 else if (!fstrncmp(tokv[0], item->text, len))
233 appenditem(item, &lprefix, &prefixend);
234 else
235 appenditem(item, &lsubstr, &substrend);
236 }
237 if (lprefix) {
238 if (matches) {
239 matchend->right = lprefix;
240 lprefix->left = matchend;
241 } else
242 matches = lprefix;
243 matchend = prefixend;
244 }
245 if (lsubstr) {
246 if (matches) {
247 matchend->right = lsubstr;
248 lsubstr->left = matchend;
249 } else
250 matches = lsubstr;
251 matchend = substrend;
252 }
253 curr = sel = matches;
254 calcoffsets();
255 }
256
257 static void
258 insert(const char *str, ssize_t n)
259 {
260 if (strlen(text) + n > sizeof text - 1)
261 return;
262 /* move existing text out of the way, insert new text, and update cursor */
263 memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
264 if (n > 0)
265 memcpy(&text[cursor], str, n);
266 cursor += n;
267 match();
268 }
269
270 static size_t
271 nextrune(int inc)
272 {
273 ssize_t n;
274
275 /* return location of next utf8 rune in the given direction (+1 or -1) */
276 for (n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc)
277 ;
278 return n;
279 }
280
281 static void
282 keypress(XKeyEvent *ev)
283 {
284 char buf[32];
285 int len;
286 KeySym ksym = NoSymbol;
287 Status status;
288
289 len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
290 if (status == XBufferOverflow)
291 return;
292 if (ev->state & ControlMask)
293 switch(ksym) {
294 case XK_a: ksym = XK_Home; break;
295 case XK_b: ksym = XK_Left; break;
296 case XK_c: ksym = XK_Escape; break;
297 case XK_d: ksym = XK_Delete; break;
298 case XK_e: ksym = XK_End; break;
299 case XK_f: ksym = XK_Right; break;
300 case XK_g: ksym = XK_Escape; break;
301 case XK_h: ksym = XK_BackSpace; break;
302 case XK_i: ksym = XK_Tab; break;
303 case XK_j: /* fallthrough */
304 case XK_J: /* fallthrough */
305 case XK_m: /* fallthrough */
306 case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
307 case XK_n: ksym = XK_Down; break;
308 case XK_p: ksym = XK_Up; break;
309
310 case XK_k: /* delete right */
311 text[cursor] = '\0';
312 match();
313 break;
314 case XK_u: /* delete left */
315 insert(NULL, 0 - cursor);
316 break;
317 case XK_w: /* delete word */
318 while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
319 insert(NULL, nextrune(-1) - cursor);
320 while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
321 insert(NULL, nextrune(-1) - cursor);
322 break;
323 case XK_y: /* paste selection */
324 case XK_Y:
325 XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
326 utf8, utf8, win, CurrentTime);
327 return;
328 case XK_Return:
329 case XK_KP_Enter:
330 break;
331 case XK_bracketleft:
332 cleanup();
333 exit(1);
334 default:
335 return;
336 }
337 else if (ev->state & Mod1Mask)
338 switch(ksym) {
339 case XK_g: ksym = XK_Home; break;
340 case XK_G: ksym = XK_End; break;
341 case XK_h: ksym = XK_Up; break;
342 case XK_j: ksym = XK_Next; break;
343 case XK_k: ksym = XK_Prior; break;
344 case XK_l: ksym = XK_Down; break;
345 default:
346 return;
347 }
348 switch(ksym) {
349 default:
350 if (!iscntrl(*buf))
351 insert(buf, len);
352 break;
353 case XK_Delete:
354 if (text[cursor] == '\0')
355 return;
356 cursor = nextrune(+1);
357 /* fallthrough */
358 case XK_BackSpace:
359 if (cursor == 0)
360 return;
361 insert(NULL, nextrune(-1) - cursor);
362 break;
363 case XK_End:
364 if (text[cursor] != '\0') {
365 cursor = strlen(text);
366 break;
367 }
368 if (next) {
369 /* jump to end of list and position items in reverse */
370 curr = matchend;
371 calcoffsets();
372 curr = prev;
373 calcoffsets();
374 while (next && (curr = curr->right))
375 calcoffsets();
376 }
377 sel = matchend;
378 break;
379 case XK_Escape:
380 cleanup();
381 exit(1);
382 case XK_Home:
383 if (sel == matches) {
384 cursor = 0;
385 break;
386 }
387 sel = curr = matches;
388 calcoffsets();
389 break;
390 case XK_Left:
391 if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
392 cursor = nextrune(-1);
393 break;
394 }
395 if (lines > 0)
396 return;
397 /* fallthrough */
398 case XK_Up:
399 if (sel && sel->left && (sel = sel->left)->right == curr) {
400 curr = prev;
401 calcoffsets();
402 }
403 break;
404 case XK_Next:
405 if (!next)
406 return;
407 sel = curr = next;
408 calcoffsets();
409 break;
410 case XK_Prior:
411 if (!prev)
412 return;
413 sel = curr = prev;
414 calcoffsets();
415 break;
416 case XK_Return:
417 case XK_KP_Enter:
418 puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
419 if (!(ev->state & ControlMask)) {
420 cleanup();
421 exit(0);
422 }
423 if (sel)
424 sel->out = 1;
425 break;
426 case XK_Right:
427 if (text[cursor] != '\0') {
428 cursor = nextrune(+1);
429 break;
430 }
431 if (lines > 0)
432 return;
433 /* fallthrough */
434 case XK_Down:
435 if (sel && sel->right && (sel = sel->right) == next) {
436 curr = next;
437 calcoffsets();
438 }
439 break;
440 case XK_Tab:
441 if (!sel)
442 return;
443 strncpy(text, sel->text, sizeof text - 1);
444 text[sizeof text - 1] = '\0';
445 cursor = strlen(text);
446 match();
447 break;
448 }
449 drawmenu();
450 }
451
452 static void
453 paste(void)
454 {
455 char *p, *q;
456 int di;
457 unsigned long dl;
458 Atom da;
459
460 /* we have been given the current selection, now insert it into input */
461 XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
462 utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
463 insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
464 XFree(p);
465 drawmenu();
466 }
467
468 static void
469 readstdin(void)
470 {
471 char buf[sizeof text], *p;
472 size_t i, imax = 0, size = 0;
473 unsigned int tmpmax = 0;
474
475 /* read each line from stdin and add it to the item list */
476 for (i = 0; fgets(buf, sizeof buf, stdin); i++) {
477 if (i + 1 >= size / sizeof *items)
478 if (!(items = realloc(items, (size += BUFSIZ))))
479 die("cannot realloc %u bytes:", size);
480 if ((p = strchr(buf, '\n')))
481 *p = '\0';
482 if (!(items[i].text = strdup(buf)))
483 die("cannot strdup %u bytes:", strlen(buf) + 1);
484 items[i].out = 0;
485 drw_font_getexts(drw->fonts, buf, strlen(buf), &tmpmax, NULL);
486 if (tmpmax > inputw) {
487 inputw = tmpmax;
488 imax = i;
489 }
490 }
491 if (items)
492 items[i].text = NULL;
493 inputw = items ? TEXTW(items[imax].text) : 0;
494 lines = MIN(lines, i);
495 }
496
497 static void
498 run(void)
499 {
500 XEvent ev;
501
502 while (!XNextEvent(dpy, &ev)) {
503 if (XFilterEvent(&ev, win))
504 continue;
505 switch(ev.type) {
506 case Expose:
507 if (ev.xexpose.count == 0)
508 drw_map(drw, win, 0, 0, mw, mh);
509 break;
510 case KeyPress:
511 keypress(&ev.xkey);
512 break;
513 case SelectionNotify:
514 if (ev.xselection.property == utf8)
515 paste();
516 break;
517 case VisibilityNotify:
518 if (ev.xvisibility.state != VisibilityUnobscured)
519 XRaiseWindow(dpy, win);
520 break;
521 }
522 }
523 }
524
525 static void
526 setup(void)
527 {
528 int x, y;
529 XSetWindowAttributes swa;
530 XIM xim;
531 #ifdef XINERAMA
532 XineramaScreenInfo *info;
533 Window w, pw, dw, *dws;
534 XWindowAttributes wa;
535 int a, j, di, n, i = 0, area = 0;
536 unsigned int du;
537 #endif
538
539 /* init appearance */
540 scheme[SchemeNorm] = drw_scm_create(drw, colors[SchemeNorm], 2);
541 scheme[SchemeSel] = drw_scm_create(drw, colors[SchemeSel], 2);
542 scheme[SchemeOut] = drw_scm_create(drw, colors[SchemeOut], 2);
543
544 clip = XInternAtom(dpy, "CLIPBOARD", False);
545 utf8 = XInternAtom(dpy, "UTF8_STRING", False);
546
547 /* calculate menu geometry */
548 bh = drw->fonts->h + 2;
549 lines = MAX(lines, 0);
550 mh = (lines + 1) * bh;
551 #ifdef XINERAMA
552 if ((info = XineramaQueryScreens(dpy, &n))) {
553 XGetInputFocus(dpy, &w, &di);
554 if (mon != -1 && mon < n)
555 i = mon;
556 else if (w != root && w != PointerRoot && w != None) {
557 /* find top-level window containing current input focus */
558 do {
559 if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
560 XFree(dws);
561 } while (w != root && w != pw);
562 /* find xinerama screen with which the window intersects most */
563 if (XGetWindowAttributes(dpy, pw, &wa))
564 for (j = 0; j < n; j++)
565 if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
566 area = a;
567 i = j;
568 }
569 }
570 /* no focused window is on screen, so use pointer location instead */
571 if (mon == -1 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
572 for (i = 0; i < n; i++)
573 if (INTERSECT(x, y, 1, 1, info[i]))
574 break;
575
576 x = info[i].x_org;
577 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
578 mw = info[i].width;
579 XFree(info);
580 } else
581 #endif
582 {
583 x = 0;
584 y = topbar ? 0 : sh - mh;
585 mw = sw;
586 }
587 promptw = (prompt && *prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
588 inputw = MIN(inputw, mw/3);
589 match();
590
591 /* create menu window */
592 swa.override_redirect = True;
593 swa.background_pixel = scheme[SchemeNorm][ColBg].pixel;
594 swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
595 win = XCreateWindow(dpy, root, x, y, mw, mh, 0,
596 DefaultDepth(dpy, screen), CopyFromParent,
597 DefaultVisual(dpy, screen),
598 CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
599
600 /* open input methods */
601 xim = XOpenIM(dpy, NULL, NULL, NULL);
602 xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
603 XNClientWindow, win, XNFocusWindow, win, NULL);
604
605 XMapRaised(dpy, win);
606 drw_resize(drw, mw, mh);
607 drawmenu();
608 }
609
610 static void
611 usage(void)
612 {
613 fputs("usage: dmenu [-b] [-f] [-i] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
614 " [-nb color] [-nf color] [-sb color] [-sf color] [-v]\n", stderr);
615 exit(1);
616 }
617
618 int
619 main(int argc, char *argv[])
620 {
621 int i, fast = 0;
622
623 for (i = 1; i < argc; i++)
624 /* these options take no arguments */
625 if (!strcmp(argv[i], "-v")) { /* prints version information */
626 puts("dmenu-"VERSION);
627 exit(0);
628 } else if (!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
629 topbar = 0;
630 else if (!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
631 fast = 1;
632 else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
633 fstrncmp = strncasecmp;
634 fstrstr = cistrstr;
635 } else if (i + 1 == argc)
636 usage();
637 /* these options take one argument */
638 else if (!strcmp(argv[i], "-l")) /* number of lines in vertical list */
639 lines = atoi(argv[++i]);
640 else if (!strcmp(argv[i], "-m"))
641 mon = atoi(argv[++i]);
642 else if (!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
643 prompt = argv[++i];
644 else if (!strcmp(argv[i], "-fn")) /* font or font set */
645 fonts[0] = argv[++i];
646 else if (!strcmp(argv[i], "-nb")) /* normal background color */
647 colors[SchemeNorm][ColBg] = argv[++i];
648 else if (!strcmp(argv[i], "-nf")) /* normal foreground color */
649 colors[SchemeNorm][ColFg] = argv[++i];
650 else if (!strcmp(argv[i], "-sb")) /* selected background color */
651 colors[SchemeSel][ColBg] = argv[++i];
652 else if (!strcmp(argv[i], "-sf")) /* selected foreground color */
653 colors[SchemeSel][ColFg] = argv[++i];
654 else
655 usage();
656
657 if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
658 fputs("warning: no locale support\n", stderr);
659 if (!(dpy = XOpenDisplay(NULL)))
660 die("cannot open display\n");
661 screen = DefaultScreen(dpy);
662 root = RootWindow(dpy, screen);
663 sw = DisplayWidth(dpy, screen);
664 sh = DisplayHeight(dpy, screen);
665 drw = drw_create(dpy, screen, root, sw, sh);
666 if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
667 die("no fonts could be loaded.\n");
668 lrpad = drw->fonts->h;
669
670 if (fast) {
671 grabkeyboard();
672 readstdin();
673 } else {
674 readstdin();
675 grabkeyboard();
676 }
677 setup();
678 run();
679
680 return 1; /* unreachable */
681 }