My dmenu build
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

672 lines
16 KiB

  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 <X11/Xlib.h>
  10. #include <X11/Xatom.h>
  11. #include <X11/Xutil.h>
  12. #ifdef XINERAMA
  13. #include <X11/extensions/Xinerama.h>
  14. #endif
  15. #include <X11/Xft/Xft.h>
  16. #include "drw.h"
  17. #include "util.h"
  18. /* macros */
  19. #define INTERSECT(x,y,w,h,r) (MAX(0, MIN((x)+(w),(r).x_org+(r).width) - MAX((x),(r).x_org)) \
  20. * MAX(0, MIN((y)+(h),(r).y_org+(r).height) - MAX((y),(r).y_org)))
  21. #define LENGTH(X) (sizeof X / sizeof X[0])
  22. #define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad)
  23. /* enums */
  24. enum { SchemeNorm, SchemeSel, SchemeOut, SchemeLast }; /* color schemes */
  25. struct item {
  26. char *text;
  27. struct item *left, *right;
  28. int out;
  29. };
  30. static char text[BUFSIZ] = "";
  31. static int bh, mw, mh;
  32. static int sw, sh; /* X display screen geometry width, height */
  33. static int inputw = 0, promptw;
  34. static int lrpad; /* sum of left and right padding */
  35. static size_t cursor;
  36. static struct item *items = NULL;
  37. static struct item *matches, *matchend;
  38. static struct item *prev, *curr, *next, *sel;
  39. static int mon = -1, screen;
  40. static Atom clip, utf8;
  41. static Display *dpy;
  42. static Window root, win;
  43. static XIC xic;
  44. static Drw *drw;
  45. static Clr *scheme[SchemeLast];
  46. #include "config.h"
  47. static int (*fstrncmp)(const char *, const char *, size_t) = strncmp;
  48. static char *(*fstrstr)(const char *, const char *) = strstr;
  49. static void
  50. appenditem(struct item *item, struct item **list, struct item **last)
  51. {
  52. if (*last)
  53. (*last)->right = item;
  54. else
  55. *list = item;
  56. item->left = *last;
  57. item->right = NULL;
  58. *last = item;
  59. }
  60. static void
  61. calcoffsets(void)
  62. {
  63. int i, n;
  64. if (lines > 0)
  65. n = lines * bh;
  66. else
  67. n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">"));
  68. /* calculate which items will begin the next page and previous page */
  69. for (i = 0, next = curr; next; next = next->right)
  70. if ((i += (lines > 0) ? bh : TEXTW(next->text)) > n)
  71. break;
  72. for (i = 0, prev = curr; prev && prev->left; prev = prev->left)
  73. if ((i += (lines > 0) ? bh : TEXTW(prev->left->text)) > n)
  74. break;
  75. }
  76. static void
  77. cleanup(void)
  78. {
  79. size_t i;
  80. XUngrabKey(dpy, AnyKey, AnyModifier, root);
  81. for (i = 0; i < SchemeLast; i++)
  82. free(scheme[i]);
  83. drw_free(drw);
  84. XSync(dpy, False);
  85. XCloseDisplay(dpy);
  86. }
  87. static char *
  88. cistrstr(const char *s, const char *sub)
  89. {
  90. size_t len;
  91. for (len = strlen(sub); *s; s++)
  92. if (!strncasecmp(s, sub, len))
  93. return (char *)s;
  94. return NULL;
  95. }
  96. static int
  97. drawitem(struct item *item, int x, int y, int w)
  98. {
  99. if (item == sel)
  100. drw_setscheme(drw, scheme[SchemeSel]);
  101. else if (item->out)
  102. drw_setscheme(drw, scheme[SchemeOut]);
  103. else
  104. drw_setscheme(drw, scheme[SchemeNorm]);
  105. return drw_text(drw, x, y, w, bh, lrpad / 2, item->text, 0);
  106. }
  107. static void
  108. drawmenu(void)
  109. {
  110. unsigned int curpos;
  111. struct item *item;
  112. int x = 0, y = 0, w;
  113. drw_setscheme(drw, scheme[SchemeNorm]);
  114. drw_rect(drw, 0, 0, mw, mh, 1, 1);
  115. if (prompt && *prompt) {
  116. drw_setscheme(drw, scheme[SchemeSel]);
  117. x = drw_text(drw, x, 0, promptw, bh, lrpad / 2, prompt, 0);
  118. }
  119. /* draw input field */
  120. w = (lines > 0 || !matches) ? mw - x : inputw;
  121. drw_setscheme(drw, scheme[SchemeNorm]);
  122. drw_text(drw, x, 0, w, bh, lrpad / 2, text, 0);
  123. drw_font_getexts(drw->fonts, text, cursor, &curpos, NULL);
  124. if ((curpos += lrpad / 2 - 1) < w) {
  125. drw_setscheme(drw, scheme[SchemeNorm]);
  126. drw_rect(drw, x + curpos, 2, 2, bh - 4, 1, 0);
  127. }
  128. if (lines > 0) {
  129. /* draw vertical list */
  130. for (item = curr; item != next; item = item->right)
  131. drawitem(item, x, y += bh, mw - x);
  132. } else if (matches) {
  133. /* draw horizontal list */
  134. x += inputw;
  135. w = TEXTW("<");
  136. if (curr->left) {
  137. drw_setscheme(drw, scheme[SchemeNorm]);
  138. drw_text(drw, x, 0, w, bh, lrpad / 2, "<", 0);
  139. }
  140. x += w;
  141. for (item = curr; item != next; item = item->right)
  142. x = drawitem(item, x, 0, MIN(TEXTW(item->text), mw - x - TEXTW(">")));
  143. if (next) {
  144. w = TEXTW(">");
  145. drw_setscheme(drw, scheme[SchemeNorm]);
  146. drw_text(drw, mw - w, 0, w, bh, lrpad / 2, ">", 0);
  147. }
  148. }
  149. drw_map(drw, win, 0, 0, mw, mh);
  150. }
  151. static void
  152. grabkeyboard(void)
  153. {
  154. struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
  155. int i;
  156. /* try to grab keyboard, we may have to wait for another process to ungrab */
  157. for (i = 0; i < 1000; i++) {
  158. if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync,
  159. GrabModeAsync, CurrentTime) == GrabSuccess)
  160. return;
  161. nanosleep(&ts, NULL);
  162. }
  163. die("cannot grab keyboard\n");
  164. }
  165. static void
  166. match(void)
  167. {
  168. static char **tokv = NULL;
  169. static int tokn = 0;
  170. char buf[sizeof text], *s;
  171. int i, tokc = 0;
  172. size_t len, textsize;
  173. struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
  174. strcpy(buf, text);
  175. /* separate input text into tokens to be matched individually */
  176. for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
  177. if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
  178. die("cannot realloc %u bytes\n", tokn * sizeof *tokv);
  179. len = tokc ? strlen(tokv[0]) : 0;
  180. matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
  181. textsize = strlen(text);
  182. for (item = items; item && item->text; item++) {
  183. for (i = 0; i < tokc; i++)
  184. if (!fstrstr(item->text, tokv[i]))
  185. break;
  186. if (i != tokc) /* not all tokens match */
  187. continue;
  188. /* exact matches go first, then prefixes, then substrings */
  189. if (!tokc || !fstrncmp(text, item->text, textsize))
  190. appenditem(item, &matches, &matchend);
  191. else if (!fstrncmp(tokv[0], item->text, len))
  192. appenditem(item, &lprefix, &prefixend);
  193. else
  194. appenditem(item, &lsubstr, &substrend);
  195. }
  196. if (lprefix) {
  197. if (matches) {
  198. matchend->right = lprefix;
  199. lprefix->left = matchend;
  200. } else
  201. matches = lprefix;
  202. matchend = prefixend;
  203. }
  204. if (lsubstr) {
  205. if (matches) {
  206. matchend->right = lsubstr;
  207. lsubstr->left = matchend;
  208. } else
  209. matches = lsubstr;
  210. matchend = substrend;
  211. }
  212. curr = sel = matches;
  213. calcoffsets();
  214. }
  215. static void
  216. insert(const char *str, ssize_t n)
  217. {
  218. if (strlen(text) + n > sizeof text - 1)
  219. return;
  220. /* move existing text out of the way, insert new text, and update cursor */
  221. memmove(&text[cursor + n], &text[cursor], sizeof text - cursor - MAX(n, 0));
  222. if (n > 0)
  223. memcpy(&text[cursor], str, n);
  224. cursor += n;
  225. match();
  226. }
  227. static size_t
  228. nextrune(int inc)
  229. {
  230. ssize_t n;
  231. /* return location of next utf8 rune in the given direction (+1 or -1) */
  232. for (n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc)
  233. ;
  234. return n;
  235. }
  236. static void
  237. keypress(XKeyEvent *ev)
  238. {
  239. char buf[32];
  240. int len;
  241. KeySym ksym = NoSymbol;
  242. Status status;
  243. len = XmbLookupString(xic, ev, buf, sizeof buf, &ksym, &status);
  244. if (status == XBufferOverflow)
  245. return;
  246. if (ev->state & ControlMask)
  247. switch(ksym) {
  248. case XK_a: ksym = XK_Home; break;
  249. case XK_b: ksym = XK_Left; break;
  250. case XK_c: ksym = XK_Escape; break;
  251. case XK_d: ksym = XK_Delete; break;
  252. case XK_e: ksym = XK_End; break;
  253. case XK_f: ksym = XK_Right; break;
  254. case XK_g: ksym = XK_Escape; break;
  255. case XK_h: ksym = XK_BackSpace; break;
  256. case XK_i: ksym = XK_Tab; break;
  257. case XK_j: /* fallthrough */
  258. case XK_J: /* fallthrough */
  259. case XK_m: /* fallthrough */
  260. case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break;
  261. case XK_n: ksym = XK_Down; break;
  262. case XK_p: ksym = XK_Up; break;
  263. case XK_k: /* delete right */
  264. text[cursor] = '\0';
  265. match();
  266. break;
  267. case XK_u: /* delete left */
  268. insert(NULL, 0 - cursor);
  269. break;
  270. case XK_w: /* delete word */
  271. while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)]))
  272. insert(NULL, nextrune(-1) - cursor);
  273. while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)]))
  274. insert(NULL, nextrune(-1) - cursor);
  275. break;
  276. case XK_y: /* paste selection */
  277. case XK_Y:
  278. XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
  279. utf8, utf8, win, CurrentTime);
  280. return;
  281. case XK_Return:
  282. case XK_KP_Enter:
  283. break;
  284. case XK_bracketleft:
  285. cleanup();
  286. exit(1);
  287. default:
  288. return;
  289. }
  290. else if (ev->state & Mod1Mask)
  291. switch(ksym) {
  292. case XK_g: ksym = XK_Home; break;
  293. case XK_G: ksym = XK_End; break;
  294. case XK_h: ksym = XK_Up; break;
  295. case XK_j: ksym = XK_Next; break;
  296. case XK_k: ksym = XK_Prior; break;
  297. case XK_l: ksym = XK_Down; break;
  298. default:
  299. return;
  300. }
  301. switch(ksym) {
  302. default:
  303. if (!iscntrl(*buf))
  304. insert(buf, len);
  305. break;
  306. case XK_Delete:
  307. if (text[cursor] == '\0')
  308. return;
  309. cursor = nextrune(+1);
  310. /* fallthrough */
  311. case XK_BackSpace:
  312. if (cursor == 0)
  313. return;
  314. insert(NULL, nextrune(-1) - cursor);
  315. break;
  316. case XK_End:
  317. if (text[cursor] != '\0') {
  318. cursor = strlen(text);
  319. break;
  320. }
  321. if (next) {
  322. /* jump to end of list and position items in reverse */
  323. curr = matchend;
  324. calcoffsets();
  325. curr = prev;
  326. calcoffsets();
  327. while (next && (curr = curr->right))
  328. calcoffsets();
  329. }
  330. sel = matchend;
  331. break;
  332. case XK_Escape:
  333. cleanup();
  334. exit(1);
  335. case XK_Home:
  336. if (sel == matches) {
  337. cursor = 0;
  338. break;
  339. }
  340. sel = curr = matches;
  341. calcoffsets();
  342. break;
  343. case XK_Left:
  344. if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
  345. cursor = nextrune(-1);
  346. break;
  347. }
  348. if (lines > 0)
  349. return;
  350. /* fallthrough */
  351. case XK_Up:
  352. if (sel && sel->left && (sel = sel->left)->right == curr) {
  353. curr = prev;
  354. calcoffsets();
  355. }
  356. break;
  357. case XK_Next:
  358. if (!next)
  359. return;
  360. sel = curr = next;
  361. calcoffsets();
  362. break;
  363. case XK_Prior:
  364. if (!prev)
  365. return;
  366. sel = curr = prev;
  367. calcoffsets();
  368. break;
  369. case XK_Return:
  370. case XK_KP_Enter:
  371. puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
  372. if (!(ev->state & ControlMask)) {
  373. cleanup();
  374. exit(0);
  375. }
  376. if (sel)
  377. sel->out = 1;
  378. break;
  379. case XK_Right:
  380. if (text[cursor] != '\0') {
  381. cursor = nextrune(+1);
  382. break;
  383. }
  384. if (lines > 0)
  385. return;
  386. /* fallthrough */
  387. case XK_Down:
  388. if (sel && sel->right && (sel = sel->right) == next) {
  389. curr = next;
  390. calcoffsets();
  391. }
  392. break;
  393. case XK_Tab:
  394. if (!sel)
  395. return;
  396. strncpy(text, sel->text, sizeof text - 1);
  397. text[sizeof text - 1] = '\0';
  398. cursor = strlen(text);
  399. match();
  400. break;
  401. }
  402. drawmenu();
  403. }
  404. static void
  405. paste(void)
  406. {
  407. char *p, *q;
  408. int di;
  409. unsigned long dl;
  410. Atom da;
  411. /* we have been given the current selection, now insert it into input */
  412. XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
  413. utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
  414. insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
  415. XFree(p);
  416. drawmenu();
  417. }
  418. static void
  419. readstdin(void)
  420. {
  421. char buf[sizeof text], *p;
  422. size_t i, imax = 0, size = 0;
  423. unsigned int tmpmax = 0;
  424. /* read each line from stdin and add it to the item list */
  425. for (i = 0; fgets(buf, sizeof buf, stdin); i++) {
  426. if (i + 1 >= size / sizeof *items)
  427. if (!(items = realloc(items, (size += BUFSIZ))))
  428. die("cannot realloc %u bytes:", size);
  429. if ((p = strchr(buf, '\n')))
  430. *p = '\0';
  431. if (!(items[i].text = strdup(buf)))
  432. die("cannot strdup %u bytes:", strlen(buf) + 1);
  433. items[i].out = 0;
  434. drw_font_getexts(drw->fonts, buf, strlen(buf), &tmpmax, NULL);
  435. if (tmpmax > inputw) {
  436. inputw = tmpmax;
  437. imax = i;
  438. }
  439. }
  440. if (items)
  441. items[i].text = NULL;
  442. inputw = TEXTW(items[imax].text);
  443. lines = MIN(lines, i);
  444. }
  445. static void
  446. run(void)
  447. {
  448. XEvent ev;
  449. while (!XNextEvent(dpy, &ev)) {
  450. if (XFilterEvent(&ev, win))
  451. continue;
  452. switch(ev.type) {
  453. case Expose:
  454. if (ev.xexpose.count == 0)
  455. drw_map(drw, win, 0, 0, mw, mh);
  456. break;
  457. case KeyPress:
  458. keypress(&ev.xkey);
  459. break;
  460. case SelectionNotify:
  461. if (ev.xselection.property == utf8)
  462. paste();
  463. break;
  464. case VisibilityNotify:
  465. if (ev.xvisibility.state != VisibilityUnobscured)
  466. XRaiseWindow(dpy, win);
  467. break;
  468. }
  469. }
  470. }
  471. static void
  472. setup(void)
  473. {
  474. int x, y;
  475. XSetWindowAttributes swa;
  476. XIM xim;
  477. #ifdef XINERAMA
  478. XineramaScreenInfo *info;
  479. Window w, pw, dw, *dws;
  480. XWindowAttributes wa;
  481. int a, j, di, n, i = 0, area = 0;
  482. unsigned int du;
  483. #endif
  484. /* init appearance */
  485. scheme[SchemeNorm] = drw_scm_create(drw, colors[SchemeNorm], 2);
  486. scheme[SchemeSel] = drw_scm_create(drw, colors[SchemeSel], 2);
  487. scheme[SchemeOut] = drw_scm_create(drw, colors[SchemeOut], 2);
  488. clip = XInternAtom(dpy, "CLIPBOARD", False);
  489. utf8 = XInternAtom(dpy, "UTF8_STRING", False);
  490. /* calculate menu geometry */
  491. bh = drw->fonts->h + 2;
  492. lines = MAX(lines, 0);
  493. mh = (lines + 1) * bh;
  494. #ifdef XINERAMA
  495. if ((info = XineramaQueryScreens(dpy, &n))) {
  496. XGetInputFocus(dpy, &w, &di);
  497. if (mon != -1 && mon < n)
  498. i = mon;
  499. else if (w != root && w != PointerRoot && w != None) {
  500. /* find top-level window containing current input focus */
  501. do {
  502. if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
  503. XFree(dws);
  504. } while (w != root && w != pw);
  505. /* find xinerama screen with which the window intersects most */
  506. if (XGetWindowAttributes(dpy, pw, &wa))
  507. for (j = 0; j < n; j++)
  508. if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
  509. area = a;
  510. i = j;
  511. }
  512. }
  513. /* no focused window is on screen, so use pointer location instead */
  514. if (mon == -1 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
  515. for (i = 0; i < n; i++)
  516. if (INTERSECT(x, y, 1, 1, info[i]))
  517. break;
  518. x = info[i].x_org;
  519. y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
  520. mw = info[i].width;
  521. XFree(info);
  522. } else
  523. #endif
  524. {
  525. x = 0;
  526. y = topbar ? 0 : sh - mh;
  527. mw = sw;
  528. }
  529. promptw = (prompt && *prompt) ? TEXTW(prompt) - lrpad / 4 : 0;
  530. inputw = MIN(inputw, mw/3);
  531. match();
  532. /* create menu window */
  533. swa.override_redirect = True;
  534. swa.background_pixel = scheme[SchemeNorm][ColBg].pixel;
  535. swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
  536. win = XCreateWindow(dpy, root, x, y, mw, mh, 0,
  537. DefaultDepth(dpy, screen), CopyFromParent,
  538. DefaultVisual(dpy, screen),
  539. CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
  540. /* open input methods */
  541. xim = XOpenIM(dpy, NULL, NULL, NULL);
  542. xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
  543. XNClientWindow, win, XNFocusWindow, win, NULL);
  544. XMapRaised(dpy, win);
  545. drw_resize(drw, mw, mh);
  546. drawmenu();
  547. }
  548. static void
  549. usage(void)
  550. {
  551. fputs("usage: dmenu [-b] [-f] [-i] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
  552. " [-nb color] [-nf color] [-sb color] [-sf color] [-v]\n", stderr);
  553. exit(1);
  554. }
  555. int
  556. main(int argc, char *argv[])
  557. {
  558. int i, fast = 0;
  559. for (i = 1; i < argc; i++)
  560. /* these options take no arguments */
  561. if (!strcmp(argv[i], "-v")) { /* prints version information */
  562. puts("dmenu-"VERSION);
  563. exit(0);
  564. } else if (!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
  565. topbar = 0;
  566. else if (!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
  567. fast = 1;
  568. else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
  569. fstrncmp = strncasecmp;
  570. fstrstr = cistrstr;
  571. } else if (i + 1 == argc)
  572. usage();
  573. /* these options take one argument */
  574. else if (!strcmp(argv[i], "-l")) /* number of lines in vertical list */
  575. lines = atoi(argv[++i]);
  576. else if (!strcmp(argv[i], "-m"))
  577. mon = atoi(argv[++i]);
  578. else if (!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
  579. prompt = argv[++i];
  580. else if (!strcmp(argv[i], "-fn")) /* font or font set */
  581. fonts[0] = argv[++i];
  582. else if (!strcmp(argv[i], "-nb")) /* normal background color */
  583. colors[SchemeNorm][ColBg] = argv[++i];
  584. else if (!strcmp(argv[i], "-nf")) /* normal foreground color */
  585. colors[SchemeNorm][ColFg] = argv[++i];
  586. else if (!strcmp(argv[i], "-sb")) /* selected background color */
  587. colors[SchemeSel][ColBg] = argv[++i];
  588. else if (!strcmp(argv[i], "-sf")) /* selected foreground color */
  589. colors[SchemeSel][ColFg] = argv[++i];
  590. else
  591. usage();
  592. if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
  593. fputs("warning: no locale support\n", stderr);
  594. if (!(dpy = XOpenDisplay(NULL)))
  595. die("cannot open display\n");
  596. screen = DefaultScreen(dpy);
  597. root = RootWindow(dpy, screen);
  598. sw = DisplayWidth(dpy, screen);
  599. sh = DisplayHeight(dpy, screen);
  600. drw = drw_create(dpy, screen, root, sw, sh);
  601. if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
  602. die("no fonts could be loaded.\n");
  603. lrpad = drw->fonts->h;
  604. if (fast) {
  605. grabkeyboard();
  606. readstdin();
  607. } else {
  608. readstdin();
  609. grabkeyboard();
  610. }
  611. setup();
  612. run();
  613. return 1; /* unreachable */
  614. }