dmenu

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

dmenu.c (24967B)


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