dmenu

fork of dmenu
git clone git://popovic.xyz/dmenu.git
Log | Files | Refs | README | LICENSE

dmenu.c.orig (20341B)


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