A mirror of phillbush's xmenu.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 

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