dmenu

my build of dmenu
git clone git://git.ckyln.com/~cem/dmenu.git
Log | Files | Refs | README | LICENSE

dmenu.c (24366B)


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