My dmenu build
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

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