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.
 
 
 
 
 
 

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