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