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.
 
 
 
 
 
 

683 lines
17 KiB

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