dmenu

My custom build of dmenu.
git clone https://git.mtkn.jp/dmenu
Log | Files | Refs | README | LICENSE

dmenu.c (19909B)


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