dmenu

my build of dynamic menu
git clone git://git.kocotian.pl/dmenu.git
Log | Files | Refs | README | LICENSE

dmenu.c (24266B)


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