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.
 
 
 
 
 

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