dmenu

git clone git://mattcarlson.org/repos/dmenu.git
Log | Files | Refs

dmenu.c (26460B)


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