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.

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