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

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