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.
 
 
 
 
 
 

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