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.
 
 
 
 
 

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