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