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.
 
 
 
 
 

1208 lines
31 KiB

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