dmenu.c (19598B) - raw


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