Skip to content

Commit cfead6d

Browse files
ctruedenclaude
andcommitted
Add the menu tree, and make Access a static utility
MenuTree arranges commands into the tree a user interface renders: labels, nesting, and order by weight, where a submenu takes the weight of its lightest child so that submenus do not all fall back to alphabetical order. It is a model and nothing else -- SciJava Common's ShadowMenu was simultaneously a Collection<ModuleInfo>, a Runnable and a Comparable, and carried a context. A test asserts that building the whole tree constructs no commands. Context.privateLookupIn becomes Access.lookupIn, a static utility. The module system cares about the module the code lives in, not whether the call is static, and the operation used no context state; the knock-on is that CommandInfo no longer needs a Context at all, so Commands.discover stopped threading one through. It still returns MethodHandles.Lookup rather than an accessor of our own. That is the JDK's token for delegated reflective access, it already spans fields, methods and constructors, and a bespoke facade would need extending every time a caller wanted access we had not anticipated. The harvester's parameter callbacks will be the first real test of whether call sites want wrapping; if they do, the wrapper belongs with that consumer. Also fixes testMenuOrdering, which asserted an exact whole-list order and broke as soon as the menu tests added fixtures -- the same brittleness fixed two commits ago in another test. Exact-list assertions over a discovered set are a standing trap here, since any test may add one. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gJpzGd3ksbME4CN6Tu2ni
1 parent 80bab69 commit cfead6d

9 files changed

Lines changed: 550 additions & 56 deletions

File tree

‎scijava-command/src/main/java/org/scijava/command/CommandInfo.java‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
import java.util.Map;
3333
import java.util.Optional;
3434

35-
import org.scijava.context.Context;
35+
import org.scijava.context.Access;
3636
import org.scijava.discovery.Discovery;
3737
import org.scijava.execute.Executable;
3838
import org.scijava.execute.ExecutableInstance;
@@ -61,15 +61,13 @@ public class CommandInfo implements Executable {
6161

6262
private final Discovery<Command> discovery;
6363
private final Map<String, String> menu;
64-
private final Context context;
6564
private Executable delegate;
6665

6766
CommandInfo(final Discovery<Command> discovery,
68-
final Map<String, String> menu, final Context context)
67+
final Map<String, String> menu)
6968
{
7069
this.discovery = discovery;
7170
this.menu = menu;
72-
this.context = context;
7371
}
7472

7573
// -- Metadata, readable without loading the class --
@@ -159,7 +157,7 @@ private synchronized Executable delegate() {
159157
// NB: the lookup comes from the context, so a command's package need
160158
// only be opened to org.scijava.context -- not additionally to the
161159
// execution layer that reads its @Parameter fields.
162-
delegate = Executables.of(type, context.privateLookupIn(type));
160+
delegate = Executables.of(type, Access.lookupIn(type));
163161
}
164162
return delegate;
165163
}

