dmenu

[fork] X11 menuing
git clone https://hhvn.uk/dmenu
git clone git://hhvn.uk/dmenu
Log | Files | Refs | README | LICENSE

dmenu.c (24512B)


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