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.
 
 
 
 
 

1362 line
35 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, "could not 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. if (i >= sizeof buf)
  220. errx(1, "font name too long");
  221. if (*p == ',')
  222. p++;
  223. buf[i] = '\0';
  224. if (nfont == 0)
  225. if ((dc.pattern = FcNameParse((FcChar8 *)buf)) == NULL)
  226. errx(1, "the first font in the cache must be loaded from a font string");
  227. if ((dc.fonts[nfont++] = XftFontOpenName(dpy, screen, buf)) == NULL)
  228. errx(1, "could not 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, "could not 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 || 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, "improper indentation detected");
  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. FcCharSet *fccharset = NULL;
  554. FcPattern *fcpattern = NULL;
  555. FcPattern *match = NULL;
  556. XftFont *retfont = NULL;
  557. XftResult result;
  558. size_t i;
  559. for (i = 0; i < dc.nfonts; i++)
  560. if (XftCharExists(dpy, dc.fonts[i], ucode) == FcTrue)
  561. return dc.fonts[i];
  562. /* create a charset containing our code point */
  563. fccharset = FcCharSetCreate();
  564. FcCharSetAddChar(fccharset, ucode);
  565. /* create a pattern akin to the dc.pattern but containing our charset */
  566. if (fccharset) {
  567. fcpattern = FcPatternDuplicate(dc.pattern);
  568. FcPatternAddCharSet(fcpattern, FC_CHARSET, fccharset);
  569. }
  570. /* find pattern matching fcpattern */
  571. if (fcpattern) {
  572. FcConfigSubstitute(NULL, fcpattern, FcMatchPattern);
  573. FcDefaultSubstitute(fcpattern);
  574. match = XftFontMatch(dpy, screen, fcpattern, &result);
  575. }
  576. /* if found a pattern, open its font */
  577. if (match) {
  578. retfont = XftFontOpenPattern(dpy, match);
  579. if (retfont && XftCharExists(dpy, retfont, ucode) == FcTrue) {
  580. if ((dc.fonts = realloc(dc.fonts, dc.nfonts+1)) == NULL)
  581. err(1, "realloc");
  582. dc.fonts[dc.nfonts] = retfont;
  583. return dc.fonts[dc.nfonts++];
  584. } else {
  585. XftFontClose(dpy, retfont);
  586. }
  587. }
  588. /* in case no fount was found, return the first one */
  589. return dc.fonts[0];
  590. }
  591. /* draw text into XftDraw, return width of text glyphs */
  592. static int
  593. drawtext(XftDraw *draw, XftColor *color, int x, int y, unsigned h, const char *text)
  594. {
  595. int textwidth = 0;
  596. while (*text) {
  597. XftFont *currfont;
  598. XGlyphInfo ext;
  599. FcChar32 ucode;
  600. const char *next;
  601. size_t len;
  602. ucode = getnextutf8char(text, &next);
  603. currfont = getfontucode(ucode);
  604. len = next - text;
  605. XftTextExtentsUtf8(dpy, currfont, (XftChar8 *)text, len, &ext);
  606. textwidth += ext.xOff;
  607. if (draw) {
  608. int texty;
  609. texty = y + (h - (currfont->ascent + currfont->descent))/2 + currfont->ascent;
  610. XftDrawStringUtf8(draw, color, currfont, x, texty, (XftChar8 *)text, len);
  611. x += ext.xOff;
  612. }
  613. text = next;
  614. }
  615. return textwidth;
  616. }
  617. /* setup the height, width and icon of the items of a menu */
  618. static void
  619. setupitems(struct Menu *menu)
  620. {
  621. struct Item *item;
  622. menu->w = config.width_pixels;
  623. for (item = menu->list; item != NULL; item = item->next) {
  624. int itemwidth;
  625. int textwidth;
  626. item->y = menu->h;
  627. if (item->label == NULL) /* height for separator item */
  628. item->h = config.separator_pixels;
  629. else
  630. item->h = config.height_pixels;
  631. menu->h += item->h;
  632. if (item->label)
  633. textwidth = drawtext(NULL, NULL, 0, 0, 0, item->label);
  634. else
  635. textwidth = 0;
  636. /*
  637. * set menu width
  638. *
  639. * the item width depends on the size of its label (textwidth),
  640. * and it is only used to calculate the width of the menu (which
  641. * is equal to the width of the largest item).
  642. *
  643. * the horizontal padding appears 4 times through the width of a
  644. * item: before and after its icon, and before and after its triangle.
  645. * if the iflag is set (icons are disabled) then the horizontal
  646. * padding appears 3 times: before the label and around the triangle.
  647. */
  648. itemwidth = textwidth + config.triangle_width + config.horzpadding * 3;
  649. itemwidth += (iflag || !menu->hasicon) ? 0 : config.iconsize + config.horzpadding;
  650. menu->w = MAX(menu->w, itemwidth);
  651. }
  652. }
  653. /* setup the position of a menu */
  654. static void
  655. setupmenupos(struct Menu *menu)
  656. {
  657. int width, height;
  658. width = menu->w + config.border_pixels * 2;
  659. height = menu->h + config.border_pixels * 2;
  660. if (menu->parent == NULL) { /* if root menu, calculate in respect to cursor */
  661. if (pflag || (config.posx > mon.x && mon.x + mon.w - config.posx >= width))
  662. menu->x = config.posx;
  663. else if (config.posx > width)
  664. menu->x = config.posx - width;
  665. if (pflag || (config.posy > mon.y && mon.y + mon.h - config.posy >= height))
  666. menu->y = config.posy;
  667. else if (mon.y + mon.h > height)
  668. menu->y = mon.y + mon.h - height;
  669. } else { /* else, calculate in respect to parent menu */
  670. int parentwidth;
  671. parentwidth = menu->parent->x + menu->parent->w + config.border_pixels + config.gap_pixels;
  672. if (mon.x + mon.w - parentwidth >= width)
  673. menu->x = parentwidth;
  674. else if (menu->parent->x > menu->w + config.border_pixels + config.gap_pixels)
  675. menu->x = menu->parent->x - menu->w - config.border_pixels - config.gap_pixels;
  676. if (mon.y + mon.h - (menu->caller->y + menu->parent->y) >= height)
  677. menu->y = menu->caller->y + menu->parent->y;
  678. else if (mon.y + mon.h > height)
  679. menu->y = mon.y + mon.h - height;
  680. }
  681. }
  682. /* recursivelly setup menu configuration and its pixmap */
  683. static void
  684. setupmenu(struct Menu *menu, XClassHint *classh)
  685. {
  686. char *title;
  687. struct Item *item;
  688. XWindowChanges changes;
  689. XSizeHints sizeh;
  690. XTextProperty wintitle;
  691. /* setup size and position of menus */
  692. setupitems(menu);
  693. setupmenupos(menu);
  694. /* update menu geometry */
  695. changes.border_width = config.border_pixels;
  696. changes.height = menu->h;
  697. changes.width = menu->w;
  698. changes.x = menu->x;
  699. changes.y = menu->y;
  700. XConfigureWindow(dpy, menu->win, CWBorderWidth | CWWidth | CWHeight | CWX | CWY, &changes);
  701. /* set window title (used if wflag is on) */
  702. if (menu->parent == NULL) {
  703. title = classh->res_name;
  704. } else {
  705. title = menu->caller->output;
  706. }
  707. XStringListToTextProperty(&title, 1, &wintitle);
  708. /* set window manager hints */
  709. sizeh.flags = USPosition | PMaxSize | PMinSize;
  710. sizeh.min_width = sizeh.max_width = menu->w;
  711. sizeh.min_height = sizeh.max_height = menu->h;
  712. XSetWMProperties(dpy, menu->win, &wintitle, NULL, NULL, 0, &sizeh, NULL, classh);
  713. /* set WM protocols and ewmh window properties */
  714. XSetWMProtocols(dpy, menu->win, &wmdelete, 1);
  715. XChangeProperty(dpy, menu->win, netatom[NetWMName], utf8string, 8,
  716. PropModeReplace, (unsigned char *)title, strlen(title));
  717. XChangeProperty(dpy, menu->win, netatom[NetWMWindowType], XA_ATOM, 32,
  718. PropModeReplace,
  719. (unsigned char *)&netatom[NetWMWindowTypePopupMenu], 1);
  720. /* calculate positions of submenus */
  721. for (item = menu->list; item != NULL; item = item->next) {
  722. if (item->submenu != NULL)
  723. setupmenu(item->submenu, classh);
  724. }
  725. }
  726. /* try to grab pointer, we may have to wait for another process to ungrab */
  727. static void
  728. grabpointer(void)
  729. {
  730. struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
  731. int i;
  732. for (i = 0; i < 1000; i++) {
  733. if (XGrabPointer(dpy, rootwin, True, ButtonPressMask,
  734. GrabModeAsync, GrabModeAsync, None,
  735. None, CurrentTime) == GrabSuccess)
  736. return;
  737. nanosleep(&ts, NULL);
  738. }
  739. errx(1, "could not grab pointer");
  740. }
  741. /* try to grab keyboard, we may have to wait for another process to ungrab */
  742. static void
  743. grabkeyboard(void)
  744. {
  745. struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 };
  746. int i;
  747. for (i = 0; i < 1000; i++) {
  748. if (XGrabKeyboard(dpy, rootwin, True, GrabModeAsync,
  749. GrabModeAsync, CurrentTime) == GrabSuccess)
  750. return;
  751. nanosleep(&ts, NULL);
  752. }
  753. errx(1, "could not grab keyboard");
  754. }
  755. /* load and scale icon */
  756. static Imlib_Image
  757. loadicon(const char *file)
  758. {
  759. Imlib_Image icon;
  760. Imlib_Load_Error errcode;
  761. const char *errstr;
  762. int width;
  763. int height;
  764. int imgsize;
  765. icon = imlib_load_image_with_error_return(file, &errcode);
  766. if (*file == '\0') {
  767. warnx("could not load icon (file name is blank)");
  768. return NULL;
  769. } else if (icon == NULL) {
  770. switch (errcode) {
  771. case IMLIB_LOAD_ERROR_FILE_DOES_NOT_EXIST:
  772. errstr = "file does not exist";
  773. break;
  774. case IMLIB_LOAD_ERROR_FILE_IS_DIRECTORY:
  775. errstr = "file is directory";
  776. break;
  777. case IMLIB_LOAD_ERROR_PERMISSION_DENIED_TO_READ:
  778. case IMLIB_LOAD_ERROR_PERMISSION_DENIED_TO_WRITE:
  779. errstr = "permission denied";
  780. break;
  781. case IMLIB_LOAD_ERROR_NO_LOADER_FOR_FILE_FORMAT:
  782. errstr = "unknown file format";
  783. break;
  784. case IMLIB_LOAD_ERROR_PATH_TOO_LONG:
  785. errstr = "path too long";
  786. break;
  787. case IMLIB_LOAD_ERROR_PATH_COMPONENT_NON_EXISTANT:
  788. case IMLIB_LOAD_ERROR_PATH_COMPONENT_NOT_DIRECTORY:
  789. case IMLIB_LOAD_ERROR_PATH_POINTS_OUTSIDE_ADDRESS_SPACE:
  790. errstr = "improper path";
  791. break;
  792. case IMLIB_LOAD_ERROR_TOO_MANY_SYMBOLIC_LINKS:
  793. errstr = "too many symbolic links";
  794. break;
  795. case IMLIB_LOAD_ERROR_OUT_OF_MEMORY:
  796. errstr = "out of memory";
  797. break;
  798. case IMLIB_LOAD_ERROR_OUT_OF_FILE_DESCRIPTORS:
  799. errstr = "out of file descriptors";
  800. break;
  801. default:
  802. errstr = "unknown error";
  803. break;
  804. }
  805. warnx("could not load icon (%s): %s", errstr, file);
  806. return NULL;
  807. }
  808. imlib_context_set_image(icon);
  809. width = imlib_image_get_width();
  810. height = imlib_image_get_height();
  811. imgsize = MIN(width, height);
  812. icon = imlib_create_cropped_scaled_image(0, 0, imgsize, imgsize,
  813. config.iconsize,
  814. config.iconsize);
  815. return icon;
  816. }
  817. /* draw pixmap for the selected and unselected version of each item on menu */
  818. static void
  819. drawitems(struct Menu *menu)
  820. {
  821. struct Item *item;
  822. for (item = menu->list; item != NULL; item = item->next) {
  823. XftDraw *dsel, *dunsel;
  824. int x, y;
  825. item->unsel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
  826. DefaultDepth(dpy, screen));
  827. XSetForeground(dpy, dc.gc, dc.normal[ColorBG].pixel);
  828. XFillRectangle(dpy, item->unsel, dc.gc, 0, 0, menu->w, item->h);
  829. if (item->label == NULL) { /* item is separator */
  830. y = item->h/2;
  831. XSetForeground(dpy, dc.gc, dc.separator.pixel);
  832. XDrawLine(dpy, item->unsel, dc.gc, config.horzpadding, y,
  833. menu->w - config.horzpadding, y);
  834. item->sel = item->unsel;
  835. } else {
  836. item->sel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
  837. DefaultDepth(dpy, screen));
  838. XSetForeground(dpy, dc.gc, dc.selected[ColorBG].pixel);
  839. XFillRectangle(dpy, item->sel, dc.gc, 0, 0, menu->w, item->h);
  840. /* draw text */
  841. x = config.horzpadding;
  842. x += (iflag || !menu->hasicon) ? 0 : config.horzpadding + config.iconsize;
  843. dsel = XftDrawCreate(dpy, item->sel, visual, colormap);
  844. dunsel = XftDrawCreate(dpy, item->unsel, visual, colormap);
  845. XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
  846. drawtext(dsel, &dc.selected[ColorFG], x, 0, item->h, item->label);
  847. XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
  848. drawtext(dunsel, &dc.normal[ColorFG], x, 0, item->h, item->label);
  849. XftDrawDestroy(dsel);
  850. XftDrawDestroy(dunsel);
  851. /* draw triangle */
  852. if (item->submenu != NULL) {
  853. x = menu->w - config.triangle_width - config.horzpadding;
  854. y = (item->h - config.triangle_height + 1) / 2;
  855. XPoint triangle[] = {
  856. {x, y},
  857. {x + config.triangle_width, y + config.triangle_height/2},
  858. {x, y + config.triangle_height},
  859. {x, y}
  860. };
  861. XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
  862. XFillPolygon(dpy, item->sel, dc.gc, triangle, LEN(triangle),
  863. Convex, CoordModeOrigin);
  864. XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
  865. XFillPolygon(dpy, item->unsel, dc.gc, triangle, LEN(triangle),
  866. Convex, CoordModeOrigin);
  867. }
  868. /* draw icon */
  869. if (item->file && !iflag)
  870. item->icon = loadicon(item->file);
  871. if (item->icon) {
  872. imlib_context_set_image(item->icon);
  873. imlib_context_set_drawable(item->sel);
  874. imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
  875. imlib_context_set_drawable(item->unsel);
  876. imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
  877. }
  878. }
  879. }
  880. }
  881. /* copy pixmaps of items of the current menu and of its ancestors into menu window */
  882. static void
  883. drawmenus(struct Menu *currmenu)
  884. {
  885. struct Menu *menu;
  886. struct Item *item;
  887. for (menu = currmenu; menu != NULL; menu = menu->parent) {
  888. if (!menu->drawn) {
  889. drawitems(menu);
  890. menu->drawn = 1;
  891. }
  892. for (item = menu->list; item != NULL; item = item->next) {
  893. if (item == menu->selected)
  894. XCopyArea(dpy, item->sel, menu->win, dc.gc, 0, 0,
  895. menu->w, item->h, 0, item->y);
  896. else
  897. XCopyArea(dpy, item->unsel, menu->win, dc.gc, 0, 0,
  898. menu->w, item->h, 0, item->y);
  899. }
  900. }
  901. }
  902. /* umap previous menus and map current menu and its parents */
  903. static void
  904. mapmenu(struct Menu *currmenu)
  905. {
  906. static struct Menu *prevmenu = NULL;
  907. struct Menu *menu, *menu_;
  908. struct Menu *lcamenu; /* lowest common ancestor menu */
  909. unsigned minlevel; /* level of the closest to root menu */
  910. unsigned maxlevel; /* level of the closest to root menu */
  911. /* do not remap current menu if it wasn't updated*/
  912. if (prevmenu == currmenu)
  913. return;
  914. /* if this is the first time mapping, skip calculations */
  915. if (prevmenu == NULL) {
  916. XMapWindow(dpy, currmenu->win);
  917. prevmenu = currmenu;
  918. return;
  919. }
  920. /* find lowest common ancestor menu */
  921. minlevel = MIN(currmenu->level, prevmenu->level);
  922. maxlevel = MAX(currmenu->level, prevmenu->level);
  923. if (currmenu->level == maxlevel) {
  924. menu = currmenu;
  925. menu_ = prevmenu;
  926. } else {
  927. menu = prevmenu;
  928. menu_ = currmenu;
  929. }
  930. while (menu->level > minlevel)
  931. menu = menu->parent;
  932. while (menu != menu_) {
  933. menu = menu->parent;
  934. menu_ = menu_->parent;
  935. }
  936. lcamenu = menu;
  937. /* unmap menus from currmenu (inclusive) until lcamenu (exclusive) */
  938. for (menu = prevmenu; menu != lcamenu; menu = menu->parent) {
  939. menu->selected = NULL;
  940. XUnmapWindow(dpy, menu->win);
  941. }
  942. /* map menus from currmenu (inclusive) until lcamenu (exclusive) */
  943. for (menu = currmenu; menu != lcamenu; menu = menu->parent) {
  944. if (wflag) {
  945. setupmenupos(menu);
  946. XMoveWindow(dpy, menu->win, menu->x, menu->y);
  947. }
  948. XMapWindow(dpy, menu->win);
  949. }
  950. prevmenu = currmenu;
  951. }
  952. /* get menu of given window */
  953. static struct Menu *
  954. getmenu(struct Menu *currmenu, Window win)
  955. {
  956. struct Menu *menu;
  957. for (menu = currmenu; menu != NULL; menu = menu->parent)
  958. if (menu->win == win)
  959. return menu;
  960. return NULL;
  961. }
  962. /* get item of given menu and position */
  963. static struct Item *
  964. getitem(struct Menu *menu, int y)
  965. {
  966. struct Item *item;
  967. if (menu == NULL)
  968. return NULL;
  969. for (item = menu->list; item != NULL; item = item->next)
  970. if (y >= item->y && y <= item->y + item->h)
  971. return item;
  972. return NULL;
  973. }
  974. /* cycle through the items; non-zero direction is next, zero is prev */
  975. static struct Item *
  976. itemcycle(struct Menu *currmenu, int direction)
  977. {
  978. struct Item *item;
  979. struct Item *lastitem;
  980. item = NULL;
  981. if (direction == ITEMNEXT) {
  982. if (currmenu->selected == NULL)
  983. item = currmenu->list;
  984. else if (currmenu->selected->next != NULL)
  985. item = currmenu->selected->next;
  986. while (item != NULL && item->label == NULL)
  987. item = item->next;
  988. if (item == NULL)
  989. item = currmenu->list;
  990. } else {
  991. for (lastitem = currmenu->list;
  992. lastitem != NULL && lastitem->next != NULL;
  993. lastitem = lastitem->next)
  994. ;
  995. if (currmenu->selected == NULL)
  996. item = lastitem;
  997. else if (currmenu->selected->prev != NULL)
  998. item = currmenu->selected->prev;
  999. while (item != NULL && item->label == NULL)
  1000. item = item->prev;
  1001. if (item == NULL)
  1002. item = lastitem;
  1003. }
  1004. return item;
  1005. }
  1006. /* run event loop */
  1007. static void
  1008. run(struct Menu *currmenu)
  1009. {
  1010. struct Menu *menu;
  1011. struct Item *item;
  1012. struct Item *previtem = NULL;
  1013. KeySym ksym;
  1014. XEvent ev;
  1015. mapmenu(currmenu);
  1016. while (!XNextEvent(dpy, &ev)) {
  1017. switch(ev.type) {
  1018. case Expose:
  1019. if (ev.xexpose.count == 0)
  1020. drawmenus(currmenu);
  1021. break;
  1022. case MotionNotify:
  1023. menu = getmenu(currmenu, ev.xbutton.window);
  1024. item = getitem(menu, ev.xbutton.y);
  1025. if (menu == NULL || item == NULL || previtem == item)
  1026. break;
  1027. previtem = item;
  1028. menu->selected = item;
  1029. if (item->submenu != NULL) {
  1030. currmenu = item->submenu;
  1031. currmenu->selected = NULL;
  1032. } else {
  1033. currmenu = menu;
  1034. }
  1035. mapmenu(currmenu);
  1036. drawmenus(currmenu);
  1037. break;
  1038. case ButtonRelease:
  1039. menu = getmenu(currmenu, ev.xbutton.window);
  1040. item = getitem(menu, ev.xbutton.y);
  1041. if (menu == NULL || item == NULL)
  1042. break;
  1043. selectitem:
  1044. if (item->label == NULL)
  1045. break; /* ignore separators */
  1046. if (item->submenu != NULL) {
  1047. currmenu = item->submenu;
  1048. } else {
  1049. printf("%s\n", item->output);
  1050. return;
  1051. }
  1052. mapmenu(currmenu);
  1053. currmenu->selected = currmenu->list;
  1054. drawmenus(currmenu);
  1055. break;
  1056. case ButtonPress:
  1057. menu = getmenu(currmenu, ev.xbutton.window);
  1058. if (menu == NULL)
  1059. return;
  1060. break;
  1061. case KeyPress:
  1062. ksym = XkbKeycodeToKeysym(dpy, ev.xkey.keycode, 0, 0);
  1063. /* esc closes xmenu when current menu is the root menu */
  1064. if (ksym == XK_Escape && currmenu->parent == NULL)
  1065. return;
  1066. /* Shift-Tab = ISO_Left_Tab */
  1067. if (ksym == XK_Tab && (ev.xkey.state & ShiftMask))
  1068. ksym = XK_ISO_Left_Tab;
  1069. /* cycle through menu */
  1070. item = NULL;
  1071. if (ksym == XK_ISO_Left_Tab || ksym == XK_Up) {
  1072. item = itemcycle(currmenu, ITEMPREV);
  1073. } else if (ksym == XK_Tab || ksym == XK_Down) {
  1074. item = itemcycle(currmenu, ITEMNEXT);
  1075. } else if ((ksym == XK_Return || ksym == XK_Right) &&
  1076. currmenu->selected != NULL) {
  1077. item = currmenu->selected;
  1078. goto selectitem;
  1079. } else if ((ksym == XK_Escape || ksym == XK_Left) &&
  1080. currmenu->parent != NULL) {
  1081. item = currmenu->parent->selected;
  1082. currmenu = currmenu->parent;
  1083. mapmenu(currmenu);
  1084. } else
  1085. break;
  1086. currmenu->selected = item;
  1087. drawmenus(currmenu);
  1088. break;
  1089. case LeaveNotify:
  1090. previtem = NULL;
  1091. currmenu->selected = NULL;
  1092. drawmenus(currmenu);
  1093. break;
  1094. case ConfigureNotify:
  1095. menu = getmenu(currmenu, ev.xconfigure.window);
  1096. if (menu == NULL)
  1097. break;
  1098. menu->x = ev.xconfigure.x;
  1099. menu->y = ev.xconfigure.y;
  1100. break;
  1101. case ClientMessage:
  1102. if ((unsigned long) ev.xclient.data.l[0] != wmdelete)
  1103. break;
  1104. /* user closed window */
  1105. menu = getmenu(currmenu, ev.xclient.window);
  1106. if (menu->parent == NULL)
  1107. return; /* closing the root menu closes the program */
  1108. currmenu = menu->parent;
  1109. mapmenu(currmenu);
  1110. break;
  1111. }
  1112. }
  1113. }
  1114. /* recursivelly free pixmaps and destroy windows */
  1115. static void
  1116. cleanmenu(struct Menu *menu)
  1117. {
  1118. struct Item *item;
  1119. struct Item *tmp;
  1120. item = menu->list;
  1121. while (item != NULL) {
  1122. if (item->submenu != NULL)
  1123. cleanmenu(item->submenu);
  1124. tmp = item;
  1125. if (menu->drawn) {
  1126. XFreePixmap(dpy, item->unsel);
  1127. if (tmp->label != NULL)
  1128. XFreePixmap(dpy, item->sel);
  1129. }
  1130. if (tmp->label != tmp->output)
  1131. free(tmp->label);
  1132. free(tmp->output);
  1133. if (tmp->file != NULL) {
  1134. free(tmp->file);
  1135. if (tmp->icon != NULL) {
  1136. imlib_context_set_image(tmp->icon);
  1137. imlib_free_image();
  1138. }
  1139. }
  1140. item = item->next;
  1141. free(tmp);
  1142. }
  1143. XDestroyWindow(dpy, menu->win);
  1144. free(menu);
  1145. }
  1146. /* cleanup X and exit */
  1147. static void
  1148. cleanup(void)
  1149. {
  1150. size_t i;
  1151. XUngrabPointer(dpy, CurrentTime);
  1152. XUngrabKeyboard(dpy, CurrentTime);
  1153. XftColorFree(dpy, visual, colormap, &dc.normal[ColorBG]);
  1154. XftColorFree(dpy, visual, colormap, &dc.normal[ColorFG]);
  1155. XftColorFree(dpy, visual, colormap, &dc.selected[ColorBG]);
  1156. XftColorFree(dpy, visual, colormap, &dc.selected[ColorFG]);
  1157. XftColorFree(dpy, visual, colormap, &dc.separator);
  1158. XftColorFree(dpy, visual, colormap, &dc.border);
  1159. for (i = 0; i < dc.nfonts; i++)
  1160. XftFontClose(dpy, dc.fonts[i]);
  1161. XFreeGC(dpy, dc.gc);
  1162. XCloseDisplay(dpy);
  1163. }
  1164. /* show usage */
  1165. static void
  1166. usage(void)
  1167. {
  1168. (void)fprintf(stderr, "usage: xmenu [-iw] [-p position] [title]\n");
  1169. exit(1);
  1170. }