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