Xinqi Bao's Git

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