A mirror of phillbush's xmenu.
 
 
 
 
 

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