Xinqi Bao's Git

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