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