Xinqi Bao's Git

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