dmenu.c
1/* See LICENSE file for copyright and license details. */
2#include <ctype.h>
3#include <locale.h>
4#include <math.h>
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8#include <strings.h>
9#include <time.h>
10#include <unistd.h>
11
12#include <X11/Xlib.h>
13#include <X11/Xatom.h>
14#include <X11/Xutil.h>
15#ifdef XINERAMA
16#include <X11/extensions/Xinerama.h>
17#endif
18#include <X11/Xft/Xft.h>
19
20#include "drw.h"
21#include "util.h"
22
23/* macros */
24#define INTERSECT(x,y,w,h,r) (MAX(0, MIN((x)+(w),(r).x_org+(r).width) - MAX((x),(r).x_org)) \
25 * MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
26#define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad)
27
28/* enums */
29enum { SchemeNorm, SchemeOdd, SchemeSel, SchemeNormHighlight,
30 SchemeOddHighlight, SchemeSelHighlight, SchemeOut, SchemeBorder,
31 SchemeLast }; /* color schemes */
32
33struct item {
34 char *text;
35 struct item *left, *right;
36 int out;
37 int idx;
38 double distance;
39};
40
41static char text[BUFSIZ] = "";
42static char matched[BUFSIZ] = "";
43static char *embed;
44static int bh, mw, mh;
45static int inputw = 0, promptw, passwd=0;
46static int lrpad; /* sum of left and right padding */
47static size_t cursor;
48static struct item *items = NULL;
49static struct item *matches, *matchend;
50static struct item *prev, *curr, *next, *sel;
51static int mon = -1, screen;
52static int print_idx;
53
54static Atom clip, utf8;
55static Display *dpy;
56static Window root, parentwin, win;
57static XIC xic;
58
59static Drw *drw;
60static Clr *scheme[SchemeLast];
61
62#include "config.h"
63
64static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
65static char *(*fstrstr)(const char *, const char *) = strstr;
66
67static unsigned int
68textw_clamp(const char *str, unsigned int n)
69{
70 unsigned int w = drw_fontset_getwidth_clamp(drw, str, n) + lrpad;
71 return MIN(w, n);
72}
73
74static void
75appenditem(struct item *item, struct item **list, struct item **last)
76{
77 if (*last)
78 (*last)->right = item;
79 else
80 *list = item;
81
82 item->left = *last;
83 item->right = NULL;
84 *last = item;
85}
86
87static void
88calcoffsets(void)
89{
90 int i, n;
91
92 if (lines > 0)
93 n = lines * bh;
94 else
95 n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">"));
96 /* calculate which items will begin the next page and previous page */
97 for (i = 0, next = curr; next; next = next->right)
98 if ((i += (lines > 0) ? bh : textw_clamp(next->text, n)) > n)
99 break;
100 for (i = 0, prev = curr; prev && prev->left; prev = prev->left)
101 if ((i += (lines > 0) ? bh : textw_clamp(prev->left->text, n)) > n)
102 break;
103}
104
105static int
106max_textw(void)
107{
108 int len = 0;
109 for (struct item *item = items; item && item->text; item++)
110 len = MAX(TEXTW(item->text), len);
111 return len;
112}
113
114static void
115cleanup(void)
116{
117 size_t i;
118
119 XUngrabKey(dpy, AnyKey, AnyModifier, root);
120 for (i = 0; i < SchemeLast; i++)
121 free(scheme[i]);
122 for (i = 0; items && items[i].text; ++i)
123 free(items[i].text);
124 free(items);
125 drw_free(drw);
126 XSync(dpy, False);
127 XCloseDisplay(dpy);
128}
129
130static char *
131cistrstr(const char *h, const char *n)
132{
133 size_t i;
134
135 if (!n[0])
136 return (char *)h;
137
138 for (; *h; ++h) {
139 for (i = 0; n[i] && tolower((unsigned char)n[i]) ==
140 tolower((unsigned char)h[i]); ++i)
141 ;
142 if (n[i] == '\0')
143 return (char *)h;
144 }
145 return NULL;
146}
147
148static void
149drawhighlights(struct item *item, int x, int y, int maxw, int n)
150{
151 int i, indent;
152 char *highlight;
153 char c;
154
155 if (!(strlen(item->text) && strlen(text)))
156 return;
157
158 drw_setscheme(drw, scheme[
159 item == sel ? SchemeSelHighlight
160 /* TODO : item->out ? SchemeOutHighlight*/
161 : n & 1 ? SchemeOddHighlight
162 : SchemeNormHighlight]);
163 for (i = 0, highlight = item->text; *highlight && text[i];) {
164 if (!fstrncmp(&(*highlight), &text[i], 1)) {
165 /* get indentation */
166 c = *highlight;
167 *highlight = '\0';
168 indent = TEXTW(item->text);
169 *highlight = c;
170
171 /* highlight character */
172 c = highlight[1];
173 highlight[1] = '\0';
174 drw_text(
175 drw,
176 x + indent - ((lrpad + 1) / 2),
177 y,
178 MIN(maxw - indent, TEXTW(highlight) - lrpad),
179 bh, 0, highlight, 0
180 );
181 highlight[1] = c;
182 i++;
183 }
184 highlight++;
185 }
186}
187
188static int
189drawitem(struct item *item, int x, int y, int w, int n)
190{
191 int r;
192 drw_setscheme(drw, scheme[
193 item == sel ? SchemeSel
194 : item->out ? SchemeOut
195 : n & 1 ? SchemeOdd
196 : SchemeNorm]);
197
198 r = drw_text(drw, x, y, w, bh, lrpad / 2, item->text, 0);
199 drawhighlights(item, x, y, w, n);
200 return r;
201}
202
203static void
204recalculatematched()
205{
206 unsigned int m = 0, t = 0;
207 struct item *item;
208 if (matchend)
209 for (item = matchend, m++; item && item->left; item = item->left, m++);
210 for (item = items; item && item->text; item++, t++);
211 snprintf(matched, BUFSIZ, "%d/%d", m, t);
212}
213
214static void
215drawmenu(void)
216{
217 unsigned int curpos;
218 struct item *item;
219 int n = 1, x = 0, y = 0, fh = drw->fonts->h, w;
220 char *censort;
221
222 drw_setscheme(drw, scheme[SchemeNorm]);
223 drw_rect(drw, 0, 0, mw, mh, 1, 1);
224
225 if (prompt && *prompt) {
226 drw_setscheme(drw, scheme[SchemeSel]);
227 x = drw_text(drw, x, 0, promptw, bh, lrpad / 2, prompt, 0);
228 }
229 /* draw input field */
230 w = (lines > 0 || !matches) ? mw - x : inputw;
231 drw_setscheme(drw, scheme[SchemeNorm]);
232 if (passwd) {
233 censort = ecalloc(1, sizeof(text));
234 memset(censort, '*', strlen(text));
235 drw_text(drw, x, 0, w, bh, lrpad / 2, censort, 0);
236 free(censort);
237 } else {
238 drw_text(drw, x, 0, w, bh, lrpad / 2, text, 0);
239 }
240
241 curpos = TEXTW(text) - TEXTW(&text[cursor]);
242 if ((curpos += lrpad / 2 - 1) < w) {
243 drw_setscheme(drw, scheme[SchemeNorm]);
244 drw_rect(drw, x + curpos, 2 + (bh-fh)/2, 2, fh - 4, 1, 0);
245 }
246
247 recalculatematched();
248 drw_rect(drw, 0, (y += im) + bh, mw, im, 1, 1);
249 if (lines > 0) {
250 /* draw vertical list */
251 for (item = curr; item != next; item = item->right)
252 drawitem(item, 0, y += bh, mw, n++);
253 } else if (matches) {
254 /* draw horizontal list */
255 x += inputw;
256 w = TEXTW("<");
257 if (curr->left) {
258 drw_setscheme(drw, scheme[SchemeNorm]);
259 drw_text(drw, x, 0, w, bh, lrpad / 2, "<", 0);
260 }
261 x += w;
262 for (item = curr; item != next; item = item->right)
263 x = drawitem(item, x, 0, textw_clamp(item->text, mw - x - TEXTW(">") - TEXTW(matched)), 0);
264 if (next) {
265 w = TEXTW(">");
266 drw_setscheme(drw, scheme[SchemeNorm]);
267 drw_text(drw, mw - w - TEXTW(matched), 0, w, bh, lrpad / 2, ">", 0);
268 }
269 }
270 drw_setscheme(drw, scheme[SchemeNorm]);
271 drw_text(drw, mw - TEXTW(matched), 0, TEXTW(matched), bh, lrpad / 2, matched, 0);
272 drw_map(drw, win, 0, 0, mw, mh);
273}
274
275static void
276grabfocus(void)
277{
278 struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 };
279 Window focuswin;
280 int i, revertwin;
281
282 for (i = 0; i < 100; ++i) {
283 XGetInputFocus(dpy, &focuswin, &revertwin);
284 if (focuswin == win)
285 return;
286 XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
287 nanosleep(&ts, NULL);
288 }
289 die("cannot grab focus");
290}
291
292static void
293grabkeyboard(void)
294{
295 struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
296 int i;
297
298 if (embed)
299 return;
300 /* try to grab keyboard, we may have to wait for another process to ungrab */
301 for (i = 0; i < 1000; i++) {
302 if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync,
303 GrabModeAsync, CurrentTime) == GrabSuccess)
304 return;
305 nanosleep(&ts, NULL);
306 }
307 die("cannot grab keyboard");
308}
309
310int
311compare_distance(const void *a, const void *b)
312{
313 struct item *da = *(struct item **) a;
314 struct item *db = *(struct item **) b;
315
316 if (!db)
317 return 1;
318 if (!da)
319 return -1;
320
321 return da->distance == db->distance ? 0 : da->distance < db->distance ? -1 : 1;
322}
323
324void
325fuzzymatch(void)
326{
327 /* bang - we have so much memory */
328 struct item *it;
329 struct item **fuzzymatches = NULL;
330 char c;
331 int number_of_matches = 0, i, pidx, sidx, eidx;
332 int text_len = strlen(text), itext_len;
333
334 matches = matchend = NULL;
335
336 /* walk through all items */
337 for (it = items; it && it->text; it++) {
338 if (text_len) {
339 itext_len = strlen(it->text);
340 pidx = 0; /* pointer */
341 sidx = eidx = -1; /* start of match, end of match */
342 /* walk through item text */
343 for (i = 0; i < itext_len && (c = it->text[i]); i++) {
344 /* fuzzy match pattern */
345 if (!fstrncmp(&text[pidx], &c, 1)) {
346 if(sidx == -1)
347 sidx = i;
348 pidx++;
349 if (pidx == text_len) {
350 eidx = i;
351 break;
352 }
353 }
354 }
355 /* build list of matches */
356 if (eidx != -1) {
357 /* compute distance */
358 /* add penalty if match starts late (log(sidx+2))
359 * add penalty for long a match without many matching characters */
360 it->distance = log(sidx + 2) + (double)(eidx - sidx - text_len);
361 /* fprintf(stderr, "distance %s %f\n", it->text, it->distance); */
362 appenditem(it, &matches, &matchend);
363 number_of_matches++;
364 }
365 } else {
366 appenditem(it, &matches, &matchend);
367 }
368 }
369
370 if (number_of_matches) {
371 /* initialize array with matches */
372 if (!(fuzzymatches = realloc(fuzzymatches, number_of_matches * sizeof(struct item*))))
373 die("cannot realloc %u bytes:", number_of_matches * sizeof(struct item*));
374 for (i = 0, it = matches; it && i < number_of_matches; i++, it = it->right) {
375 fuzzymatches[i] = it;
376 }
377 /* sort matches according to distance */
378 qsort(fuzzymatches, number_of_matches, sizeof(struct item*), compare_distance);
379 /* rebuild list of matches */
380 matches = matchend = NULL;
381 for (i = 0, it = fuzzymatches[i]; i < number_of_matches && it && \
382 it->text; i++, it = fuzzymatches[i]) {
383 appenditem(it, &matches, &matchend);
384 }
385 free(fuzzymatches);
386 }
387 curr = sel = matches;
388 calcoffsets();
389}
390
391static void
392match(void)
393{
394 if (fuzzy) {
395 fuzzymatch();
396 return;
397 }
398 static char **tokv = NULL;
399 static int tokn = 0;
400
401 char buf[sizeof text], *s;
402 int i, tokc = 0;
403 size_t len, textsize;
404 struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
405
406 strcpy(buf, text);
407 /* separate input text into tokens to be matched individually */
408 for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
409 if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
410 die("cannot realloc %zu bytes:", tokn * sizeof *tokv);
411 len = tokc ? strlen(tokv[0]) : 0;
412
413 matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
414 textsize = strlen(text) + 1;
415 for (item = items; item && item->text; item++) {
416 for (i = 0; i < tokc; i++)
417 if (!fstrstr(item->text, tokv[i]))
418 break;
419 if (i != tokc) /* not all tokens match */
420 continue;
421 /* exact matches go first, then prefixes, then substrings */
422 if (!tokc || !fstrncmp(text, item->text, textsize))
423 appenditem(item, &matches, &matchend);
424 else if (!fstrncmp(tokv[0], item->text, len))
425 appenditem(item, &lprefix, &prefixend);
426 else
427 appenditem(item, &lsubstr, &substrend);
428 }
429 if (lprefix) {
430 if (matches) {
431 matchend->right = lprefix;
432 lprefix->left = matchend;
433 } else
434 matches = lprefix;
435 matchend = prefixend;
436 }
437 if (lsubstr) {
438 if (matches) {
439 matchend->right = lsubstr;
440 lsubstr->left = matchend;
441 } else
442 matches = lsubstr;
443 matchend = substrend;
444 }
445 curr = sel = matches;
446 calcoffsets();
447}
448
449static void
450insert(const char *str, ssize_t n)
451{
452 if (strlen(text) + n > sizeof text - 1)
453 return;
454 /* move existing text out of the way, insert new text, and update cursor */
455 memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
456 if (n > 0)
457 memcpy(&text[cursor], str, n);
458 cursor += n;
459 match();
460}
461
462static size_t
463nextrune(int inc)
464{
465 ssize_t n;
466
467 /* return location of next utf8 rune in the given direction (+1 or -1) */
468 for (n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc)
469 ;
470 return n;
471}
472
473static void
474movewordedge(int dir)
475{
476 if (dir < 0) { /* move cursor to the start of the word*/
477 while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
478 cursor = nextrune(-1);
479 while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
480 cursor = nextrune(-1);
481 } else { /* move cursor to the end of the word */
482 while (text[cursor] && strchr(worddelimiters, text[cursor]))
483 cursor = nextrune(+1);
484 while (text[cursor] && !strchr(worddelimiters, text[cursor]))
485 cursor = nextrune(+1);
486 }
487}
488
489static void
490keypress(XKeyEvent *ev)
491{
492 char buf[64];
493 int len;
494 KeySym ksym = NoSymbol;
495 Status status;
496
497 len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
498 switch (status) {
499 default: /* XLookupNone, XBufferOverflow */
500 return;
501 case XLookupChars: /* composed string from input method */
502 goto insert;
503 case XLookupKeySym:
504 case XLookupBoth: /* a KeySym and a string are returned: use keysym */
505 break;
506 }
507
508 if (ev->state & ControlMask) {
509 switch(ksym) {
510 case XK_a: ksym = XK_Home; break;
511 case XK_b: ksym = XK_Left; break;
512 case XK_c: ksym = XK_Escape; break;
513 case XK_d: ksym = XK_Delete; break;
514 case XK_e: ksym = XK_End; break;
515 case XK_f: ksym = XK_Right; break;
516 case XK_g: ksym = XK_Escape; break;
517 case XK_h: ksym = XK_BackSpace; break;
518 case XK_i: ksym = XK_Tab; break;
519 case XK_j: /* fallthrough */
520 case XK_J: /* fallthrough */
521 case XK_m: /* fallthrough */
522 case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
523 case XK_n: ksym = XK_Down; break;
524 case XK_p: ksym = XK_Up; break;
525
526 case XK_k: /* delete right */
527 text[cursor] = '\0';
528 match();
529 break;
530 case XK_u: /* delete left */
531 insert(NULL, 0 - cursor);
532 break;
533 case XK_w: /* delete word */
534 while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
535 insert(NULL, nextrune(-1) - cursor);
536 while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
537 insert(NULL, nextrune(-1) - cursor);
538 break;
539 case XK_y: /* paste selection */
540 case XK_Y:
541 XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
542 utf8, utf8, win, CurrentTime);
543 return;
544 case XK_Left:
545 case XK_KP_Left:
546 movewordedge(-1);
547 goto draw;
548 case XK_Right:
549 case XK_KP_Right:
550 movewordedge(+1);
551 goto draw;
552 case XK_Return:
553 case XK_KP_Enter:
554 break;
555 case XK_bracketleft:
556 cleanup();
557 exit(1);
558 default:
559 return;
560 }
561 } else if (ev->state & Mod1Mask) {
562 switch(ksym) {
563 case XK_b:
564 movewordedge(-1);
565 goto draw;
566 case XK_f:
567 movewordedge(+1);
568 goto draw;
569 case XK_g: ksym = XK_Home; break;
570 case XK_G: ksym = XK_End; break;
571 case XK_h: ksym = lines > 0 ? XK_Prior : XK_Up; break;
572 case XK_j: ksym = lines > 0 ? XK_Down : XK_Next; break;
573 case XK_k: ksym = lines > 0 ? XK_Up : XK_Prior; break;
574 case XK_l: ksym = lines > 0 ? XK_Next : XK_Down; break;
575 default:
576 return;
577 }
578 }
579
580 switch(ksym) {
581 default:
582insert:
583 if (!iscntrl((unsigned char)*buf))
584 insert(buf, len);
585 break;
586 case XK_Delete:
587 case XK_KP_Delete:
588 if (text[cursor] == '\0')
589 return;
590 cursor = nextrune(+1);
591 /* fallthrough */
592 case XK_BackSpace:
593 if (cursor == 0)
594 return;
595 insert(NULL, nextrune(-1) - cursor);
596 break;
597 case XK_End:
598 case XK_KP_End:
599 if (text[cursor] != '\0') {
600 cursor = strlen(text);
601 break;
602 }
603 if (next) {
604 /* jump to end of list and position items in reverse */
605 curr = matchend;
606 calcoffsets();
607 curr = prev;
608 calcoffsets();
609 while (next && (curr = curr->right))
610 calcoffsets();
611 }
612 sel = matchend;
613 break;
614 case XK_Escape:
615 cleanup();
616 exit(1);
617 case XK_Home:
618 case XK_KP_Home:
619 if (sel == matches) {
620 cursor = 0;
621 break;
622 }
623 sel = curr = matches;
624 calcoffsets();
625 break;
626 case XK_Left:
627 case XK_KP_Left:
628 if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
629 cursor = nextrune(-1);
630 break;
631 }
632 if (lines > 0)
633 return;
634 /* fallthrough */
635 case XK_Up:
636 case XK_KP_Up:
637 if (sel && sel->left && (sel = sel->left)->right == curr) {
638 curr = prev;
639 calcoffsets();
640 }
641 break;
642 case XK_Next:
643 case XK_KP_Next:
644 if (!next)
645 return;
646 sel = curr = next;
647 calcoffsets();
648 break;
649 case XK_Prior:
650 case XK_KP_Prior:
651 if (!prev)
652 return;
653 sel = curr = prev;
654 calcoffsets();
655 break;
656 case XK_Return:
657 case XK_KP_Enter:
658 if (print_idx)
659 printf("%d\n", (sel && !(ev->state & ShiftMask)) ? sel->idx : -1);
660 else
661 puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
662 if (!(ev->state & ControlMask)) {
663 cleanup();
664 exit(0);
665 }
666 if (sel)
667 sel->out = 1;
668 break;
669 case XK_Right:
670 case XK_KP_Right:
671 if (text[cursor] != '\0') {
672 cursor = nextrune(+1);
673 break;
674 }
675 if (lines > 0)
676 return;
677 /* fallthrough */
678 case XK_Down:
679 case XK_KP_Down:
680 if (sel && sel->right && (sel = sel->right) == next) {
681 curr = next;
682 calcoffsets();
683 }
684 break;
685 case XK_Tab:
686 if (!sel)
687 return;
688 cursor = strnlen(sel->text, sizeof text - 1);
689 memcpy(text, sel->text, cursor);
690 text[cursor] = '\0';
691 match();
692 break;
693 }
694
695draw:
696 drawmenu();
697}
698
699static void
700paste(void)
701{
702 char *p, *q;
703 int di;
704 unsigned long dl;
705 Atom da;
706
707 /* we have been given the current selection, now insert it into input */
708 if (XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
709 utf8, &da, &di, &dl, &dl, (unsigned char **)&p)
710 == Success && p) {
711 insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
712 XFree(p);
713 }
714 drawmenu();
715}
716
717static void
718readstdin(void)
719{
720 char *line = NULL;
721 size_t i, itemsiz = 0, linesiz = 0;
722 ssize_t len;
723
724 if (passwd) {
725 inputw = lines = 0;
726 return;
727 }
728
729 /* read each line from stdin and add it to the item list */
730 for (i = 0; (len = getline(&line, &linesiz, stdin)) != -1; i++) {
731 if (i + 1 >= itemsiz) {
732 itemsiz += 256;
733 if (!(items = realloc(items, itemsiz * sizeof(*items))))
734 die("cannot realloc %zu bytes:", itemsiz * sizeof(*items));
735 }
736 if (line[len - 1] == '\n')
737 line[len - 1] = '\0';
738 if (!(items[i].text = strdup(line)))
739 die("strdup:");
740
741 items[i].out = 0;
742 items[i].idx = i;
743 }
744 free(line);
745 if (items)
746 items[i].text = NULL;
747 lines = MIN(lines, i);
748}
749
750static void
751run(void)
752{
753 XEvent ev;
754
755 while (!XNextEvent(dpy, &ev)) {
756 if (XFilterEvent(&ev, win))
757 continue;
758 switch(ev.type) {
759 case DestroyNotify:
760 if (ev.xdestroywindow.window != win)
761 break;
762 cleanup();
763 exit(1);
764 case Expose:
765 if (ev.xexpose.count == 0)
766 drw_map(drw, win, 0, 0, mw, mh);
767 break;
768 case FocusIn:
769 /* regrab focus from parent window */
770 if (ev.xfocus.window != win)
771 grabfocus();
772 break;
773 case KeyPress:
774 keypress(&ev.xkey);
775 break;
776 case SelectionNotify:
777 if (ev.xselection.property == utf8)
778 paste();
779 break;
780 case VisibilityNotify:
781 if (ev.xvisibility.state != VisibilityUnobscured)
782 XRaiseWindow(dpy, win);
783 break;
784 }
785 }
786}
787
788static void
789setup(void)
790{
791 int x, y, i, j;
792 unsigned int du;
793 XSetWindowAttributes swa;
794 XIM xim;
795 Window w, dw, *dws;
796 XWindowAttributes wa;
797 XClassHint ch = {"dmenu", "dmenu"};
798#ifdef XINERAMA
799 XineramaScreenInfo *info;
800 Window pw;
801 int a, di, n, area = 0;
802#endif
803 /* init appearance */
804 for (j = 0; j < SchemeLast; j++)
805 scheme[j] = drw_scm_create(drw, colors[j], 2);
806
807 clip = XInternAtom(dpy, "CLIPBOARD", False);
808 utf8 = XInternAtom(dpy, "UTF8_STRING", False);
809
810 /* calculate menu geometry */
811 bh = drw->fonts->h + 2;
812 bh = MAX(bh,lineheight); /* make a menu line AT LEAST 'lineheight' tall */
813 lines = MAX(lines, 0);
814 mh = (lines + 1) * bh + im;
815 promptw = (prompt && *prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
816#ifdef XINERAMA
817 i = 0;
818 if (parentwin == root && (info = XineramaQueryScreens(dpy, &n))) {
819 XGetInputFocus(dpy, &w, &di);
820 if (mon >= 0 && mon < n)
821 i = mon;
822 else if (w != root && w != PointerRoot && w != None) {
823 /* find top-level window containing current input focus */
824 do {
825 if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
826 XFree(dws);
827 } while (w != root && w != pw);
828 /* find xinerama screen with which the window intersects most */
829 if (XGetWindowAttributes(dpy, pw, &wa))
830 for (j = 0; j < n; j++)
831 if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
832 area = a;
833 i = j;
834 }
835 }
836 /* no focused window is on screen, so use pointer location instead */
837 if (mon < 0 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
838 for (i = 0; i < n; i++)
839 if (INTERSECT(x, y, 1, 1, info[i]) != 0)
840 break;
841
842 if (centered) {
843 mw = MIN(MAX(max_textw() + promptw, min_width), info[i].width);
844 x = info[i].x_org + ((info[i].width - mw - bw) / 2);
845 y = info[i].y_org + ((info[i].height - mh) / 2);
846 } else {
847 x = info[i].x_org;
848 y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
849 mw = info[i].width;
850 }
851
852 XFree(info);
853 } else
854#endif
855 {
856 if (!XGetWindowAttributes(dpy, parentwin, &wa))
857 die("could not get embedding window attributes: 0x%lx",
858 parentwin);
859
860 if (centered) {
861 mw = MIN(MAX(max_textw() + promptw, min_width), wa.width);
862 x = (wa.width - mw - bw) / 2;
863 y = (wa.height - mh) / 2;
864 } else {
865 x = 0;
866 y = topbar ? 0 : wa.height - mh;
867 mw = wa.width;
868 }
869 }
870 promptw = (prompt && *prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
871 inputw = mw / 6; /* input width: ~1666..% of monitor width */
872 match();
873
874 /* create menu window */
875 swa.override_redirect = True;
876 swa.background_pixel = scheme[SchemeNorm][ColBg].pixel;
877 swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
878 win = XCreateWindow(dpy, root, x, y, mw, mh, bw,
879 CopyFromParent, CopyFromParent, CopyFromParent,
880 CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
881 if (bw)
882 XSetWindowBorder(dpy, win, scheme[SchemeBorder][ColBg].pixel);
883 XSetClassHint(dpy, win, &ch);
884
885
886 /* input methods */
887 if ((xim = XOpenIM(dpy, NULL, NULL, NULL)) == NULL)
888 die("XOpenIM failed: could not open input device");
889
890 xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
891 XNClientWindow, win, XNFocusWindow, win, NULL);
892
893 XMapRaised(dpy, win);
894 if (embed) {
895 XReparentWindow(dpy, win, parentwin, x, y);
896 XSelectInput(dpy, parentwin, FocusChangeMask | SubstructureNotifyMask);
897 if (XQueryTree(dpy, parentwin, &dw, &w, &dws, &du) && dws) {
898 for (i = 0; i < du && dws[i] != win; ++i)
899 XSelectInput(dpy, dws[i], FocusChangeMask);
900 XFree(dws);
901 }
902 grabfocus();
903 }
904 drw_resize(drw, mw, mh);
905 drawmenu();
906}
907
908static void
909usage(void)
910{
911 die("usage: dmenu [-bfiPv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
912 " [-h height]\n"
913 " [-nb color] [-nf color] [-sb color] [-sf color]\n"
914 " [-nhb color] [-nhf color] [-shb color] [-shf color] [-w windowid]\n", stderr);
915 exit(1);
916}
917
918int
919main(int argc, char *argv[])
920{
921 XWindowAttributes wa;
922 int i, fast = 0;
923
924 for (i = 1; i < argc; i++)
925 /* these options take no arguments */
926 if (!strcmp(argv[i], "-v")) { /* prints version information */
927 puts("dmenu-"VERSION);
928 exit(0);
929 } else if (!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
930 topbar = 0;
931 else if (!strcmp(argv[i], "-c")) /* center on screen */
932 centered = 1;
933 else if (!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
934 fast = 1;
935 else if (!strcmp(argv[i], "-F")) /* grabs keyboard before reading stdin */
936 fuzzy = 0;
937 else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
938 fstrncmp = strncasecmp;
939 fstrstr = cistrstr;
940 } else if (!strcmp(argv[i], "-P")) /* doesn't show typed text */
941 passwd = 1;
942 else if (!strcmp(argv[i], "-I")) /* returns selected index */
943 print_idx = 1;
944 else if (i + 1 == argc)
945 usage();
946 /* these options take one argument */
947 else if (!strcmp(argv[i], "-l")) /* number of lines in vertical list */
948 lines = atoi(argv[++i]);
949 else if (!strcmp(argv[i], "-m"))
950 mon = atoi(argv[++i]);
951 else if (!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
952 prompt = argv[++i];
953 else if (!strcmp(argv[i], "-fn")) /* font or font set */
954 fonts[0] = argv[++i];
955 else if(!strcmp(argv[i], "-h")) { /* minimum height of one menu line */
956 lineheight = atoi(argv[++i]);
957 lineheight = MAX(lineheight,8); /* reasonable default in case of value too small/negative */
958 }
959 else if (!strcmp(argv[i], "-nb")) /* normal background color */
960 colors[SchemeNorm][ColBg] = argv[++i];
961 else if (!strcmp(argv[i], "-nf")) /* normal foreground color */
962 colors[SchemeNorm][ColFg] = argv[++i];
963 else if (!strcmp(argv[i], "-ob")) /* odd background color */
964 colors[SchemeOdd][ColBg] = argv[++i];
965 else if (!strcmp(argv[i], "-of")) /* odd foreground color */
966 colors[SchemeOdd][ColFg] = argv[++i];
967 else if (!strcmp(argv[i], "-sb")) /* selected background color */
968 colors[SchemeSel][ColBg] = argv[++i];
969 else if (!strcmp(argv[i], "-sf")) /* selected foreground color */
970 colors[SchemeSel][ColFg] = argv[++i];
971 else if (!strcmp(argv[i], "-nhb")) /* normal hi background color */
972 colors[SchemeNormHighlight][ColBg] = argv[++i];
973 else if (!strcmp(argv[i], "-nhf")) /* normal hi foreground color */
974 colors[SchemeNormHighlight][ColFg] = argv[++i];
975 else if (!strcmp(argv[i], "-ohb")) /* odd hi background color */
976 colors[SchemeOddHighlight][ColBg] = argv[++i];
977 else if (!strcmp(argv[i], "-ohf")) /* odd hi foreground color */
978 colors[SchemeOddHighlight][ColFg] = argv[++i];
979 else if (!strcmp(argv[i], "-shb")) /* selected hi background color */
980 colors[SchemeSelHighlight][ColBg] = argv[++i];
981 else if (!strcmp(argv[i], "-shf")) /* selected hi foreground color */
982 colors[SchemeSelHighlight][ColFg] = argv[++i];
983 else if (!strcmp(argv[i], "-bb")) /* border background color */
984 colors[SchemeBorder][ColBg] = argv[++i];
985 else if (!strcmp(argv[i], "-w")) /* embedding window id */
986 embed = argv[++i];
987 else if (!strcmp(argv[i], "-bw")) /* border width */
988 bw = atoi(argv[++i]);
989 else if (!strcmp(argv[i], "-it") && ++i) /* insert initial text */
990 insert(argv[i], strlen(argv[i]));
991 else
992 usage();
993
994 if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
995 fputs("warning: no locale support\n", stderr);
996 if (!(dpy = XOpenDisplay(NULL)))
997 die("cannot open display");
998 screen = DefaultScreen(dpy);
999 root = RootWindow(dpy, screen);
1000 if (!embed || !(parentwin = strtol(embed, NULL, 0)))
1001 parentwin = root;
1002 if (!XGetWindowAttributes(dpy, parentwin, &wa))
1003 die("could not get embedding window attributes: 0x%lx",
1004 parentwin);
1005 drw = drw_create(dpy, screen, root, wa.width, wa.height);
1006 if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
1007 die("no fonts could be loaded.");
1008 lrpad = drw->fonts->h;
1009
1010#ifdef __OpenBSD__
1011 if (pledge("stdio rpath", NULL) == -1)
1012 die("pledge");
1013#endif
1014
1015 if (fast && !isatty(0)) {
1016 grabkeyboard();
1017 readstdin();
1018 } else {
1019 readstdin();
1020 grabkeyboard();
1021 }
1022 setup();
1023 run();
1024
1025 return 1; /* unreachable */
1026}