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