dmenu for lunch applications in dwm
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.

620 lines
15 KiB

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