A mirror of phillbush's xmenu.
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.
 
 
 
 
 

1061 lines
28 KiB

  1. #include <err.h>
  2. #include <errno.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <limits.h>
  7. #include <time.h>
  8. #include <unistd.h>
  9. #include <X11/Xlib.h>
  10. #include <X11/Xatom.h>
  11. #include <X11/Xutil.h>
  12. #include <X11/Xresource.h>
  13. #include <X11/XKBlib.h>
  14. #include <X11/Xft/Xft.h>
  15. #include <Imlib2.h>
  16. #include "xmenu.h"
  17. /*
  18. * Function declarations
  19. */
  20. /* argument parser */
  21. static void parseposition(const char *optarg);
  22. /* initializers, and their helper routines */
  23. static void ealloccolor(const char *s, XftColor *color);
  24. static void initresources(void);
  25. static void initdc(void);
  26. static void initconfig(void);
  27. static void initatoms(void);
  28. /* structure builders, and their helper routines */
  29. static struct Item *allocitem(const char *label, const char *output, char *file);
  30. static struct Menu *allocmenu(struct Menu *parent, struct Item *list, unsigned level);
  31. static struct Menu *buildmenutree(unsigned level, const char *label, const char *output, char *file);
  32. static struct Menu *parsestdin(void);
  33. /* image loader */
  34. static Imlib_Image loadicon(const char *file);
  35. /* structure setters, and their helper routines */
  36. static void setupitems(struct Menu *menu);
  37. static void setupmenupos(struct Menu *menu);
  38. static void setupmenu(struct Menu *menu, XClassHint *classh);
  39. /* grabbers */
  40. static void grabpointer(void);
  41. static void grabkeyboard(void);
  42. /* window drawers and mappers */
  43. static void mapmenu(struct Menu *currmenu);
  44. static void drawseparator(struct Menu *menu, struct Item *item);
  45. static void drawitem(struct Menu *menu, struct Item *item, XftColor *color);
  46. static void drawmenu(struct Menu *currmenu);
  47. /* main event loop, and its helper routines */
  48. static struct Menu *getmenu(struct Menu *currmenu, Window win);
  49. static struct Item *getitem(struct Menu *menu, int y);
  50. static struct Item *itemcycle(struct Menu *currmenu, int direction);
  51. static void run(struct Menu *currmenu);
  52. /* cleaners */
  53. static void cleanmenu(struct Menu *menu);
  54. static void cleanup(void);
  55. /* show usage */
  56. static void usage(void);
  57. /*
  58. * Variable declarations
  59. */
  60. /* X stuff */
  61. static Display *dpy;
  62. static int screen;
  63. static Visual *visual;
  64. static Window rootwin;
  65. static Colormap colormap;
  66. static struct DC dc;
  67. static Atom utf8string;
  68. static Atom wmdelete;
  69. static Atom netatom[NetLast];
  70. /* flags */
  71. static int iflag = 0; /* whether to disable icons */
  72. static int pflag = 0; /* whether the user specified a position */
  73. static int wflag = 0; /* whether to let the window manager control XMenu */
  74. /* include config variable */
  75. #include "config.h"
  76. /*
  77. * Function implementations
  78. */
  79. /* xmenu: generate menu from stdin and print selected entry to stdout */
  80. int
  81. main(int argc, char *argv[])
  82. {
  83. struct Menu *rootmenu;
  84. XClassHint classh;
  85. int ch;
  86. while ((ch = getopt(argc, argv, "ip:w")) != -1) {
  87. switch (ch) {
  88. case 'i':
  89. iflag = 1;
  90. break;
  91. case 'p':
  92. pflag = 1;
  93. parseposition(optarg);
  94. break;
  95. case 'w':
  96. wflag = 1;
  97. break;
  98. default:
  99. usage();
  100. break;
  101. }
  102. }
  103. argc -= optind;
  104. argv += optind;
  105. if (argc > 1)
  106. usage();
  107. /* open connection to server and set X variables */
  108. if ((dpy = XOpenDisplay(NULL)) == NULL)
  109. errx(1, "cannot open display");
  110. screen = DefaultScreen(dpy);
  111. visual = DefaultVisual(dpy, screen);
  112. rootwin = RootWindow(dpy, screen);
  113. colormap = DefaultColormap(dpy, screen);
  114. /* imlib2 stuff */
  115. if (!iflag) {
  116. imlib_set_cache_size(2048 * 1024);
  117. imlib_context_set_dither(1);
  118. imlib_context_set_display(dpy);
  119. imlib_context_set_visual(visual);
  120. imlib_context_set_colormap(colormap);
  121. }
  122. /* initializers */
  123. initresources();
  124. initdc();
  125. initconfig();
  126. initatoms();
  127. /* set window class */
  128. classh.res_class = PROGNAME;
  129. if (argc == 1)
  130. classh.res_name = *argv;
  131. else
  132. classh.res_name = PROGNAME;
  133. /* generate menus and set them up */
  134. rootmenu = parsestdin();
  135. if (rootmenu == NULL)
  136. errx(1, "no menu generated");
  137. setupmenu(rootmenu, &classh);
  138. /* grab mouse and keyboard */
  139. if (!wflag) {
  140. grabpointer();
  141. grabkeyboard();
  142. }
  143. /* run event loop */
  144. run(rootmenu);
  145. /* freeing stuff */
  146. cleanmenu(rootmenu);
  147. cleanup();
  148. return 0;
  149. }
  150. /* parse position string from -p, put results on config.x and config.y */
  151. static void
  152. parseposition(const char *optarg)
  153. {
  154. long n;
  155. const char *s = optarg;
  156. char *endp;
  157. n = strtol(s, &endp, 10);
  158. if (errno == ERANGE || n > INT_MAX || n < 0 || endp == s || *endp != 'x')
  159. goto error;
  160. config.posx = n;
  161. s = endp+1;
  162. n = strtol(s, &endp, 10);
  163. if (errno == ERANGE || n > INT_MAX || n < 0 || endp == s || *endp != '\0')
  164. goto error;
  165. config.posy = n;
  166. return;
  167. error:
  168. errx(1, "improper position: %s", optarg);
  169. }
  170. /* get color from color string */
  171. static void
  172. ealloccolor(const char *s, XftColor *color)
  173. {
  174. if(!XftColorAllocName(dpy, visual, colormap, s, color))
  175. errx(1, "cannot allocate color: %s", s);
  176. }
  177. /* read xrdb for configuration options */
  178. static void
  179. initresources(void)
  180. {
  181. char *xrm;
  182. long n;
  183. char *type;
  184. XrmDatabase xdb;
  185. XrmValue xval;
  186. XrmInitialize();
  187. if ((xrm = XResourceManagerString(dpy)) == NULL)
  188. return;
  189. xdb = XrmGetStringDatabase(xrm);
  190. if (XrmGetResource(xdb, "xmenu.borderWidth", "*", &type, &xval) == True)
  191. if ((n = strtol(xval.addr, NULL, 10)) > 0)
  192. config.border_pixels = n;
  193. if (XrmGetResource(xdb, "xmenu.separatorWidth", "*", &type, &xval) == True)
  194. if ((n = strtol(xval.addr, NULL, 10)) > 0)
  195. config.separator_pixels = n;
  196. if (XrmGetResource(xdb, "xmenu.height", "*", &type, &xval) == True)
  197. if ((n = strtol(xval.addr, NULL, 10)) > 0)
  198. config.height_pixels = n;
  199. if (XrmGetResource(xdb, "xmenu.width", "*", &type, &xval) == True)
  200. if ((n = strtol(xval.addr, NULL, 10)) > 0)
  201. config.width_pixels = n;
  202. if (XrmGetResource(xdb, "xmenu.gap", "*", &type, &xval) == True)
  203. if ((n = strtol(xval.addr, NULL, 10)) > 0)
  204. config.gap_pixels = n;
  205. if (XrmGetResource(xdb, "xmenu.background", "*", &type, &xval) == True)
  206. config.background_color = strdup(xval.addr);
  207. if (XrmGetResource(xdb, "xmenu.foreground", "*", &type, &xval) == True)
  208. config.foreground_color = strdup(xval.addr);
  209. if (XrmGetResource(xdb, "xmenu.selbackground", "*", &type, &xval) == True)
  210. config.selbackground_color = strdup(xval.addr);
  211. if (XrmGetResource(xdb, "xmenu.selforeground", "*", &type, &xval) == True)
  212. config.selforeground_color = strdup(xval.addr);
  213. if (XrmGetResource(xdb, "xmenu.separator", "*", &type, &xval) == True)
  214. config.separator_color = strdup(xval.addr);
  215. if (XrmGetResource(xdb, "xmenu.border", "*", &type, &xval) == True)
  216. config.border_color = strdup(xval.addr);
  217. if (XrmGetResource(xdb, "xmenu.font", "*", &type, &xval) == True)
  218. config.font = strdup(xval.addr);
  219. XrmDestroyDatabase(xdb);
  220. }
  221. /* init draw context */
  222. static void
  223. initdc(void)
  224. {
  225. /* get color pixels */
  226. ealloccolor(config.background_color, &dc.normal[ColorBG]);
  227. ealloccolor(config.foreground_color, &dc.normal[ColorFG]);
  228. ealloccolor(config.selbackground_color, &dc.selected[ColorBG]);
  229. ealloccolor(config.selforeground_color, &dc.selected[ColorFG]);
  230. ealloccolor(config.separator_color, &dc.separator);
  231. ealloccolor(config.border_color, &dc.border);
  232. /* try to get font */
  233. if ((dc.font = XftFontOpenName(dpy, screen, config.font)) == NULL)
  234. errx(1, "cannot load font");
  235. /* create common GC */
  236. dc.gc = XCreateGC(dpy, rootwin, 0, NULL);
  237. }
  238. /* calculate configuration values that are not set manually */
  239. static void
  240. initconfig(void)
  241. {
  242. Window dw; /* dummy variable */
  243. int di; /* dummy variable */
  244. unsigned du; /* dummy variable */
  245. if (!pflag) /* if the user haven't specified a position, use cursor position*/
  246. XQueryPointer(dpy, rootwin, &dw, &dw, &config.posx, &config.posy, &di, &di, &du);
  247. config.screenw = DisplayWidth(dpy, screen);
  248. config.screenh = DisplayHeight(dpy, screen);
  249. config.iconsize = config.height_pixels - config.iconpadding * 2;
  250. }
  251. /* intern atoms */
  252. static void
  253. initatoms(void)
  254. {
  255. utf8string = XInternAtom(dpy, "UTF8_STRING", False);
  256. wmdelete = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
  257. netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
  258. netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
  259. netatom[NetWMWindowTypePopupMenu] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_POPUP_MENU", False);
  260. }
  261. /* allocate an item */
  262. static struct Item *
  263. allocitem(const char *label, const char *output, char *file)
  264. {
  265. struct Item *item;
  266. if ((item = malloc(sizeof *item)) == NULL)
  267. err(1, "malloc");
  268. if (label == NULL) {
  269. item->label = NULL;
  270. item->output = NULL;
  271. } else {
  272. if ((item->label = strdup(label)) == NULL)
  273. err(1, "strdup");
  274. if (label == output) {
  275. item->output = item->label;
  276. } else {
  277. if ((item->output = strdup(output)) == NULL)
  278. err(1, "strdup");
  279. }
  280. }
  281. if (file == NULL) {
  282. item->file = NULL;
  283. } else {
  284. if ((item->file = strdup(file)) == NULL)
  285. err(1, "strdup");
  286. }
  287. item->y = 0;
  288. item->h = 0;
  289. if (item->label == NULL)
  290. item->labellen = 0;
  291. else
  292. item->labellen = strlen(item->label);
  293. item->next = NULL;
  294. item->submenu = NULL;
  295. item->icon = NULL;
  296. return item;
  297. }
  298. /* allocate a menu and create its window */
  299. static struct Menu *
  300. allocmenu(struct Menu *parent, struct Item *list, unsigned level)
  301. {
  302. XSetWindowAttributes swa;
  303. struct Menu *menu;
  304. if ((menu = malloc(sizeof *menu)) == NULL)
  305. err(1, "malloc");
  306. menu->parent = parent;
  307. menu->list = list;
  308. menu->caller = NULL;
  309. menu->selected = NULL;
  310. menu->w = 0; /* calculated by setupmenu() */
  311. menu->h = 0; /* calculated by setupmenu() */
  312. menu->x = 0; /* calculated by setupmenu() */
  313. menu->y = 0; /* calculated by setupmenu() */
  314. menu->level = level;
  315. swa.override_redirect = (wflag) ? False : True;
  316. swa.background_pixel = dc.normal[ColorBG].pixel;
  317. swa.border_pixel = dc.border.pixel;
  318. swa.save_under = True; /* pop-up windows should save_under*/
  319. swa.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask
  320. | PointerMotionMask | LeaveWindowMask;
  321. if (wflag)
  322. swa.event_mask |= StructureNotifyMask;
  323. menu->win = XCreateWindow(dpy, rootwin, 0, 0, 1, 1, 0,
  324. CopyFromParent, CopyFromParent, CopyFromParent,
  325. CWOverrideRedirect | CWBackPixel |
  326. CWBorderPixel | CWEventMask | CWSaveUnder,
  327. &swa);
  328. return menu;
  329. }
  330. /* build the menu tree */
  331. static struct Menu *
  332. buildmenutree(unsigned level, const char *label, const char *output, char *file)
  333. {
  334. static struct Menu *prevmenu = NULL; /* menu the previous item was added to */
  335. static struct Menu *rootmenu = NULL; /* menu to be returned */
  336. struct Item *curritem = NULL; /* item currently being read */
  337. struct Item *item; /* dummy item for loops */
  338. struct Menu *menu; /* dummy menu for loops */
  339. unsigned i;
  340. /* create the item */
  341. curritem = allocitem(label, output, file);
  342. /* put the item in the menu tree */
  343. if (prevmenu == NULL) { /* there is no menu yet */
  344. menu = allocmenu(NULL, curritem, level);
  345. rootmenu = menu;
  346. prevmenu = menu;
  347. curritem->prev = NULL;
  348. } else if (level < prevmenu->level) { /* item is continuation of a parent menu */
  349. /* go up the menu tree until find the menu this item continues */
  350. for (menu = prevmenu, i = level;
  351. menu != NULL && i != prevmenu->level;
  352. menu = menu->parent, i++)
  353. ;
  354. if (menu == NULL)
  355. errx(1, "reached NULL menu");
  356. /* find last item in the new menu */
  357. for (item = menu->list; item->next != NULL; item = item->next)
  358. ;
  359. prevmenu = menu;
  360. item->next = curritem;
  361. curritem->prev = item;
  362. } else if (level == prevmenu->level) { /* item is a continuation of current menu */
  363. /* find last item in the previous menu */
  364. for (item = prevmenu->list; item->next != NULL; item = item->next)
  365. ;
  366. item->next = curritem;
  367. curritem->prev = item;
  368. } else if (level > prevmenu->level) { /* item begins a new menu */
  369. menu = allocmenu(prevmenu, curritem, level);
  370. /* find last item in the previous menu */
  371. for (item = prevmenu->list; item->next != NULL; item = item->next)
  372. ;
  373. prevmenu = menu;
  374. menu->caller = item;
  375. item->submenu = menu;
  376. curritem->prev = NULL;
  377. }
  378. return rootmenu;
  379. }
  380. /* create menus and items from the stdin */
  381. static struct Menu *
  382. parsestdin(void)
  383. {
  384. struct Menu *rootmenu;
  385. char *s, buf[BUFSIZ];
  386. char *file, *label, *output;
  387. unsigned level = 0;
  388. rootmenu = NULL;
  389. while (fgets(buf, BUFSIZ, stdin) != NULL) {
  390. /* get the indentation level */
  391. level = strspn(buf, "\t");
  392. /* get the label */
  393. s = level + buf;
  394. label = strtok(s, "\t\n");
  395. /* get the filename */
  396. file = NULL;
  397. if (label != NULL && strncmp(label, "IMG:", 4) == 0) {
  398. file = label + 4;
  399. label = strtok(NULL, "\t\n");
  400. }
  401. /* get the output */
  402. output = strtok(NULL, "\n");
  403. if (output == NULL) {
  404. output = label;
  405. } else {
  406. while (*output == '\t')
  407. output++;
  408. }
  409. rootmenu = buildmenutree(level, label, output, file);
  410. }
  411. return rootmenu;
  412. }
  413. /* load and scale icon */
  414. static Imlib_Image
  415. loadicon(const char *file)
  416. {
  417. Imlib_Image icon;
  418. int width;
  419. int height;
  420. int imgsize;
  421. icon = imlib_load_image(file);
  422. if (icon == NULL)
  423. errx(1, "cannot load icon %s", file);
  424. imlib_context_set_image(icon);
  425. width = imlib_image_get_width();
  426. height = imlib_image_get_height();
  427. imgsize = MIN(width, height);
  428. icon = imlib_create_cropped_scaled_image(0, 0, imgsize, imgsize,
  429. config.iconsize,
  430. config.iconsize);
  431. return icon;
  432. }
  433. /* setup the height, width and icon of the items of a menu */
  434. static void
  435. setupitems(struct Menu *menu)
  436. {
  437. XGlyphInfo ext;
  438. struct Item *item;
  439. int itemwidth;
  440. menu->w = config.width_pixels;
  441. for (item = menu->list; item != NULL; item = item->next) {
  442. item->y = menu->h;
  443. if (item->label == NULL) /* height for separator item */
  444. item->h = config.separator_pixels;
  445. else
  446. item->h = config.height_pixels;
  447. menu->h += item->h;
  448. /* get length of item->label rendered in the font */
  449. XftTextExtentsUtf8(dpy, dc.font, (XftChar8 *)item->label,
  450. item->labellen, &ext);
  451. /*
  452. * set menu width
  453. *
  454. * the item width depends on the size of its label (ext.xOff),
  455. * and it is only used to calculate the width of the menu (which
  456. * is equal to the width of the largest item).
  457. *
  458. * the horizontal padding appears 4 times through the width of a
  459. * item: before and after its icon, and before and after its triangle
  460. * if the iflag is set (icons are disabled) then the horizontal
  461. * padding appears before the label and around the triangle.
  462. */
  463. itemwidth = ext.xOff + config.triangle_width + config.horzpadding * 3;
  464. itemwidth += (iflag) ? 0 : config.iconsize + config.horzpadding;
  465. menu->w = MAX(menu->w, itemwidth);
  466. /* create icon */
  467. if (item->file != NULL && !iflag)
  468. item->icon = loadicon(item->file);
  469. }
  470. }
  471. /* setup the position of a menu */
  472. static void
  473. setupmenupos(struct Menu *menu)
  474. {
  475. int width, height;
  476. width = menu->w + config.border_pixels * 2;
  477. height = menu->h + config.border_pixels * 2;
  478. if (menu->parent == NULL) { /* if root menu, calculate in respect to cursor */
  479. if (pflag || config.screenw - config.posx >= menu->w)
  480. menu->x = config.posx;
  481. else if (config.posx > width)
  482. menu->x = config.posx - width;
  483. if (pflag || config.screenh - config.posy >= height)
  484. menu->y = config.posy;
  485. else if (config.screenh > height)
  486. menu->y = config.screenh - height;
  487. } else { /* else, calculate in respect to parent menu */
  488. if (config.screenw - (menu->parent->x + menu->parent->w + config.border_pixels + config.gap_pixels) >= width)
  489. menu->x = menu->parent->x + menu->parent->w + config.border_pixels + config.gap_pixels;
  490. else if (menu->parent->x > menu->w + config.border_pixels + config.gap_pixels)
  491. menu->x = menu->parent->x - menu->w - config.border_pixels - config.gap_pixels;
  492. if (config.screenh - (menu->caller->y + menu->parent->y) > height)
  493. menu->y = menu->caller->y + menu->parent->y;
  494. else if (config.screenh - menu->parent->y > height)
  495. menu->y = menu->parent->y;
  496. else if (config.screenh > height)
  497. menu->y = config.screenh - height;
  498. }
  499. }
  500. /* recursivelly setup menu configuration and its pixmap */
  501. static void
  502. setupmenu(struct Menu *menu, XClassHint *classh)
  503. {
  504. char *title;
  505. struct Item *item;
  506. XWindowChanges changes;
  507. XSizeHints sizeh;
  508. XTextProperty wintitle;
  509. /* setup size and position of menus */
  510. setupitems(menu);
  511. setupmenupos(menu);
  512. /* update menu geometry */
  513. changes.border_width = config.border_pixels;
  514. changes.height = menu->h;
  515. changes.width = menu->w;
  516. changes.x = menu->x;
  517. changes.y = menu->y;
  518. XConfigureWindow(dpy, menu->win, CWBorderWidth | CWWidth | CWHeight | CWX | CWY, &changes);
  519. /* set window title (used if wflag is on) */
  520. if (menu->parent == NULL) {
  521. title = classh->res_name;
  522. } else {
  523. title = menu->caller->output;
  524. }
  525. XStringListToTextProperty(&title, 1, &wintitle);
  526. /* set window manager hints */
  527. sizeh.flags = PMaxSize | PMinSize;
  528. sizeh.min_width = sizeh.max_width = menu->w;
  529. sizeh.min_height = sizeh.max_height = menu->h;
  530. XSetWMProperties(dpy, menu->win, &wintitle, NULL, NULL, 0, &sizeh, NULL, classh);
  531. /* create pixmap and XftDraw */
  532. menu->pixmap = XCreatePixmap(dpy, menu->win, menu->w, menu->h,
  533. DefaultDepth(dpy, screen));
  534. menu->draw = XftDrawCreate(dpy, menu->pixmap, visual, colormap);
  535. /* set WM protocols and ewmh window properties */
  536. XSetWMProtocols(dpy, menu->win, &wmdelete, 1);
  537. XChangeProperty(dpy, menu->win, netatom[NetWMName], utf8string, 8,
  538. PropModeReplace, (unsigned char *)title, strlen(title));
  539. XChangeProperty(dpy, menu->win, netatom[NetWMWindowType], XA_ATOM, 32,
  540. PropModeReplace,
  541. (unsigned char *)&netatom[NetWMWindowTypePopupMenu], 1);
  542. /* calculate positions of submenus */
  543. for (item = menu->list; item != NULL; item = item->next) {
  544. if (item->submenu != NULL)
  545. setupmenu(item->submenu, classh);
  546. }
  547. }
  548. /* try to grab pointer, we may have to wait for another process to ungrab */
  549. static void
  550. grabpointer(void)
  551. {
  552. struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
  553. int i;
  554. for (i = 0; i < 1000; i++) {
  555. if (XGrabPointer(dpy, rootwin, True, ButtonPressMask,
  556. GrabModeAsync, GrabModeAsync, None,
  557. None, CurrentTime) == GrabSuccess)
  558. return;
  559. nanosleep(&ts, NULL);
  560. }
  561. errx(1, "cannot grab keyboard");
  562. }
  563. /* try to grab keyboard, we may have to wait for another process to ungrab */
  564. static void
  565. grabkeyboard(void)
  566. {
  567. struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
  568. int i;
  569. for (i = 0; i < 1000; i++) {
  570. if (XGrabKeyboard(dpy, rootwin, True, GrabModeAsync,
  571. GrabModeAsync, CurrentTime) == GrabSuccess)
  572. return;
  573. nanosleep(&ts, NULL);
  574. }
  575. errx(1, "cannot grab keyboard");
  576. }
  577. /* umap previous menus and map current menu and its parents */
  578. static void
  579. mapmenu(struct Menu *currmenu)
  580. {
  581. static struct Menu *prevmenu = NULL;
  582. struct Menu *menu, *menu_;
  583. struct Menu *lcamenu; /* lowest common ancestor menu */
  584. unsigned minlevel; /* level of the closest to root menu */
  585. unsigned maxlevel; /* level of the closest to root menu */
  586. /* do not remap current menu if it wasn't updated*/
  587. if (prevmenu == currmenu)
  588. return;
  589. /* if this is the first time mapping, skip calculations */
  590. if (prevmenu == NULL) {
  591. XMapWindow(dpy, currmenu->win);
  592. prevmenu = currmenu;
  593. return;
  594. }
  595. /* find lowest common ancestor menu */
  596. minlevel = MIN(currmenu->level, prevmenu->level);
  597. maxlevel = MAX(currmenu->level, prevmenu->level);
  598. if (currmenu->level == maxlevel) {
  599. menu = currmenu;
  600. menu_ = prevmenu;
  601. } else {
  602. menu = prevmenu;
  603. menu_ = currmenu;
  604. }
  605. while (menu->level > minlevel)
  606. menu = menu->parent;
  607. while (menu != menu_) {
  608. menu = menu->parent;
  609. menu_ = menu_->parent;
  610. }
  611. lcamenu = menu;
  612. /* unmap menus from currmenu (inclusive) until lcamenu (exclusive) */
  613. for (menu = prevmenu; menu != lcamenu; menu = menu->parent) {
  614. menu->selected = NULL;
  615. XUnmapWindow(dpy, menu->win);
  616. }
  617. /* map menus from currmenu (inclusive) until lcamenu (exclusive) */
  618. for (menu = currmenu; menu != lcamenu; menu = menu->parent) {
  619. if (wflag) {
  620. setupmenupos(menu);
  621. XMoveWindow(dpy, menu->win, menu->x, menu->y);
  622. }
  623. XMapWindow(dpy, menu->win);
  624. }
  625. prevmenu = currmenu;
  626. }
  627. /* draw separator item */
  628. static void
  629. drawseparator(struct Menu *menu, struct Item *item)
  630. {
  631. int y;
  632. y = item->y + item->h/2;
  633. XSetForeground(dpy, dc.gc, dc.separator.pixel);
  634. XDrawLine(dpy, menu->pixmap, dc.gc, config.horzpadding, y,
  635. menu->w - config.horzpadding, y);
  636. }
  637. /* draw regular item */
  638. static void
  639. drawitem(struct Menu *menu, struct Item *item, XftColor *color)
  640. {
  641. int x, y;
  642. x = config.horzpadding;
  643. x += (iflag) ? 0 : config.horzpadding + config.iconsize;
  644. y = item->y + (item->h + dc.font->ascent) / 2;
  645. XSetForeground(dpy, dc.gc, color[ColorFG].pixel);
  646. XftDrawStringUtf8(menu->draw, &color[ColorFG], dc.font,
  647. x, y, (XftChar8 *)item->label, item->labellen);
  648. /* draw triangle, if item contains a submenu */
  649. if (item->submenu != NULL) {
  650. x = menu->w - config.triangle_width - config.horzpadding;
  651. y = item->y + (item->h - config.triangle_height + 1) / 2;
  652. XPoint triangle[] = {
  653. {x, y},
  654. {x + config.triangle_width, y + config.triangle_height/2},
  655. {x, y + config.triangle_height},
  656. {x, y}
  657. };
  658. XFillPolygon(dpy, menu->pixmap, dc.gc, triangle, LEN(triangle),
  659. Convex, CoordModeOrigin);
  660. }
  661. /* draw icon */
  662. if (item->icon != NULL) {
  663. x = config.horzpadding;
  664. y = item->y + config.iconpadding;
  665. imlib_context_set_drawable(menu->pixmap);
  666. imlib_context_set_image(item->icon);
  667. imlib_render_image_on_drawable(x, y);
  668. }
  669. }
  670. /* draw items of the current menu and of its ancestors */
  671. static void
  672. drawmenu(struct Menu *currmenu)
  673. {
  674. struct Menu *menu;
  675. struct Item *item;
  676. for (menu = currmenu; menu != NULL; menu = menu->parent) {
  677. for (item = menu->list; item != NULL; item = item->next) {
  678. XftColor *color;
  679. /* determine item color */
  680. if (item == menu->selected && item->label != NULL)
  681. color = dc.selected;
  682. else
  683. color = dc.normal;
  684. /* draw item box */
  685. XSetForeground(dpy, dc.gc, color[ColorBG].pixel);
  686. XFillRectangle(dpy, menu->pixmap, dc.gc, 0, item->y,
  687. menu->w, item->h);
  688. if (item->label == NULL) /* item is a separator */
  689. drawseparator(menu, item);
  690. else /* item is a regular item */
  691. drawitem(menu, item, color);
  692. }
  693. XCopyArea(dpy, menu->pixmap, menu->win, dc.gc, 0, 0,
  694. menu->w, menu->h, 0, 0);
  695. }
  696. }
  697. /* get menu of given window */
  698. static struct Menu *
  699. getmenu(struct Menu *currmenu, Window win)
  700. {
  701. struct Menu *menu;
  702. for (menu = currmenu; menu != NULL; menu = menu->parent)
  703. if (menu->win == win)
  704. return menu;
  705. return NULL;
  706. }
  707. /* get item of given menu and position */
  708. static struct Item *
  709. getitem(struct Menu *menu, int y)
  710. {
  711. struct Item *item;
  712. if (menu == NULL)
  713. return NULL;
  714. for (item = menu->list; item != NULL; item = item->next)
  715. if (y >= item->y && y <= item->y + item->h)
  716. return item;
  717. return NULL;
  718. }
  719. /* cycle through the items; non-zero direction is next, zero is prev */
  720. static struct Item *
  721. itemcycle(struct Menu *currmenu, int direction)
  722. {
  723. struct Item *item;
  724. struct Item *lastitem;
  725. item = NULL;
  726. if (direction == ITEMNEXT) {
  727. if (currmenu->selected == NULL)
  728. item = currmenu->list;
  729. else if (currmenu->selected->next != NULL)
  730. item = currmenu->selected->next;
  731. while (item != NULL && item->label == NULL)
  732. item = item->next;
  733. if (item == NULL)
  734. item = currmenu->list;
  735. } else {
  736. for (lastitem = currmenu->list;
  737. lastitem != NULL && lastitem->next != NULL;
  738. lastitem = lastitem->next)
  739. ;
  740. if (currmenu->selected == NULL)
  741. item = lastitem;
  742. else if (currmenu->selected->prev != NULL)
  743. item = currmenu->selected->prev;
  744. while (item != NULL && item->label == NULL)
  745. item = item->prev;
  746. if (item == NULL)
  747. item = lastitem;
  748. }
  749. return item;
  750. }
  751. /* run event loop */
  752. static void
  753. run(struct Menu *currmenu)
  754. {
  755. struct Menu *menu;
  756. struct Item *item;
  757. struct Item *previtem = NULL;
  758. KeySym ksym;
  759. XEvent ev;
  760. mapmenu(currmenu);
  761. while (!XNextEvent(dpy, &ev)) {
  762. switch(ev.type) {
  763. case Expose:
  764. if (ev.xexpose.count == 0)
  765. drawmenu(currmenu);
  766. break;
  767. case MotionNotify:
  768. menu = getmenu(currmenu, ev.xbutton.window);
  769. item = getitem(menu, ev.xbutton.y);
  770. if (menu == NULL || item == NULL || previtem == item)
  771. break;
  772. previtem = item;
  773. menu->selected = item;
  774. if (item->submenu != NULL) {
  775. currmenu = item->submenu;
  776. currmenu->selected = NULL;
  777. } else {
  778. currmenu = menu;
  779. }
  780. mapmenu(currmenu);
  781. drawmenu(currmenu);
  782. break;
  783. case ButtonRelease:
  784. menu = getmenu(currmenu, ev.xbutton.window);
  785. item = getitem(menu, ev.xbutton.y);
  786. if (menu == NULL || item == NULL)
  787. break;
  788. selectitem:
  789. if (item->label == NULL)
  790. break; /* ignore separators */
  791. if (item->submenu != NULL) {
  792. currmenu = item->submenu;
  793. } else {
  794. printf("%s\n", item->output);
  795. return;
  796. }
  797. mapmenu(currmenu);
  798. currmenu->selected = currmenu->list;
  799. drawmenu(currmenu);
  800. break;
  801. case ButtonPress:
  802. menu = getmenu(currmenu, ev.xbutton.window);
  803. if (menu == NULL)
  804. return;
  805. break;
  806. case KeyPress:
  807. ksym = XkbKeycodeToKeysym(dpy, ev.xkey.keycode, 0, 0);
  808. /* esc closes xmenu when current menu is the root menu */
  809. if (ksym == XK_Escape && currmenu->parent == NULL)
  810. return;
  811. /* Shift-Tab = ISO_Left_Tab */
  812. if (ksym == XK_Tab && (ev.xkey.state & ShiftMask))
  813. ksym = XK_ISO_Left_Tab;
  814. /* cycle through menu */
  815. item = NULL;
  816. if (ksym == XK_ISO_Left_Tab || ksym == XK_Up) {
  817. item = itemcycle(currmenu, ITEMPREV);
  818. } else if (ksym == XK_Tab || ksym == XK_Down) {
  819. item = itemcycle(currmenu, ITEMNEXT);
  820. } else if ((ksym == XK_Return || ksym == XK_Right) &&
  821. currmenu->selected != NULL) {
  822. item = currmenu->selected;
  823. goto selectitem;
  824. } else if ((ksym == XK_Escape || ksym == XK_Left) &&
  825. currmenu->parent != NULL) {
  826. item = currmenu->parent->selected;
  827. currmenu = currmenu->parent;
  828. mapmenu(currmenu);
  829. } else
  830. break;
  831. currmenu->selected = item;
  832. drawmenu(currmenu);
  833. break;
  834. case LeaveNotify:
  835. previtem = NULL;
  836. currmenu->selected = NULL;
  837. drawmenu(currmenu);
  838. break;
  839. case ConfigureNotify:
  840. menu = getmenu(currmenu, ev.xconfigure.window);
  841. if (menu == NULL)
  842. break;
  843. menu->x = ev.xconfigure.x;
  844. menu->y = ev.xconfigure.y;
  845. break;
  846. case ClientMessage:
  847. if ((unsigned long) ev.xclient.data.l[0] != wmdelete)
  848. break;
  849. /* user closed window */
  850. menu = getmenu(currmenu, ev.xclient.window);
  851. if (menu->parent == NULL)
  852. return; /* closing the root menu closes the program */
  853. currmenu = menu->parent;
  854. mapmenu(currmenu);
  855. break;
  856. }
  857. }
  858. }
  859. /* recursivelly free pixmaps and destroy windows */
  860. static void
  861. cleanmenu(struct Menu *menu)
  862. {
  863. struct Item *item;
  864. struct Item *tmp;
  865. item = menu->list;
  866. while (item != NULL) {
  867. if (item->submenu != NULL)
  868. cleanmenu(item->submenu);
  869. tmp = item;
  870. if (tmp->label != tmp->output)
  871. free(tmp->label);
  872. free(tmp->output);
  873. if (tmp->file != NULL) {
  874. free(tmp->file);
  875. if (tmp->icon != NULL) {
  876. imlib_context_set_image(tmp->icon);
  877. imlib_free_image();
  878. }
  879. }
  880. item = item->next;
  881. free(tmp);
  882. }
  883. XFreePixmap(dpy, menu->pixmap);
  884. XftDrawDestroy(menu->draw);
  885. XDestroyWindow(dpy, menu->win);
  886. free(menu);
  887. }
  888. /* cleanup X and exit */
  889. static void
  890. cleanup(void)
  891. {
  892. XUngrabPointer(dpy, CurrentTime);
  893. XUngrabKeyboard(dpy, CurrentTime);
  894. XftColorFree(dpy, visual, colormap, &dc.normal[ColorBG]);
  895. XftColorFree(dpy, visual, colormap, &dc.normal[ColorFG]);
  896. XftColorFree(dpy, visual, colormap, &dc.selected[ColorBG]);
  897. XftColorFree(dpy, visual, colormap, &dc.selected[ColorFG]);
  898. XftColorFree(dpy, visual, colormap, &dc.separator);
  899. XftColorFree(dpy, visual, colormap, &dc.border);
  900. XFreeGC(dpy, dc.gc);
  901. XCloseDisplay(dpy);
  902. }
  903. /* show usage */
  904. static void
  905. usage(void)
  906. {
  907. (void)fprintf(stderr, "usage: xmenu [-iw] [-p position] [title]\n");
  908. exit(1);
  909. }