[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 PATCH_NUMBERS /* {{{ */
  38 #define NUMBERSMAXDIGITS      100
  39 #define NUMBERSBUFSIZE        (NUMBERSMAXDIGITS * 2) + 1
  40 static char numbers[NUMBERSBUFSIZE] = "";
  41 static void recalculatenumbers();
  42 #endif /* }}} */
  43 #if PATCH_MOUSE_SUPPORT /* {{{ */
  44 static void buttonpress(XEvent *e);
  45 #endif /* }}} */
  46 
  47 static char text[BUFSIZ] = "";
  48 static char *embed;
  49 static int bh, mw, mh;
  50 static int inputw = 0, promptw;
  51 static int lrpad; /* sum of left and right padding */
  52 static size_t cursor;
  53 static struct item *items = NULL;
  54 static struct item *matches, *matchend;
  55 static struct item *prev, *curr, *next, *sel;
  56 static int mon = -1, screen;
  57 
  58 static Atom clip, utf8;
  59 static Display *dpy;
  60 static Window root, parentwin, win;
  61 static XIC xic;
  62 
  63 static Drw *drw;
  64 static Clr *scheme[SchemeLast];
  65 
  66 #include "config.h"
  67 
  68 static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
  69 static char *(*fstrstr)(const char *, const char *) = strstr;
  70 
  71 static void
  72 appenditem(struct item *item, struct item **list, struct item **last)
  73 {
  74 	if (*last)
  75 		(*last)->right = item;
  76 	else
  77 		*list = item;
  78 
  79 	item->left = *last;
  80 	item->right = NULL;
  81 	*last = item;
  82 }
  83 
  84 static void
  85 calcoffsets(void)
  86 {
  87 	int i, n;
  88 
  89 	if (lines > 0)
  90 		n = lines * bh;
  91 	else
  92 		n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">"));
  93 	/* calculate which items will begin the next page and previous page */
  94 	for (i = 0, next = curr; next; next = next->right)
  95 		if ((i += (lines > 0) ? bh : MIN(TEXTW(next->text), n)) > n)
  96 			break;
  97 	for (i = 0, prev = curr; prev && prev->left; prev = prev->left)
  98 		if ((i += (lines > 0) ? bh : MIN(TEXTW(prev->left->text), n)) > n)
  99 			break;
 100 }
 101 
 102 static void
 103 cleanup(void)
 104 {
 105 	size_t i;
 106 
 107 	XUngrabKey(dpy, AnyKey, AnyModifier, root);
 108 	for (i = 0; i < SchemeLast; i++)
 109 		free(scheme[i]);
 110 	drw_free(drw);
 111 	XSync(dpy, False);
 112 	XCloseDisplay(dpy);
 113 }
 114 
 115 static char *
 116 cistrstr(const char *s, const char *sub)
 117 {
 118 	size_t len;
 119 
 120 	for (len = strlen(sub); *s; s++)
 121 		if (!strncasecmp(s, sub, len))
 122 			return (char *)s;
 123 	return NULL;
 124 }
 125 
 126 static int
 127 drawitem(struct item *item, int x, int y, int w)
 128 {
 129 	if (item == sel)
 130 		drw_setscheme(drw, scheme[SchemeSel]);
 131 	else if (item->out)
 132 		drw_setscheme(drw, scheme[SchemeOut]);
 133 	else
 134 		drw_setscheme(drw, scheme[SchemeNorm]);
 135 
 136 	return drw_text(drw, x, y, w, bh, lrpad / 2, item->text, 0);
 137 }
 138 
 139 static void
 140 drawmenu(void)
 141 {
 142 	unsigned int curpos;
 143 	struct item *item;
 144 	int x = 0, y = 0, w;
 145 
 146 	drw_setscheme(drw, scheme[SchemeNorm]);
 147 	drw_rect(drw, 0, 0, mw, mh, 1, 1);
 148 
 149 	if (prompt && *prompt) {
 150 		drw_setscheme(drw, scheme[SchemeSel]);
 151 		x = drw_text(drw, x, 0, promptw, bh, lrpad / 2, prompt, 0);
 152 	}
 153 	/* draw input field */
 154 	w = (lines > 0 || !matches) ? mw - x : inputw;
 155 	drw_setscheme(drw, scheme[SchemeNorm]);
 156 	drw_text(drw, x, 0, w, bh, lrpad / 2, text, 0);
 157 
 158 	curpos = TEXTW(text) - TEXTW(&text[cursor]);
 159 	if ((curpos += lrpad / 2 - 1) < w) {
 160 		drw_setscheme(drw, scheme[SchemeNorm]);
 161 		drw_rect(drw, x + curpos, 2, 2, bh - 4, 1, 0);
 162 	}
 163 
 164 #if PATCH_NUMBERS /* {{{ */
 165 	recalculatenumbers();
 166 #endif /* }}} */
 167 	if (lines > 0) {
 168 		/* draw vertical list */
 169 		for (item = curr; item != next; item = item->right)
 170 			drawitem(item, x, y += bh, mw - x);
 171 	} else if (matches) {
 172 		/* draw horizontal list */
 173 		x += inputw;
 174 		w = TEXTW("<");
 175 		if (curr->left) {
 176 			drw_setscheme(drw, scheme[SchemeNorm]);
 177 			drw_text(drw, x, 0, w, bh, lrpad / 2, "<", 0);
 178 		}
 179 		x += w;
 180 		for (item = curr; item != next; item = item->right)
 181 #if PATCH_NUMBERS /* {{{ */
 182 			x = drawitem(item, x, 0, MIN(TEXTW(item->text), mw - x - TEXTW(">") - TEXTW(numbers)));
 183 #else /* }}} */
 184 			x = drawitem(item, x, 0, MIN(TEXTW(item->text), mw - x - TEXTW(">")));
 185 #endif
 186 		if (next) {
 187 			w = TEXTW(">");
 188 			drw_setscheme(drw, scheme[SchemeNorm]);
 189 #if PATCH_NUMBERS /* {{{ */
 190 			drw_text(drw, mw - w - TEXTW(numbers), 0, w, bh, lrpad / 2, ">", 0);
 191 #else /* }}} */
 192 			drw_text(drw, mw - w, 0, w, bh, lrpad / 2, ">", 0);
 193 #endif
 194 		}
 195 	}
 196 #if PATCH_NUMBERS /* {{{ */
 197 	drw_setscheme(drw, scheme[SchemeNorm]);
 198 	drw_text(drw, mw - TEXTW(numbers), 0, TEXTW(numbers), bh, lrpad / 2, numbers, 0);
 199 #endif /* }}} */
 200 	drw_map(drw, win, 0, 0, mw, mh);
 201 }
 202 
 203 static void
 204 grabfocus(void)
 205 {
 206 	struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000  };
 207 	Window focuswin;
 208 	int i, revertwin;
 209 
 210 	for (i = 0; i < 100; ++i) {
 211 		XGetInputFocus(dpy, &focuswin, &revertwin);
 212 		if (focuswin == win)
 213 			return;
 214 		XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
 215 		nanosleep(&ts, NULL);
 216 	}
 217 	die("cannot grab focus");
 218 }
 219 
 220 static void
 221 grabkeyboard(void)
 222 {
 223 	struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000  };
 224 	int i;
 225 
 226 	if (embed)
 227 		return;
 228 	/* try to grab keyboard, we may have to wait for another process to ungrab */
 229 	for (i = 0; i < 1000; i++) {
 230 		if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync,
 231 		                  GrabModeAsync, CurrentTime) == GrabSuccess)
 232 			return;
 233 		nanosleep(&ts, NULL);
 234 	}
 235 	die("cannot grab keyboard");
 236 }
 237 
 238 static void
 239 match(void)
 240 {
 241 	static char **tokv = NULL;
 242 	static int tokn = 0;
 243 
 244 	char buf[sizeof text], *s;
 245 	int i, tokc = 0;
 246 	size_t len, textsize;
 247 	struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
 248 
 249 	strcpy(buf, text);
 250 	/* separate input text into tokens to be matched individually */
 251 	for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
 252 		if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
 253 			die("cannot realloc %u bytes:", tokn * sizeof *tokv);
 254 	len = tokc ? strlen(tokv[0]) : 0;
 255 
 256 	matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
 257 	textsize = strlen(text) + 1;
 258 	for (item = items; item && item->text; item++) {
 259 		for (i = 0; i < tokc; i++)
 260 			if (!fstrstr(item->text, tokv[i]))
 261 				break;
 262 		if (i != tokc) /* not all tokens match */
 263 			continue;
 264 		/* exact matches go first, then prefixes, then substrings */
 265 		if (!tokc || !fstrncmp(text, item->text, textsize))
 266 			appenditem(item, &matches, &matchend);
 267 		else if (!fstrncmp(tokv[0], item->text, len))
 268 			appenditem(item, &lprefix, &prefixend);
 269 		else
 270 			appenditem(item, &lsubstr, &substrend);
 271 	}
 272 	if (lprefix) {
 273 		if (matches) {
 274 			matchend->right = lprefix;
 275 			lprefix->left = matchend;
 276 		} else
 277 			matches = lprefix;
 278 		matchend = prefixend;
 279 	}
 280 	if (lsubstr) {
 281 		if (matches) {
 282 			matchend->right = lsubstr;
 283 			lsubstr->left = matchend;
 284 		} else
 285 			matches = lsubstr;
 286 		matchend = substrend;
 287 	}
 288 	curr = sel = matches;
 289 	calcoffsets();
 290 }
 291 
 292 static void
 293 insert(const char *str, ssize_t n)
 294 {
 295 	if (strlen(text) + n > sizeof text - 1)
 296 		return;
 297 	/* move existing text out of the way, insert new text, and update cursor */
 298 	memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
 299 	if (n > 0)
 300 		memcpy(&text[cursor], str, n);
 301 	cursor += n;
 302 	match();
 303 }
 304 
 305 static size_t
 306 nextrune(int inc)
 307 {
 308 	ssize_t n;
 309 
 310 	/* return location of next utf8 rune in the given direction (+1 or -1) */
 311 	for (n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc)
 312 		;
 313 	return n;
 314 }
 315 
 316 static void
 317 movewordedge(int dir)
 318 {
 319 	if (dir < 0) { /* move cursor to the start of the word*/
 320 		while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
 321 			cursor = nextrune(-1);
 322 		while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
 323 			cursor = nextrune(-1);
 324 	} else { /* move cursor to the end of the word */
 325 		while (text[cursor] && strchr(worddelimiters, text[cursor]))
 326 			cursor = nextrune(+1);
 327 		while (text[cursor] && !strchr(worddelimiters, text[cursor]))
 328 			cursor = nextrune(+1);
 329 	}
 330 }
 331 
 332 static void
 333 keypress(XKeyEvent *ev)
 334 {
 335 	char buf[32];
 336 	int len;
 337 	KeySym ksym;
 338 	Status status;
 339 
 340 	len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
 341 	switch (status) {
 342 	default: /* XLookupNone, XBufferOverflow */
 343 		return;
 344 	case XLookupChars:
 345 		goto insert;
 346 	case XLookupKeySym:
 347 	case XLookupBoth:
 348 		break;
 349 	}
 350 
 351 	if (ev->state & ControlMask) {
 352 		switch(ksym) {
 353 		case XK_a: ksym = XK_Home;      break;
 354 		case XK_b: ksym = XK_Left;      break;
 355 		case XK_c: ksym = XK_Escape;    break;
 356 		case XK_d: ksym = XK_Delete;    break;
 357 		case XK_e: ksym = XK_End;       break;
 358 		case XK_f: ksym = XK_Right;     break;
 359 		case XK_g: ksym = XK_Escape;    break;
 360 		case XK_h: ksym = XK_BackSpace; break;
 361 		case XK_i: ksym = XK_Tab;       break;
 362 		case XK_j: /* fallthrough */
 363 		case XK_J: /* fallthrough */
 364 		case XK_m: /* fallthrough */
 365 		case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
 366 		case XK_n: ksym = XK_Down;      break;
 367 		case XK_p: ksym = XK_Up;        break;
 368 
 369 		case XK_k: /* delete right */
 370 			text[cursor] = '\0';
 371 			match();
 372 			break;
 373 		case XK_u: /* delete left */
 374 			insert(NULL, 0 - cursor);
 375 			break;
 376 		case XK_w: /* delete word */
 377 			while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
 378 				insert(NULL, nextrune(-1) - cursor);
 379 			while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
 380 				insert(NULL, nextrune(-1) - cursor);
 381 			break;
 382 		case XK_y: /* paste selection */
 383 		case XK_Y:
 384 			XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
 385 			                  utf8, utf8, win, CurrentTime);
 386 			return;
 387 		case XK_Left:
 388 			movewordedge(-1);
 389 			goto draw;
 390 		case XK_Right:
 391 			movewordedge(+1);
 392 			goto draw;
 393 		case XK_Return:
 394 		case XK_KP_Enter:
 395 			break;
 396 		case XK_bracketleft:
 397 			cleanup();
 398 			exit(1);
 399 		default:
 400 			return;
 401 		}
 402 	} else if (ev->state & Mod1Mask) {
 403 		switch(ksym) {
 404 		case XK_b:
 405 			movewordedge(-1);
 406 			goto draw;
 407 		case XK_f:
 408 			movewordedge(+1);
 409 			goto draw;
 410 		case XK_g: ksym = XK_Home;  break;
 411 		case XK_G: ksym = XK_End;   break;
 412 		case XK_h: ksym = XK_Up;    break;
 413 		case XK_j: ksym = XK_Next;  break;
 414 		case XK_k: ksym = XK_Prior; break;
 415 		case XK_l: ksym = XK_Down;  break;
 416 		default:
 417 			return;
 418 		}
 419 	}
 420 
 421 	switch(ksym) {
 422 	default:
 423 insert:
 424 		if (!iscntrl(*buf))
 425 			insert(buf, len);
 426 		break;
 427 	case XK_Delete:
 428 		if (text[cursor] == '\0')
 429 			return;
 430 		cursor = nextrune(+1);
 431 		/* fallthrough */
 432 	case XK_BackSpace:
 433 		if (cursor == 0)
 434 			return;
 435 		insert(NULL, nextrune(-1) - cursor);
 436 		break;
 437 	case XK_End:
 438 		if (text[cursor] != '\0') {
 439 			cursor = strlen(text);
 440 			break;
 441 		}
 442 		if (next) {
 443 			/* jump to end of list and position items in reverse */
 444 			curr = matchend;
 445 			calcoffsets();
 446 			curr = prev;
 447 			calcoffsets();
 448 			while (next && (curr = curr->right))
 449 				calcoffsets();
 450 		}
 451 		sel = matchend;
 452 		break;
 453 	case XK_Escape:
 454 		cleanup();
 455 		exit(1);
 456 	case XK_Home:
 457 		if (sel == matches) {
 458 			cursor = 0;
 459 			break;
 460 		}
 461 		sel = curr = matches;
 462 		calcoffsets();
 463 		break;
 464 	case XK_Left:
 465 		if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
 466 			cursor = nextrune(-1);
 467 			break;
 468 		}
 469 		if (lines > 0)
 470 			return;
 471 		/* fallthrough */
 472 	case XK_Up:
 473 		if (sel && sel->left && (sel = sel->left)->right == curr) {
 474 			curr = prev;
 475 			calcoffsets();
 476 		}
 477 		break;
 478 	case XK_Next:
 479 		if (!next)
 480 			return;
 481 		sel = curr = next;
 482 		calcoffsets();
 483 		break;
 484 	case XK_Prior:
 485 		if (!prev)
 486 			return;
 487 		sel = curr = prev;
 488 		calcoffsets();
 489 		break;
 490 	case XK_Return:
 491 	case XK_KP_Enter:
 492 		puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
 493 		if (!(ev->state & ControlMask)) {
 494 			cleanup();
 495 			exit(0);
 496 		}
 497 		if (sel)
 498 			sel->out = 1;
 499 		break;
 500 	case XK_Right:
 501 		if (text[cursor] != '\0') {
 502 			cursor = nextrune(+1);
 503 			break;
 504 		}
 505 		if (lines > 0)
 506 			return;
 507 		/* fallthrough */
 508 	case XK_Down:
 509 		if (sel && sel->right && (sel = sel->right) == next) {
 510 			curr = next;
 511 			calcoffsets();
 512 		}
 513 		break;
 514 	case XK_Tab:
 515 		if (!sel)
 516 			return;
 517 		strncpy(text, sel->text, sizeof text - 1);
 518 		text[sizeof text - 1] = '\0';
 519 		cursor = strlen(text);
 520 		match();
 521 		break;
 522 	}
 523 
 524 draw:
 525 	drawmenu();
 526 }
 527 
 528 static void
 529 paste(void)
 530 {
 531 	char *p, *q;
 532 	int di;
 533 	unsigned long dl;
 534 	Atom da;
 535 
 536 	/* we have been given the current selection, now insert it into input */
 537 	if (XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
 538 	                   utf8, &da, &di, &dl, &dl, (unsigned char **)&p)
 539 	    == Success && p) {
 540 		insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
 541 		XFree(p);
 542 	}
 543 	drawmenu();
 544 }
 545 
 546 static void
 547 readstdin(void)
 548 {
 549 	char buf[sizeof text], *p;
 550 	size_t i, imax = 0, size = 0;
 551 	unsigned int tmpmax = 0;
 552 
 553 	/* read each line from stdin and add it to the item list */
 554 	for (i = 0; fgets(buf, sizeof buf, stdin); i++) {
 555 		if (i + 1 >= size / sizeof *items)
 556 			if (!(items = realloc(items, (size += BUFSIZ))))
 557 				die("cannot realloc %u bytes:", size);
 558 		if ((p = strchr(buf, '\n')))
 559 			*p = '\0';
 560 		if (!(items[i].text = strdup(buf)))
 561 			die("cannot strdup %u bytes:", strlen(buf) + 1);
 562 		items[i].out = 0;
 563 		drw_font_getexts(drw->fonts, buf, strlen(buf), &tmpmax, NULL);
 564 		if (tmpmax > inputw) {
 565 			inputw = tmpmax;
 566 			imax = i;
 567 		}
 568 	}
 569 	if (items)
 570 		items[i].text = NULL;
 571 	inputw = items ? TEXTW(items[imax].text) : 0;
 572 	lines = MIN(lines, i);
 573 }
 574 
 575 static void
 576 run(void)
 577 {
 578 	XEvent ev;
 579 
 580 	while (!XNextEvent(dpy, &ev)) {
 581 		if (XFilterEvent(&ev, win))
 582 			continue;
 583 		switch(ev.type) {
 584 		case DestroyNotify:
 585 			if (ev.xdestroywindow.window != win)
 586 				break;
 587 			cleanup();
 588 			exit(1);
 589 #if PATCH_MOUSE_SUPPORT /* {{{ */
 590 		case ButtonPress:
 591 			buttonpress(&ev);
 592 			break;
 593 #endif /* }}} */
 594 		case Expose:
 595 			if (ev.xexpose.count == 0)
 596 				drw_map(drw, win, 0, 0, mw, mh);
 597 			break;
 598 		case FocusIn:
 599 			/* regrab focus from parent window */
 600 			if (ev.xfocus.window != win)
 601 				grabfocus();
 602 			break;
 603 		case KeyPress:
 604 			keypress(&ev.xkey);
 605 			break;
 606 		case SelectionNotify:
 607 			if (ev.xselection.property == utf8)
 608 				paste();
 609 			break;
 610 		case VisibilityNotify:
 611 			if (ev.xvisibility.state != VisibilityUnobscured)
 612 				XRaiseWindow(dpy, win);
 613 			break;
 614 		}
 615 	}
 616 }
 617 
 618 static void
 619 setup(void)
 620 {
 621 	int x, y, i, j;
 622 	unsigned int du;
 623 	XSetWindowAttributes swa;
 624 	XIM xim;
 625 	Window w, dw, *dws;
 626 	XWindowAttributes wa;
 627 	XClassHint ch = {"dmenu", "dmenu"};
 628 #ifdef XINERAMA
 629 	XineramaScreenInfo *info;
 630 	Window pw;
 631 	int a, di, n, area = 0;
 632 #endif
 633 	/* init appearance */
 634 	for (j = 0; j < SchemeLast; j++)
 635 		scheme[j] = drw_scm_create(drw, colors[j], 2);
 636 
 637 	clip = XInternAtom(dpy, "CLIPBOARD",   False);
 638 	utf8 = XInternAtom(dpy, "UTF8_STRING", False);
 639 
 640 	/* calculate menu geometry */
 641 #if BARHEIGHT /* {{{ */
 642 	bh = BARHEIGHT;
 643 #else /* }}} */
 644 	bh = drw->fonts->h + 2;
 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 PATCH_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 PATCH_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 #if PATCH_MOUSE_SUPPORT /* {{{ */
 827 static void
 828 buttonpress(XEvent *e)
 829 {
 830 	struct item *item;
 831 	XButtonPressedEvent *ev = &e->xbutton;
 832 	int x = 0, y = 0, h = bh, w;
 833 	static int xx = 0, yy = 0;
 834 
 835 	if (ev->window != win)
 836 		return;
 837 
 838 	if (prompt && *prompt)
 839 		x += promptw;
 840 
 841 	/* input field */
 842 	w = (lines > 0 || !matches) ? mw - x : inputw;
 843 
 844 	/* middle-mouse click: paste selection */
 845 	if (ev->button == Button2) {
 846 		XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY, utf8, utf8, win, CurrentTime);
 847 		drawmenu();
 848 		return;
 849 	}
 850 	/* scroll up */
 851 	if (ev->button == Button4) {
 852 		if (sel && sel->left && (sel = sel->left)->right == curr) curr = prev;
 853 		calcoffsets();
 854 		drawmenu();
 855 		return;
 856 	}
 857 	/* scroll down */
 858 	if (ev->button == Button5) {
 859 		if (sel && sel->right && (sel = sel->right) == next) curr = next;
 860 		calcoffsets();
 861 		drawmenu();
 862 		return;
 863 	}
 864 	if (lines > 0) {
 865 		/* vertical list: left-click on item */
 866 		w = mw - x;
 867 		for (item = curr; item != next; item = item->right) {
 868 			y += h;
 869 			if (ev->y >= y && ev->y <= (y + h)) {
 870 				if (ev->button == Button1) {
 871 					if (ev->x == xx && ev->y == yy) {
 872 						puts(item->text);
 873 						exit(0);
 874 					}
 875 					xx = ev->x;
 876 					yy = ev->y;
 877 					sel = item;
 878 					drawmenu();
 879 				}
 880 				if (ev->button == Button3) {
 881 					item->out = 1;
 882 					drawmenu();
 883 					puts(item->text);
 884 				}
 885 				return;
 886 			}
 887 		}
 888 	} else if (matches) {
 889 		/* horizontal list: left-click on item */
 890 		for (item = curr; item != next; item = item->right) {
 891 			x += w;
 892 			w = MIN(TEXTW(item->text), mw - x - TEXTW(">"));
 893 			if (ev->x >= x && ev->x <= x + w) {
 894 				if (ev->button == Button1) {
 895 					if (ev->x == xx && ev->y == yy) {
 896 						puts(item->text);
 897 						exit(0);
 898 					}
 899 					xx = ev->x;
 900 					yy = ev->y;
 901 					sel = item;
 902 					drawmenu();
 903 				}
 904 				if (ev->button == Button3) {
 905 					item->out = 1;
 906 					drawmenu();
 907 					puts(item->text);
 908 				}
 909 				return;
 910 			}
 911 		}
 912 	}
 913 }
 914 #endif /* }}} */