A mirror of phillbush's xmenu.
 
 
 
 
 

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