birdmenu

mrgrouse's dmenu - a dmenu fork by the bird
Log | Files | Refs | README | LICENSE

birdmenu.c (25104B)


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