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