‎scijava-command/src/main/java/org/scijava/command/Commands.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ public static List<CommandInfo> discover(final Context context) {
7171
final List<CommandInfo> commands = new ArrayList<>();
7272
for (final Discovery<Command> discovery : context.plugins(Command.class)) {
7373
commands.add(new CommandInfo(discovery, menus.getOrDefault( //
74-
discovery.implClassName(), Map.of()), context));
74+
discovery.implClassName(), Map.of())));
7575
}
7676
commands.sort(Comparator.comparingDouble(CommandInfo::weight) //
7777
.thenComparing(CommandInfo::label));
Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
1+
/*
2+
* #%L
3+
* Discoverable commands, with the metadata a menu is built from.
4+
* %%
5+
* Copyright (C) 2026 SciJava developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.command;
31+
32+
import java.util.ArrayList;
33+
import java.util.Collection;
34+
import java.util.Comparator;
35+
import java.util.LinkedHashMap;
36+
import java.util.List;
37+
import java.util.Map;
38+
import java.util.Optional;
39+
40+
/**
41+
* A tree of menu entries, built from the menu paths of commands.
42+
* <p>
43+
* This is a model, not a widget: it knows about labels, order, shortcuts and
44+
* icons, and nothing about Swing, JavaFX or the platform. A user interface
45+
* walks it and builds whatever its toolkit calls a menu.
46+
* </p>
47+
* <p>
48+
* Building one loads no command classes. Every entry here comes from the
49+
* annotation index, and the command behind a leaf is loaded when somebody
50+
* actually runs it.
51+
* </p>
52+
* <p>
53+
* NB: SciJava Common called this {@code ShadowMenu}, which also implemented
54+
* {@code Collection<ModuleInfo>}, {@code Runnable} and {@code Comparable} and
55+
* carried a context. Here it is a tree and nothing else; running a leaf is the
56+
* caller's business, through {@code Runner}.
57+
* </p>
58+
*
59+
* @author Curtis Rueden
60+
*/
61+
public class MenuTree {
62+
63+
/** The separator between elements of a menu path. */
64+
public static final String SEPARATOR = ">";
65+
66+
private final String label;
67+
private final CommandInfo command;
68+
private final Map<String, MenuTree> children = new LinkedHashMap<>();
69+
70+
private MenuTree(final String label, final CommandInfo command) {
71+
this.label = label;
72+
this.command = command;
73+
}
74+
75+
/**
76+
* Builds a menu tree from the given commands.
77+
* <p>
78+
* Commands with no menu path, and those marked not visible, are left out:
79+
* they remain perfectly runnable, they simply do not appear.
80+
* </p>
81+
*
82+
* @param commands the commands to arrange
83+
* @return the root of the tree, whose children are the top-level menus
84+
*/
85+
public static MenuTree of(final Collection<CommandInfo> commands) {
86+
final MenuTree root = new MenuTree("", null);
87+
for (final CommandInfo command : commands) {
88+
if (!command.isVisible()) continue;
89+
final Optional<String> path = command.menuPath();
90+
if (path.isEmpty()) continue;
91+
root.add(command, path.get().split(SEPARATOR));
92+
}
93+
root.sort();
94+
return root;
95+
}
96+
97+
/** Gets this entry's label. Empty for the root. */
98+
public String label() {
99+
return label;
100+
}
101+
102+
/** Gets the command this entry runs, if it is a leaf. */
103+
public Optional<CommandInfo> command() {
104+
return Optional.ofNullable(command);
105+
}
106+
107+
/** Gets whether this entry runs a command, rather than holding others. */
108+
public boolean isLeaf() {
109+
return command != null;
110+
}
111+
112+
/** Gets the entries directly beneath this one, in display order. */
113+
public List<MenuTree> children() {
114+
return List.copyOf(children.values());
115+
}
116+
117+
/** Gets the child with the given label, if there is one. */
118+
public Optional<MenuTree> child(final String label) {
119+
return Optional.ofNullable(children.get(label));
120+
}
121+
122+
/**
123+
* Gets the entry at the given path, if there is one.
124+
*
125+
* @param path a {@code >}-separated path, as {@link Menu#path()} uses
126+
*/
127+
public Optional<MenuTree> find(final String path) {
128+
MenuTree current = this;
129+
for (final String element : path.split(SEPARATOR)) {
130+
final Optional<MenuTree> child = current.child(element.trim());
131+
if (child.isEmpty()) return Optional.empty();
132+
current = child.get();
133+
}
134+
return Optional.of(current);
135+
}
136+
137+
/** Gets every command in this subtree, in display order. */
138+
public List<CommandInfo> leaves() {
139+
final List<CommandInfo> leaves = new ArrayList<>();
140+
collectLeaves(leaves);
141+
return leaves;
142+
}
143+
144+
@Override
145+
public String toString() {
146+
return label + (isLeaf() ? "" : children.keySet());
147+
}
148+
149+
// -- Helper methods --
150+
151+
private void add(final CommandInfo command, final String[] path) {
152+
add(command, path, 0);
153+
}
154+
155+
private void add(final CommandInfo command, final String[] path,
156+
final int depth)
157+
{
158+
final String element = path[depth].trim();
159+
final boolean last = depth == path.length - 1;
160+
if (last) {
161+
// NB: two commands may claim one path; the first wins, so that an
162+
// unlucky collision does not silently discard the earlier entry.
163+
children.putIfAbsent(element, new MenuTree(element, command));
164+
return;
165+
}
166+
final MenuTree child = children.computeIfAbsent(element, //
167+
l -> new MenuTree(l, null));
168+
child.add(command, path, depth + 1);
169+
}
170+
171+
/** Orders each level by weight, then by label. */
172+
private void sort() {
173+
final List<MenuTree> sorted = new ArrayList<>(children.values());
174+
sorted.sort(Comparator.comparingDouble(MenuTree::weight) //
175+
.thenComparing(MenuTree::label));
176+
children.clear();
177+
for (final MenuTree child : sorted) {
178+
children.put(child.label(), child);
179+
child.sort();
180+
}
181+
}
182+
183+
/**
184+
* Gets the weight this entry sorts by: a leaf's own, or the lightest of the
185+
* entries beneath it.
186+
* <p>
187+
* NB: a submenu has no weight of its own, so it takes the position of its
188+
* most prominent child. Otherwise every submenu would sort equally and fall
189+
* back to alphabetical order.
190+
* </p>
191+
*/
192+
private double weight() {
193+
if (isLeaf()) return command.weight();
194+
return children.values().stream() //
195+
.mapToDouble(MenuTree::weight) //
196+
.min().orElse(Double.POSITIVE_INFINITY);
197+
}
198+
199+
private void collectLeaves(final List<CommandInfo> leaves) {
200+
if (isLeaf()) {
201+
leaves.add(command);
202+
return;
203+
}
204+
for (final MenuTree child : children.values())
205+
child.collectLeaves(leaves);
206+
}
207+
}

