A mirror of phillbush's xmenu.
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 

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