dmynu

[fork] my dmenu configuration
git clone https://git.lukeonline.net/repos/dmynu
Log | Files | Refs | README | LICENSE

dmenu.c (22690B)


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