Xinqi Bao's Git

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