A mirror of phillbush's xmenu.
 
 
 
 
 

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