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.
 
 
 
 
 

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