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