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.
 
 
 
 
 
 

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