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.
 
 
 
 
 
 

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