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.
 
 
 
 
 

1273 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 (BETWEEN(cursx, info[i].x_org, info[i].x_org + info[i].width) &&
  253. BETWEEN(cursy, info[i].y_org, 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. item->next = NULL;
  379. item->submenu = NULL;
  380. item->icon = NULL;
  381. return item;
  382. }
  383. /* allocate a menu and create its window */
  384. static struct Menu *
  385. allocmenu(struct Menu *parent, struct Item *list, unsigned level)
  386. {
  387. XSetWindowAttributes swa;
  388. struct Menu *menu;
  389. if ((menu = malloc(sizeof *menu)) == NULL)
  390. err(1, "malloc");
  391. menu->parent = parent;
  392. menu->list = list;
  393. menu->caller = NULL;
  394. menu->selected = NULL;
  395. menu->w = 0; /* recalculated by setupmenu() */
  396. menu->h = 0; /* recalculated by setupmenu() */
  397. menu->x = mon.x; /* recalculated by setupmenu() */
  398. menu->y = mon.y; /* recalculated by setupmenu() */
  399. menu->level = level;
  400. menu->drawn = 0;
  401. menu->hasicon = 0;
  402. swa.override_redirect = (wflag) ? False : True;
  403. swa.background_pixel = dc.normal[ColorBG].pixel;
  404. swa.border_pixel = dc.border.pixel;
  405. swa.save_under = True; /* pop-up windows should save_under*/
  406. swa.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask
  407. | PointerMotionMask | LeaveWindowMask;
  408. if (wflag)
  409. swa.event_mask |= StructureNotifyMask;
  410. menu->win = XCreateWindow(dpy, rootwin, 0, 0, 1, 1, 0,
  411. CopyFromParent, CopyFromParent, CopyFromParent,
  412. CWOverrideRedirect | CWBackPixel |
  413. CWBorderPixel | CWEventMask | CWSaveUnder,
  414. &swa);
  415. return menu;
  416. }
  417. /* build the menu tree */
  418. static struct Menu *
  419. buildmenutree(unsigned level, const char *label, const char *output, char *file)
  420. {
  421. static struct Menu *prevmenu = NULL; /* menu the previous item was added to */
  422. static struct Menu *rootmenu = NULL; /* menu to be returned */
  423. struct Item *curritem = NULL; /* item currently being read */
  424. struct Item *item; /* dummy item for loops */
  425. struct Menu *menu; /* dummy menu for loops */
  426. unsigned i;
  427. /* create the item */
  428. curritem = allocitem(label, output, file);
  429. /* put the item in the menu tree */
  430. if (prevmenu == NULL) { /* there is no menu yet */
  431. menu = allocmenu(NULL, curritem, level);
  432. rootmenu = menu;
  433. prevmenu = menu;
  434. curritem->prev = NULL;
  435. } else if (level < prevmenu->level) { /* item is continuation of a parent menu */
  436. /* go up the menu tree until find the menu this item continues */
  437. for (menu = prevmenu, i = level;
  438. menu != NULL && i != prevmenu->level;
  439. menu = menu->parent, i++)
  440. ;
  441. if (menu == NULL)
  442. errx(1, "reached NULL menu");
  443. /* find last item in the new menu */
  444. for (item = menu->list; item->next != NULL; item = item->next)
  445. ;
  446. prevmenu = menu;
  447. item->next = curritem;
  448. curritem->prev = item;
  449. } else if (level == prevmenu->level) { /* item is a continuation of current menu */
  450. /* find last item in the previous menu */
  451. for (item = prevmenu->list; item->next != NULL; item = item->next)
  452. ;
  453. item->next = curritem;
  454. curritem->prev = item;
  455. } else if (level > prevmenu->level) { /* item begins a new menu */
  456. menu = allocmenu(prevmenu, curritem, level);
  457. /* find last item in the previous menu */
  458. for (item = prevmenu->list; item->next != NULL; item = item->next)
  459. ;
  460. prevmenu = menu;
  461. menu->caller = item;
  462. item->submenu = menu;
  463. curritem->prev = NULL;
  464. }
  465. if (curritem->file)
  466. prevmenu->hasicon = 1;
  467. return rootmenu;
  468. }
  469. /* create menus and items from the stdin */
  470. static struct Menu *
  471. parsestdin(void)
  472. {
  473. struct Menu *rootmenu;
  474. char *s, buf[BUFSIZ];
  475. char *file, *label, *output;
  476. unsigned level = 0;
  477. rootmenu = NULL;
  478. while (fgets(buf, BUFSIZ, stdin) != NULL) {
  479. /* get the indentation level */
  480. level = strspn(buf, "\t");
  481. /* get the label */
  482. s = level + buf;
  483. label = strtok(s, "\t\n");
  484. /* get the filename */
  485. file = NULL;
  486. if (label != NULL && strncmp(label, "IMG:", 4) == 0) {
  487. file = label + 4;
  488. label = strtok(NULL, "\t\n");
  489. }
  490. /* get the output */
  491. output = strtok(NULL, "\n");
  492. if (output == NULL) {
  493. output = label;
  494. } else {
  495. while (*output == '\t')
  496. output++;
  497. }
  498. rootmenu = buildmenutree(level, label, output, file);
  499. }
  500. return rootmenu;
  501. }
  502. /* get next utf8 char from s return its codepoint and set next_ret to pointer to end of character */
  503. static FcChar32
  504. getnextutf8char(const char *s, const char **next_ret)
  505. {
  506. static const unsigned char utfbyte[] = {0x80, 0x00, 0xC0, 0xE0, 0xF0};
  507. static const unsigned char utfmask[] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
  508. static const FcChar32 utfmin[] = {0, 0x00, 0x80, 0x800, 0x10000};
  509. static const FcChar32 utfmax[] = {0, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
  510. /* 0xFFFD is the replacement character, used to represent unknown characters */
  511. static const FcChar32 unknown = 0xFFFD;
  512. FcChar32 ucode; /* FcChar32 type holds 32 bits */
  513. size_t usize = 0; /* n' of bytes of the utf8 character */
  514. size_t i;
  515. *next_ret = s+1;
  516. /* get code of first byte of utf8 character */
  517. for (i = 0; i < sizeof utfmask; i++) {
  518. if (((unsigned char)*s & utfmask[i]) == utfbyte[i]) {
  519. usize = i;
  520. ucode = (unsigned char)*s & ~utfmask[i];
  521. break;
  522. }
  523. }
  524. /* if first byte is a continuation byte or is not allowed, return unknown */
  525. if (i == sizeof utfmask || usize == 0)
  526. return unknown;
  527. /* check the other usize-1 bytes */
  528. s++;
  529. for (i = 1; i < usize; i++) {
  530. *next_ret = s+1;
  531. /* if byte is nul or is not a continuation byte, return unknown */
  532. if (*s == '\0' || ((unsigned char)*s & utfmask[0]) != utfbyte[0])
  533. return unknown;
  534. /* 6 is the number of relevant bits in the continuation byte */
  535. ucode = (ucode << 6) | ((unsigned char)*s & ~utfmask[0]);
  536. s++;
  537. }
  538. /* check if ucode is invalid or in utf-16 surrogate halves */
  539. if (!BETWEEN(ucode, utfmin[usize], utfmax[usize])
  540. || BETWEEN (ucode, 0xD800, 0xDFFF))
  541. return unknown;
  542. return ucode;
  543. }
  544. /* draw text into XftDraw */
  545. static int
  546. drawtext(XftDraw *draw, XftColor *color, int x, int y, unsigned h, const char *text)
  547. {
  548. const char *s, *nexts;
  549. FcChar32 ucode;
  550. XftFont *currfont;
  551. int textlen = 0;
  552. s = text;
  553. while (*s) {
  554. XGlyphInfo ext;
  555. int charexists;
  556. size_t len;
  557. size_t i;
  558. charexists = 0;
  559. ucode = getnextutf8char(s, &nexts);
  560. for (i = 0; i < dc.nfonts; i++) {
  561. charexists = XftCharExists(dpy, dc.fonts[i], ucode);
  562. if (charexists)
  563. break;
  564. }
  565. if (charexists)
  566. currfont = dc.fonts[i];
  567. len = nexts - s;
  568. XftTextExtentsUtf8(dpy, currfont, (XftChar8 *)s,
  569. len, &ext);
  570. textlen += ext.xOff;
  571. if (draw) {
  572. int texty;
  573. texty = y + (h - (currfont->ascent + currfont->descent))/2 + currfont->ascent;
  574. XftDrawStringUtf8(draw, color, currfont, x, texty,
  575. (XftChar8 *)s, len);
  576. x += ext.xOff;
  577. }
  578. s = nexts;
  579. }
  580. return textlen;
  581. }
  582. /* setup the height, width and icon of the items of a menu */
  583. static void
  584. setupitems(struct Menu *menu)
  585. {
  586. struct Item *item;
  587. menu->w = config.width_pixels;
  588. for (item = menu->list; item != NULL; item = item->next) {
  589. int itemwidth;
  590. int textwidth;
  591. item->y = menu->h;
  592. if (item->label == NULL) /* height for separator item */
  593. item->h = config.separator_pixels;
  594. else
  595. item->h = config.height_pixels;
  596. menu->h += item->h;
  597. if (item->label)
  598. textwidth = drawtext(NULL, NULL, 0, 0, 0, item->label);
  599. else
  600. textwidth = 0;
  601. /*
  602. * set menu width
  603. *
  604. * the item width depends on the size of its label (textwidth),
  605. * and it is only used to calculate the width of the menu (which
  606. * is equal to the width of the largest item).
  607. *
  608. * the horizontal padding appears 4 times through the width of a
  609. * item: before and after its icon, and before and after its triangle.
  610. * if the iflag is set (icons are disabled) then the horizontal
  611. * padding appears 3 times: before the label and around the triangle.
  612. */
  613. itemwidth = textwidth + config.triangle_width + config.horzpadding * 3;
  614. itemwidth += (iflag || !menu->hasicon) ? 0 : config.iconsize + config.horzpadding;
  615. menu->w = MAX(menu->w, itemwidth);
  616. }
  617. }
  618. /* setup the position of a menu */
  619. static void
  620. setupmenupos(struct Menu *menu)
  621. {
  622. int width, height;
  623. width = menu->w + config.border_pixels * 2;
  624. height = menu->h + config.border_pixels * 2;
  625. if (menu->parent == NULL) { /* if root menu, calculate in respect to cursor */
  626. if (pflag || (config.posx > mon.x && mon.x + mon.w - config.posx >= width))
  627. menu->x = config.posx;
  628. else if (config.posx > width)
  629. menu->x = config.posx - width;
  630. if (pflag || (config.posy > mon.y && mon.y + mon.h - config.posy >= height))
  631. menu->y = config.posy;
  632. else if (mon.y + mon.h > height)
  633. menu->y = mon.y + mon.h - height;
  634. } else { /* else, calculate in respect to parent menu */
  635. int parentwidth;
  636. parentwidth = menu->parent->x + menu->parent->w + config.border_pixels + config.gap_pixels;
  637. if (mon.x + mon.w - parentwidth >= width)
  638. menu->x = parentwidth;
  639. else if (menu->parent->x > menu->w + config.border_pixels + config.gap_pixels)
  640. menu->x = menu->parent->x - menu->w - config.border_pixels - config.gap_pixels;
  641. if (mon.y + mon.h - (menu->caller->y + menu->parent->y) >= height)
  642. menu->y = menu->caller->y + menu->parent->y;
  643. else if (mon.y + mon.h > height)
  644. menu->y = mon.y + mon.h - height;
  645. }
  646. }
  647. /* recursivelly setup menu configuration and its pixmap */
  648. static void
  649. setupmenu(struct Menu *menu, XClassHint *classh)
  650. {
  651. char *title;
  652. struct Item *item;
  653. XWindowChanges changes;
  654. XSizeHints sizeh;
  655. XTextProperty wintitle;
  656. /* setup size and position of menus */
  657. setupitems(menu);
  658. setupmenupos(menu);
  659. /* update menu geometry */
  660. changes.border_width = config.border_pixels;
  661. changes.height = menu->h;
  662. changes.width = menu->w;
  663. changes.x = menu->x;
  664. changes.y = menu->y;
  665. XConfigureWindow(dpy, menu->win, CWBorderWidth | CWWidth | CWHeight | CWX | CWY, &changes);
  666. /* set window title (used if wflag is on) */
  667. if (menu->parent == NULL) {
  668. title = classh->res_name;
  669. } else {
  670. title = menu->caller->output;
  671. }
  672. XStringListToTextProperty(&title, 1, &wintitle);
  673. /* set window manager hints */
  674. sizeh.flags = USPosition | PMaxSize | PMinSize;
  675. sizeh.min_width = sizeh.max_width = menu->w;
  676. sizeh.min_height = sizeh.max_height = menu->h;
  677. XSetWMProperties(dpy, menu->win, &wintitle, NULL, NULL, 0, &sizeh, NULL, classh);
  678. /* set WM protocols and ewmh window properties */
  679. XSetWMProtocols(dpy, menu->win, &wmdelete, 1);
  680. XChangeProperty(dpy, menu->win, netatom[NetWMName], utf8string, 8,
  681. PropModeReplace, (unsigned char *)title, strlen(title));
  682. XChangeProperty(dpy, menu->win, netatom[NetWMWindowType], XA_ATOM, 32,
  683. PropModeReplace,
  684. (unsigned char *)&netatom[NetWMWindowTypePopupMenu], 1);
  685. /* calculate positions of submenus */
  686. for (item = menu->list; item != NULL; item = item->next) {
  687. if (item->submenu != NULL)
  688. setupmenu(item->submenu, classh);
  689. }
  690. }
  691. /* try to grab pointer, we may have to wait for another process to ungrab */
  692. static void
  693. grabpointer(void)
  694. {
  695. struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
  696. int i;
  697. for (i = 0; i < 1000; i++) {
  698. if (XGrabPointer(dpy, rootwin, True, ButtonPressMask,
  699. GrabModeAsync, GrabModeAsync, None,
  700. None, CurrentTime) == GrabSuccess)
  701. return;
  702. nanosleep(&ts, NULL);
  703. }
  704. errx(1, "cannot grab keyboard");
  705. }
  706. /* try to grab keyboard, we may have to wait for another process to ungrab */
  707. static void
  708. grabkeyboard(void)
  709. {
  710. struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
  711. int i;
  712. for (i = 0; i < 1000; i++) {
  713. if (XGrabKeyboard(dpy, rootwin, True, GrabModeAsync,
  714. GrabModeAsync, CurrentTime) == GrabSuccess)
  715. return;
  716. nanosleep(&ts, NULL);
  717. }
  718. errx(1, "cannot grab keyboard");
  719. }
  720. /* load and scale icon */
  721. static Imlib_Image
  722. loadicon(const char *file)
  723. {
  724. Imlib_Image icon;
  725. int width;
  726. int height;
  727. int imgsize;
  728. icon = imlib_load_image(file);
  729. if (icon == NULL)
  730. errx(1, "cannot load icon %s", file);
  731. imlib_context_set_image(icon);
  732. width = imlib_image_get_width();
  733. height = imlib_image_get_height();
  734. imgsize = MIN(width, height);
  735. icon = imlib_create_cropped_scaled_image(0, 0, imgsize, imgsize,
  736. config.iconsize,
  737. config.iconsize);
  738. return icon;
  739. }
  740. /* draw pixmap for the selected and unselected version of each item on menu */
  741. static void
  742. drawitems(struct Menu *menu)
  743. {
  744. struct Item *item;
  745. for (item = menu->list; item != NULL; item = item->next) {
  746. XftDraw *dsel, *dunsel;
  747. int x, y;
  748. item->unsel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
  749. DefaultDepth(dpy, screen));
  750. XSetForeground(dpy, dc.gc, dc.normal[ColorBG].pixel);
  751. XFillRectangle(dpy, item->unsel, dc.gc, 0, 0, menu->w, item->h);
  752. if (item->label == NULL) { /* item is separator */
  753. y = item->h/2;
  754. XSetForeground(dpy, dc.gc, dc.separator.pixel);
  755. XDrawLine(dpy, item->unsel, dc.gc, config.horzpadding, y,
  756. menu->w - config.horzpadding, y);
  757. item->sel = item->unsel;
  758. } else {
  759. item->sel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
  760. DefaultDepth(dpy, screen));
  761. XSetForeground(dpy, dc.gc, dc.selected[ColorBG].pixel);
  762. XFillRectangle(dpy, item->sel, dc.gc, 0, 0, menu->w, item->h);
  763. /* draw text */
  764. x = config.horzpadding;
  765. x += (iflag || !menu->hasicon) ? 0 : config.horzpadding + config.iconsize;
  766. dsel = XftDrawCreate(dpy, item->sel, visual, colormap);
  767. dunsel = XftDrawCreate(dpy, item->unsel, visual, colormap);
  768. XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
  769. drawtext(dsel, &dc.selected[ColorFG], x, 0, item->h, item->label);
  770. XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
  771. drawtext(dunsel, &dc.normal[ColorFG], x, 0, item->h, item->label);
  772. XftDrawDestroy(dsel);
  773. XftDrawDestroy(dunsel);
  774. /* draw triangle */
  775. if (item->submenu != NULL) {
  776. x = menu->w - config.triangle_width - config.horzpadding;
  777. y = (item->h - config.triangle_height + 1) / 2;
  778. XPoint triangle[] = {
  779. {x, y},
  780. {x + config.triangle_width, y + config.triangle_height/2},
  781. {x, y + config.triangle_height},
  782. {x, y}
  783. };
  784. XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
  785. XFillPolygon(dpy, item->sel, dc.gc, triangle, LEN(triangle),
  786. Convex, CoordModeOrigin);
  787. XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
  788. XFillPolygon(dpy, item->unsel, dc.gc, triangle, LEN(triangle),
  789. Convex, CoordModeOrigin);
  790. }
  791. /* draw icon */
  792. if (item->file != NULL && !iflag) {
  793. item->icon = loadicon(item->file);
  794. imlib_context_set_image(item->icon);
  795. imlib_context_set_drawable(item->sel);
  796. imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
  797. imlib_context_set_drawable(item->unsel);
  798. imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
  799. }
  800. }
  801. }
  802. }
  803. /* copy pixmaps of items of the current menu and of its ancestors into menu window */
  804. static void
  805. drawmenus(struct Menu *currmenu)
  806. {
  807. struct Menu *menu;
  808. struct Item *item;
  809. for (menu = currmenu; menu != NULL; menu = menu->parent) {
  810. if (!menu->drawn) {
  811. drawitems(menu);
  812. menu->drawn = 1;
  813. }
  814. for (item = menu->list; item != NULL; item = item->next) {
  815. if (item == menu->selected)
  816. XCopyArea(dpy, item->sel, menu->win, dc.gc, 0, 0,
  817. menu->w, item->h, 0, item->y);
  818. else
  819. XCopyArea(dpy, item->unsel, menu->win, dc.gc, 0, 0,
  820. menu->w, item->h, 0, item->y);
  821. }
  822. }
  823. }
  824. /* umap previous menus and map current menu and its parents */
  825. static void
  826. mapmenu(struct Menu *currmenu)
  827. {
  828. static struct Menu *prevmenu = NULL;
  829. struct Menu *menu, *menu_;
  830. struct Menu *lcamenu; /* lowest common ancestor menu */
  831. unsigned minlevel; /* level of the closest to root menu */
  832. unsigned maxlevel; /* level of the closest to root menu */
  833. /* do not remap current menu if it wasn't updated*/
  834. if (prevmenu == currmenu)
  835. return;
  836. /* if this is the first time mapping, skip calculations */
  837. if (prevmenu == NULL) {
  838. XMapWindow(dpy, currmenu->win);
  839. prevmenu = currmenu;
  840. return;
  841. }
  842. /* find lowest common ancestor menu */
  843. minlevel = MIN(currmenu->level, prevmenu->level);
  844. maxlevel = MAX(currmenu->level, prevmenu->level);
  845. if (currmenu->level == maxlevel) {
  846. menu = currmenu;
  847. menu_ = prevmenu;
  848. } else {
  849. menu = prevmenu;
  850. menu_ = currmenu;
  851. }
  852. while (menu->level > minlevel)
  853. menu = menu->parent;
  854. while (menu != menu_) {
  855. menu = menu->parent;
  856. menu_ = menu_->parent;
  857. }
  858. lcamenu = menu;
  859. /* unmap menus from currmenu (inclusive) until lcamenu (exclusive) */
  860. for (menu = prevmenu; menu != lcamenu; menu = menu->parent) {
  861. menu->selected = NULL;
  862. XUnmapWindow(dpy, menu->win);
  863. }
  864. /* map menus from currmenu (inclusive) until lcamenu (exclusive) */
  865. for (menu = currmenu; menu != lcamenu; menu = menu->parent) {
  866. if (wflag) {
  867. setupmenupos(menu);
  868. XMoveWindow(dpy, menu->win, menu->x, menu->y);
  869. }
  870. XMapWindow(dpy, menu->win);
  871. }
  872. prevmenu = currmenu;
  873. }
  874. /* get menu of given window */
  875. static struct Menu *
  876. getmenu(struct Menu *currmenu, Window win)
  877. {
  878. struct Menu *menu;
  879. for (menu = currmenu; menu != NULL; menu = menu->parent)
  880. if (menu->win == win)
  881. return menu;
  882. return NULL;
  883. }
  884. /* get item of given menu and position */
  885. static struct Item *
  886. getitem(struct Menu *menu, int y)
  887. {
  888. struct Item *item;
  889. if (menu == NULL)
  890. return NULL;
  891. for (item = menu->list; item != NULL; item = item->next)
  892. if (y >= item->y && y <= item->y + item->h)
  893. return item;
  894. return NULL;
  895. }
  896. /* cycle through the items; non-zero direction is next, zero is prev */
  897. static struct Item *
  898. itemcycle(struct Menu *currmenu, int direction)
  899. {
  900. struct Item *item;
  901. struct Item *lastitem;
  902. item = NULL;
  903. if (direction == ITEMNEXT) {
  904. if (currmenu->selected == NULL)
  905. item = currmenu->list;
  906. else if (currmenu->selected->next != NULL)
  907. item = currmenu->selected->next;
  908. while (item != NULL && item->label == NULL)
  909. item = item->next;
  910. if (item == NULL)
  911. item = currmenu->list;
  912. } else {
  913. for (lastitem = currmenu->list;
  914. lastitem != NULL && lastitem->next != NULL;
  915. lastitem = lastitem->next)
  916. ;
  917. if (currmenu->selected == NULL)
  918. item = lastitem;
  919. else if (currmenu->selected->prev != NULL)
  920. item = currmenu->selected->prev;
  921. while (item != NULL && item->label == NULL)
  922. item = item->prev;
  923. if (item == NULL)
  924. item = lastitem;
  925. }
  926. return item;
  927. }
  928. /* run event loop */
  929. static void
  930. run(struct Menu *currmenu)
  931. {
  932. struct Menu *menu;
  933. struct Item *item;
  934. struct Item *previtem = NULL;
  935. KeySym ksym;
  936. XEvent ev;
  937. mapmenu(currmenu);
  938. while (!XNextEvent(dpy, &ev)) {
  939. switch(ev.type) {
  940. case Expose:
  941. if (ev.xexpose.count == 0)
  942. drawmenus(currmenu);
  943. break;
  944. case MotionNotify:
  945. menu = getmenu(currmenu, ev.xbutton.window);
  946. item = getitem(menu, ev.xbutton.y);
  947. if (menu == NULL || item == NULL || previtem == item)
  948. break;
  949. previtem = item;
  950. menu->selected = item;
  951. if (item->submenu != NULL) {
  952. currmenu = item->submenu;
  953. currmenu->selected = NULL;
  954. } else {
  955. currmenu = menu;
  956. }
  957. mapmenu(currmenu);
  958. drawmenus(currmenu);
  959. break;
  960. case ButtonRelease:
  961. menu = getmenu(currmenu, ev.xbutton.window);
  962. item = getitem(menu, ev.xbutton.y);
  963. if (menu == NULL || item == NULL)
  964. break;
  965. selectitem:
  966. if (item->label == NULL)
  967. break; /* ignore separators */
  968. if (item->submenu != NULL) {
  969. currmenu = item->submenu;
  970. } else {
  971. printf("%s\n", item->output);
  972. return;
  973. }
  974. mapmenu(currmenu);
  975. currmenu->selected = currmenu->list;
  976. drawmenus(currmenu);
  977. break;
  978. case ButtonPress:
  979. menu = getmenu(currmenu, ev.xbutton.window);
  980. if (menu == NULL)
  981. return;
  982. break;
  983. case KeyPress:
  984. ksym = XkbKeycodeToKeysym(dpy, ev.xkey.keycode, 0, 0);
  985. /* esc closes xmenu when current menu is the root menu */
  986. if (ksym == XK_Escape && currmenu->parent == NULL)
  987. return;
  988. /* Shift-Tab = ISO_Left_Tab */
  989. if (ksym == XK_Tab && (ev.xkey.state & ShiftMask))
  990. ksym = XK_ISO_Left_Tab;
  991. /* cycle through menu */
  992. item = NULL;
  993. if (ksym == XK_ISO_Left_Tab || ksym == XK_Up) {
  994. item = itemcycle(currmenu, ITEMPREV);
  995. } else if (ksym == XK_Tab || ksym == XK_Down) {
  996. item = itemcycle(currmenu, ITEMNEXT);
  997. } else if ((ksym == XK_Return || ksym == XK_Right) &&
  998. currmenu->selected != NULL) {
  999. item = currmenu->selected;
  1000. goto selectitem;
  1001. } else if ((ksym == XK_Escape || ksym == XK_Left) &&
  1002. currmenu->parent != NULL) {
  1003. item = currmenu->parent->selected;
  1004. currmenu = currmenu->parent;
  1005. mapmenu(currmenu);
  1006. } else
  1007. break;
  1008. currmenu->selected = item;
  1009. drawmenus(currmenu);
  1010. break;
  1011. case LeaveNotify:
  1012. previtem = NULL;
  1013. currmenu->selected = NULL;
  1014. drawmenus(currmenu);
  1015. break;
  1016. case ConfigureNotify:
  1017. menu = getmenu(currmenu, ev.xconfigure.window);
  1018. if (menu == NULL)
  1019. break;
  1020. menu->x = ev.xconfigure.x;
  1021. menu->y = ev.xconfigure.y;
  1022. break;
  1023. case ClientMessage:
  1024. if ((unsigned long) ev.xclient.data.l[0] != wmdelete)
  1025. break;
  1026. /* user closed window */
  1027. menu = getmenu(currmenu, ev.xclient.window);
  1028. if (menu->parent == NULL)
  1029. return; /* closing the root menu closes the program */
  1030. currmenu = menu->parent;
  1031. mapmenu(currmenu);
  1032. break;
  1033. }
  1034. }
  1035. }
  1036. /* recursivelly free pixmaps and destroy windows */
  1037. static void
  1038. cleanmenu(struct Menu *menu)
  1039. {
  1040. struct Item *item;
  1041. struct Item *tmp;
  1042. item = menu->list;
  1043. while (item != NULL) {
  1044. if (item->submenu != NULL)
  1045. cleanmenu(item->submenu);
  1046. tmp = item;
  1047. if (menu->drawn) {
  1048. XFreePixmap(dpy, item->unsel);
  1049. if (tmp->label != NULL)
  1050. XFreePixmap(dpy, item->sel);
  1051. }
  1052. if (tmp->label != tmp->output)
  1053. free(tmp->label);
  1054. free(tmp->output);
  1055. if (tmp->file != NULL) {
  1056. free(tmp->file);
  1057. if (tmp->icon != NULL) {
  1058. imlib_context_set_image(tmp->icon);
  1059. imlib_free_image();
  1060. }
  1061. }
  1062. item = item->next;
  1063. free(tmp);
  1064. }
  1065. XDestroyWindow(dpy, menu->win);
  1066. free(menu);
  1067. }
  1068. /* cleanup X and exit */
  1069. static void
  1070. cleanup(void)
  1071. {
  1072. XUngrabPointer(dpy, CurrentTime);
  1073. XUngrabKeyboard(dpy, CurrentTime);
  1074. XftColorFree(dpy, visual, colormap, &dc.normal[ColorBG]);
  1075. XftColorFree(dpy, visual, colormap, &dc.normal[ColorFG]);
  1076. XftColorFree(dpy, visual, colormap, &dc.selected[ColorBG]);
  1077. XftColorFree(dpy, visual, colormap, &dc.selected[ColorFG]);
  1078. XftColorFree(dpy, visual, colormap, &dc.separator);
  1079. XftColorFree(dpy, visual, colormap, &dc.border);
  1080. XFreeGC(dpy, dc.gc);
  1081. XCloseDisplay(dpy);
  1082. }
  1083. /* show usage */
  1084. static void
  1085. usage(void)
  1086. {
  1087. (void)fprintf(stderr, "usage: xmenu [-iw] [-p position] [title]\n");
  1088. exit(1);
  1089. }