[download]

local/src/dmenu/dmenu.c

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