dmenu

Menú dinámico y lanzador de programas para X11
Log | Files | Refs | README | LICENSE

dmenu.c (23053B)


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