dmenu

dynamic menu
git clone git://mfeller.io/dmenu.git
Log | Files | Refs | README | LICENSE

dmenu.c (20334B)


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