dmenu

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

dmenu.c (24603B)


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