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