dmenu

My dmenu build
git clone https://git.regexghost.com/dmenu.git
Log | Files | Refs | README | LICENSE

dmenu.c (29864B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <ctype.h>
      3 #include <locale.h>
      4 #include <math.h>
      5 #include <stdio.h>
      6 #include <stdlib.h>
      7 #include <string.h>
      8 #include <strings.h>
      9 #include <time.h>
     10 #include <unistd.h>
     11 
     12 #include <X11/Xlib.h>
     13 #include <X11/Xatom.h>
     14 #include <X11/Xutil.h>
     15 #ifdef XINERAMA
     16 #include <X11/extensions/Xinerama.h>
     17 #endif
     18 #include <X11/Xft/Xft.h>
     19 
     20 #include "drw.h"
     21 #include "util.h"
     22 
     23 /* macros */
     24 #define INTERSECT(x,y,w,h,r)  (MAX(0, MIN((x)+(w),(r).x_org+(r).width)  - MAX((x),(r).x_org)) \
     25                              * MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
     26 #define TEXTW(X)              (drw_fontset_getwidth(drw, (X)) + lrpad)
     27 
     28 /* enums */
     29 enum { SchemeNorm, SchemeSel, SchemeNormHighlight, SchemeSelHighlight,
     30        SchemeOut, SchemeCaret, SchemeCursor, SchemePrompt, SchemeBorder, SchemeLast }; /* color schemes */
     31 
     32 
     33 struct item {
     34 	char *text;
     35 	unsigned int width;
     36 	struct item *left, *right;
     37 	int out;
     38 	int index;
     39 	double distance;
     40 };
     41 
     42 typedef struct {
     43 	KeySym ksym;
     44 	unsigned int state;
     45 } Key;
     46 
     47 static char text[BUFSIZ] = "";
     48 static char *embed;
     49 static int bh, mw, mh;
     50 static int inputw = 0, promptw;
     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 static unsigned int using_vi_mode = 0;
     58 static int print_index = 0;
     59 
     60 static Atom clip, utf8;
     61 static Display *dpy;
     62 static Window root, parentwin, win;
     63 static XIC xic;
     64 
     65 static Drw *drw;
     66 static Clr *scheme[SchemeLast];
     67 
     68 static int printAnyway = False;
     69 
     70 #include "config.h"
     71 
     72 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
     73 static char *(*fstrstr)(const char *, const char *) = strstr;
     74 
     75 static unsigned int
     76 textw_clamp(const char *str, unsigned int n)
     77 {
     78 	unsigned int w = drw_fontset_getwidth_clamp(drw, str, n) + lrpad;
     79 	return MIN(w, n);
     80 }
     81 
     82 static void
     83 appenditem(struct item *item, struct item **list, struct item **last)
     84 {
     85 	if (*last)
     86 		(*last)->right = item;
     87 	else
     88 		*list = item;
     89 
     90 	item->left = *last;
     91 	item->right = NULL;
     92 	*last = item;
     93 }
     94 
     95 static void
     96 calcoffsets(void)
     97 {
     98 	int i, n;
     99 
    100 	if (lines > 0)
    101 		n = lines * bh;
    102 	else
    103 		n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">"));
    104 	/* calculate which items will begin the next page and previous page */
    105 	for (i = 0, next = curr; next; next = next->right)
    106 		if ((i += (lines > 0) ? bh : textw_clamp(next->text, n)) > n)
    107 			break;
    108 	for (i = 0, prev = curr; prev && prev->left; prev = prev->left)
    109 		if ((i += (lines > 0) ? bh : textw_clamp(prev->left->text, n)) > n)
    110 			break;
    111 }
    112 
    113 static int
    114 max_textw(void)
    115 {
    116 	int len = 0;
    117 	for (struct item *item = items; item && item->text; item++)
    118 		len = MAX(item->width, len);
    119 	return len;
    120 }
    121 
    122 static void
    123 cleanup(void)
    124 {
    125 	size_t i;
    126 
    127 	XUngrabKeyboard(dpy, CurrentTime);
    128 	for (i = 0; i < SchemeLast; i++)
    129 		drw_scm_free(drw, scheme[i], 2);
    130 	for (i = 0; items && items[i].text; ++i)
    131 		free(items[i].text);
    132 	free(items);
    133 	drw_free(drw);
    134 	XSync(dpy, False);
    135 	XCloseDisplay(dpy);
    136 }
    137 
    138 static char *
    139 cistrstr(const char *h, const char *n)
    140 {
    141 	size_t i;
    142 
    143 	if (!n[0])
    144 		return (char *)h;
    145 
    146 	for (; *h; ++h) {
    147 		for (i = 0; n[i] && tolower((unsigned char)n[i]) ==
    148 		            tolower((unsigned char)h[i]); ++i)
    149 			;
    150 		if (n[i] == '\0')
    151 			return (char *)h;
    152 	}
    153 	return NULL;
    154 }
    155 
    156 static void
    157 drawhighlights(struct item *item, int x, int y, int maxw)
    158 {
    159 	int i, indent;
    160 	char c, *highlight;
    161 
    162 	if (!(strlen(item->text) && strlen(text)))
    163 		return;
    164 
    165 	drw_setscheme(drw, scheme[item == sel
    166 	                   ? SchemeSelHighlight
    167 	                   : SchemeNormHighlight]);
    168 	for (i = 0, highlight = item->text; *highlight && text[i];) {
    169 		if (!fstrncmp(highlight, &text[i], 1)) {
    170 			/* get indentation */
    171 			c = *highlight;
    172 			*highlight = '\0';
    173 			indent = TEXTW(item->text);
    174 			*highlight = c;
    175 
    176 			/* highlight character */
    177 			c = highlight[1];
    178 			highlight[1] = '\0';
    179 			drw_text(
    180 				drw,
    181 				x + indent - (lrpad / 2.),
    182 				y,
    183 				MIN(maxw - indent, TEXTW(highlight) - lrpad),
    184 				bh, 0, highlight, 0
    185 			);
    186 			highlight[1] = c;
    187 			++i;
    188 		}
    189 		++highlight;
    190 	}
    191 }
    192 
    193 static int
    194 drawitem(struct item *item, int x, int y, int w)
    195 {
    196 	int r;
    197 	if (item == sel)
    198 		drw_setscheme(drw, scheme[SchemeSel]);
    199 	else if (item->out)
    200 		drw_setscheme(drw, scheme[SchemeOut]);
    201 	else
    202 		drw_setscheme(drw, scheme[SchemeNorm]);
    203 
    204 	r = drw_text(drw, x, y, w, bh, lrpad / 2, item->text, 0);
    205 	drawhighlights(item, x, y, w);
    206 	return r;
    207 }
    208 
    209 static void
    210 drawmenu(void)
    211 {
    212 	unsigned int curpos;
    213 	struct item *item;
    214 	int x = 0, y = 0, w;
    215 
    216 	drw_setscheme(drw, scheme[SchemeNorm]);
    217 	drw_rect(drw, 0, 0, mw, mh, 1, 1);
    218 
    219 	w = (lines > 0 || !matches) ? mw - x : inputw;
    220 
    221 	if (text[0] == '\0' && prompt && *prompt) {
    222 		drw_setscheme(drw, scheme[SchemePrompt]);
    223 		/* If vertical list: use full width (w), else just promptw */
    224 		drw_text(drw, x, 0, (lines > 0 ? w : promptw), bh, lrpad / 2, prompt, 0);
    225 	} else if (using_vi_mode && text[0] != '\0') {
    226 		drw_setscheme(drw, scheme[SchemeCursor]);
    227 		char vi_char[] = {text[cursor], '\0'};
    228 		drw_text(drw, x, 0, TEXTW(vi_char) - lrpad, bh, 0, vi_char, 0);
    229 	} else if (using_vi_mode) {
    230 		drw_setscheme(drw, scheme[SchemeNorm]);
    231 		drw_rect(drw, x, 2, lrpad / 2, bh - 4, 1, 0);
    232 	} else {
    233 		drw_setscheme(drw, scheme[SchemeNorm]);
    234 		drw_text(drw, x, 0, w, bh, lrpad / 2, text, 0);
    235 	}
    236 
    237 	if (text[0] != '\0') {
    238 		curpos = TEXTW(text) - TEXTW(&text[cursor]);
    239 		if ((curpos += lrpad / 2 - 1) < w) {
    240 			drw_setscheme(drw, scheme[SchemeNorm]);
    241 			drw_rect(drw, x + curpos, 1, 2, bh - 4, 1, 0);
    242 		}
    243 	}
    244 
    245 	if (lines > 0) {
    246 		/* draw vertical list */
    247 		for (item = curr; item != next; item = item->right)
    248 			drawitem(item, x, y += bh, mw - x);
    249 	} else if (matches) {
    250 		/* draw horizontal list */
    251 		x += inputw;
    252 		w = TEXTW("<");
    253 		if (curr->left) {
    254 			drw_setscheme(drw, scheme[SchemeNorm]);
    255 			drw_text(drw, x, 0, w, bh, lrpad / 2, "<", 0);
    256 		}
    257 		x += w;
    258 		for (item = curr; item != next; item = item->right)
    259 			x = drawitem(item, x, 0, textw_clamp(item->text, mw - x - TEXTW(">")));
    260 		if (next) {
    261 			w = TEXTW(">");
    262 			drw_setscheme(drw, scheme[SchemeNorm]);
    263 			drw_text(drw, mw - w, 0, w, bh, lrpad / 2, ">", 0);
    264 		}
    265 	}
    266 	drw_map(drw, win, 0, 0, mw, mh);
    267 }
    268 
    269 static void
    270 grabfocus(void)
    271 {
    272 	struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000  };
    273 	Window focuswin;
    274 	int i, revertwin;
    275 
    276 	for (i = 0; i < 100; ++i) {
    277 		XGetInputFocus(dpy, &focuswin, &revertwin);
    278 		if (focuswin == win)
    279 			return;
    280 		XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
    281 		nanosleep(&ts, NULL);
    282 	}
    283 	die("cannot grab focus");
    284 }
    285 
    286 static void
    287 grabkeyboard(void)
    288 {
    289 	struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000  };
    290 	int i;
    291 
    292 	if (embed)
    293 		return;
    294 	/* try to grab keyboard, we may have to wait for another process to ungrab */
    295 	for (i = 0; i < 1000; i++) {
    296 		if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync,
    297 		                  GrabModeAsync, CurrentTime) == GrabSuccess)
    298 			return;
    299 		nanosleep(&ts, NULL);
    300 	}
    301 	die("cannot grab keyboard");
    302 }
    303 
    304 int
    305 compare_distance(const void *a, const void *b)
    306 {
    307 	struct item *da = *(struct item **) a;
    308 	struct item *db = *(struct item **) b;
    309 
    310 	if (!db)
    311 		return 1;
    312 	if (!da)
    313 		return -1;
    314 
    315 	return da->distance == db->distance ? 0 : da->distance < db->distance ? -1 : 1;
    316 }
    317 
    318 void
    319 fuzzymatch(void)
    320 {
    321 	/* bang - we have so much memory */
    322 	struct item *it;
    323 	struct item **fuzzymatches = NULL;
    324 	char c;
    325 	int number_of_matches = 0, i, pidx, sidx, eidx;
    326 	int text_len = strlen(text), itext_len;
    327 
    328 	matches = matchend = NULL;
    329 
    330 	/* walk through all items */
    331 	for (it = items; it && it->text; ++it) {
    332 		if (text_len) {
    333 			itext_len = strlen(it->text);
    334 			pidx = 0; /* pointer */
    335 			sidx = eidx = -1; /* start of match, end of match */
    336 			/* walk through item text */
    337 			for (i = 0; i < itext_len && (c = it->text[i]); ++i) {
    338 				/* fuzzy match pattern */
    339 				if (!fstrncmp(&text[pidx], &c, 1)) {
    340 					if(sidx == -1)
    341 						sidx = i;
    342 					++pidx;
    343 					if (pidx == text_len) {
    344 						eidx = i;
    345 						break;
    346 					}
    347 				}
    348 			}
    349 			/* build list of matches */
    350 			if (eidx != -1) {
    351 				/* compute distance */
    352 				/* add penalty if match starts late (log(sidx+2))
    353 				 * add penalty for long a match without many matching characters */
    354 				it->distance = log(sidx + 2) + (double)(eidx - sidx - text_len);
    355 				/* fprintf(stderr, "distance %s %f\n", it->text, it->distance); */
    356 				appenditem(it, &matches, &matchend);
    357 				++number_of_matches;
    358 			}
    359 		} else {
    360 			appenditem(it, &matches, &matchend);
    361 		}
    362 	}
    363 
    364 	if (number_of_matches) {
    365 		/* initialize array with matches */
    366 		if (!(fuzzymatches = realloc(fuzzymatches,
    367 		                             number_of_matches * sizeof(struct item *))))
    368 			die("cannot realloc %u bytes:", number_of_matches * sizeof(struct item *));
    369 		for (i = 0, it = matches; it && i < number_of_matches; ++i, it = it->right)
    370 			fuzzymatches[i] = it;
    371 		/* sort matches according to distance */
    372 		qsort(fuzzymatches, number_of_matches, sizeof(struct item*), compare_distance);
    373 		/* rebuild list of matches */
    374 		matches = matchend = NULL;
    375 		for (i = 0, it = fuzzymatches[i]; i < number_of_matches && it &&
    376 		        it->text; ++i, it = fuzzymatches[i])
    377 			appenditem(it, &matches, &matchend);
    378 		free(fuzzymatches);
    379 	}
    380 	curr = sel = matches;
    381 	calcoffsets();
    382 }
    383 
    384 static void
    385 match(void)
    386 {
    387 	if (fuzzy) {
    388 		fuzzymatch();
    389 		return;
    390 	}
    391 	static char **tokv = NULL;
    392 	static int tokn = 0;
    393 
    394 	char buf[sizeof text], *s;
    395 	int i, tokc = 0;
    396 	size_t len, textsize;
    397 	struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
    398 
    399 	strcpy(buf, text);
    400 	/* separate input text into tokens to be matched individually */
    401 	for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
    402 		if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
    403 			die("cannot realloc %zu bytes:", tokn * sizeof *tokv);
    404 	len = tokc ? strlen(tokv[0]) : 0;
    405 
    406 	matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
    407 	textsize = strlen(text) + 1;
    408 	for (item = items; item && item->text; item++) {
    409 		for (i = 0; i < tokc; i++)
    410 			if (!fstrstr(item->text, tokv[i]))
    411 				break;
    412 		if (i != tokc) /* not all tokens match */
    413 			continue;
    414 		/* exact matches go first, then prefixes, then substrings */
    415 		if (!tokc || !fstrncmp(text, item->text, textsize))
    416 			appenditem(item, &matches, &matchend);
    417 		else if (!fstrncmp(tokv[0], item->text, len))
    418 			appenditem(item, &lprefix, &prefixend);
    419 		else
    420 			appenditem(item, &lsubstr, &substrend);
    421 	}
    422 	if (lprefix) {
    423 		if (matches) {
    424 			matchend->right = lprefix;
    425 			lprefix->left = matchend;
    426 		} else
    427 			matches = lprefix;
    428 		matchend = prefixend;
    429 	}
    430 	if (lsubstr) {
    431 		if (matches) {
    432 			matchend->right = lsubstr;
    433 			lsubstr->left = matchend;
    434 		} else
    435 			matches = lsubstr;
    436 		matchend = substrend;
    437 	}
    438 	curr = sel = matches;
    439 	calcoffsets();
    440 }
    441 
    442 static void
    443 insert(const char *str, ssize_t n)
    444 {
    445 	if (strlen(text) + n > sizeof text - 1)
    446 		return;
    447 	/* move existing text out of the way, insert new text, and update cursor */
    448 	memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
    449 	if (n > 0)
    450 		memcpy(&text[cursor], str, n);
    451 	cursor += n;
    452 	match();
    453 }
    454 
    455 static size_t
    456 nextrune(int inc)
    457 {
    458 	ssize_t n;
    459 
    460 	/* return location of next utf8 rune in the given direction (+1 or -1) */
    461 	for (n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc)
    462 		;
    463 	return n;
    464 }
    465 
    466 static void
    467 movewordedge(int dir)
    468 {
    469 	if (dir < 0) { /* move cursor to the start of the word*/
    470 		while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
    471 			cursor = nextrune(-1);
    472 		while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
    473 			cursor = nextrune(-1);
    474 	} else { /* move cursor to the end of the word */
    475 		while (text[cursor] && strchr(worddelimiters, text[cursor]))
    476 			cursor = nextrune(+1);
    477 		while (text[cursor] && !strchr(worddelimiters, text[cursor]))
    478 			cursor = nextrune(+1);
    479 	}
    480 }
    481 
    482 static void
    483 vi_keypress(KeySym ksym, const XKeyEvent *ev)
    484 {
    485 	static const size_t quit_len = LENGTH(quit_keys);
    486 	if (ev->state & ControlMask) {
    487 		switch(ksym) {
    488 		/* movement */
    489 		case XK_d: /* fallthrough */
    490 			if (next) {
    491 				sel = curr = next;
    492 				calcoffsets();
    493 				goto draw;
    494 			} else
    495 				ksym = XK_G;
    496 			break;
    497 		case XK_u:
    498 			if (prev) {
    499 				sel = curr = prev;
    500 				calcoffsets();
    501 				goto draw;
    502 			} else
    503 				ksym = XK_g;
    504 			break;
    505 		case XK_p: /* fallthrough */
    506 		case XK_P: break;
    507 		case XK_c:
    508 			cleanup();
    509 			exit(1);
    510 		case XK_Return: /* fallthrough */
    511 		case XK_KP_Enter: break;
    512 		default: return;
    513 		}
    514 	}
    515 
    516 	switch(ksym) {
    517 	/* movement */
    518 	case XK_0:
    519 		cursor = 0;
    520 		break;
    521 	case XK_dollar:
    522 		if (text[cursor + 1] != '\0') {
    523 			cursor = strlen(text) - 1;
    524 			break;
    525 		}
    526 		break;
    527 	case XK_b:
    528 		movewordedge(-1);
    529 		break;
    530 	case XK_e:
    531 		cursor = nextrune(+1);
    532 		movewordedge(+1);
    533 		if (text[cursor] == '\0')
    534 			--cursor;
    535 		else
    536 			cursor = nextrune(-1);
    537 		break;
    538 	case XK_g:
    539 		if (sel == matches) {
    540 			break;
    541 		}
    542 		sel = curr = matches;
    543 		calcoffsets();
    544 		break;
    545 	case XK_G:
    546 		if (next) {
    547 			/* jump to end of list and position items in reverse */
    548 			curr = matchend;
    549 			calcoffsets();
    550 			curr = prev;
    551 			calcoffsets();
    552 			while (next && (curr = curr->right))
    553 				calcoffsets();
    554 		}
    555 		sel = matchend;
    556 		break;
    557 	case XK_h:
    558 		if (cursor)
    559 			cursor = nextrune(-1);
    560 		break;
    561 	case XK_j:
    562 		if (sel && sel->right && (sel = sel->right) == next) {
    563 			curr = next;
    564 			calcoffsets();
    565 		}
    566 		break;
    567 	case XK_k:
    568 		if (sel && sel->left && (sel = sel->left)->right == curr) {
    569 			curr = prev;
    570 			calcoffsets();
    571 		}
    572 		break;
    573 	case XK_l:
    574 		if (text[cursor] != '\0' && text[cursor + 1] != '\0')
    575 			cursor = nextrune(+1);
    576 		else if (text[cursor] == '\0' && cursor)
    577 			--cursor;
    578 		break;
    579 	case XK_w:
    580 		movewordedge(+1);
    581 		if (text[cursor] != '\0' && text[cursor + 1] != '\0')
    582 			cursor = nextrune(+1);
    583 		else if (cursor)
    584 			--cursor;
    585 		break;
    586 	/* insertion */
    587 	case XK_a:
    588 		cursor = nextrune(+1);
    589 		/* fallthrough */
    590 	case XK_i:
    591 		using_vi_mode = 0;
    592 		break;
    593 	case XK_A:
    594 		if (text[cursor] != '\0')
    595 			cursor = strlen(text);
    596 		using_vi_mode = 0;
    597 		break;
    598 	case XK_I:
    599 		cursor = using_vi_mode = 0;
    600 		break;
    601 	case XK_p:
    602 		if (text[cursor] != '\0')
    603 			cursor = nextrune(+1);
    604 		XConvertSelection(dpy, (ev->state & ControlMask) ? clip : XA_PRIMARY,
    605 							utf8, utf8, win, CurrentTime);
    606 		return;
    607 	case XK_P:
    608 		XConvertSelection(dpy, (ev->state & ControlMask) ? clip : XA_PRIMARY,
    609 							utf8, utf8, win, CurrentTime);
    610 		return;
    611 	/* deletion */
    612 	case XK_D:
    613 		text[cursor] = '\0';
    614 		if (cursor)
    615 			cursor = nextrune(-1);
    616 		match();
    617 		break;
    618 	case XK_x:
    619 		cursor = nextrune(+1);
    620 		insert(NULL, nextrune(-1) - cursor);
    621 		if (text[cursor] == '\0' && text[0] != '\0')
    622 			--cursor;
    623 		match();
    624 		break;
    625 	/* misc. */
    626 	case XK_Return:
    627 	case XK_KP_Enter:
    628 		puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
    629 		if (!(ev->state & ControlMask)) {
    630 			cleanup();
    631 			exit(0);
    632 		}
    633 		if (sel)
    634 			sel->out = 1;
    635 		break;
    636 	case XK_Tab:
    637 		if (!sel)
    638 			return;
    639 		strncpy(text, sel->text, sizeof text - 1);
    640 		text[sizeof text - 1] = '\0';
    641 		cursor = strlen(text) - 1;
    642 		match();
    643 		break;
    644 	default:
    645 		for (size_t i = 0; i < quit_len; ++i)
    646 			if (quit_keys[i].ksym == ksym &&
    647 				(quit_keys[i].state & ev->state) == quit_keys[i].state) {
    648 				cleanup();
    649 				exit(1);
    650 			}
    651 	}
    652 
    653 draw:
    654 	drawmenu();
    655 }
    656 
    657 static void pressedEnter(XKeyEvent *ev, int retsig, int forceExit) {
    658 	if (print_index) {
    659 		printf("%d\n", sel->index);
    660 	} else {
    661 		if (sel) {
    662 			puts(sel->text);
    663 		} else if (printAnyway) {
    664 			puts(text);
    665 		}
    666 	}
    667 		//puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
    668 
    669 	if (forceExit || !(ev->state & ControlMask)) {
    670 		cleanup();
    671 		exit(retsig);
    672 	}
    673 	if (sel)
    674 		sel->out = 1;
    675 }
    676 
    677 static void
    678 keypress(XKeyEvent *ev)
    679 {
    680 	char buf[64];
    681 	int len;
    682 	KeySym ksym = NoSymbol;
    683 	Status status;
    684 
    685 	len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
    686 	switch (status) {
    687 	default: /* XLookupNone, XBufferOverflow */
    688 		return;
    689 	case XLookupChars: /* composed string from input method */
    690 		goto insert;
    691 	case XLookupKeySym:
    692 	case XLookupBoth: /* a KeySym and a string are returned: use keysym */
    693 		break;
    694 	}
    695 
    696 	if (using_vi_mode) {
    697 		vi_keypress(ksym, ev);
    698 		return;
    699 	} else if (vi_mode &&
    700 			   (ksym == global_esc.ksym &&
    701 				(ev->state & global_esc.state) == global_esc.state)) {
    702 		using_vi_mode = 1;
    703 		if (cursor)
    704 			cursor = nextrune(-1);
    705 		goto draw;
    706 	}
    707 
    708 	if (ev->state & ControlMask) {
    709 		switch(ksym) {
    710 		case XK_a:
    711 			pressedEnter(ev, 11, True);
    712 			return;
    713 		case XK_b: ksym = XK_Left;      break;
    714 		case XK_c: ksym = XK_Escape;    break;
    715 		case XK_d: ksym = XK_Delete;    break;
    716 		case XK_e: ksym = XK_End;       break;
    717 		case XK_f: ksym = XK_Right;     break;
    718 		case XK_g: ksym = XK_Escape;    break;
    719 		case XK_h: ksym = XK_BackSpace; break;
    720 		case XK_i: ksym = XK_Tab;       break;
    721 		case XK_j: /* fallthrough */
    722 		case XK_J: /* fallthrough */
    723 		case XK_m: /* fallthrough */
    724 		case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
    725 		case XK_n: ksym = XK_Down;      break;
    726 		case XK_p: ksym = XK_Up;        break;
    727 
    728 		case XK_k: /* delete right */
    729 			text[cursor] = '\0';
    730 			match();
    731 			break;
    732 		case XK_u: /* delete left */
    733 			insert(NULL, 0 - cursor);
    734 			break;
    735 		case XK_w: /* delete word */
    736 			pressedEnter(ev, 12, True);
    737 			return;
    738 			/* while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
    739 				insert(NULL, nextrune(-1) - cursor);
    740 			while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
    741 				insert(NULL, nextrune(-1) - cursor);
    742 			break; */
    743 		case XK_y: /* paste selection */
    744 		case XK_Y:
    745 			XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
    746 			                  utf8, utf8, win, CurrentTime);
    747 			return;
    748 		case XK_Left:
    749 		case XK_KP_Left:
    750 			movewordedge(-1);
    751 			goto draw;
    752 		case XK_Right:
    753 		case XK_KP_Right:
    754 			movewordedge(+1);
    755 			goto draw;
    756 		case XK_Return:
    757 		case XK_KP_Enter:
    758 			break;
    759 		case XK_bracketleft:
    760 			cleanup();
    761 			exit(1);
    762 		default:
    763 			return;
    764 		}
    765 	} else if (ev->state & Mod1Mask) {
    766 		switch(ksym) {
    767 		case XK_b:
    768 			movewordedge(-1);
    769 			goto draw;
    770 		case XK_f:
    771 			movewordedge(+1);
    772 			goto draw;
    773 		case XK_g: ksym = XK_Home;  break;
    774 		case XK_G: ksym = XK_End;   break;
    775 		case XK_h: ksym = XK_Up;    break;
    776 		case XK_j: ksym = XK_Next;  break;
    777 		case XK_k: ksym = XK_Prior; break;
    778 		case XK_l: ksym = XK_Down;  break;
    779 		default:
    780 			return;
    781 		}
    782 	}
    783 
    784 	switch(ksym) {
    785 	default:
    786 insert:
    787 		if (!iscntrl((unsigned char)*buf))
    788 			insert(buf, len);
    789 		break;
    790 	case XK_Delete:
    791 	case XK_KP_Delete:
    792 		if (text[cursor] == '\0')
    793 			return;
    794 		cursor = nextrune(+1);
    795 		/* fallthrough */
    796 	case XK_BackSpace:
    797 		if (cursor == 0)
    798 			return;
    799 		insert(NULL, nextrune(-1) - cursor);
    800 		break;
    801 	case XK_End:
    802 	case XK_KP_End:
    803 		if (text[cursor] != '\0') {
    804 			cursor = strlen(text);
    805 			break;
    806 		}
    807 		if (next) {
    808 			/* jump to end of list and position items in reverse */
    809 			curr = matchend;
    810 			calcoffsets();
    811 			curr = prev;
    812 			calcoffsets();
    813 			while (next && (curr = curr->right))
    814 				calcoffsets();
    815 		}
    816 		sel = matchend;
    817 		break;
    818 	case XK_Escape:
    819 		cleanup();
    820 		exit(1);
    821 	case XK_Home:
    822 	case XK_KP_Home:
    823 		if (sel == matches) {
    824 			cursor = 0;
    825 			break;
    826 		}
    827 		sel = curr = matches;
    828 		calcoffsets();
    829 		break;
    830 	case XK_Left:
    831 	case XK_KP_Left:
    832 		if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
    833 			cursor = nextrune(-1);
    834 			break;
    835 		}
    836 		if (lines > 0)
    837 			return;
    838 		/* fallthrough */
    839 	case XK_Up:
    840 	case XK_KP_Up:
    841 		if (sel && sel->left && (sel = sel->left)->right == curr) {
    842 			curr = prev;
    843 			calcoffsets();
    844 		}
    845 		break;
    846 	case XK_Next:
    847 	case XK_KP_Next:
    848 		if (!next)
    849 			return;
    850 		sel = curr = next;
    851 		calcoffsets();
    852 		break;
    853 	case XK_Prior:
    854 	case XK_KP_Prior:
    855 		if (!prev)
    856 			return;
    857 		sel = curr = prev;
    858 		calcoffsets();
    859 		break;
    860 	case XK_Return:
    861 	case XK_KP_Enter:
    862 		pressedEnter(ev, 0, False);
    863 		break;
    864 	case XK_Right:
    865 	case XK_KP_Right:
    866 		if (text[cursor] != '\0') {
    867 			cursor = nextrune(+1);
    868 			break;
    869 		}
    870 		if (lines > 0)
    871 			return;
    872 		/* fallthrough */
    873 	case XK_Down:
    874 	case XK_KP_Down:
    875 		if (sel && sel->right && (sel = sel->right) == next) {
    876 			curr = next;
    877 			calcoffsets();
    878 		}
    879 		break;
    880 	case XK_Tab:
    881 		if (!sel)
    882 			return;
    883 		cursor = strnlen(sel->text, sizeof text - 1);
    884 		memcpy(text, sel->text, cursor);
    885 		text[cursor] = '\0';
    886 		match();
    887 		break;
    888 	}
    889 
    890 draw:
    891 	drawmenu();
    892 }
    893 
    894 static void
    895 paste(void)
    896 {
    897 	char *p, *q;
    898 	int di;
    899 	unsigned long dl;
    900 	Atom da;
    901 
    902 	/* we have been given the current selection, now insert it into input */
    903 	if (XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
    904 	                   utf8, &da, &di, &dl, &dl, (unsigned char **)&p)
    905 	    == Success && p) {
    906 		insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
    907 		XFree(p);
    908 	}
    909 	if (using_vi_mode && text[cursor] == '\0')
    910 		--cursor;
    911 	drawmenu();
    912 }
    913 
    914 static void
    915 readstdin(void)
    916 {
    917 	char *line = NULL;
    918 	size_t i, itemsiz = 0, linesiz = 0;
    919 	ssize_t len;
    920 
    921 	/* read each line from stdin and add it to the item list */
    922 	for (i = 0; (len = getline(&line, &linesiz, stdin)) != -1; i++) {
    923 		if (i + 1 >= itemsiz) {
    924 			itemsiz += 256;
    925 			if (!(items = realloc(items, itemsiz * sizeof(*items))))
    926 				die("cannot realloc %zu bytes:", itemsiz * sizeof(*items));
    927 		}
    928 		if (line[len - 1] == '\n')
    929 			line[len - 1] = '\0';
    930 		if (!(items[i].text = strdup(line)))
    931 			die("strdup:");
    932 		items[i].width = TEXTW(line);
    933 
    934 		items[i].out = 0;
    935 		items[i].index = i;
    936 	}
    937 	free(line);
    938 	if (items)
    939 		items[i].text = NULL;
    940 	lines = MIN(lines, i);
    941 }
    942 
    943 static void
    944 run(void)
    945 {
    946 	XEvent ev;
    947 
    948 	while (!XNextEvent(dpy, &ev)) {
    949 		if (XFilterEvent(&ev, win))
    950 			continue;
    951 		switch(ev.type) {
    952 		case DestroyNotify:
    953 			if (ev.xdestroywindow.window != win)
    954 				break;
    955 			cleanup();
    956 			exit(1);
    957 		case Expose:
    958 			if (ev.xexpose.count == 0)
    959 				drw_map(drw, win, 0, 0, mw, mh);
    960 			break;
    961 		case FocusIn:
    962 			/* regrab focus from parent window */
    963 			if (ev.xfocus.window != win)
    964 				grabfocus();
    965 			break;
    966 		case KeyPress:
    967 			keypress(&ev.xkey);
    968 			break;
    969 		case SelectionNotify:
    970 			if (ev.xselection.property == utf8)
    971 				paste();
    972 			break;
    973 		case VisibilityNotify:
    974 			if (ev.xvisibility.state != VisibilityUnobscured)
    975 				XRaiseWindow(dpy, win);
    976 			break;
    977 		}
    978 	}
    979 }
    980 
    981 static void
    982 setup(void)
    983 {
    984 	int x, y, i, j;
    985 	unsigned int du;
    986 	XSetWindowAttributes swa;
    987 	XIM xim;
    988 	Window w, dw, *dws;
    989 	XWindowAttributes wa;
    990 	XClassHint ch = {"dmenu", "dmenu"};
    991 #ifdef XINERAMA
    992 	XineramaScreenInfo *info;
    993 	Window pw;
    994 	int a, di, n, area = 0;
    995 #endif
    996 	/* init appearance */
    997 	for (j = 0; j < SchemeLast; j++)
    998 		scheme[j] = drw_scm_create(drw, colors[j], 2);
    999 
   1000 	clip = XInternAtom(dpy, "CLIPBOARD",   False);
   1001 	utf8 = XInternAtom(dpy, "UTF8_STRING", False);
   1002 
   1003 	/* calculate menu geometry */
   1004 	bh = drw->fonts->h + vertpadbar;
   1005 	lines = MAX(lines, 0);
   1006 	mh = (lines + 1) * bh;
   1007 	promptw = (prompt && *prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
   1008 #ifdef XINERAMA
   1009 	i = 0;
   1010 	if (parentwin == root && (info = XineramaQueryScreens(dpy, &n))) {
   1011 		XGetInputFocus(dpy, &w, &di);
   1012 		if (mon >= 0 && mon < n)
   1013 			i = mon;
   1014 		else if (w != root && w != PointerRoot && w != None) {
   1015 			/* find top-level window containing current input focus */
   1016 			do {
   1017 				if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
   1018 					XFree(dws);
   1019 			} while (w != root && w != pw);
   1020 			/* find xinerama screen with which the window intersects most */
   1021 			if (XGetWindowAttributes(dpy, pw, &wa))
   1022 				for (j = 0; j < n; j++)
   1023 					if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
   1024 						area = a;
   1025 						i = j;
   1026 					}
   1027 		}
   1028 		/* no focused window is on screen, so use pointer location instead */
   1029 		if (mon < 0 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
   1030 			for (i = 0; i < n; i++)
   1031 				if (INTERSECT(x, y, 1, 1, info[i]) != 0)
   1032 					break;
   1033 
   1034 		if (centered) {
   1035 			mw = MIN(MAX(max_textw() + promptw, min_width), info[i].width);
   1036 			x = info[i].x_org + ((info[i].width  - mw) / 2);
   1037 			y = info[i].y_org + ((info[i].height - mh) / menu_height_ratio);
   1038 		} else {
   1039 			x = info[i].x_org;
   1040 			y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
   1041 			mw = info[i].width;
   1042 		}
   1043 
   1044 		XFree(info);
   1045 	} else
   1046 #endif
   1047 	{
   1048 		if (!XGetWindowAttributes(dpy, parentwin, &wa))
   1049 			die("could not get embedding window attributes: 0x%lx",
   1050 			    parentwin);
   1051 
   1052 		if (centered) {
   1053 			mw = MIN(MAX(max_textw() + promptw, min_width), wa.width);
   1054 			x = (wa.width  - mw) / 2;
   1055 			y = (wa.height - mh) / 2;
   1056 		} else {
   1057 			x = 0;
   1058 			y = topbar ? 0 : wa.height - mh;
   1059 			mw = wa.width;
   1060 		}
   1061 	}
   1062 	promptw = (prompt && *prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
   1063 	inputw = mw / 3; /* input width: ~33% of monitor width */
   1064 	match();
   1065 
   1066 	/* create menu window */
   1067 	swa.override_redirect = True;
   1068 	swa.background_pixel = scheme[SchemeNorm][ColBg].pixel;
   1069 	swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
   1070 	win = XCreateWindow(dpy, root, x, y, mw, mh, border_width,
   1071 	                    CopyFromParent, CopyFromParent, CopyFromParent,
   1072 	                    CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
   1073 	if (border_width)
   1074 		XSetWindowBorder(dpy, win, scheme[SchemeBorder][ColBg].pixel);
   1075 	XSetClassHint(dpy, win, &ch);
   1076 
   1077 	/* input methods */
   1078 	if ((xim = XOpenIM(dpy, NULL, NULL, NULL)) == NULL)
   1079 		die("XOpenIM failed: could not open input device");
   1080 
   1081 	xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
   1082 	                XNClientWindow, win, XNFocusWindow, win, NULL);
   1083 
   1084 	XMapRaised(dpy, win);
   1085 	if (embed) {
   1086 		XReparentWindow(dpy, win, parentwin, x, y);
   1087 		XSelectInput(dpy, parentwin, FocusChangeMask | SubstructureNotifyMask);
   1088 		if (XQueryTree(dpy, parentwin, &dw, &w, &dws, &du) && dws) {
   1089 			for (i = 0; i < du && dws[i] != win; ++i)
   1090 				XSelectInput(dpy, dws[i], FocusChangeMask);
   1091 			XFree(dws);
   1092 		}
   1093 		grabfocus();
   1094 	}
   1095 	drw_resize(drw, mw, mh);
   1096 	drawmenu();
   1097 }
   1098 
   1099 static void
   1100 usage(void)
   1101 {
   1102 	die("usage: dmenu [-bFfiv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
   1103 	    "             [-nb color] [-nf color] [-sb color] [-sf color]\n"
   1104 	    "             [-nhb color] [-nhf color] [-shb color] [-shf color] [-w windowid]");
   1105 }
   1106 
   1107 int
   1108 main(int argc, char *argv[])
   1109 {
   1110 	XWindowAttributes wa;
   1111 	int i, fast = 0;
   1112 
   1113 	for (i = 1; i < argc; i++)
   1114 		/* these options take no arguments */
   1115 		if (!strcmp(argv[i], "-v")) {      /* prints version information */
   1116 			puts("dmenu-"VERSION);
   1117 			exit(0);
   1118 		} else if (!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
   1119 			topbar = 0;
   1120 		else if (!strcmp(argv[i], "-F"))   /* disables fuzzy matching */
   1121 			fuzzy = 0;
   1122 		else if (!strcmp(argv[i], "-f"))   /* grabs keyboard before reading stdin */
   1123 			fast = 1;
   1124 		else if (!strcmp(argv[i], "-c"))   /* centers dmenu on screen */
   1125 			centered = 1;
   1126 		else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
   1127 			fstrncmp = strncasecmp;
   1128 			fstrstr = cistrstr;
   1129 		} else if (!strcmp(argv[i], "-vi")) {
   1130 			vi_mode = 1;
   1131 			using_vi_mode = start_mode;
   1132 			global_esc.ksym = XK_Escape;
   1133 			global_esc.state = 0;
   1134 		} else if (!strcmp(argv[i], "-ix"))  /* adds ability to return index in list */
   1135 			print_index = 1;
   1136 		else if (i + 1 == argc)
   1137 			usage();
   1138 		/* these options take one argument */
   1139 		else if (!strcmp(argv[i], "-l"))   /* number of lines in vertical list */
   1140 			lines = atoi(argv[++i]);
   1141 		else if (!strcmp(argv[i], "-m"))
   1142 			mon = atoi(argv[++i]);
   1143 		else if (!strcmp(argv[i], "-p"))   /* adds prompt to left of input field */
   1144 			prompt = argv[++i];
   1145 		else if (!strcmp(argv[i], "-pa"))   /* print anyway, i.e. if no match, print inputted text */
   1146 			printAnyway = True;
   1147 		else if (!strcmp(argv[i], "-fn"))  /* font or font set */
   1148 			fonts[0] = argv[++i];
   1149 		else if (!strcmp(argv[i], "-nb"))  /* normal background color */
   1150 			colors[SchemeNorm][ColBg] = argv[++i];
   1151 		else if (!strcmp(argv[i], "-nf"))  /* normal foreground color */
   1152 			colors[SchemeNorm][ColFg] = argv[++i];
   1153 		else if (!strcmp(argv[i], "-sb"))  /* selected background color */
   1154 			colors[SchemeSel][ColBg] = argv[++i];
   1155 		else if (!strcmp(argv[i], "-sf"))  /* selected foreground color */
   1156 			colors[SchemeSel][ColFg] = argv[++i];
   1157 		else if (!strcmp(argv[i], "-nhb")) /* normal hi background color */
   1158 			colors[SchemeNormHighlight][ColBg] = argv[++i];
   1159 		else if (!strcmp(argv[i], "-nhf")) /* normal hi foreground color */
   1160 			colors[SchemeNormHighlight][ColFg] = argv[++i];
   1161 		else if (!strcmp(argv[i], "-shb")) /* selected hi background color */
   1162 			colors[SchemeSelHighlight][ColBg] = argv[++i];
   1163 		else if (!strcmp(argv[i], "-shf")) /* selected hi foreground color */
   1164 			colors[SchemeSelHighlight][ColFg] = argv[++i];
   1165 		else if (!strcmp(argv[i], "-ob"))  /* outline background color */
   1166 			colors[SchemeOut][ColBg] = argv[++i];
   1167 		else if (!strcmp(argv[i], "-of"))  /* outline foreground color */
   1168 			colors[SchemeOut][ColFg] = argv[++i];
   1169 		else if (!strcmp(argv[i], "-pb"))  /* prompt background color */
   1170 			colors[SchemePrompt][ColBg] = argv[++i];
   1171 		else if (!strcmp(argv[i], "-pf"))  /* prompt foreground color */
   1172 			colors[SchemePrompt][ColFg] = argv[++i];
   1173 		else if (!strcmp(argv[i], "-bb"))  /* border color */
   1174 			colors[SchemeBorder][ColBg] = argv[++i];
   1175 		else if (!strcmp(argv[i], "-w"))   /* embedding window id */
   1176 			embed = argv[++i];
   1177 		else if (!strcmp(argv[i], "-bw"))
   1178 			border_width = atoi(argv[++i]); /* border width */
   1179 		else
   1180 			usage();
   1181 
   1182 	if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
   1183 		fputs("warning: no locale support\n", stderr);
   1184 	if (!(dpy = XOpenDisplay(NULL)))
   1185 		die("cannot open display");
   1186 	screen = DefaultScreen(dpy);
   1187 	root = RootWindow(dpy, screen);
   1188 	if (!embed || !(parentwin = strtol(embed, NULL, 0)))
   1189 		parentwin = root;
   1190 	if (!XGetWindowAttributes(dpy, parentwin, &wa))
   1191 		die("could not get embedding window attributes: 0x%lx",
   1192 		    parentwin);
   1193 	drw = drw_create(dpy, screen, root, wa.width, wa.height);
   1194 	if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
   1195 		die("no fonts could be loaded.");
   1196 	lrpad = drw->fonts->h + horizpadbar;
   1197 
   1198 #ifdef __OpenBSD__
   1199 	if (pledge("stdio rpath", NULL) == -1)
   1200 		die("pledge");
   1201 #endif
   1202 
   1203 	if (fast && !isatty(0)) {
   1204 		grabkeyboard();
   1205 		readstdin();
   1206 	} else {
   1207 		readstdin();
   1208 		grabkeyboard();
   1209 	}
   1210 	setup();
   1211 	run();
   1212 
   1213 	return 1; /* unreachable */
   1214 }