Xinqi Bao's Git

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