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.
 
 
 
 
 
 

595 lines
15 KiB

  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 = "#cccccc";
  45. static const char *normfgcolor = "#000000";
  46. static const char *selbgcolor = "#0066ff";
  47. static const char *selfgcolor = "#ffffff";
  48. static unsigned int lines = 0;
  49. static unsigned long normcol[ColLast];
  50. static unsigned long selcol[ColLast];
  51. static Atom 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-2011 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 EXIT_FAILURE; /* 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) {
  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. KeySym lower, upper;
  223. XConvertCase(ksym, &lower, &upper);
  224. switch(lower) {
  225. case XK_a: ksym = XK_Home; break;
  226. case XK_b: ksym = XK_Left; break;
  227. case XK_c: ksym = XK_Escape; break;
  228. case XK_d: ksym = XK_Delete; break;
  229. case XK_e: ksym = XK_End; break;
  230. case XK_f: ksym = XK_Right; break;
  231. case XK_h: ksym = XK_BackSpace; break;
  232. case XK_i: ksym = XK_Tab; break;
  233. case XK_j: ksym = XK_Return; break;
  234. case XK_m: ksym = XK_Return; break;
  235. case XK_n: ksym = XK_Up; break;
  236. case XK_p: ksym = XK_Down; break;
  237. case XK_k: /* delete right */
  238. text[cursor] = '\0';
  239. match();
  240. break;
  241. case XK_u: /* delete left */
  242. insert(NULL, 0 - cursor);
  243. break;
  244. case XK_w: /* delete word */
  245. while(cursor > 0 && text[nextrune(-1)] == ' ')
  246. insert(NULL, nextrune(-1) - cursor);
  247. while(cursor > 0 && text[nextrune(-1)] != ' ')
  248. insert(NULL, nextrune(-1) - cursor);
  249. break;
  250. case XK_y: /* paste selection */
  251. XConvertSelection(dc->dpy, XA_PRIMARY, utf8, utf8, win, CurrentTime);
  252. return;
  253. default:
  254. return;
  255. }
  256. }
  257. switch(ksym) {
  258. default:
  259. if(!iscntrl(*buf))
  260. insert(buf, len);
  261. break;
  262. case XK_Delete:
  263. if(text[cursor] == '\0')
  264. return;
  265. cursor = nextrune(+1);
  266. /* fallthrough */
  267. case XK_BackSpace:
  268. if(cursor == 0)
  269. return;
  270. insert(NULL, nextrune(-1) - cursor);
  271. break;
  272. case XK_End:
  273. if(text[cursor] != '\0') {
  274. cursor = strlen(text);
  275. break;
  276. }
  277. if(next) {
  278. /* jump to end of list and position items in reverse */
  279. curr = matchend;
  280. calcoffsets();
  281. curr = prev;
  282. calcoffsets();
  283. while(next && (curr = curr->right))
  284. calcoffsets();
  285. }
  286. sel = matchend;
  287. break;
  288. case XK_Escape:
  289. exit(EXIT_FAILURE);
  290. case XK_Home:
  291. if(sel == matches) {
  292. cursor = 0;
  293. break;
  294. }
  295. sel = curr = matches;
  296. calcoffsets();
  297. break;
  298. case XK_Left:
  299. if(cursor > 0 && (!sel || !sel->left || lines > 0)) {
  300. cursor = nextrune(-1);
  301. break;
  302. }
  303. /* fallthrough */
  304. case XK_Up:
  305. if(sel && sel->left && (sel = sel->left)->right == curr) {
  306. curr = prev;
  307. calcoffsets();
  308. }
  309. break;
  310. case XK_Next:
  311. if(!next)
  312. return;
  313. sel = curr = next;
  314. calcoffsets();
  315. break;
  316. case XK_Prior:
  317. if(!prev)
  318. return;
  319. sel = curr = prev;
  320. calcoffsets();
  321. break;
  322. case XK_Return:
  323. case XK_KP_Enter:
  324. puts((sel && !(ev->state & ShiftMask)) ? sel->text : text);
  325. exit(EXIT_SUCCESS);
  326. case XK_Right:
  327. if(text[cursor] != '\0') {
  328. cursor = nextrune(+1);
  329. break;
  330. }
  331. /* fallthrough */
  332. case XK_Down:
  333. if(sel && sel->right && (sel = sel->right) == next) {
  334. curr = next;
  335. calcoffsets();
  336. }
  337. break;
  338. case XK_Tab:
  339. if(!sel)
  340. return;
  341. strncpy(text, sel->text, sizeof text);
  342. cursor = strlen(text);
  343. match();
  344. break;
  345. }
  346. drawmenu();
  347. }
  348. void
  349. match(void) {
  350. static char **tokv = NULL;
  351. static int tokn = 0;
  352. char buf[sizeof text], *s;
  353. int i, tokc = 0;
  354. size_t len;
  355. Item *item, *lprefix, *lsubstr, *prefixend, *substrend;
  356. strcpy(buf, text);
  357. /* separate input text into tokens to be matched individually */
  358. for(s = strtok(buf, " "); s; tokv[tokc-1] = s, s = strtok(NULL, " "))
  359. if(++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
  360. eprintf("cannot realloc %u bytes\n", tokn * sizeof *tokv);
  361. len = tokc ? strlen(tokv[0]) : 0;
  362. matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
  363. for(item = items; item && item->text; item++) {
  364. for(i = 0; i < tokc; i++)
  365. if(!fstrstr(item->text, tokv[i]))
  366. break;
  367. if(i != tokc) /* not all tokens match */
  368. continue;
  369. /* exact matches go first, then prefixes, then substrings */
  370. if(!tokc || !fstrncmp(tokv[0], item->text, len+1))
  371. appenditem(item, &matches, &matchend);
  372. else if(!fstrncmp(tokv[0], item->text, len))
  373. appenditem(item, &lprefix, &prefixend);
  374. else
  375. appenditem(item, &lsubstr, &substrend);
  376. }
  377. if(lprefix) {
  378. if(matches) {
  379. matchend->right = lprefix;
  380. lprefix->left = matchend;
  381. }
  382. else
  383. matches = lprefix;
  384. matchend = prefixend;
  385. }
  386. if(lsubstr) {
  387. if(matches) {
  388. matchend->right = lsubstr;
  389. lsubstr->left = matchend;
  390. }
  391. else
  392. matches = lsubstr;
  393. matchend = substrend;
  394. }
  395. curr = sel = matches;
  396. calcoffsets();
  397. }
  398. size_t
  399. nextrune(int inc) {
  400. ssize_t n;
  401. /* return location of next utf8 rune in the given direction (+1 or -1) */
  402. for(n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc);
  403. return n;
  404. }
  405. void
  406. paste(void) {
  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(dc->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. void
  419. readstdin(void) {
  420. char buf[sizeof text], *p, *maxstr = NULL;
  421. size_t i, max = 0, size = 0;
  422. /* read each line from stdin and add it to the item list */
  423. for(i = 0; fgets(buf, sizeof buf, stdin); i++) {
  424. if(i+1 >= size / sizeof *items)
  425. if(!(items = realloc(items, (size += BUFSIZ))))
  426. eprintf("cannot realloc %u bytes:", size);
  427. if((p = strchr(buf, '\n')))
  428. *p = '\0';
  429. if(!(items[i].text = strdup(buf)))
  430. eprintf("cannot strdup %u bytes:", strlen(buf)+1);
  431. if(strlen(items[i].text) > max)
  432. max = strlen(maxstr = items[i].text);
  433. }
  434. if(items)
  435. items[i].text = NULL;
  436. inputw = maxstr ? textw(dc, maxstr) : 0;
  437. lines = MIN(lines, i);
  438. }
  439. void
  440. run(void) {
  441. XEvent ev;
  442. while(!XNextEvent(dc->dpy, &ev)) {
  443. if(XFilterEvent(&ev, win))
  444. continue;
  445. switch(ev.type) {
  446. case Expose:
  447. if(ev.xexpose.count == 0)
  448. mapdc(dc, win, mw, mh);
  449. break;
  450. case KeyPress:
  451. keypress(&ev.xkey);
  452. break;
  453. case SelectionNotify:
  454. if(ev.xselection.property == utf8)
  455. paste();
  456. break;
  457. case VisibilityNotify:
  458. if(ev.xvisibility.state != VisibilityUnobscured)
  459. XRaiseWindow(dc->dpy, win);
  460. break;
  461. }
  462. }
  463. }
  464. void
  465. setup(void) {
  466. int x, y, screen = DefaultScreen(dc->dpy);
  467. Window root = RootWindow(dc->dpy, screen);
  468. XSetWindowAttributes swa;
  469. XIM xim;
  470. #ifdef XINERAMA
  471. int n;
  472. XineramaScreenInfo *info;
  473. #endif
  474. normcol[ColBG] = getcolor(dc, normbgcolor);
  475. normcol[ColFG] = getcolor(dc, normfgcolor);
  476. selcol[ColBG] = getcolor(dc, selbgcolor);
  477. selcol[ColFG] = getcolor(dc, selfgcolor);
  478. utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);
  479. /* calculate menu geometry */
  480. bh = dc->font.height + 2;
  481. lines = MAX(lines, 0);
  482. mh = (lines + 1) * bh;
  483. #ifdef XINERAMA
  484. if((info = XineramaQueryScreens(dc->dpy, &n))) {
  485. int a, j, di, i = 0, area = 0;
  486. unsigned int du;
  487. Window w, pw, dw, *dws;
  488. XWindowAttributes wa;
  489. XGetInputFocus(dc->dpy, &w, &di);
  490. if(w != root && w != PointerRoot && w != None) {
  491. /* find top-level window containing current input focus */
  492. do {
  493. if(XQueryTree(dc->dpy, (pw = w), &dw, &w, &dws, &du) && dws)
  494. XFree(dws);
  495. } while(w != root && w != pw);
  496. /* find xinerama screen with which the window intersects most */
  497. if(XGetWindowAttributes(dc->dpy, pw, &wa))
  498. for(j = 0; j < n; j++)
  499. if((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
  500. area = a;
  501. i = j;
  502. }
  503. }
  504. /* no focused window is on screen, so use pointer location instead */
  505. if(!area && XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
  506. for(i = 0; i < n; i++)
  507. if(INTERSECT(x, y, 1, 1, info[i]))
  508. break;
  509. x = info[i].x_org;
  510. y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
  511. mw = info[i].width;
  512. XFree(info);
  513. }
  514. else
  515. #endif
  516. {
  517. x = 0;
  518. y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - mh;
  519. mw = DisplayWidth(dc->dpy, screen);
  520. }
  521. promptw = prompt ? textw(dc, prompt) : 0;
  522. inputw = MIN(inputw, mw/3);
  523. match();
  524. /* create menu window */
  525. swa.override_redirect = True;
  526. swa.background_pixmap = ParentRelative;
  527. swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
  528. win = XCreateWindow(dc->dpy, root, x, y, mw, mh, 0,
  529. DefaultDepth(dc->dpy, screen), CopyFromParent,
  530. DefaultVisual(dc->dpy, screen),
  531. CWOverrideRedirect | CWBackPixmap | CWEventMask, &swa);
  532. /* open input methods */
  533. xim = XOpenIM(dc->dpy, NULL, NULL, NULL);
  534. xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
  535. XNClientWindow, win, XNFocusWindow, win, NULL);
  536. XMapRaised(dc->dpy, win);
  537. resizedc(dc, mw, mh);
  538. drawmenu();
  539. }
  540. void
  541. usage(void) {
  542. fputs("usage: dmenu [-b] [-f] [-i] [-l lines] [-p prompt] [-fn font]\n"
  543. " [-nb color] [-nf color] [-sb color] [-sf color] [-v]\n", stderr);
  544. exit(EXIT_FAILURE);
  545. }