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