A mirror of phillbush's xmenu.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 

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