dmenu-nihal

My personal build of dmenu
git clone git://nihaljere.xyz/dmenu-nihal
Log | Files | Refs | README | LICENSE

dmenu.c (22725B)


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