From a351fc237c0e400db22ddf0e94aaeb78a2b5dea2 Mon Sep 17 00:00:00 2001 From: Overlord Date: Sat, 3 Oct 2026 13:22:47 +0200 Subject: [PATCH] Add client command integration for Build 42: define APIs, event system, hooks, patches, and Lua table converters. Include tests, documentation, and mod support. --- MOD_DEVELOPMENT.md | 80 +++++++++-- .../zomboidforge/api/Cancellable.java | 14 ++ .../zomboidforge/api/ClientCommandEvent.java | 55 +++++++ .../zomboidforge/api/ClientCommands.java | 35 +++++ .../dev/overlord/zomboidforge/api/Mod.java | 3 + .../overlord/zomboidforge/api/ModContext.java | 3 + .../overlord/zomboidforge/api/PlayerRef.java | 19 +++ .../zomboidforge/compat/b42/B42PatchSet.java | 1 + .../b42/patches/ClientCommandPatch.java | 43 ++++++ .../compat/b42/ForgeInstance.java | 5 +- .../b42/commands/ClientCommandChannel.java | 55 +++++++ .../compat/b42/commands/LuaTables.java | 134 ++++++++++++++++++ .../compat/b42/commands/package-info.java | 5 +- .../compat/b42/hooks/ClientCommandHooks.java | 54 +++++++ .../compat/b42/commands/LuaTablesTest.java | 127 +++++++++++++++++ .../dev/overlord/zomboidforge/core/Forge.java | 36 +++-- .../core/commands/ClientCommandSender.java | 21 +++ .../core/commands/ModClientCommands.java | 45 ++++++ .../core/commands/package-info.java | 3 +- .../zomboidforge/core/mods/ModLoader.java | 29 ++-- .../zomboidforge/core/mods/ModServices.java | 14 +- .../overlord/zomboidforge/core/ForgeTest.java | 23 ++- .../core/commands/ModClientCommandsTest.java | 107 ++++++++++++++ core/src/test/java/testmods/CommandMod.java | 7 +- 24 files changed, 870 insertions(+), 48 deletions(-) create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/Cancellable.java create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/ClientCommandEvent.java create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/ClientCommands.java create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/PlayerRef.java create mode 100644 compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ClientCommandPatch.java create mode 100644 compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/ClientCommandChannel.java create mode 100644 compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/LuaTables.java create mode 100644 compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ClientCommandHooks.java create mode 100644 compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/commands/LuaTablesTest.java create mode 100644 core/src/main/java/dev/overlord/zomboidforge/core/commands/ClientCommandSender.java create mode 100644 core/src/main/java/dev/overlord/zomboidforge/core/commands/ModClientCommands.java create mode 100644 core/src/test/java/dev/overlord/zomboidforge/core/commands/ModClientCommandsTest.java diff --git a/MOD_DEVELOPMENT.md b/MOD_DEVELOPMENT.md index 6f35c15..4e45b50 100644 --- a/MOD_DEVELOPMENT.md +++ b/MOD_DEVELOPMENT.md @@ -164,20 +164,21 @@ public final class ShopMod extends Mod Methods of `Mod`, usable from the constructor on (also in field initializers): -| Method | Returns | Use | -|-----------------|-----------------|---------------------------------------------------------------| -| `id()` | `String` | the mod's id from `mod.toml` | -| `version()` | `String` | the mod's version from `mod.toml` | -| `gameVersion()` | `GameVersion` | the running Project Zomboid version | -| `config()` | `ModConfig` | settings from `config.toml`, bound to records or read by path | -| `logger()` | `System.Logger` | messages in the Project Zomboid log, marked with the mod's id | -| `directory()` | `Path` | the mod's folder, `/mods/` | -| `events()` | `Events` | event listeners | -| `main()` | `MainThread` | code that touches game objects | -| `modThread()` | `ModThread` | the mod's own work, one task at a time | -| `async()` | `AsyncExecutor` | blocking work such as HTTP calls or file I/O | -| `storage()` | `ModStorage` | the mod's tables in the world's `zomboidforge.db` | -| `commands()` | `Commands` | admin commands for chat, the server console, and RCON | +| Method | Returns | Use | +|--------------------|------------------|---------------------------------------------------------------| +| `id()` | `String` | the mod's id from `mod.toml` | +| `version()` | `String` | the mod's version from `mod.toml` | +| `gameVersion()` | `GameVersion` | the running Project Zomboid version | +| `config()` | `ModConfig` | settings from `config.toml`, bound to records or read by path | +| `logger()` | `System.Logger` | messages in the Project Zomboid log, marked with the mod's id | +| `directory()` | `Path` | the mod's folder, `/mods/` | +| `events()` | `Events` | event listeners | +| `main()` | `MainThread` | code that touches game objects | +| `modThread()` | `ModThread` | the mod's own work, one task at a time | +| `async()` | `AsyncExecutor` | blocking work such as HTTP calls or file I/O | +| `storage()` | `ModStorage` | the mod's tables in the world's `zomboidforge.db` | +| `commands()` | `Commands` | admin commands for chat, the server console, and RCON | +| `clientCommands()` | `ClientCommands` | server commands to clients, received by their Lua mods | ## Threads @@ -259,6 +260,57 @@ public void onLoad() { this.commands().register(HelloCommand.class); } that the work started. - Project Zomboid's commands are looked up first; mods' commands follow in load order. +## Client commands + +A Java mod on the server and a Lua mod on the client (for example from the Workshop) talk +through Project Zomboid's command channel, so players keep the official client. + +Client to server: the Lua mod calls `sendClientCommand`, and the server posts +`ClientCommandEvent` on the main thread. + +```lua +sendClientCommand(getPlayer(), "Shop", "buy", { item = "Base.Axe", count = 2 }) +``` + +```java +this.events().onMain(ClientCommandEvent.class, event -> +{ + if (!event.module().equals("Shop")) return; + event.cancel(); // Lua's OnClientCommand does not see it + + String item = (String) event.args().get("item"); + int count = ((Double) event.args().get("count")).intValue(); + // ... + this.clientCommands().send(event.player(), "Shop", "bought", Map.of("item", item, "count", count)); +}); +``` + +Server to client: `clientCommands().send(player, ...)` and `sendToAll(...)`; the Lua mod +receives them in `Events.OnServerCommand`. + +```lua +Events.OnServerCommand.Add(function(module, command, args) + if module == "Shop" and command == "bought" then print(args.item, args.count) end +end) +``` + +- **Every** client command is posted, including those of Project Zomboid (`vehicle`, + `player`, ...) and of other mods; filter by `module()`. The event is a `MainThreadEvent`. +- **`cancel()`** stops Project Zomboid from passing the command to Lua's `OnClientCommand`. + Every listener still runs; `isCancelled()` tells whether another one cancelled. +- **`args()`** is the Lua table as an unmodifiable map: keys are `String` or `Double` (Lua + arrays have the keys `1.0`, `2.0`, ...); values are `String`, `Double` (every Lua number), + `Boolean`, nested maps, or game objects (inventory items, directions, dead bodies). It is + empty when the client sent no table. +- **`player()`** is a `PlayerRef` (online id and username), a value that stays valid on other + threads and after the player left. Sending to a player who left sends nothing. +- **Sending** works from any thread. The arguments are copied and checked at once + (`IllegalArgumentException` for unsupported types, `null`, or cycles); numbers become Lua + numbers, lists become Lua arrays. The command is sent on the main thread: at once when + called there, otherwise as one of the mod's queued main-thread tasks. +- Client commands come from players and can be forged by a modified client. Check every + argument and the player's rights before acting on it. + ## Storage Mod data belongs in `storage()`: tables in `zomboidforge.db`, a SQLite database in the world's diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/Cancellable.java b/api/src/main/java/dev/overlord/zomboidforge/api/Cancellable.java new file mode 100644 index 0000000..cd2edcd --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Cancellable.java @@ -0,0 +1,14 @@ +package dev.overlord.zomboidforge.api; + +/** + * An event whose default action, what Project Zomboid does after the event, can be prevented. + * Only listeners on the main thread can cancel: the default action runs once every main-thread + * listener returned. Every listener is called, also after one cancelled. + */ +public interface Cancellable +{ + /** Prevents the default action. */ + void cancel(); + + boolean isCancelled(); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommandEvent.java b/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommandEvent.java new file mode 100644 index 0000000..78f40d3 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommandEvent.java @@ -0,0 +1,55 @@ +package dev.overlord.zomboidforge.api; + +import java.util.Map; +import java.util.Objects; + +/** + * A client command arrived: a client called Lua's {@code sendClientCommand(module, command, args)}. + * Posted on the main thread for every client command, including those of Project Zomboid and of + * Lua mods, so listeners filter by {@link #module()}. + * + *

