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.
 
 
 
 
 
 

680 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. XUngrabKey(dpy, AnyKey, AnyModifier, root);
  81. drw_clr_free(scheme[SchemeNorm].bg);
  82. drw_clr_free(scheme[SchemeNorm].fg);
  83. drw_clr_free(scheme[SchemeSel].fg);
  84. drw_clr_free(scheme[SchemeSel].bg);
  85. drw_clr_free(scheme[SchemeOut].fg);
  86. drw_clr_free(scheme[SchemeOut].bg);
  87. drw_free(drw);
  88. XSync(dpy, False);
  89. XCloseDisplay(dpy);
  90. }
  91. static char *
  92. cistrstr(const char *s, const char *sub)
  93. {
  94. size_t len;
  95. for (len = strlen(sub); *s; s++)
  96. if (!strncasecmp(s, sub, len))
  97. return (char *)s;
  98. return NULL;
  99. }
  100. static void
  101. drawmenu(void)
  102. {
  103. int curpos;
  104. struct item *item;
  105. int x = 0, y = 0, h = bh, w;
  106. drw_setscheme(drw, &scheme[SchemeNorm]);
  107. drw_rect(drw, 0, 0, mw, mh, 1, 1, 1);
  108. if (prompt && *prompt) {
  109. drw_setscheme(drw, &scheme[SchemeSel]);
  110. drw_text(drw, x, 0, promptw, bh, prompt, 0);
  111. x += promptw;
  112. }
  113. /* draw input field */
  114. w = (lines > 0 || !matches) ? mw - x : inputw;
  115. drw_setscheme(drw, &scheme[SchemeNorm]);
  116. drw_text(drw, x, 0, w, bh, text, 0);
  117. if ((curpos = TEXTNW(text, cursor) + bh / 2 - 2) < w) {
  118. drw_setscheme(drw, &scheme[SchemeNorm]);
  119. drw_rect(drw, x + curpos + 2, 2, 1, bh - 4, 1, 1, 0);
  120. }
  121. if (lines > 0) {
  122. /* draw vertical list */
  123. w = mw - x;
  124. for (item = curr; item != next; item = item->right) {
  125. y += h;
  126. if (item == sel)
  127. drw_setscheme(drw, &scheme[SchemeSel]);
  128. else if (item->out)
  129. drw_setscheme(drw, &scheme[SchemeOut]);
  130. else
  131. drw_setscheme(drw, &scheme[SchemeNorm]);
  132. drw_text(drw, x, y, w, bh, item->text, 0);
  133. }
  134. } else if (matches) {
  135. /* draw horizontal list */
  136. x += inputw;
  137. w = TEXTW("<");
  138. if (curr->left) {
  139. drw_setscheme(drw, &scheme[SchemeNorm]);
  140. drw_text(drw, x, 0, w, bh, "<", 0);
  141. }
  142. for (item = curr; item != next; item = item->right) {
  143. x += w;
  144. w = MIN(TEXTW(item->text), mw - x - TEXTW(">"));
  145. if (item == sel)
  146. drw_setscheme(drw, &scheme[SchemeSel]);
  147. else if (item->out)
  148. drw_setscheme(drw, &scheme[SchemeOut]);
  149. else
  150. drw_setscheme(drw, &scheme[SchemeNorm]);
  151. drw_text(drw, x, 0, w, bh, item->text, 0);
  152. }
  153. w = TEXTW(">");
  154. x = mw - w;
  155. if (next) {
  156. drw_setscheme(drw, &scheme[SchemeNorm]);
  157. drw_text(drw, x, 0, w, bh, ">", 0);
  158. }
  159. }
  160. drw_map(drw, win, 0, 0, mw, mh);
  161. }
  162. static void
  163. grabkeyboard(void)
  164. {
  165. struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
  166. int i;
  167. /* try to grab keyboard, we may have to wait for another process to ungrab */
  168. for (i = 0; i < 1000; i++) {
  169. if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True,
  170. GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
  171. return;
  172. nanosleep(&ts, NULL);
  173. }
  174. die("cannot grab keyboard\n");
  175. }
  176. static void
  177. match(void)
  178. {
  179. static char **tokv = NULL;
  180. static int tokn = 0;
  181. char buf[sizeof text], *s;
  182. int i, tokc = 0;
  183. size_t len;
  184. struct item *item, *lprefix, *lsubstr, *prefixend, *substrend;
  185. strcpy(buf, text);
  186. /* separate input text into tokens to be matched individually */
  187. for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " "))
  188. if (++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
  189. die("cannot realloc %u bytes\n", tokn * sizeof *tokv);
  190. len = tokc ? strlen(tokv[0]) : 0;
  191. matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
  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(tokv[0], item->text, len + 1))
  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. XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY,
  288. utf8, utf8, win, CurrentTime);
  289. return;
  290. case XK_Return:
  291. case XK_KP_Enter:
  292. break;
  293. case XK_bracketleft:
  294. cleanup();
  295. exit(1);
  296. default:
  297. return;
  298. }
  299. else if (ev->state & Mod1Mask)
  300. switch(ksym) {
  301. case XK_g: ksym = XK_Home; break;
  302. case XK_G: ksym = XK_End; break;
  303. case XK_h: ksym = XK_Up; break;
  304. case XK_j: ksym = XK_Next; break;
  305. case XK_k: ksym = XK_Prior; break;
  306. case XK_l: ksym = XK_Down; break;
  307. default:
  308. return;
  309. }
  310. switch(ksym) {
  311. default:
  312. if (!iscntrl(*buf))
  313. insert(buf, len);
  314. break;
  315. case XK_Delete:
  316. if (text[cursor] == '\0')
  317. return;
  318. cursor = nextrune(+1);
  319. /* fallthrough */
  320. case XK_BackSpace:
  321. if (cursor == 0)
  322. return;
  323. insert(NULL, nextrune(-1) - cursor);
  324. break;
  325. case XK_End:
  326. if (text[cursor] != '\0') {
  327. cursor = strlen(text);
  328. break;
  329. }
  330. if (next) {
  331. /* jump to end of list and position items in reverse */
  332. curr = matchend;
  333. calcoffsets();
  334. curr = prev;
  335. calcoffsets();
  336. while (next && (curr = curr->right))
  337. calcoffsets();
  338. }
  339. sel = matchend;
  340. break;
  341. case XK_Escape:
  342. cleanup();
  343. exit(1);
  344. case XK_Home:
  345. if (sel == matches) {
  346. cursor = 0;
  347. break;
  348. }
  349. sel = curr = matches;
  350. calcoffsets();
  351. break;
  352. case XK_Left:
  353. if (cursor > 0 && (!sel || !sel->left || lines > 0)) {
  354. cursor = nextrune(-1);
  355. break;
  356. }
  357. if (lines > 0)
  358. return;
  359. /* fallthrough */
  360. case XK_Up:
  361. if (sel && sel->left && (sel = sel->left)->right == curr) {
  362. curr = prev;
  363. calcoffsets();
  364. }
  365. break;
  366. case XK_Next:
  367. if (!next)
  368. return;
  369. sel = curr = next;
  370. calcoffsets();
  371. break;
  372. case XK_Prior:
  373. if (!prev)
  374. return;
  375. sel = curr = prev;
  376. calcoffsets();
  377. break;
  378. case XK_Return:
  379. case XK_KP_Enter:
  380. puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
  381. if (!(ev->state & ControlMask)) {
  382. cleanup();
  383. exit(0);
  384. }
  385. if (sel)
  386. sel->out = true;
  387. break;
  388. case XK_Right:
  389. if (text[cursor] != '\0') {
  390. cursor = nextrune(+1);
  391. break;
  392. }
  393. if (lines > 0)
  394. return;
  395. /* fallthrough */
  396. case XK_Down:
  397. if (sel && sel->right && (sel = sel->right) == next) {
  398. curr = next;
  399. calcoffsets();
  400. }
  401. break;
  402. case XK_Tab:
  403. if (!sel)
  404. return;
  405. strncpy(text, sel->text, sizeof text - 1);
  406. text[sizeof text - 1] = '\0';
  407. cursor = strlen(text);
  408. match();
  409. break;
  410. }
  411. drawmenu();
  412. }
  413. static void
  414. paste(void)
  415. {
  416. char *p, *q;
  417. int di;
  418. unsigned long dl;
  419. Atom da;
  420. /* we have been given the current selection, now insert it into input */
  421. XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
  422. utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
  423. insert(p, (q = strchr(p, '\n')) ? q - p : (ssize_t)strlen(p));
  424. XFree(p);
  425. drawmenu();
  426. }
  427. static void
  428. readstdin(void)
  429. {
  430. char buf[sizeof text], *p, *maxstr = NULL;
  431. size_t i, max = 0, size = 0;
  432. /* read each line from stdin and add it to the item list */
  433. for (i = 0; fgets(buf, sizeof buf, stdin); i++) {
  434. if (i + 1 >= size / sizeof *items)
  435. if (!(items = realloc(items, (size += BUFSIZ))))
  436. die("cannot realloc %u bytes:", size);
  437. if ((p = strchr(buf, '\n')))
  438. *p = '\0';
  439. if (!(items[i].text = strdup(buf)))
  440. die("cannot strdup %u bytes:", strlen(buf) + 1);
  441. items[i].out = false;
  442. if (strlen(items[i].text) > max)
  443. max = strlen(maxstr = items[i].text);
  444. }
  445. if (items)
  446. items[i].text = NULL;
  447. inputw = maxstr ? TEXTW(maxstr) : 0;
  448. lines = MIN(lines, i);
  449. }
  450. static void
  451. run(void)
  452. {
  453. XEvent ev;
  454. while (!XNextEvent(dpy, &ev)) {
  455. if (XFilterEvent(&ev, win))
  456. continue;
  457. switch(ev.type) {
  458. case Expose:
  459. if (ev.xexpose.count == 0)
  460. drw_map(drw, win, 0, 0, mw, mh);
  461. break;
  462. case KeyPress:
  463. keypress(&ev.xkey);
  464. break;
  465. case SelectionNotify:
  466. if (ev.xselection.property == utf8)
  467. paste();
  468. break;
  469. case VisibilityNotify:
  470. if (ev.xvisibility.state != VisibilityUnobscured)
  471. XRaiseWindow(dpy, win);
  472. break;
  473. }
  474. }
  475. }
  476. static void
  477. setup(void)
  478. {
  479. int x, y;
  480. XSetWindowAttributes swa;
  481. XIM xim;
  482. #ifdef XINERAMA
  483. XineramaScreenInfo *info;
  484. Window w, pw, dw, *dws;
  485. XWindowAttributes wa;
  486. int a, j, di, n, i = 0, area = 0;
  487. unsigned int du;
  488. #endif
  489. /* init appearance */
  490. scheme[SchemeNorm].bg = drw_clr_create(drw, normbgcolor);
  491. scheme[SchemeNorm].fg = drw_clr_create(drw, normfgcolor);
  492. scheme[SchemeSel].bg = drw_clr_create(drw, selbgcolor);
  493. scheme[SchemeSel].fg = drw_clr_create(drw, selfgcolor);
  494. scheme[SchemeOut].bg = drw_clr_create(drw, outbgcolor);
  495. scheme[SchemeOut].fg = drw_clr_create(drw, outfgcolor);
  496. clip = XInternAtom(dpy, "CLIPBOARD", False);
  497. utf8 = XInternAtom(dpy, "UTF8_STRING", False);
  498. /* calculate menu geometry */
  499. bh = drw->fonts[0]->h + 2;
  500. lines = MAX(lines, 0);
  501. mh = (lines + 1) * bh;
  502. #ifdef XINERAMA
  503. if ((info = XineramaQueryScreens(dpy, &n))) {
  504. XGetInputFocus(dpy, &w, &di);
  505. if (mon != -1 && mon < n)
  506. i = mon;
  507. if (!i && w != root && w != PointerRoot && w != None) {
  508. /* find top-level window containing current input focus */
  509. do {
  510. if (XQueryTree(dpy, (pw = w), &dw, &w, &dws, &du) && dws)
  511. XFree(dws);
  512. } while (w != root && w != pw);
  513. /* find xinerama screen with which the window intersects most */
  514. if (XGetWindowAttributes(dpy, pw, &wa))
  515. for (j = 0; j < n; j++)
  516. if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
  517. area = a;
  518. i = j;
  519. }
  520. }
  521. /* no focused window is on screen, so use pointer location instead */
  522. if (mon == -1 && !area && XQueryPointer(dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
  523. for (i = 0; i < n; i++)
  524. if (INTERSECT(x, y, 1, 1, info[i]))
  525. break;
  526. x = info[i].x_org;
  527. y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
  528. mw = info[i].width;
  529. XFree(info);
  530. } else
  531. #endif
  532. {
  533. x = 0;
  534. y = topbar ? 0 : sh - mh;
  535. mw = sw;
  536. }
  537. promptw = (prompt && *prompt) ? TEXTW(prompt) : 0;
  538. inputw = MIN(inputw, mw/3);
  539. match();
  540. /* create menu window */
  541. swa.override_redirect = True;
  542. swa.background_pixel = scheme[SchemeNorm].bg->pix;
  543. swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
  544. win = XCreateWindow(dpy, root, x, y, mw, mh, 0,
  545. DefaultDepth(dpy, screen), CopyFromParent,
  546. DefaultVisual(dpy, screen),
  547. CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
  548. /* open input methods */
  549. xim = XOpenIM(dpy, NULL, NULL, NULL);
  550. xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
  551. XNClientWindow, win, XNFocusWindow, win, NULL);
  552. XMapRaised(dpy, win);
  553. drw_resize(drw, mw, mh);
  554. drawmenu();
  555. }
  556. static void
  557. usage(void)
  558. {
  559. fputs("usage: dmenu [-b] [-f] [-i] [-l lines] [-p prompt] [-fn font] [-m monitor]\n"
  560. " [-nb color] [-nf color] [-sb color] [-sf color] [-v]\n", stderr);
  561. exit(1);
  562. }
  563. int
  564. main(int argc, char *argv[])
  565. {
  566. bool fast = false;
  567. int i;
  568. for (i = 1; i < argc; i++)
  569. /* these options take no arguments */
  570. if (!strcmp(argv[i], "-v")) { /* prints version information */
  571. puts("dmenu-"VERSION);
  572. exit(0);
  573. } else if (!strcmp(argv[i], "-b")) /* appears at the bottom of the screen */
  574. topbar = false;
  575. else if (!strcmp(argv[i], "-f")) /* grabs keyboard before reading stdin */
  576. fast = true;
  577. else if (!strcmp(argv[i], "-i")) { /* case-insensitive item matching */
  578. fstrncmp = strncasecmp;
  579. fstrstr = cistrstr;
  580. } else if (i + 1 == argc)
  581. usage();
  582. /* these options take one argument */
  583. else if (!strcmp(argv[i], "-l")) /* number of lines in vertical list */
  584. lines = atoi(argv[++i]);
  585. else if (!strcmp(argv[i], "-m"))
  586. mon = atoi(argv[++i]);
  587. else if (!strcmp(argv[i], "-p")) /* adds prompt to left of input field */
  588. prompt = argv[++i];
  589. else if (!strcmp(argv[i], "-fn")) /* font or font set */
  590. fonts[0] = argv[++i];
  591. else if (!strcmp(argv[i], "-nb")) /* normal background color */
  592. normbgcolor = argv[++i];
  593. else if (!strcmp(argv[i], "-nf")) /* normal foreground color */
  594. normfgcolor = argv[++i];
  595. else if (!strcmp(argv[i], "-sb")) /* selected background color */
  596. selbgcolor = argv[++i];
  597. else if (!strcmp(argv[i], "-sf")) /* selected foreground color */
  598. selfgcolor = argv[++i];
  599. else
  600. usage();
  601. if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
  602. fputs("warning: no locale support\n", stderr);
  603. if (!(dpy = XOpenDisplay(NULL)))
  604. die("cannot open display\n");
  605. screen = DefaultScreen(dpy);
  606. root = RootWindow(dpy, screen);
  607. sw = DisplayWidth(dpy, screen);
  608. sh = DisplayHeight(dpy, screen);
  609. drw = drw_create(dpy, screen, root, sw, sh);
  610. drw_load_fonts(drw, fonts, LENGTH(fonts));
  611. if (!drw->fontcount)
  612. die("no fonts could be loaded.\n");
  613. drw_setscheme(drw, &scheme[SchemeNorm]);
  614. if (fast) {
  615. grabkeyboard();
  616. readstdin();
  617. } else {
  618. readstdin();
  619. grabkeyboard();
  620. }
  621. setup();
  622. run();
  623. return 1; /* unreachable */
  624. }