dmenu

my customized dmenu build
git clone git://git.hanetzok.net/dmenu
Log | Files | Refs | README | LICENSE

dmenu.c (22818B)


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