Default action: Project Zomboid passes the command to Lua's {@code Events.OnClientCommand}. + * {@link #cancel()} prevents that, for example when a Java mod handles the module itself. + * + *

{@link #args()} is the Lua table converted to Java: keys are {@code String} or + * {@code Double} (Lua arrays have the keys {@code 1.0}, {@code 2.0}, ...), values are + * {@code String}, {@code Double}, {@code Boolean}, a nested {@code Map} of the same kind, or a + * game object that Project Zomboid sends with commands (in Build 42 an inventory item, an + * {@code IsoDirections}, or a dead body). The maps cannot be modified. + */ +public final class ClientCommandEvent implements MainThreadEvent, Cancellable +{ + private final PlayerRef player; + private final String module; + private final String command; + private final Map args; + + private boolean cancelled; + + /** @param args the converted arguments; empty when the client sent none */ + public ClientCommandEvent(PlayerRef player, String module, String command, Map args) + { + this.player = Objects.requireNonNull(player, "player"); + this.module = Objects.requireNonNull(module, "module"); + this.command = Objects.requireNonNull(command, "command"); + this.args = Objects.requireNonNull(args, "args"); + } + + /** The player who sent the command. */ + public PlayerRef player() { return this.player; } + + public String module() { return this.module; } + + public String command() { return this.command; } + + public Map args() { return this.args; } + + @Override + public void cancel() { this.cancelled = true; } + + @Override + public boolean isCancelled() { return this.cancelled; } + + @Override + public String toString() { return "ClientCommandEvent[" + this.player + ", " + this.module + "." + this.command + ", " + this.args + (this.cancelled ? ", cancelled" : "") + "]"; } +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommands.java b/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommands.java new file mode 100644 index 0000000..4264e62 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommands.java @@ -0,0 +1,35 @@ +package dev.overlord.zomboidforge.api; + +import java.util.Map; + +/** + * Server commands to clients, the reply channel to {@link ClientCommandEvent}: a client receives + * them in Lua's {@code Events.OnServerCommand(module, command, args)}. Together, a Java mod on the + * server and a Lua mod on the client exchange commands while players keep the official client. + * + *

{@code args} becomes a Lua table: keys are {@code String} or a {@code Number} (sent as a + * Lua number), values are {@code String}, {@code Number}, {@code Boolean}, a nested {@code Map}, a + * {@code List} (a Lua array, indexed from 1), or a game object that Project Zomboid sends with + * commands (see {@link ClientCommandEvent}). {@code null} keys or values, and cycles, are not + * allowed. An empty map sends no arguments; the client then receives {@code nil}. + * + *

The methods can be called on any thread. The arguments are checked at once; the command is + * sent on the main thread, at once when called there, otherwise with the mod's queued + * main-thread tasks. + */ +public interface ClientCommands +{ + /** + * Sends a command to {@code player}. Nothing is sent when the player is no longer connected. + * + * @throws IllegalArgumentException when {@code args} contains a key or value that cannot be sent + */ + void send(PlayerRef player, String module, String command, Map args); + + /** + * Sends a command to every connected client. + * + * @throws IllegalArgumentException when {@code args} contains a key or value that cannot be sent + */ + void sendToAll(String module, String command, Map args); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java b/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java index ca2e2ac..d5666f5 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java @@ -87,4 +87,7 @@ public abstract class Mod /** Admin command registration. */ protected final Commands commands() { return this.context.commands(); } + + /** Server commands to clients, received by their Lua mods. */ + protected final ClientCommands clientCommands() { return this.context.clientCommands(); } } diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java b/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java index 3aed3d3..5f03a8c 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java @@ -45,4 +45,7 @@ public interface ModContext /** Admin command registration. */ Commands commands(); + + /** Server commands to clients, received by their Lua mods. */ + ClientCommands clientCommands(); } diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/PlayerRef.java b/api/src/main/java/dev/overlord/zomboidforge/api/PlayerRef.java new file mode 100644 index 0000000..e17cac5 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/PlayerRef.java @@ -0,0 +1,19 @@ +package dev.overlord.zomboidforge.api; + +import java.util.Objects; + +/** + * A connected player, by value: usable on any thread and after the player left. Project + * Zomboid reuses online ids of players who left, so ZomboidForge matches both the id and the + * username before it acts on a player. + * + * @param onlineId the player's online id while connected + * @param username the player's account name + */ +public record PlayerRef(int onlineId, String username) +{ + public PlayerRef + { + Objects.requireNonNull(username, "username"); + } +} diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java index ffef12a..c28494a 100644 --- a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java @@ -20,6 +20,7 @@ public final class B42PatchSet implements PatchSet new BackupStoragePatch(), new CommandLookupPatch(), new CommandListPatch(), + new ClientCommandPatch(), new IsoZombieVehiclePerformancePatch(), new IsoZombieNetworkComponentPerformancePatch(), new IsoZombieSpotChancePerformancePatch(), diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ClientCommandPatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ClientCommandPatch.java new file mode 100644 index 0000000..efa039d --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ClientCommandPatch.java @@ -0,0 +1,43 @@ +package dev.overlord.zomboidforge.compat.b42.patches; + +import dev.overlord.zomboidforge.patcher.Anchor; +import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.HookArgument; +import dev.overlord.zomboidforge.patcher.Patches.CancellableHookPatch; + +import java.util.List; + +/** + * Makes the Lua event {@code OnClientCommand} in {@code GameServer.receiveClientCommand} depend on + * {@code ClientCommandHooks.onClientCommand(module, command, player, tbl)}: + * + *

{@code
+ * if (!ClientCommandHooks.onClientCommand(module, command, player, tbl))
+ *     LuaEventManager.triggerEvent("OnClientCommand", module, command, player, tbl);
+ * }
+ * + * The arguments are the method's local variables of these names. + */ +public final class ClientCommandPatch extends CancellableHookPatch +{ + private static final Anchor.Call ANCHOR = new Anchor.Call( + new Anchor.Method("receiveClientCommand", "(Lzombie/core/network/ByteBufferReader;Lzombie/core/raknet/UdpConnection;S)V"), + "zombie/Lua/LuaEventManager", "triggerEvent", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V" + ); + + private static final Hook HOOK = new Hook( + "dev/overlord/zomboidforge/compat/b42/hooks/ClientCommandHooks", "onClientCommand", + "(Ljava/lang/String;Ljava/lang/String;Lzombie/characters/IsoPlayer;Lse/krka/kahlua/vm/KahluaTable;)Z" + ); + + private static final List ARGUMENTS = List.of( + new HookArgument.Local("module"), + new HookArgument.Local("command"), + new HookArgument.Local("player"), + new HookArgument.Local("tbl") + ); + + public ClientCommandPatch() { + super("zombie/network/GameServer", ClientCommandPatch.ANCHOR, ClientCommandPatch.HOOK, ClientCommandPatch.ARGUMENTS); + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/ForgeInstance.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/ForgeInstance.java index e84f01d..f9b5960 100644 --- a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/ForgeInstance.java +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/ForgeInstance.java @@ -1,12 +1,15 @@ package dev.overlord.zomboidforge.compat.b42; +import dev.overlord.zomboidforge.compat.b42.commands.ClientCommandChannel; import dev.overlord.zomboidforge.compat.b42.commands.ModCommands; import dev.overlord.zomboidforge.core.Forge; /** The one {@link Forge} of the server, shared by the hook classes. */ public final class ForgeInstance { - public static final Forge FORGE = Forge.fromSystemProperties(ModCommands::check); + public static final Forge FORGE = Forge.fromSystemProperties( + ModCommands::check, ClientCommandChannel::prepare + ); private ForgeInstance() {} } diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/ClientCommandChannel.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/ClientCommandChannel.java new file mode 100644 index 0000000..2d71720 --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/ClientCommandChannel.java @@ -0,0 +1,55 @@ +package dev.overlord.zomboidforge.compat.b42.commands; + +import dev.overlord.zomboidforge.api.PlayerRef; + +import org.jetbrains.annotations.Nullable; + +import se.krka.kahlua.vm.KahluaTable; + +import zombie.Lua.LuaManager; +import zombie.characters.IsoPlayer; +import zombie.network.GameServer; + +import java.util.Map; + +/** Client commands in Build 42: players as {@link PlayerRef}s, and server commands to clients. */ +public final class ClientCommandChannel +{ + private ClientCommandChannel() {} + + public static PlayerRef ref(IsoPlayer player) { return new PlayerRef(player.getOnlineID(), player.getUsername()); } + + /** + * Copies {@code args} at once and returns the action that sends the command with + * {@code GameServer.sendServerCommand}, to every connection when {@code player} is + * {@code null}. The action runs on the main thread and sends nothing when the player is no + * longer connected. + * + * @throws IllegalArgumentException naming a key or value that cannot be sent + */ + public static Runnable prepare(@Nullable PlayerRef player, String module, String command, Map args) + { + Map copy = LuaTables.copy(args); + + return () -> + { + KahluaTable table = copy.isEmpty() ? null : LuaTables.toLua(copy, LuaManager.platform::newTable); + + if (player == null) { + GameServer.sendServerCommand(module, command, table); + return; + } + + IsoPlayer target = ClientCommandChannel.find(player); + if (target != null) GameServer.sendServerCommand(target, module, command, table); + }; + } + + /** The connected player with the online id and the username of {@code player}, or {@code null}. Main thread. */ + private static @Nullable IsoPlayer find(PlayerRef player) + { + Object connected = GameServer.IDToPlayerMap.get((short) player.onlineId()); + + return connected instanceof IsoPlayer target && player.username().equals(target.getUsername()) ? target : null; + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/LuaTables.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/LuaTables.java new file mode 100644 index 0000000..1aed19c --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/LuaTables.java @@ -0,0 +1,134 @@ +package dev.overlord.zomboidforge.compat.b42.commands; + +import org.jetbrains.annotations.Nullable; + +import se.krka.kahlua.vm.KahluaTable; +import se.krka.kahlua.vm.KahluaTableIterator; + +import zombie.inventory.InventoryItem; +import zombie.iso.IsoDirections; +import zombie.iso.objects.IsoDeadBody; + +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; + +/** + * Conversion between the Kahlua tables of command arguments and the Java maps of the API. The + * types are those {@code TableNetworkUtils} sends: {@code String} and {@code Double} keys; + * {@code String}, {@code Double}, {@code Boolean}, table, {@code InventoryItem}, + * {@code IsoDirections}, and {@code IsoDeadBody} values. + */ +public final class LuaTables +{ + private LuaTables() {} + + /** {@code table} as an unmodifiable map, nested tables as nested maps; empty for {@code null}. */ + public static Map toJava(@Nullable KahluaTable table) + { + if (table == null) return Map.of(); + + Map map = new LinkedHashMap<>(); + KahluaTableIterator iterator = table.iterator(); + + while (iterator.advance()) + { + Object value = iterator.getValue(); + map.put(iterator.getKey(), value instanceof KahluaTable nested ? LuaTables.toJava(nested) : value); + } + + return Collections.unmodifiableMap(map); + } + + /** + * A deep, unmodifiable copy of {@code args} in Lua's types: number keys and values become + * {@code Double}, lists become maps with the keys {@code 1.0}, {@code 2.0}, .... + * + * @throws IllegalArgumentException naming the first key or value that cannot be sent, or a + * map or list that contains itself + */ + public static Map copy(Map args) { return LuaTables.copy(args, "args", Collections.newSetFromMap(new IdentityHashMap<>())); } + + /** A new table with the entries of {@code args}, a result of {@link #copy}; nested maps become nested tables. */ + public static KahluaTable toLua(Map args, Supplier newTable) + { + KahluaTable table = newTable.get(); + + for (Map.Entry entry : args.entrySet()) + { + Object value = entry.getValue(); + + @SuppressWarnings("unchecked") + Object luaValue = value instanceof Map nested ? LuaTables.toLua((Map) nested, newTable) : value; + + table.rawset(entry.getKey(), luaValue); + } + + return table; + } + + private static Map copy(Map map, String path, Set open) + { + if (!open.add(map)) throw new IllegalArgumentException("'" + path + "' contains itself."); + + Map copy = new LinkedHashMap<>(); + + for (Map.Entry entry : map.entrySet()) + { + Object key = LuaTables.key(entry.getKey(), path); + String here = path + "[" + key + "]"; + + copy.put(key, LuaTables.value(entry.getValue(), here, open)); + } + + open.remove(map); + + return Collections.unmodifiableMap(copy); + } + + private static Map copy(List list, String path, Set open) + { + if (!open.add(list)) throw new IllegalArgumentException("'" + path + "' contains itself."); + + Map copy = new LinkedHashMap<>(); + + for (int i = 0; i < list.size(); i++) copy.put((double) (i + 1), LuaTables.value(list.get(i), path + "[" + (i + 1) + "]", open)); + + open.remove(list); + + return Collections.unmodifiableMap(copy); + } + + private static Object key(@Nullable Object key, String path) + { + if (key instanceof String) return key; + if (key instanceof Number number) return number.doubleValue(); + + throw new IllegalArgumentException("'" + path + "' has the key '" + key + "'" + LuaTables.typeOf(key) + "; keys are strings or numbers."); + } + + private static Object value(@Nullable Object value, String path, Set open) + { + return switch (value) + { + case String string -> string; + case Boolean bool -> bool; + case Number number -> number.doubleValue(); + case Map map -> LuaTables.copy(map, path, open); + case List list -> LuaTables.copy(list, path, open); + case InventoryItem item -> item; + case IsoDirections direction -> direction; + case IsoDeadBody body -> body; + case null -> throw new IllegalArgumentException("'" + path + "' is null."); + default -> throw new IllegalArgumentException( + "'" + path + "' is a '" + value.getClass().getName() + "'; values are strings, numbers, booleans, maps, lists, inventory items, directions, or dead bodies." + ); + }; + } + + private static String typeOf(@Nullable Object value) { return value == null ? "" : " ('" + value.getClass().getName() + "')"; } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/package-info.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/package-info.java index a3f2f19..79fc54e 100644 --- a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/package-info.java +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/package-info.java @@ -1,6 +1,7 @@ /** - * Admin commands of mods in Build 42: checks for registered command classes and the lookup that - * mirrors {@code zombie.commands.CommandBase.findCommandCls}. + * Commands of mods in Build 42: checks for registered admin command classes and the lookup that + * mirrors {@code zombie.commands.CommandBase.findCommandCls}; client commands and the conversion + * of their Lua tables. * * @noinspection UnstableApiUsage, RedundantSuppression */ diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ClientCommandHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ClientCommandHooks.java new file mode 100644 index 0000000..c0d37bb --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ClientCommandHooks.java @@ -0,0 +1,54 @@ +package dev.overlord.zomboidforge.compat.b42.hooks; + +import dev.overlord.zomboidforge.api.ClientCommandEvent; +import dev.overlord.zomboidforge.compat.b42.ForgeInstance; +import dev.overlord.zomboidforge.compat.b42.commands.ClientCommandChannel; +import dev.overlord.zomboidforge.compat.b42.commands.LuaTables; + +import org.jetbrains.annotations.Nullable; + +import se.krka.kahlua.vm.KahluaTable; + +import zombie.characters.IsoPlayer; + +/** + * Hooks called by patched {@code zombie.network.GameServer.receiveClientCommand} code, on the main + * thread (client commands are queued for the main loop). Exceptions are caught here; the command + * then reaches Lua as in vanilla. + */ +@SuppressWarnings("CallToPrintStackTrace") +public final class ClientCommandHooks +{ + private ClientCommandHooks() {} + + /** + * Called directly before {@code LuaEventManager.triggerEvent("OnClientCommand", module, command, player, args)}, + * after the vanilla checks (the player exists; {@code vehicle.remove} only with permission). + * Posts {@link ClientCommandEvent} when a mod listens for it. + * + * @param args {@code null} when the client sent no arguments + * @return {@code true} when a listener cancelled the event, which skips the Lua event + */ + public static boolean onClientCommand(String module, String command, IsoPlayer player, @Nullable KahluaTable args) + { + try + { + if (!ForgeInstance.FORGE.hasListeners(ClientCommandEvent.class)) return false; + + ClientCommandEvent event = new ClientCommandEvent( + ClientCommandChannel.ref(player), + module, command, + LuaTables.toJava(args) + ); + + ForgeInstance.FORGE.post(event); + + return event.isCancelled(); + } + catch (Throwable t) + { + t.printStackTrace(); + return false; + } + } +} diff --git a/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/commands/LuaTablesTest.java b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/commands/LuaTablesTest.java new file mode 100644 index 0000000..1654add --- /dev/null +++ b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/commands/LuaTablesTest.java @@ -0,0 +1,127 @@ +package dev.overlord.zomboidforge.compat.b42.commands; + +import org.junit.jupiter.api.Test; + +import se.krka.kahlua.j2se.KahluaTableImpl; +import se.krka.kahlua.vm.KahluaTable; + +import zombie.iso.IsoDirections; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Runs against the Kahlua classes of the server jar; {@code LuaManager.platform} is not used. */ +class LuaTablesTest +{ + private static final Supplier NEW_TABLE = () -> new KahluaTableImpl(new HashMap<>()); + + @Test + void convertsTablesToUnmodifiableMaps() + { + KahluaTable items = LuaTablesTest.NEW_TABLE.get(); + items.rawset(1.0, "Base.Axe"); + items.rawset(2.0, "Base.Saw"); + + KahluaTable table = LuaTablesTest.NEW_TABLE.get(); + table.rawset("count", 3.0); + table.rawset("gift", true); + table.rawset("facing", IsoDirections.N); + table.rawset("items", items); + + Map args = LuaTables.toJava(table); + + assertEquals(Map.of("count", 3.0, "gift", true, "facing", IsoDirections.N, "items", Map.of(1.0, "Base.Axe", 2.0, "Base.Saw")), args); + assertThrows(UnsupportedOperationException.class, () -> args.put("x", "y")); + assertThrows(UnsupportedOperationException.class, () -> ((Map) args.get("items")).clear()); + } + + @Test + void convertsMissingArgumentsToAnEmptyMap() + { + assertEquals(Map.of(), LuaTables.toJava(null)); + } + + @Test + void copiesJavaValuesInLuaTypes() + { + Map args = new LinkedHashMap<>(); + args.put("count", 3); + args.put("price", 2.5F); + args.put("items", List.of("Base.Axe", "Base.Saw")); + args.put("seller", Map.of("name", "alice", 7, false)); + + assertEquals( + Map.of( + "count", 3.0, + "price", 2.5, + "items", Map.of(1.0, "Base.Axe", 2.0, "Base.Saw"), + "seller", Map.of("name", "alice", 7.0, false) + ), + LuaTables.copy(args) + ); + } + + @Test + void copiesAtOnceSoLaterChangesAreNotSent() + { + Map args = new HashMap<>(Map.of("count", 1)); + Map copy = LuaTables.copy(args); + + args.put("count", 2); + + assertEquals(Map.of("count", 1.0), copy); + } + + @Test + void buildsNestedTablesFromACopy() + { + KahluaTable table = LuaTables.toLua(LuaTables.copy(Map.of("count", 3, "items", List.of("Base.Axe"))), LuaTablesTest.NEW_TABLE); + + assertEquals(3.0, table.rawget("count")); + + KahluaTable items = (KahluaTable) table.rawget("items"); + assertEquals("Base.Axe", items.rawget(1.0)); + assertNull(items.rawget(2.0)); + assertEquals(1, items.len()); + } + + @Test + void namesTheFirstValueThatCannotBeSent() + { + IllegalArgumentException e = assertThrows( + IllegalArgumentException.class, + () -> LuaTables.copy(Map.of("seller", Map.of("since", new Object()))) + ); + + assertTrue(e.getMessage().startsWith("'args[seller][since]' is a 'java.lang.Object'; values are strings, numbers, booleans,"), e.getMessage()); + } + + @Test + void rejectsNullValuesOtherKeysAndCycles() + { + Map withNull = new HashMap<>(); + withNull.put("name", null); + + Map withObjectKey = new HashMap<>(); + withObjectKey.put(true, "yes"); + + List cycle = new ArrayList<>(); + cycle.add(cycle); + + assertEquals("'args[name]' is null.", assertThrows(IllegalArgumentException.class, () -> LuaTables.copy(withNull)).getMessage()); + assertEquals( + "'args' has the key 'true' ('java.lang.Boolean'); keys are strings or numbers.", + assertThrows(IllegalArgumentException.class, () -> LuaTables.copy(withObjectKey)).getMessage() + ); + assertEquals("'args[list][1]' contains itself.", assertThrows(IllegalArgumentException.class, () -> LuaTables.copy(Map.of("list", cycle))).getMessage()); + } +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java index c769065..839065d 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java @@ -2,11 +2,14 @@ package dev.overlord.zomboidforge.core; import dev.overlord.zomboidforge.api.Event; import dev.overlord.zomboidforge.api.GameVersion; +import dev.overlord.zomboidforge.api.MainThread; import dev.overlord.zomboidforge.api.Mod; import dev.overlord.zomboidforge.api.TickEvent; import dev.overlord.zomboidforge.api.ZomboidForge; import dev.overlord.zomboidforge.api.storage.StorageException; +import dev.overlord.zomboidforge.core.commands.ClientCommandSender; import dev.overlord.zomboidforge.core.commands.CommandRegistry; +import dev.overlord.zomboidforge.core.commands.ModClientCommands; import dev.overlord.zomboidforge.core.config.ForgeSettings; import dev.overlord.zomboidforge.core.mods.GameClasses; import dev.overlord.zomboidforge.core.mods.ModDiscovery; @@ -54,6 +57,7 @@ public final class Forge private final Path directory; private final @Nullable ModVersion api; private final CommandRegistry commands; + private final ClientCommandSender clientCommands; private volatile List mods = List.of(); private volatile ForgeSettings settings = ForgeSettings.DEFAULTS; @@ -63,14 +67,16 @@ public final class Forge * @param directory the ZomboidForge directory * @param api the API version mods are checked against, or {@code null} to skip the * check - * @param commands checks the command classes that mods register against the running game - * version + * @param commands checks the command classes that mods register against the running + * game version + * @param clientCommands sends the mods' server commands to clients in the running game version */ - public Forge(Path directory, @Nullable ModVersion api, CommandRegistry.Validator commands) + public Forge(Path directory, @Nullable ModVersion api, CommandRegistry.Validator commands, ClientCommandSender clientCommands) { - this.directory = directory; - this.api = api; - this.commands = new CommandRegistry(commands, this::commandsOpen); + this.directory = directory; + this.api = api; + this.commands = new CommandRegistry(commands, this::commandsOpen); + this.clientCommands = clientCommands; } /** @@ -78,17 +84,18 @@ public final class Forge * version from {@link ZomboidForge#VERSION}. Builds without a release version ({@code dev}, * {@code 0.0.0-...}) skip the API check. * - * @param commands checks the command classes that mods register against the running game - * version + * @param commands checks the command classes that mods register against the running + * game version + * @param clientCommands sends the mods' server commands to clients in the running game version */ - public static Forge fromSystemProperties(CommandRegistry.Validator commands) + public static Forge fromSystemProperties(CommandRegistry.Validator commands, ClientCommandSender clientCommands) { Path directory = Path.of(System.getProperty(Forge.DIRECTORY_PROPERTY, Forge.DEFAULT_DIRECTORY)); ModVersion api = ModVersion.tryParse(ZomboidForge.VERSION) .filter(version -> version.major() != 0 || version.minor() != 0 || version.patch() != 0) .orElse(null); - return new Forge(directory, api, commands); + return new Forge(directory, api, commands, clientCommands); } public Lifecycle.Phase phase() { return this.lifecycle.phase(); } @@ -197,6 +204,9 @@ public final class Forge */ public void post(Event event) { this.events.post(event); } + /** Whether any mod listens for {@code type}, so a hook can skip creating the event. */ + public boolean hasListeners(Class type) { return this.events.hasListeners(type); } + /** * Pauses storage for a backup of the save folder (see {@link StorageDatabase#backupStarted()}). * Called by the patched {@code ZipBackup.makeBackupFile}, on the thread that makes the backup. @@ -268,14 +278,16 @@ public final class Forge ModThreads.ModExecutors executors = this.threads.create(id, logger); StorageDatabase storage = Objects.requireNonNull(this.storage, "storage"); + MainThread main = this.queue.forMod(id, logger); return new ModServices( this.events.forMod(id, executors.modThread(), logger), - this.queue.forMod(id, logger), + main, executors.modThread(), executors.async(), new ModTables(id, storage, logger), - this.commands.forMod(logger) + this.commands.forMod(logger), + new ModClientCommands(this.clientCommands, main) ); } } diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/commands/ClientCommandSender.java b/core/src/main/java/dev/overlord/zomboidforge/core/commands/ClientCommandSender.java new file mode 100644 index 0000000..287ca6d --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/commands/ClientCommandSender.java @@ -0,0 +1,21 @@ +package dev.overlord.zomboidforge.core.commands; + +import dev.overlord.zomboidforge.api.PlayerRef; + +import org.jetbrains.annotations.Nullable; + +import java.util.Map; + +/** Sends server commands to clients; implemented by the compat module of the running game version. */ +@FunctionalInterface +public interface ClientCommandSender +{ + /** + * Checks {@code args} on the calling thread and returns the action that converts and sends + * the command, which runs on the main thread. + * + * @param player the receiving player, or {@code null} for every connected client + * @throws IllegalArgumentException naming a key or value that cannot be sent + */ + Runnable prepare(@Nullable PlayerRef player, String module, String command, Map args); +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/commands/ModClientCommands.java b/core/src/main/java/dev/overlord/zomboidforge/core/commands/ModClientCommands.java new file mode 100644 index 0000000..02a9db9 --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/commands/ModClientCommands.java @@ -0,0 +1,45 @@ +package dev.overlord.zomboidforge.core.commands; + +import dev.overlord.zomboidforge.api.ClientCommands; +import dev.overlord.zomboidforge.api.MainThread; +import dev.overlord.zomboidforge.api.PlayerRef; + +import java.util.Map; +import java.util.Objects; + +/** + * The {@link ClientCommands} of one mod: checks on the calling thread, sends through the mod's + * {@link MainThread}, so a command sent off the main thread is one of the mod's queued tasks. + */ +public final class ModClientCommands implements ClientCommands +{ + private final ClientCommandSender sender; + private final MainThread main; + + public ModClientCommands(ClientCommandSender sender, MainThread main) + { + this.sender = Objects.requireNonNull(sender); + this.main = Objects.requireNonNull(main); + } + + @Override + public void send(PlayerRef player, String module, String command, Map args) + { + Objects.requireNonNull(player, "player"); + + this.main.execute(this.sender.prepare(player, ModClientCommands.require(module, "module"), ModClientCommands.require(command, "command"), Objects.requireNonNull(args, "args"))); + } + + @Override + public void sendToAll(String module, String command, Map args) + { + this.main.execute(this.sender.prepare(null, ModClientCommands.require(module, "module"), ModClientCommands.require(command, "command"), Objects.requireNonNull(args, "args"))); + } + + private static String require(String value, String name) + { + if (Objects.requireNonNull(value, name).isEmpty()) throw new IllegalArgumentException("'" + name + "' is empty."); + + return value; + } +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/commands/package-info.java b/core/src/main/java/dev/overlord/zomboidforge/core/commands/package-info.java index ba64d1f..3224c22 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/commands/package-info.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/commands/package-info.java @@ -1,5 +1,6 @@ /** - * Admin commands of loaded mods: the registry that the compat hooks consult. + * Commands of loaded mods: the registry of admin commands that the compat hooks consult, and + * server commands to clients. * * @noinspection UnstableApiUsage, RedundantSuppression */ diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java index 1811403..d988a9d 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java @@ -1,6 +1,7 @@ package dev.overlord.zomboidforge.core.mods; import dev.overlord.zomboidforge.api.AsyncExecutor; +import dev.overlord.zomboidforge.api.ClientCommands; import dev.overlord.zomboidforge.api.Commands; import dev.overlord.zomboidforge.api.Events; import dev.overlord.zomboidforge.api.GameVersion; @@ -37,18 +38,19 @@ public final class ModLoader public record LoadedMod(ModDescriptor descriptor, Path directory, ClassLoader classLoader, Mod mod) {} private record Context( - String id, - String version, - GameVersion gameVersion, - System.Logger logger, - Path directory, - ModConfig config, - Events events, - MainThread main, - ModThread modThread, - AsyncExecutor async, - ModStorage storage, - Commands commands + String id, + String version, + GameVersion gameVersion, + System.Logger logger, + Path directory, + ModConfig config, + Events events, + MainThread main, + ModThread modThread, + AsyncExecutor async, + ModStorage storage, + Commands commands, + ClientCommands clientCommands ) implements ModContext {} private ModLoader() {} @@ -96,7 +98,8 @@ public final class ModLoader provided.modThread(), provided.async(), provided.storage(), - provided.commands() + provided.commands(), + provided.clientCommands() ); loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context))); diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java index bbd0c36..2bcff11 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java @@ -1,15 +1,23 @@ package dev.overlord.zomboidforge.core.mods; import dev.overlord.zomboidforge.api.AsyncExecutor; +import dev.overlord.zomboidforge.api.ClientCommands; import dev.overlord.zomboidforge.api.Commands; import dev.overlord.zomboidforge.api.Events; import dev.overlord.zomboidforge.api.MainThread; import dev.overlord.zomboidforge.api.ModThread; import dev.overlord.zomboidforge.api.storage.ModStorage; -/** The threads, event and command registration, and storage of one mod, created before its entry point. */ -public record ModServices(Events events, MainThread main, ModThread modThread, AsyncExecutor async, ModStorage storage, Commands commands) -{ +/** The threads, event and command registration, storage, and client commands of one mod, created before its entry point. */ +public record ModServices( + Events events, + MainThread main, + ModThread modThread, + AsyncExecutor async, + ModStorage storage, + Commands commands, + ClientCommands clientCommands +) { /** Creates the services of one mod. */ @FunctionalInterface public interface Factory diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java index 63f282c..6c584f0 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java @@ -51,6 +51,9 @@ class ForgeTest /** Classes that mods registered as commands, as {@code " after "}; every class is accepted. */ private final List checkedCommands = new ArrayList<>(); + /** Client commands that mods sent, as {@code " . "}. */ + private final List sentClientCommands = new ArrayList<>(); + @BeforeEach void setUp() throws IOException { @@ -64,7 +67,12 @@ class ForgeTest private Forge forge() { - return new Forge(this.directory, ModVersion.parse("0.3.0"), (command, registered) -> this.checkedCommands.add(command.getName() + " after " + registered.size())); + return new Forge( + this.directory, + ModVersion.parse("0.3.0"), + (command, registered) -> this.checkedCommands.add(command.getName() + " after " + registered.size()), + (player, module, command, args) -> () -> this.sentClientCommands.add((player == null ? "all" : player.username()) + " " + module + "." + command + " " + args) + ); } private Forge load() throws ModLoadException @@ -133,6 +141,19 @@ class ForgeTest assertEquals(1, forge.commands().size()); } + @Test + void modsSendClientCommandsThroughTheGameSender() throws Exception + { + TestMods.folder(this.mods, "commands", TestMods.toml("commands", CommandMod.class.getName(), ""), Map.of( + "testmods/CommandMod", TestMods.classFile(CommandMod.class), + "testmods/CommandMod$Command", TestMods.classFile(CommandMod.Command.class) + )); + + this.load().started(); + + assertEquals(List.of("all Test.started {count=1}"), this.sentClientCommands); + } + @Test void modsSeeTheirContextAndSettingsInTheConstructor() throws Exception { diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/commands/ModClientCommandsTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/commands/ModClientCommandsTest.java new file mode 100644 index 0000000..2cbcd81 --- /dev/null +++ b/core/src/test/java/dev/overlord/zomboidforge/core/commands/ModClientCommandsTest.java @@ -0,0 +1,107 @@ +package dev.overlord.zomboidforge.core.commands; + +import dev.overlord.zomboidforge.api.ClientCommands; +import dev.overlord.zomboidforge.api.PlayerRef; +import dev.overlord.zomboidforge.core.RecordingLogger; +import dev.overlord.zomboidforge.core.runtime.MainThreadQueue; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** The test thread is the main thread. */ +class ModClientCommandsTest +{ + private static final PlayerRef PLAYER = new PlayerRef(3, "alice"); + + /** What the sender prepared ({@code "prepare ..."}) and sent ({@code "send ... on "}). */ + private final List log = new CopyOnWriteArrayList<>(); + + /** Records both steps; rejects arguments that contain the key {@code "bad"}. */ + private final ClientCommandSender sender = (player, module, command, args) -> + { + if (args.containsKey("bad")) throw new IllegalArgumentException("'args[bad]' cannot be sent."); + + String target = player == null ? "all" : player.username(); + this.log.add("prepare " + target + " " + module + "." + command + " " + args); + + return () -> this.log.add("send " + target + " " + module + "." + command + " on " + Thread.currentThread().getName()); + }; + + private MainThreadQueue queue; + private ClientCommands commands; + + @BeforeEach + void setUp() + { + this.queue = new MainThreadQueue(Duration.ofSeconds(10)); + this.queue.bindToCurrentThread(); + + this.commands = new ModClientCommands(this.sender, this.queue.forMod("shop", new RecordingLogger())); + } + + @Test + void sendsAtOnceOnTheMainThread() + { + this.commands.send(ModClientCommandsTest.PLAYER, "Shop", "bought", Map.of("item", "Base.Axe")); + this.commands.sendToAll("Shop", "opened", Map.of()); + + String main = Thread.currentThread().getName(); + + assertEquals( + List.of( + "prepare alice Shop.bought {item=Base.Axe}", "send alice Shop.bought on " + main, + "prepare all Shop.opened {}", "send all Shop.opened on " + main + ), + this.log + ); + } + + @Test + void checksOnTheCallingThreadAndSendsOnTheMainThreadLater() throws InterruptedException + { + Thread other = Thread.ofPlatform().name("worker").start(() -> this.commands.sendToAll("Shop", "opened", Map.of())); + other.join(); + + assertEquals(List.of("prepare all Shop.opened {}"), this.log); + + this.queue.drain(); + + assertEquals(List.of("prepare all Shop.opened {}", "send all Shop.opened on " + Thread.currentThread().getName()), this.log); + } + + @Test + void rejectedArgumentsThrowToTheCallerOnAnyThread() throws InterruptedException + { + AtomicReference thrown = new AtomicReference<>(); + + Thread other = Thread.ofPlatform().start(() -> + { + try { this.commands.sendToAll("Shop", "opened", Map.of("bad", 1)); } + catch (Throwable t) { thrown.set(t); } + }); + other.join(); + + assertInstanceOf(IllegalArgumentException.class, thrown.get()); + + this.queue.drain(); + assertEquals(List.of(), this.log); + } + + @Test + void rejectsEmptyModuleAndCommand() + { + assertThrows(IllegalArgumentException.class, () -> this.commands.sendToAll("", "opened", Map.of())); + assertThrows(IllegalArgumentException.class, () -> this.commands.send(ModClientCommandsTest.PLAYER, "Shop", "", Map.of())); + assertEquals(List.of(), this.log); + } +} diff --git a/core/src/test/java/testmods/CommandMod.java b/core/src/test/java/testmods/CommandMod.java index 7e38208..d26f480 100644 --- a/core/src/test/java/testmods/CommandMod.java +++ b/core/src/test/java/testmods/CommandMod.java @@ -4,9 +4,12 @@ import dev.overlord.zomboidforge.api.Mod; import org.jetbrains.annotations.Nullable; +import java.util.Map; + /** * Entry point that tests package into a mod jar. Registers {@link Command} in {@code onLoad()} - * and tries again in {@code onServerStarted()}, which is too late. + * and tries again in {@code onServerStarted()}, which is too late; sends a client command to + * every client there. */ public final class CommandMod extends Mod { @@ -23,5 +26,7 @@ public final class CommandMod extends Mod { try { this.commands().register(CommandMod.Command.class); } catch (RuntimeException e) { this.lateRegistration = e; } + + this.clientCommands().sendToAll("Test", "started", Map.of("count", 1)); } }