dmenu

My fork of dmenu.
git clone git://git.alex.balgavy.eu/dmenu.git
Log | Files | Refs | README | LICENSE

dmenu.c (18959B)


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