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.
 
 
 
 
 
 

619 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. 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. 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. if(!(ev->state & ControlMask))
  340. exit(EXIT_SUCCESS);
  341. sel->out = True;
  342. break;
  343. case XK_Right:
  344. if(text[cursor] != '\0') {
  345. cursor = nextrune(+1);
  346. break;
  347. }
  348. if(lines > 0)
  349. return;
  350. /* fallthrough */
  351. case XK_Down:
  352. if(sel && sel->right && (sel = sel->right) == next) {
  353. curr = next;
  354. calcoffsets();
  355. }
  356. break;
  357. case XK_Tab:
  358. if(!sel)
  359. return;
  360. strncpy(text, sel->text, sizeof text - 1);
  361. text[sizeof text - 1] = '\0';
  362. cursor = strlen(text);
  363. match();
  364. break;
  365. }
  366. drawmenu();
  367. }
  368. void
  369. match(void) {
  370. static char **tokv = NULL;
  371. static int tokn = 0;
  372. char buf[sizeof text], *s;
  373. int i, tokc = 0;
  374. size_t len;
  375. Item *item, *lprefix, *lsubstr, *prefixend, *substrend;
  376. strcpy(buf, text);
  377. /* separate input text into tokens to be matched individually */
  378. for(s = strtok(buf, " "); s; tokv[tokc-1] = s, s = strtok(NULL, " "))
  379. if(++tokc > tokn && !(tokv = realloc(tokv, ++tokn * sizeof *tokv)))
  380. eprintf("cannot realloc %u bytes\n", tokn * sizeof *tokv);
  381. len = tokc ? strlen(tokv[0]) : 0;
  382. matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL;
  383. for(item = items; item && item->text; item++) {
  384. for(i = 0; i < tokc; i++)
  385. if(!fstrstr(item->text, tokv[i]))
  386. break;
  387. if(i != tokc) /* not all tokens match */
  388. continue;
  389. /* exact matches go first, then prefixes, then substrings */
  390. if(!tokc || !fstrncmp(tokv[0], item->text, len+1))
  391. appenditem(item, &matches, &matchend);
  392. else if(!fstrncmp(tokv[0], item->text, len))
  393. appenditem(item, &lprefix, &prefixend);
  394. else
  395. appenditem(item, &lsubstr, &substrend);
  396. }
  397. if(lprefix) {
  398. if(matches) {
  399. matchend->right = lprefix;
  400. lprefix->left = matchend;
  401. }
  402. else
  403. matches = lprefix;
  404. matchend = prefixend;
  405. }
  406. if(lsubstr) {
  407. if(matches) {
  408. matchend->right = lsubstr;
  409. lsubstr->left = matchend;
  410. }
  411. else
  412. matches = lsubstr;
  413. matchend = substrend;
  414. }
  415. curr = sel = matches;
  416. calcoffsets();
  417. }
  418. size_t
  419. nextrune(int inc) {
  420. ssize_t n;
  421. /* return location of next utf8 rune in the given direction (+1 or -1) */
  422. for(n = cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc);
  423. return n;
  424. }
  425. void
  426. paste(void) {
  427. char *p, *q;
  428. int di;
  429. unsigned long dl;
  430. Atom da;
  431. /* we have been given the current selection, now insert it into input */
  432. XGetWindowProperty(dc->dpy, win, utf8, 0, (sizeof text / 4) + 1, False,
  433. utf8, &da, &di, &dl, &dl, (unsigned char **)&p);
  434. insert(p, (q = strchr(p, '\n')) ? q-p : (ssize_t)strlen(p));
  435. XFree(p);
  436. drawmenu();
  437. }
  438. void
  439. readstdin(void) {
  440. char buf[sizeof text], *p, *maxstr = NULL;
  441. size_t i, max = 0, size = 0;
  442. /* read each line from stdin and add it to the item list */
  443. for(i = 0; fgets(buf, sizeof buf, stdin); i++) {
  444. if(i+1 >= size / sizeof *items)
  445. if(!(items = realloc(items, (size += BUFSIZ))))
  446. eprintf("cannot realloc %u bytes:", size);
  447. if((p = strchr(buf, '\n')))
  448. *p = '\0';
  449. if(!(items[i].text = strdup(buf)))
  450. eprintf("cannot strdup %u bytes:", strlen(buf)+1);
  451. items[i].out = False;
  452. if(strlen(items[i].text) > max)
  453. max = strlen(maxstr = items[i].text);
  454. }
  455. if(items)
  456. items[i].text = NULL;
  457. inputw = maxstr ? textw(dc, maxstr) : 0;
  458. lines = MIN(lines, i);
  459. }
  460. void
  461. run(void) {
  462. XEvent ev;
  463. while(!XNextEvent(dc->dpy, &ev)) {
  464. if(XFilterEvent(&ev, win))
  465. continue;
  466. switch(ev.type) {
  467. case Expose:
  468. if(ev.xexpose.count == 0)
  469. mapdc(dc, win, mw, mh);
  470. break;
  471. case KeyPress:
  472. keypress(&ev.xkey);
  473. break;
  474. case SelectionNotify:
  475. if(ev.xselection.property == utf8)
  476. paste();
  477. break;
  478. case VisibilityNotify:
  479. if(ev.xvisibility.state != VisibilityUnobscured)
  480. XRaiseWindow(dc->dpy, win);
  481. break;
  482. }
  483. }
  484. }
  485. void
  486. setup(void) {
  487. int x, y, screen = DefaultScreen(dc->dpy);
  488. Window root = RootWindow(dc->dpy, screen);
  489. XSetWindowAttributes swa;
  490. XIM xim;
  491. #ifdef XINERAMA
  492. int n;
  493. XineramaScreenInfo *info;
  494. #endif
  495. normcol[ColBG] = getcolor(dc, normbgcolor);
  496. normcol[ColFG] = getcolor(dc, normfgcolor);
  497. selcol[ColBG] = getcolor(dc, selbgcolor);
  498. selcol[ColFG] = getcolor(dc, selfgcolor);
  499. outcol[ColBG] = getcolor(dc, outbgcolor);
  500. outcol[ColFG] = getcolor(dc, outfgcolor);
  501. clip = XInternAtom(dc->dpy, "CLIPBOARD", False);
  502. utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);
  503. /* calculate menu geometry */
  504. bh = dc->font.height + 2;
  505. lines = MAX(lines, 0);
  506. mh = (lines + 1) * bh;
  507. #ifdef XINERAMA
  508. if((info = XineramaQueryScreens(dc->dpy, &n))) {
  509. int a, j, di, i = 0, area = 0;
  510. unsigned int du;
  511. Window w, pw, dw, *dws;
  512. XWindowAttributes wa;
  513. XGetInputFocus(dc->dpy, &w, &di);
  514. if(w != root && w != PointerRoot && w != None) {
  515. /* find top-level window containing current input focus */
  516. do {
  517. if(XQueryTree(dc->dpy, (pw = w), &dw, &w, &dws, &du) && dws)
  518. XFree(dws);
  519. } while(w != root && w != pw);
  520. /* find xinerama screen with which the window intersects most */
  521. if(XGetWindowAttributes(dc->dpy, pw, &wa))
  522. for(j = 0; j < n; j++)
  523. if((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
  524. area = a;
  525. i = j;
  526. }
  527. }
  528. /* no focused window is on screen, so use pointer location instead */
  529. if(!area && XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
  530. for(i = 0; i < n; i++)
  531. if(INTERSECT(x, y, 1, 1, info[i]))
  532. break;
  533. x = info[i].x_org;
  534. y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
  535. mw = info[i].width;
  536. XFree(info);
  537. }
  538. else
  539. #endif
  540. {
  541. x = 0;
  542. y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - mh;
  543. mw = DisplayWidth(dc->dpy, screen);
  544. }
  545. promptw = (prompt && *prompt) ? textw(dc, prompt) : 0;
  546. inputw = MIN(inputw, mw/3);
  547. match();
  548. /* create menu window */
  549. swa.override_redirect = True;
  550. swa.background_pixel = normcol[ColBG];
  551. swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
  552. win = XCreateWindow(dc->dpy, root, x, y, mw, mh, 0,
  553. DefaultDepth(dc->dpy, screen), CopyFromParent,
  554. DefaultVisual(dc->dpy, screen),
  555. CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);
  556. /* open input methods */
  557. xim = XOpenIM(dc->dpy, NULL, NULL, NULL);
  558. xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
  559. XNClientWindow, win, XNFocusWindow, win, NULL);
  560. XMapRaised(dc->dpy, win);
  561. resizedc(dc, mw, mh);
  562. drawmenu();
  563. }
  564. void
  565. usage(void) {
  566. fputs("usage: dmenu [-b] [-f] [-i] [-l lines] [-p prompt] [-fn font]\n"
  567. " [-nb color] [-nf color] [-sb color] [-sf color] [-v]\n", stderr);
  568. exit(EXIT_FAILURE);
  569. }