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