‎scijava-command/src/test/java/org/scijava/command/CommandsTest.java‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -93,13 +93,17 @@ public void testMenuMetadataWithoutLoadingCommands() {
9393
@Test
9494
public void testMenuOrdering() {
9595
try (final Context context = Context.create()) {
96+
// NB: restricted to the commands this test is about. Asserting the
97+
// whole list would break whenever another test adds a fixture, which
98+
// is exactly what happened when the menu tree tests arrived.
99+
final List<String> ofInterest = List.of("Count Beans", "Say Hello...",
100+
"Never Run");
96101
final List<String> labels = Commands.discover(context).stream() //
97-
.filter(c -> c.menuPath().isPresent()) //
98102
.map(CommandInfo::label) //
103+
.filter(ofInterest::contains) //
99104
.collect(Collectors.toList());
100105
// Weights: CountBeans 3, SayHello 12, NeverRun 50.
101-
assertEquals(List.of("Count Beans", "Say Hello...", "Never Run"),
102-
labels);
106+
assertEquals(ofInterest, labels);
103107
}
104108
}
105109

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
* #%L
3+
* Discoverable commands, with the metadata a menu is built from.
4+
* %%
5+
* Copyright (C) 2026 SciJava developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.command;
31+
32+
import org.scijava.context.Plugin;
33+
import org.scijava.execute.Parameter;
34+
35+
/** A command nested several menus deep. */
36+
@Plugin(type = Command.class)
37+
@Menu(path = "Image>Adjust>Brightness/Contrast...", weight = 5)
38+
public class DeepCommand implements Command {
39+
40+
@Parameter
41+
private int level;
42+
43+
@Override
44+
public void run() {
45+
// NB: nothing to do.
46+
}
47+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
* #%L
3+
* Discoverable commands, with the metadata a menu is built from.
4+
* %%
5+
* Copyright (C) 2026 SciJava developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.command;
31+
32+
import org.scijava.context.Plugin;
33+
34+
/** A command with a menu path that asks not to be shown. */
35+
@Plugin(type = Command.class)
36+
@Menu(path = "Help>Should Not Appear", visible = false)
37+
public class HiddenCommand implements Command {
38+
39+
@Override
40+
public void run() {
41+
// NB: nothing to do.
42+
}
43+
}

0 commit comments

Comments
 (0)