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.
 
 
 
 
 

1364 lines
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. XFree(info);
  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. long n;
  285. char *type;
  286. char *xrm;
  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, "improper indentation detected");
  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, "could not grab pointer");
  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, "could not grab keyboard");
  755. }
  756. /* load and scale icon */
  757. static Imlib_Image
  758. loadicon(const char *file)
  759. {
  760. Imlib_Image icon;
  761. Imlib_Load_Error errcode;
  762. const char *errstr;
  763. int width;
  764. int height;
  765. int imgsize;
  766. icon = imlib_load_image_with_error_return(file, &errcode);
  767. if (*file == '\0') {
  768. warnx("could not load icon (file name is blank)");
  769. return NULL;
  770. } else if (icon == NULL) {
  771. switch (errcode) {
  772. case IMLIB_LOAD_ERROR_FILE_DOES_NOT_EXIST:
  773. errstr = "file does not exist";
  774. break;
  775. case IMLIB_LOAD_ERROR_FILE_IS_DIRECTORY:
  776. errstr = "file is directory";
  777. break;
  778. case IMLIB_LOAD_ERROR_PERMISSION_DENIED_TO_READ:
  779. case IMLIB_LOAD_ERROR_PERMISSION_DENIED_TO_WRITE:
  780. errstr = "permission denied";
  781. break;
  782. case IMLIB_LOAD_ERROR_NO_LOADER_FOR_FILE_FORMAT:
  783. errstr = "unknown file format";
  784. break;
  785. case IMLIB_LOAD_ERROR_PATH_TOO_LONG:
  786. errstr = "path too long";
  787. break;
  788. case IMLIB_LOAD_ERROR_PATH_COMPONENT_NON_EXISTANT:
  789. case IMLIB_LOAD_ERROR_PATH_COMPONENT_NOT_DIRECTORY:
  790. case IMLIB_LOAD_ERROR_PATH_POINTS_OUTSIDE_ADDRESS_SPACE:
  791. errstr = "improper path";
  792. break;
  793. case IMLIB_LOAD_ERROR_TOO_MANY_SYMBOLIC_LINKS:
  794. errstr = "too many symbolic links";
  795. break;
  796. case IMLIB_LOAD_ERROR_OUT_OF_MEMORY:
  797. errstr = "out of memory";
  798. break;
  799. case IMLIB_LOAD_ERROR_OUT_OF_FILE_DESCRIPTORS:
  800. errstr = "out of file descriptors";
  801. break;
  802. default:
  803. errstr = "unknown error";
  804. break;
  805. }
  806. warnx("could not load icon (%s): %s", errstr, file);
  807. return NULL;
  808. }
  809. imlib_context_set_image(icon);
  810. width = imlib_image_get_width();
  811. height = imlib_image_get_height();
  812. imgsize = MIN(width, height);
  813. icon = imlib_create_cropped_scaled_image(0, 0, imgsize, imgsize,
  814. config.iconsize,
  815. config.iconsize);
  816. return icon;
  817. }
  818. /* draw pixmap for the selected and unselected version of each item on menu */
  819. static void
  820. drawitems(struct Menu *menu)
  821. {
  822. struct Item *item;
  823. for (item = menu->list; item != NULL; item = item->next) {
  824. XftDraw *dsel, *dunsel;
  825. int x, y;
  826. item->unsel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
  827. DefaultDepth(dpy, screen));
  828. XSetForeground(dpy, dc.gc, dc.normal[ColorBG].pixel);
  829. XFillRectangle(dpy, item->unsel, dc.gc, 0, 0, menu->w, item->h);
  830. if (item->label == NULL) { /* item is separator */
  831. y = item->h/2;
  832. XSetForeground(dpy, dc.gc, dc.separator.pixel);
  833. XDrawLine(dpy, item->unsel, dc.gc, config.horzpadding, y,
  834. menu->w - config.horzpadding, y);
  835. item->sel = item->unsel;
  836. } else {
  837. item->sel = XCreatePixmap(dpy, menu->win, menu->w, item->h,
  838. DefaultDepth(dpy, screen));
  839. XSetForeground(dpy, dc.gc, dc.selected[ColorBG].pixel);
  840. XFillRectangle(dpy, item->sel, dc.gc, 0, 0, menu->w, item->h);
  841. /* draw text */
  842. x = config.horzpadding;
  843. x += (iflag || !menu->hasicon) ? 0 : config.horzpadding + config.iconsize;
  844. dsel = XftDrawCreate(dpy, item->sel, visual, colormap);
  845. dunsel = XftDrawCreate(dpy, item->unsel, visual, colormap);
  846. XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
  847. drawtext(dsel, &dc.selected[ColorFG], x, 0, item->h, item->label);
  848. XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
  849. drawtext(dunsel, &dc.normal[ColorFG], x, 0, item->h, item->label);
  850. XftDrawDestroy(dsel);
  851. XftDrawDestroy(dunsel);
  852. /* draw triangle */
  853. if (item->submenu != NULL) {
  854. x = menu->w - config.triangle_width - config.horzpadding;
  855. y = (item->h - config.triangle_height + 1) / 2;
  856. XPoint triangle[] = {
  857. {x, y},
  858. {x + config.triangle_width, y + config.triangle_height/2},
  859. {x, y + config.triangle_height},
  860. {x, y}
  861. };
  862. XSetForeground(dpy, dc.gc, dc.selected[ColorFG].pixel);
  863. XFillPolygon(dpy, item->sel, dc.gc, triangle, LEN(triangle),
  864. Convex, CoordModeOrigin);
  865. XSetForeground(dpy, dc.gc, dc.normal[ColorFG].pixel);
  866. XFillPolygon(dpy, item->unsel, dc.gc, triangle, LEN(triangle),
  867. Convex, CoordModeOrigin);
  868. }
  869. /* draw icon */
  870. if (item->file && !iflag)
  871. item->icon = loadicon(item->file);
  872. if (item->icon) {
  873. imlib_context_set_image(item->icon);
  874. imlib_context_set_drawable(item->sel);
  875. imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
  876. imlib_context_set_drawable(item->unsel);
  877. imlib_render_image_on_drawable(config.horzpadding, config.iconpadding);
  878. }
  879. }
  880. }
  881. }
  882. /* copy pixmaps of items of the current menu and of its ancestors into menu window */
  883. static void
  884. drawmenus(struct Menu *currmenu)
  885. {
  886. struct Menu *menu;
  887. struct Item *item;
  888. for (menu = currmenu; menu != NULL; menu = menu->parent) {
  889. if (!menu->drawn) {
  890. drawitems(menu);
  891. menu->drawn = 1;
  892. }
  893. for (item = menu->list; item != NULL; item = item->next) {
  894. if (item == menu->selected)
  895. XCopyArea(dpy, item->sel, menu->win, dc.gc, 0, 0,
  896. menu->w, item->h, 0, item->y);
  897. else
  898. XCopyArea(dpy, item->unsel, menu->win, dc.gc, 0, 0,
  899. menu->w, item->h, 0, item->y);
  900. }
  901. }
  902. }
  903. /* umap previous menus and map current menu and its parents */
  904. static void
  905. mapmenu(struct Menu *currmenu)
  906. {
  907. static struct Menu *prevmenu = NULL;
  908. struct Menu *menu, *menu_;
  909. struct Menu *lcamenu; /* lowest common ancestor menu */
  910. unsigned minlevel; /* level of the closest to root menu */
  911. unsigned maxlevel; /* level of the closest to root menu */
  912. /* do not remap current menu if it wasn't updated*/
  913. if (prevmenu == currmenu)
  914. return;
  915. /* if this is the first time mapping, skip calculations */
  916. if (prevmenu == NULL) {
  917. XMapWindow(dpy, currmenu->win);
  918. prevmenu = currmenu;
  919. return;
  920. }
  921. /* find lowest common ancestor menu */
  922. minlevel = MIN(currmenu->level, prevmenu->level);
  923. maxlevel = MAX(currmenu->level, prevmenu->level);
  924. if (currmenu->level == maxlevel) {
  925. menu = currmenu;
  926. menu_ = prevmenu;
  927. } else {
  928. menu = prevmenu;
  929. menu_ = currmenu;
  930. }
  931. while (menu->level > minlevel)
  932. menu = menu->parent;
  933. while (menu != menu_) {
  934. menu = menu->parent;
  935. menu_ = menu_->parent;
  936. }
  937. lcamenu = menu;
  938. /* unmap menus from currmenu (inclusive) until lcamenu (exclusive) */
  939. for (menu = prevmenu; menu != lcamenu; menu = menu->parent) {
  940. menu->selected = NULL;
  941. XUnmapWindow(dpy, menu->win);
  942. }
  943. /* map menus from currmenu (inclusive) until lcamenu (exclusive) */
  944. for (menu = currmenu; menu != lcamenu; menu = menu->parent) {
  945. if (wflag) {
  946. setupmenupos(menu);
  947. XMoveWindow(dpy, menu->win, menu->x, menu->y);
  948. }
  949. XMapWindow(dpy, menu->win);
  950. }
  951. prevmenu = currmenu;
  952. }
  953. /* get menu of given window */
  954. static struct Menu *
  955. getmenu(struct Menu *currmenu, Window win)
  956. {
  957. struct Menu *menu;
  958. for (menu = currmenu; menu != NULL; menu = menu->parent)
  959. if (menu->win == win)
  960. return menu;
  961. return NULL;
  962. }
  963. /* get item of given menu and position */
  964. static struct Item *
  965. getitem(struct Menu *menu, int y)
  966. {
  967. struct Item *item;
  968. if (menu == NULL)
  969. return NULL;
  970. for (item = menu->list; item != NULL; item = item->next)
  971. if (y >= item->y && y <= item->y + item->h)
  972. return item;
  973. return NULL;
  974. }
  975. /* cycle through the items; non-zero direction is next, zero is prev */
  976. static struct Item *
  977. itemcycle(struct Menu *currmenu, int direction)
  978. {
  979. struct Item *item;
  980. struct Item *lastitem;
  981. item = NULL;
  982. if (direction == ITEMNEXT) {
  983. if (currmenu->selected == NULL)
  984. item = currmenu->list;
  985. else if (currmenu->selected->next != NULL)
  986. item = currmenu->selected->next;
  987. while (item != NULL && item->label == NULL)
  988. item = item->next;
  989. if (item == NULL)
  990. item = currmenu->list;
  991. } else {
  992. for (lastitem = currmenu->list;
  993. lastitem != NULL && lastitem->next != NULL;
  994. lastitem = lastitem->next)
  995. ;
  996. if (currmenu->selected == NULL)
  997. item = lastitem;
  998. else if (currmenu->selected->prev != NULL)
  999. item = currmenu->selected->prev;
  1000. while (item != NULL && item->label == NULL)
  1001. item = item->prev;
  1002. if (item == NULL)
  1003. item = lastitem;
  1004. }
  1005. return item;
  1006. }
  1007. /* run event loop */
  1008. static void
  1009. run(struct Menu *currmenu)
  1010. {
  1011. struct Menu *menu;
  1012. struct Item *item;
  1013. struct Item *previtem = NULL;
  1014. KeySym ksym;
  1015. XEvent ev;
  1016. mapmenu(currmenu);
  1017. while (!XNextEvent(dpy, &ev)) {
  1018. switch(ev.type) {
  1019. case Expose:
  1020. if (ev.xexpose.count == 0)
  1021. drawmenus(currmenu);
  1022. break;
  1023. case MotionNotify:
  1024. menu = getmenu(currmenu, ev.xbutton.window);
  1025. item = getitem(menu, ev.xbutton.y);
  1026. if (menu == NULL || item == NULL || previtem == item)
  1027. break;
  1028. previtem = item;
  1029. menu->selected = item;
  1030. if (item->submenu != NULL) {
  1031. currmenu = item->submenu;
  1032. currmenu->selected = NULL;
  1033. } else {
  1034. currmenu = menu;
  1035. }
  1036. mapmenu(currmenu);
  1037. drawmenus(currmenu);
  1038. break;
  1039. case ButtonRelease:
  1040. menu = getmenu(currmenu, ev.xbutton.window);
  1041. item = getitem(menu, ev.xbutton.y);
  1042. if (menu == NULL || item == NULL)
  1043. break;
  1044. selectitem:
  1045. if (item->label == NULL)
  1046. break; /* ignore separators */
  1047. if (item->submenu != NULL) {
  1048. currmenu = item->submenu;
  1049. } else {
  1050. printf("%s\n", item->output);
  1051. return;
  1052. }
  1053. mapmenu(currmenu);
  1054. currmenu->selected = currmenu->list;
  1055. drawmenus(currmenu);
  1056. break;
  1057. case ButtonPress:
  1058. menu = getmenu(currmenu, ev.xbutton.window);
  1059. if (menu == NULL)
  1060. return;
  1061. break;
  1062. case KeyPress:
  1063. ksym = XkbKeycodeToKeysym(dpy, ev.xkey.keycode, 0, 0);
  1064. /* esc closes xmenu when current menu is the root menu */
  1065. if (ksym == XK_Escape && currmenu->parent == NULL)
  1066. return;
  1067. /* Shift-Tab = ISO_Left_Tab */
  1068. if (ksym == XK_Tab && (ev.xkey.state & ShiftMask))
  1069. ksym = XK_ISO_Left_Tab;
  1070. /* cycle through menu */
  1071. item = NULL;
  1072. if (ksym == XK_ISO_Left_Tab || ksym == XK_Up) {
  1073. item = itemcycle(currmenu, ITEMPREV);
  1074. } else if (ksym == XK_Tab || ksym == XK_Down) {
  1075. item = itemcycle(currmenu, ITEMNEXT);
  1076. } else if ((ksym == XK_Return || ksym == XK_Right) &&
  1077. currmenu->selected != NULL) {
  1078. item = currmenu->selected;
  1079. goto selectitem;
  1080. } else if ((ksym == XK_Escape || ksym == XK_Left) &&
  1081. currmenu->parent != NULL) {
  1082. item = currmenu->parent->selected;
  1083. currmenu = currmenu->parent;
  1084. mapmenu(currmenu);
  1085. } else
  1086. break;
  1087. currmenu->selected = item;
  1088. drawmenus(currmenu);
  1089. break;
  1090. case LeaveNotify:
  1091. previtem = NULL;
  1092. currmenu->selected = NULL;
  1093. drawmenus(currmenu);
  1094. break;
  1095. case ConfigureNotify:
  1096. menu = getmenu(currmenu, ev.xconfigure.window);
  1097. if (menu == NULL)
  1098. break;
  1099. menu->x = ev.xconfigure.x;
  1100. menu->y = ev.xconfigure.y;
  1101. break;
  1102. case ClientMessage:
  1103. if ((unsigned long) ev.xclient.data.l[0] != wmdelete)
  1104. break;
  1105. /* user closed window */
  1106. menu = getmenu(currmenu, ev.xclient.window);
  1107. if (menu->parent == NULL)
  1108. return; /* closing the root menu closes the program */
  1109. currmenu = menu->parent;
  1110. mapmenu(currmenu);
  1111. break;
  1112. }
  1113. }
  1114. }
  1115. /* recursivelly free pixmaps and destroy windows */
  1116. static void
  1117. cleanmenu(struct Menu *menu)
  1118. {
  1119. struct Item *item;
  1120. struct Item *tmp;
  1121. item = menu->list;
  1122. while (item != NULL) {
  1123. if (item->submenu != NULL)
  1124. cleanmenu(item->submenu);
  1125. tmp = item;
  1126. if (menu->drawn) {
  1127. XFreePixmap(dpy, item->unsel);
  1128. if (tmp->label != NULL)
  1129. XFreePixmap(dpy, item->sel);
  1130. }
  1131. if (tmp->label != tmp->output)
  1132. free(tmp->label);
  1133. free(tmp->output);
  1134. if (tmp->file != NULL) {
  1135. free(tmp->file);
  1136. if (tmp->icon != NULL) {
  1137. imlib_context_set_image(tmp->icon);
  1138. imlib_free_image();
  1139. }
  1140. }
  1141. item = item->next;
  1142. free(tmp);
  1143. }
  1144. XDestroyWindow(dpy, menu->win);
  1145. free(menu);
  1146. }
  1147. /* cleanup X and exit */
  1148. static void
  1149. cleanup(void)
  1150. {
  1151. size_t i;
  1152. XUngrabPointer(dpy, CurrentTime);
  1153. XUngrabKeyboard(dpy, CurrentTime);
  1154. XftColorFree(dpy, visual, colormap, &dc.normal[ColorBG]);
  1155. XftColorFree(dpy, visual, colormap, &dc.normal[ColorFG]);
  1156. XftColorFree(dpy, visual, colormap, &dc.selected[ColorBG]);
  1157. XftColorFree(dpy, visual, colormap, &dc.selected[ColorFG]);
  1158. XftColorFree(dpy, visual, colormap, &dc.separator);
  1159. XftColorFree(dpy, visual, colormap, &dc.border);
  1160. for (i = 0; i < dc.nfonts; i++)
  1161. XftFontClose(dpy, dc.fonts[i]);
  1162. XFreeGC(dpy, dc.gc);
  1163. XCloseDisplay(dpy);
  1164. }
  1165. /* show usage */
  1166. static void
  1167. usage(void)
  1168. {
  1169. (void)fprintf(stderr, "usage: xmenu [-iw] [-p position] [title]\n");
  1170. exit(1);
  1171. }