Add support for @OnClientCommand annotation to register and filter client command event handlers.

This commit is contained in:
Overlord committed 2026-10-07 13:09:27 +02:00
1 parent b4d70c3d3a
commit 1664bb6f28
6 files changed
+177 -24

No files matched your search

+10
View File
@@ -313,6 +313,16 @@ this.events().onMain(ClientCommandEvent.class, event ->
});
```
The same as an annotated listener method (see [Events](#events)), which filters and cancels:
```java
@OnClientCommand(module = "Shop", command = "buy", cancel = true) // command optional: every command of the module
void buy(ClientCommandEvent event) { ... }
```
`cancel = true` cancels the event before the method runs, so Lua does not receive the command
even when the method throws.
Server to client: `clientCommands().send(player, ...)` and `sendToAll(...)`; the Lua mod
receives them in `Events.OnServerCommand`.
@@ -1,5 +1,6 @@
package dev.overlord.zomboidforge.api;
import dev.overlord.zomboidforge.api.annotations.OnClientCommand;
import dev.overlord.zomboidforge.api.annotations.OnMain;
import dev.overlord.zomboidforge.api.annotations.OnModThread;
@@ -29,18 +30,19 @@ public interface Events
<E extends Event> Subscription onModThread(Class<E> type, Consumer<? super E> listener);
/**
* Registers the methods of {@code listener} annotated with {@link OnMain} or
* {@link OnModThread}, as {@link #onMain} and {@link #onModThread} do. ZomboidForge registers
* the mod's entry point this way after its constructor and before {@link Mod#onLoad()}; other
* objects opt in through this method.
* Registers the methods of {@code listener} annotated with {@link OnMain},
* {@link OnModThread}, or {@link OnClientCommand}, as {@link #onMain} and {@link #onModThread}
* do. ZomboidForge registers the mod's entry point this way after its constructor and before
* {@link Mod#onLoad()}; other objects opt in through this method.
*
* <p>Each annotated method:
* <ul>
* <li>returns {@code void} and has one parameter, a class that implements {@link Event}
* and is neither abstract nor an interface, because listeners are matched by the
* event's exact class;</li>
* <li>carries one of the two annotations; {@link OnModThread} not for a
* {@link MainThreadEvent};</li>
* <li>carries one of the annotations; {@link OnModThread} not for a
* {@link MainThreadEvent}, {@link OnClientCommand} only for a
* {@link ClientCommandEvent};</li>
* <li>may be static, private, and declared in a superclass of {@code listener}'s class.
* An instance method that a subclass overrides listens only when the override carries
* the annotation itself.</li>
@@ -19,8 +19,9 @@ import java.nio.file.Path;
* <p>Lifecycle, in this order:
* <ol>
* <li>Listener methods: the methods annotated with
* {@link dev.overlord.zomboidforge.api.annotations.OnMain} or
* {@link dev.overlord.zomboidforge.api.annotations.OnModThread} are registered (see
* {@link dev.overlord.zomboidforge.api.annotations.OnMain OnMain},
* {@link dev.overlord.zomboidforge.api.annotations.OnModThread OnModThread}, or
* {@link dev.overlord.zomboidforge.api.annotations.OnClientCommand OnClientCommand} are registered (see
* {@link Events#register(Object)}).</li>
* <li>{@link #onLoad()}: registration and setup. The server database, Lua, and the world do
* not exist yet.</li>
@@ -0,0 +1,39 @@
package dev.overlord.zomboidforge.api.annotations;
import dev.overlord.zomboidforge.api.ClientCommandEvent;
import dev.overlord.zomboidforge.api.Events;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Registers the method with {@link Events#onMain} for the {@link ClientCommandEvent}s of one
* module, and optionally one command. The method has one parameter, a {@code ClientCommandEvent};
* otherwise the rules of {@link Events#register(Object)} apply, and the method carries none of
* the other listener annotations.
*
* <pre>{@code
* @OnClientCommand(module = "Shop", command = "buy", cancel = true)
* void buy(ClientCommandEvent event) { ... }
* }</pre>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnClientCommand
{
/** The Lua module, matched exactly; not blank. */
String module();
/** The command, matched exactly; empty matches every command of the module. */
String command() default "";
/**
* Cancels the event before the method runs, so Lua's {@code OnClientCommand} does not
* receive the command, also when the method throws.
*/
boolean cancel() default false;
}
@@ -1,8 +1,10 @@
package dev.overlord.zomboidforge.core.runtime;
import dev.overlord.zomboidforge.api.ClientCommandEvent;
import dev.overlord.zomboidforge.api.Event;
import dev.overlord.zomboidforge.api.MainThreadEvent;
import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.api.annotations.OnClientCommand;
import dev.overlord.zomboidforge.api.annotations.OnMain;
import dev.overlord.zomboidforge.api.annotations.OnModThread;
@@ -23,9 +25,12 @@ import java.util.function.Consumer;
/**
* Finds the listener methods of an object for {@code Events.register(Object)}: methods annotated
* with {@link OnMain} or {@link OnModThread} in its class and superclasses, up to {@link Mod} or
* {@code Object}. Methods do not have to be public; they are called through method handles from
* a private lookup, as {@code RecordCodec} reads records.
* with {@link OnMain}, {@link OnModThread}, or {@link OnClientCommand} in its class and
* superclasses, up to {@link Mod} or {@code Object}. Methods do not have to be public; they are
* called through method handles from a private lookup, as {@code RecordCodec} reads records.
*
* <p>An {@link OnClientCommand} method is a main-thread listener for {@link ClientCommandEvent}
* with a filter in front: only the commands of its module (and command) reach it.
*/
final class ListenerScanner
{
@@ -33,7 +38,8 @@ final class ListenerScanner
* One listener method, bound to its object.
*
* @param type the event class, the method's parameter type
* @param main {@code true} for {@link OnMain}, {@code false} for {@link OnModThread}
* @param main {@code true} for {@link OnMain} and {@link OnClientCommand}, {@code false} for
* {@link OnModThread}
* @param action calls the method; rethrows what the method throws, unchanged
*/
record ListenerMethod(Class<?> type, boolean main, String name, Consumer<Object> action) {}
@@ -63,14 +69,15 @@ final class ListenerScanner
for (Method method : hierarchy.get(types.get(i)))
{
boolean main = method.isAnnotationPresent(OnMain.class);
boolean modThread = method.isAnnotationPresent(OnModThread.class);
boolean main = method.isAnnotationPresent(OnMain.class);
boolean modThread = method.isAnnotationPresent(OnModThread.class);
OnClientCommand clientCommand = method.getAnnotation(OnClientCommand.class);
// javac copies method annotations to bridge methods.
if ((!main && !modThread) || method.isBridge() || method.isSynthetic()) continue;
if (ListenerScanner.isOverridden(method, subclasses, hierarchy)) continue;
if ((!main && !modThread && clientCommand == null) || method.isBridge() || method.isSynthetic()) continue;
if (ListenerScanner.isOverridden(method, subclasses, hierarchy)) continue;
ListenerMethod listener = ListenerScanner.listener(target, method, main, modThread, problems);
ListenerMethod listener = ListenerScanner.listener(target, method, main, modThread, clientCommand, problems);
if (listener != null) found.add(listener);
}
}
@@ -136,15 +143,18 @@ final class ListenerScanner
}
/** The listener for {@code method}, or {@code null} after adding its problems to {@code problems}. */
private static @Nullable ListenerMethod listener(Object target, Method method, boolean main, boolean modThread, List<String> problems)
private static @Nullable ListenerMethod listener(Object target, Method method, boolean main, boolean modThread, @Nullable OnClientCommand clientCommand, List<String> problems)
{
String where = "'" + method.getDeclaringClass().getName() + "." + method.getName() + "'";
Class<?>[] parameters = method.getParameterTypes();
int before = problems.size();
int kinds = (main ? 1 : 0) + (modThread ? 1 : 0) + (clientCommand == null ? 0 : 1);
if (main && modThread) problems.add(where + " carries both @OnMain and @OnModThread.");
if (kinds > 1) problems.add(where + " carries more than one of @OnMain, @OnModThread, and @OnClientCommand.");
if (method.getReturnType() != void.class) problems.add(where + " must return void.");
if (clientCommand != null && clientCommand.module().isBlank()) problems.add(where + ": @OnClientCommand needs a module.");
if (parameters.length != 1)
{
problems.add(where + " must have one parameter, the event; found " + parameters.length + ".");
@@ -159,6 +169,8 @@ final class ListenerScanner
problems.add(where + ": the parameter type '" + type.getName() + "' is " + (type.isInterface() ? "an interface" : "abstract") + "; listeners are matched by the event's exact class.");
else if (modThread && MainThreadEvent.class.isAssignableFrom(type))
problems.add(where + ": '" + type.getName() + "' is a main-thread event; annotate the method with @OnMain.");
else if (clientCommand != null && type != ClientCommandEvent.class)
problems.add(where + ": @OnClientCommand methods take a ClientCommandEvent, found '" + type.getName() + "'.");
if (problems.size() > before) return null;
@@ -167,12 +179,15 @@ final class ListenerScanner
MethodHandle handle = MethodHandles.privateLookupIn(method.getDeclaringClass(), MethodHandles.lookup()).unreflect(method);
if (!Modifier.isStatic(method.getModifiers())) handle = handle.bindTo(target);
MethodHandle invoker = handle.asType(MethodType.methodType(void.class, Object.class));
return new ListenerMethod(type, main, method.getName(), event -> {
MethodHandle invoker = handle.asType(MethodType.methodType(void.class, Object.class));
Consumer<Object> call = event -> {
try { invoker.invokeExact(event); }
catch (Throwable t) { throw ListenerScanner.<RuntimeException>rethrow(t); }
});
};
return clientCommand == null
? new ListenerMethod(type, main, method.getName(), call)
: new ListenerMethod(type, true, method.getName(), ListenerScanner.filter(clientCommand, call));
}
catch (IllegalAccessException e)
{
@@ -181,6 +196,24 @@ final class ListenerScanner
}
}
/** {@code call} for the commands that {@code annotation} selects; cancels them first when it says so. */
private static Consumer<Object> filter(OnClientCommand annotation, Consumer<Object> call)
{
String module = annotation.module();
String command = annotation.command();
boolean cancel = annotation.cancel();
return event -> {
ClientCommandEvent received = (ClientCommandEvent) event;
if (!received.module().equals(module)) return;
if (!command.isEmpty() && !received.command().equals(command)) return;
if (cancel) received.cancel();
call.accept(event);
};
}
/** Throws {@code t} unchanged, also a checked exception; the listener's caller logs every {@code Throwable}. */
@SuppressWarnings("unchecked")
private static <T extends Throwable> RuntimeException rethrow(Throwable t) throws T { throw (T) t; }
@@ -1,9 +1,12 @@
package dev.overlord.zomboidforge.core.runtime;
import dev.overlord.zomboidforge.api.ClientCommandEvent;
import dev.overlord.zomboidforge.api.Event;
import dev.overlord.zomboidforge.api.Events;
import dev.overlord.zomboidforge.api.PlayerRef;
import dev.overlord.zomboidforge.api.Subscription;
import dev.overlord.zomboidforge.api.TickEvent;
import dev.overlord.zomboidforge.api.annotations.OnClientCommand;
import dev.overlord.zomboidforge.api.annotations.OnMain;
import dev.overlord.zomboidforge.api.annotations.OnModThread;
import dev.overlord.zomboidforge.core.RecordingLogger;
@@ -13,6 +16,7 @@ import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -91,6 +95,34 @@ class EventBusTest
@OnModThread
void mainOnly(TickEvent event) {}
@OnClientCommand(module = "Shop")
void wrongEvent(Joined event) {}
@OnClientCommand(module = " ")
void noModule(ClientCommandEvent event) {}
@OnMain
@OnClientCommand(module = "Shop")
void mixed(ClientCommandEvent event) {}
}
/** Client command handlers of the module {@code Shop}. */
private static final class ShopCommands
{
final List<String> log = new ArrayList<>();
@OnClientCommand(module = "Shop")
void any(ClientCommandEvent event) { this.log.add("any " + event.command() + (event.isCancelled() ? " cancelled" : "")); }
@OnClientCommand(module = "Shop", command = "buy", cancel = true)
void buy(ClientCommandEvent event) { this.log.add("buy" + (event.isCancelled() ? " cancelled" : "")); }
}
private static final class FailingCommand
{
@OnClientCommand(module = "Shop", cancel = true)
void fail(ClientCommandEvent event) { throw new IllegalStateException("broken"); }
}
private static final class FailingListener
@@ -228,7 +260,7 @@ class EventBusTest
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> a.register(new InvalidListeners()));
// Every method, and the parameter types that break a rule.
for (String method : List.of("anAbstract", "anInterface", "both", "mainOnly", "notEvent", "returns", "two"))
for (String method : List.of("anAbstract", "anInterface", "both", "mainOnly", "mixed", "noModule", "notEvent", "returns", "two", "wrongEvent"))
EventBusTest.assertContainsAll(e.getMessage(), InvalidListeners.class.getName() + "." + method);
EventBusTest.assertContainsAll(e.getMessage(), AbstractEvent.class.getName(), Event.class.getName(), TickEvent.class.getName(), "java.lang.String");
@@ -246,6 +278,42 @@ class EventBusTest
EventBusTest.assertContainsAll(this.logger.messages.getFirst(), "ERROR", "'fail'", "Joined", "java.io.IOException: broken");
}
@Test
void clientCommandMethodsReceiveTheirModuleAndCommandOnly()
{
Events a = this.bus.forMod("a", this.modThread, this.logger);
ShopCommands commands = new ShopCommands();
a.register(commands);
ClientCommandEvent buy = EventBusTest.command("Shop", "buy");
ClientCommandEvent sell = EventBusTest.command("Shop", "sell");
ClientCommandEvent other = EventBusTest.command("Bank", "buy");
this.bus.post(buy);
this.bus.post(sell);
this.bus.post(other);
assertEquals(List.of("any buy", "buy cancelled", "any sell"), commands.log, "cancelled before the method runs, after the listeners before it");
assertTrue(buy.isCancelled());
assertFalse(sell.isCancelled());
assertFalse(other.isCancelled());
}
@Test
void clientCommandMethodsCancelAlsoWhenTheyThrow()
{
this.bus.forMod("a", this.modThread, this.logger).register(new FailingCommand());
ClientCommandEvent event = EventBusTest.command("Shop", "buy");
this.bus.post(event);
assertTrue(event.isCancelled());
assertEquals(1, this.logger.messages.size());
EventBusTest.assertContainsAll(this.logger.messages.getFirst(), "'fail'", "ClientCommandEvent", "broken");
}
private static ClientCommandEvent command(String module, String command) { return new ClientCommandEvent(new PlayerRef(1, "bob"), module, command, Map.of()); }
private static void assertContainsAll(String message, String... parts)
{
for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message);