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