diff --git a/src/main/java/world/bentobox/border/Border.java b/src/main/java/world/bentobox/border/Border.java index 0cc2b61..5748776 100644 --- a/src/main/java/world/bentobox/border/Border.java +++ b/src/main/java/world/bentobox/border/Border.java @@ -37,6 +37,14 @@ public class Border extends Addon { private final Config config = new Config<>(this, Settings.class); private final @NonNull List gameModes = new ArrayList<>(); + private final Map gameModeSettings = new HashMap<>(); + /** + * How game modes are asked for the settings they want + */ + java.util.function.BiFunction> requester = GameModeRequests::ask; + private static final Set REQUESTABLE = Set.of("bounce-back", "return-teleport", + "return-teleport-safety-block", "use-barrier-blocks", "show-max-border", "show-particles", + "barrier-offset"); private final Set availableBorderTypes = EnumSet.of(BorderType.VANILLA, BorderType.BARRIER); @@ -51,12 +59,14 @@ public void onLoad() { @Override public void onEnable() { gameModes.clear(); + gameModeSettings.clear(); // Register commands getPlugin().getAddonsManager().getGameModeAddons().forEach(gameModeAddon -> { if (!this.settings.getDisabledGameModes().contains(gameModeAddon.getDescription().getName())) { gameModes.add(gameModeAddon); + loadRequests(gameModeAddon); log("Border hooking into " + gameModeAddon.getDescription().getName()); gameModeAddon.getPlayerCommand().ifPresent(c -> new IslandBorderCommand(this, c, "border")); @@ -116,6 +126,51 @@ public Settings getSettings() { return this.settings; } + /** + * Gets the settings that apply in a world. These are the settings from the config unless + * the world's game mode asked for different ones and the admin allows that. The border + * type, color and whether it is shown are each player's choice and are not affected. + * @param world a world, may be null + * @return settings for the world + */ + public Settings getSettings(World world) { + if (world != null && !gameModeSettings.isEmpty()) { + for (Map.Entry en : gameModeSettings.entrySet()) { + if (en.getKey().inWorld(world)) { + return en.getValue(); + } + } + } + return settings; + } + + /** + * Settings a game mode may ask for: how the border behaves, not how it looks to a player + * or which game modes it is used in. + */ + static boolean isRequestable(String path) { + return REQUESTABLE.contains(path); + } + + /** + * Asks a game mode which settings it needs and works out the settings for its worlds. + */ + void loadRequests(GameModeAddon gm) { + String name = gm.getDescription().getName(); + if (!settings.isAllowRequests() || settings.getIgnoreRequests().stream().anyMatch(name::equalsIgnoreCase)) { + return; + } + Map requests = requester.apply(gm, getDescription().getName()); + if (requests.isEmpty()) { + return; + } + GameModeRequests.Result result = GameModeRequests.apply(settings, requests, Border::isRequestable); + result.refused().forEach(r -> logWarning(name + " asked for something that cannot be done: " + r)); + log(name + " asked for these settings in its worlds: " + + (result.applied().isEmpty() ? "none that differ from the config" : String.join(", ", result.applied()))); + gameModeSettings.put(gm, result.settings()); + } + /** * @param world to check * @return true if world is being handled by Border diff --git a/src/main/java/world/bentobox/border/GameModeRequests.java b/src/main/java/world/bentobox/border/GameModeRequests.java new file mode 100644 index 0000000..2d1f075 --- /dev/null +++ b/src/main/java/world/bentobox/border/GameModeRequests.java @@ -0,0 +1,186 @@ +package world.bentobox.border; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.function.Predicate; + +import org.eclipse.jdt.annotation.NonNull; + +import world.bentobox.bentobox.api.addons.GameModeAddon; +import world.bentobox.bentobox.api.configuration.ConfigEntry; + +/** + * Lets game modes ask for the settings they need in their own worlds. A game mode asks by + * having a {@code getGameModeRequests(String addonName)} method, which BentoBox 3.25.0 adds + * to GameModeAddon. It returns config paths of this addon and the values wanted. The method is + * looked up by name so that this addon still builds and runs with older BentoBox versions, + * where no game mode can ask for anything. + *

+ * Requests are applied to a copy of the settings, so the admin's config is never changed. + * + * @author tastybento + */ +public final class GameModeRequests { + + private GameModeRequests() { + } + + /** + * Asks a game mode which settings it wants. + * @param gm the game mode + * @param addonName name of the addon whose settings are being asked about + * @return config path to requested value, empty if the game mode asks for nothing + */ + @NonNull + public static Map ask(@NonNull GameModeAddon gm, @NonNull String addonName) { + try { + Method method = gm.getClass().getMethod("getRequestedSettings", String.class); + if (method.invoke(gm, addonName) instanceof Map map) { + Map requests = new java.util.LinkedHashMap<>(); + map.forEach((k, v) -> requests.put(String.valueOf(k), v)); + return requests; + } + } catch (ReflectiveOperationException | RuntimeException e) { + // This game mode, or this BentoBox, does not have requests + } + return Map.of(); + } + + /** + * What came of a set of requests. + * @param the settings class + * @param settings a copy of the settings with the accepted requests applied + * @param applied the accepted requests, as "path: value", for telling the admin + * @param refused the requests that could not be applied, with the reason + */ + public record Result(@NonNull T settings, @NonNull List applied, @NonNull List refused) { + } + + /** + * Copies settings and applies requests to the copy. A request is refused if no setting has + * that path, the path is not one that may be requested, or the value is of the wrong type. + * A request that matches the current value is accepted but not listed as applied. + * + * @param the settings class, which must have a constructor with no arguments + * @param settings the settings as the admin configured them. They are not changed. + * @param requests config path to requested value + * @param requestable says which config paths may be requested + * @return the copy and what was applied and refused + */ + @NonNull + public static Result apply(@NonNull T settings, @NonNull Map requests, + @NonNull Predicate requestable) { + List applied = new ArrayList<>(); + List refused = new ArrayList<>(); + T copy; + try { + copy = copy(settings); + } catch (ReflectiveOperationException | RuntimeException e) { + requests.keySet().forEach(k -> refused.add(k + " (settings cannot be copied: " + e + ")")); + return new Result<>(settings, applied, refused); + } + requests.forEach((path, value) -> { + Field field = requestable.test(path) ? find(copy.getClass(), path) : null; + if (field == null) { + refused.add(path + " (not a setting that can be requested)"); + return; + } + try { + Object converted = convert(field.getType(), value); + if (converted == null) { + refused.add(path + " (" + value + " is not a valid value)"); + } else if (!converted.equals(field.get(copy))) { + field.set(copy, converted); // NOSONAR the field is made accessible on purpose + applied.add(path + ": " + value); + } + } catch (ReflectiveOperationException | RuntimeException e) { + refused.add(path + " (" + e + ")"); + } + }); + return new Result<>(copy, applied, refused); + } + + @SuppressWarnings("unchecked") + private static T copy(T settings) throws ReflectiveOperationException { + var constructor = settings.getClass().getDeclaredConstructor(); + constructor.setAccessible(true); // NOSONAR + T copy = (T) constructor.newInstance(); + for (Class c = settings.getClass(); c != null && c != Object.class; c = c.getSuperclass()) { + for (Field f : c.getDeclaredFields()) { + if (!Modifier.isStatic(f.getModifiers()) && !Modifier.isFinal(f.getModifiers())) { + f.setAccessible(true); // NOSONAR + f.set(copy, f.get(settings)); // NOSONAR + } + } + } + return copy; + } + + private static Field find(Class clazz, String path) { + for (Class c = clazz; c != null && c != Object.class; c = c.getSuperclass()) { + for (Field f : c.getDeclaredFields()) { + ConfigEntry entry = f.getAnnotation(ConfigEntry.class); + if (entry != null && entry.path().equals(path) && !Modifier.isStatic(f.getModifiers()) + && !Modifier.isFinal(f.getModifiers())) { + f.setAccessible(true); // NOSONAR + return f; + } + } + } + return null; + } + + /** + * Turns a requested value into the type of the setting. Only simple settings can be + * requested: booleans, numbers, strings and enums. + * @return the value, or null if it does not fit + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static Object convert(Class type, Object value) { + if (value == null) { + return null; + } + if (type == boolean.class || type == Boolean.class) { + return value instanceof Boolean ? value : null; + } + if (value instanceof Number n) { + return convertNumber(type, n); + } + if (type == String.class) { + return value.toString(); + } + if (type.isEnum()) { + return type.isInstance(value) ? value : convertEnum((Class) type, value.toString()); + } + return null; + } + + private static Object convertNumber(Class type, Number n) { + if (type == int.class || type == Integer.class) { + return n.intValue(); + } else if (type == long.class || type == Long.class) { + return n.longValue(); + } else if (type == double.class || type == Double.class) { + return n.doubleValue(); + } else if (type == float.class || type == Float.class) { + return n.floatValue(); + } else if (type == String.class) { + return n.toString(); + } + return null; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static Object convertEnum(Class type, String name) { + try { + return Enum.valueOf(type, name.toUpperCase(Locale.ENGLISH)); + } catch (IllegalArgumentException e) { + return null; + } + } +} diff --git a/src/main/java/world/bentobox/border/Settings.java b/src/main/java/world/bentobox/border/Settings.java index c53a802..72859f0 100644 --- a/src/main/java/world/bentobox/border/Settings.java +++ b/src/main/java/world/bentobox/border/Settings.java @@ -87,6 +87,47 @@ public enum BorderColor { @ConfigEntry(path = "barrier-offset") private int barrierOffset = 0; + @ConfigComment("") + @ConfigComment("Game modes can ask for the settings they need in their own worlds, so that you do not") + @ConfigComment("have to set them up by hand. Only how the border behaves can be asked for: bounce-back,") + @ConfigComment("return-teleport, return-teleport-safety-block, use-barrier-blocks, show-max-border,") + @ConfigComment("show-particles and barrier-offset. Nothing in this file is changed and other game modes") + @ConfigComment("keep the settings above. What was asked for is listed in the console at startup.") + @ConfigComment("Set to false to ignore all requests.") + @ConfigEntry(path = "game-mode-requests.allow") + private boolean allowRequests = true; + @ConfigComment("Game modes whose requests are ignored, e.g. Boxed. They use the settings above.") + @ConfigEntry(path = "game-mode-requests.ignore") + private Set ignoreRequests = new HashSet<>(); + + /** + * @return true if game modes may ask for settings in their own worlds + */ + public boolean isAllowRequests() { + return allowRequests; + } + + /** + * @param allowRequests true if game modes may ask for settings in their own worlds + */ + public void setAllowRequests(boolean allowRequests) { + this.allowRequests = allowRequests; + } + + /** + * @return names of the game modes whose requests are ignored + */ + public Set getIgnoreRequests() { + return ignoreRequests; + } + + /** + * @param ignoreRequests names of the game modes whose requests are ignored + */ + public void setIgnoreRequests(Set ignoreRequests) { + this.ignoreRequests = ignoreRequests; + } + /** * @param disabledGameModes new disabledGameModes value. */ diff --git a/src/main/java/world/bentobox/border/listeners/PlayerListener.java b/src/main/java/world/bentobox/border/listeners/PlayerListener.java index 61ef3af..79e1524 100644 --- a/src/main/java/world/bentobox/border/listeners/PlayerListener.java +++ b/src/main/java/world/bentobox/border/listeners/PlayerListener.java @@ -73,6 +73,12 @@ */ public class PlayerListener implements Listener { + /** + * Permission, after the game mode's prefix, that lets a player walk outside the border + */ + public static final String BYPASS_PERM = "border.bypass"; + + private static final Vector XZ = new Vector(1, 0, 1); /** How close to a death spot, in blocks, an item must spawn to count as a death drop. */ private static final double DEATH_DROP_RADIUS_SQUARED = 5 * 5D; @@ -214,6 +220,17 @@ public void onPlayerRespawn(PlayerRespawnEvent e) { } } + /** + * Checks if a player is free to walk outside the border. Operators always are, so that + * admins can go anywhere, and so is anyone with the game mode's border bypass permission. + * @param player player + * @return true if the player must not be moved back inside the border + */ + boolean canBypass(Player player) { + return player.isOp() || addon.getPlugin().getIWM().getAddon(player.getWorld()) + .map(gm -> player.hasPermission(gm.getPermissionPrefix() + BYPASS_PERM)).orElse(false); + } + /** * Check if the border is on or off for a player. * @@ -303,11 +320,11 @@ public void onPlayerLeaveIsland(PlayerMoveEvent e) { return; } Player p = e.getPlayer(); - if (!isOn(p)) { + if (!isOn(p) || canBypass(p)) { return; } Location from = e.getFrom(); - if (!addon.getSettings().isReturnTeleport() || !outsideCheck(e.getPlayer(), from, e.getTo())) { + if (!addon.getSettings(e.getPlayer().getWorld()).isReturnTeleport() || !outsideCheck(e.getPlayer(), from, e.getTo())) { return; } // Move the player back inside the border @@ -405,7 +422,8 @@ private boolean outsideCheck(Player player, Location from, Location to) { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onEntityMount(EntityMountEvent event) { Entity entity = event.getEntity(); - if (!(entity instanceof Player player) || !isOn(player) || !addon.getSettings().isReturnTeleport()) { + if (!(entity instanceof Player player) || !isOn(player) || canBypass(player) + || !addon.getSettings(player.getWorld()).isReturnTeleport()) { return; } @@ -501,7 +519,7 @@ public void onProtectionRangeChange(IslandProtectionRangeChangeEvent e) { */ @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onItemDrop(PlayerDropItemEvent event) { - if (addon.getSettings().isBounceBack() + if (addon.getSettings(event.getPlayer().getWorld()).isBounceBack() && addon.inGameWorld(event.getPlayer().getWorld()) && isOn(event.getPlayer()) ) { @@ -524,7 +542,7 @@ && isOn(event.getPlayer()) */ @EventHandler(priority = EventPriority.MONITOR) public void onPlayerDeath(PlayerDeathEvent event) { - if (!addon.getSettings().isBounceBack() + if (!addon.getSettings(event.getPlayer().getWorld()).isBounceBack() || event.getDrops().isEmpty() || !addon.inGameWorld(event.getPlayer().getWorld()) || !isOn(event.getPlayer())) { diff --git a/src/main/java/world/bentobox/border/listeners/ShowBarrier.java b/src/main/java/world/bentobox/border/listeners/ShowBarrier.java index ccb6629..e07322d 100644 --- a/src/main/java/world/bentobox/border/listeners/ShowBarrier.java +++ b/src/main/java/world/bentobox/border/listeners/ShowBarrier.java @@ -64,7 +64,7 @@ public void showBorder(Player player, Island island) { || !Objects.requireNonNull(User.getInstance(player)).getMetaData(BORDER_STATE_META_DATA).map(MetaDataValue::asBoolean).orElse(addon.getSettings().isShowByDefault())) { return; } - int offset = addon.getSettings().getBarrierOffset(); + int offset = addon.getSettings(player.getWorld()).getBarrierOffset(); // Get the locations to show Location loc = player.getLocation(); showWalls(player, loc, @@ -73,7 +73,7 @@ public void showBorder(Player player, Island island) { Math.max(island.getMinZ(),island.getMinProtectedZ() - offset), Math.min(island.getMaxZ(), island.getMaxProtectedZ() + offset), false); // If the max border needs to be shown, show it as well - if (addon.getSettings().isShowMaxBorder()) { + if (addon.getSettings(player.getWorld()).isShowMaxBorder()) { showWalls(player, loc, island.getMinX(), @@ -124,7 +124,7 @@ private void showWallAlongX(Player player, Location loc, int xMin, int xMax, int */ private void showPlayer(Player player, int i, int j, int k, boolean max) { // Get if on or in border - if (addon.getSettings().isUseBarrierBlocks() + if (addon.getSettings(player.getWorld()).isUseBarrierBlocks() && player.getLocation().getBlockX() == i && player.getLocation().getBlockZ() == k) { teleportEntity(player); @@ -135,10 +135,10 @@ private void showPlayer(Player player, int i, int j, int k, boolean max) { } private void renderBorderBlock(Player player, Location l, int i, int j, int k, boolean max) { - if (addon.getSettings().isShowParticles()) { + if (addon.getSettings(player.getWorld()).isShowParticles()) { spawnBorderParticle(player, i, j, k, max); } - if (addon.getSettings().isUseBarrierBlocks() && (l.getBlock().isEmpty() || l.getBlock().isLiquid())) { + if (addon.getSettings(player.getWorld()).isUseBarrierBlocks() && (l.getBlock().isEmpty() || l.getBlock().isLiquid())) { player.sendBlockChange(l, Material.BARRIER.createBlockData()); barrierBlocks.computeIfAbsent(player.getUniqueId(), u -> new HashSet<>()).add(new BarrierBlock(l, l.getBlock().getBlockData())); } diff --git a/src/main/java/world/bentobox/border/listeners/ShowWorldBorder.java b/src/main/java/world/bentobox/border/listeners/ShowWorldBorder.java index 9ebe3e7..d281e40 100644 --- a/src/main/java/world/bentobox/border/listeners/ShowWorldBorder.java +++ b/src/main/java/world/bentobox/border/listeners/ShowWorldBorder.java @@ -47,7 +47,7 @@ public void showBorder(Player player, Island island) { Location l = island.getProtectionCenter().toVector().toLocation(player.getWorld()); WorldBorder wb = Bukkit.createWorldBorder(); wb.setCenter(l); - double size = Math.min(island.getRange() * 2D, (island.getProtectionRange() + addon.getSettings().getBarrierOffset()) * 2D); + double size = Math.min(island.getRange() * 2D, (island.getProtectionRange() + addon.getSettings(island.getWorld()).getBarrierOffset()) * 2D); wb.setSize(size); wb.setWarningDistance(0); BorderColor borderColor = user.getMetaData(PerPlayerBorderProxy.BORDER_COLOR_META_DATA) diff --git a/src/main/resources/addon.yml b/src/main/resources/addon.yml index a0d2570..29694ac 100644 --- a/src/main/resources/addon.yml +++ b/src/main/resources/addon.yml @@ -12,6 +12,9 @@ permissions: '[gamemode].border.toggle': description: Player can use border command default: op + '[gamemode].border.bypass': + description: Player is not moved back when they walk outside the border. Operators always have this. + default: op '[gamemode].border.type': description: Player can use border type setting command default: true diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 7e4a657..56bf64a 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -45,3 +45,14 @@ show-particles: true # This does not extend the protection range, but will enable players to go outside their protected area. # The barrier will not go further than the island distance. Minimum and default value is 0. barrier-offset: 0 +# +# Game modes can ask for the settings they need in their own worlds, so that you do not +# have to set them up by hand. Only how the border behaves can be asked for: bounce-back, +# return-teleport, return-teleport-safety-block, use-barrier-blocks, show-max-border, +# show-particles and barrier-offset. Nothing in this file is changed and other game modes +# keep the settings above. What was asked for is listed in the console at startup. +# Set to false to ignore all requests. +game-mode-requests: + allow: true + # Game modes whose requests are ignored, e.g. Boxed. They use the settings above. + ignore: [] diff --git a/src/test/java/world/bentobox/border/BorderTest.java b/src/test/java/world/bentobox/border/BorderTest.java index 262cc16..e90736c 100644 --- a/src/test/java/world/bentobox/border/BorderTest.java +++ b/src/test/java/world/bentobox/border/BorderTest.java @@ -99,6 +99,50 @@ void testGetAvailableBorderTypesViewIsUnmodifiable() { assertThrows(UnsupportedOperationException.class, () -> view.add(BorderType.VANILLA)); } + /** + * A game mode's request applies in its own worlds only and leaves the config alone. + */ + @Test + void testGameModeRequest() { + Settings settings = new Settings(); + settings.setReturnTeleport(false); + setField(border, "settings", settings); + border.setDescription(new world.bentobox.bentobox.api.addons.AddonDescription.Builder("main", "Border", "1").build()); + GameModeAddon gm = mock(GameModeAddon.class); + when(gm.getDescription()) + .thenReturn(new world.bentobox.bentobox.api.addons.AddonDescription.Builder("main", "Boxed", "1").build()); + when(gm.inWorld(world)).thenReturn(true); + // The border type is each player's choice and cannot be asked for + border.requester = (g, n) -> java.util.Map.of("return-teleport", true, "type", "BARRIER"); + + border.loadRequests(gm); + + assertTrue(border.getSettings(world).isReturnTeleport()); + assertSame(BorderType.VANILLA, border.getSettings(world).getType()); + assertFalse(border.getSettings().isReturnTeleport()); + assertFalse(border.getSettings(mock(org.bukkit.World.class)).isReturnTeleport()); + } + + /** + * The admin can ignore requests. + */ + @Test + void testGameModeRequestIgnored() { + Settings settings = new Settings(); + settings.setReturnTeleport(false); + settings.setIgnoreRequests(Set.of("boxed")); + setField(border, "settings", settings); + GameModeAddon gm = mock(GameModeAddon.class); + when(gm.getDescription()) + .thenReturn(new world.bentobox.bentobox.api.addons.AddonDescription.Builder("main", "Boxed", "1").build()); + when(gm.inWorld(world)).thenReturn(true); + border.requester = (g, n) -> java.util.Map.of("return-teleport", true); + + border.loadRequests(gm); + + assertFalse(border.getSettings(world).isReturnTeleport()); + } + @Test void testGetSettingsReturnsConfiguredInstance() { Settings settings = new Settings(); diff --git a/src/test/java/world/bentobox/border/PerPlayerBorderProxyTest.java b/src/test/java/world/bentobox/border/PerPlayerBorderProxyTest.java index 92b3264..ce58430 100644 --- a/src/test/java/world/bentobox/border/PerPlayerBorderProxyTest.java +++ b/src/test/java/world/bentobox/border/PerPlayerBorderProxyTest.java @@ -53,6 +53,7 @@ void setUp() { closeable = MockitoAnnotations.openMocks(this); settings = new Settings(); when(addon.getSettings()).thenReturn(settings); + when(addon.getSettings(org.mockito.ArgumentMatchers.nullable(org.bukkit.World.class))).thenReturn(settings); when(addon.getAvailableBorderTypesView()).thenReturn(EnumSet.of(BorderType.VANILLA, BorderType.BARRIER)); mockedUser = Mockito.mockStatic(User.class, Mockito.RETURNS_MOCKS); diff --git a/src/test/java/world/bentobox/border/commands/BorderColorCommandTest.java b/src/test/java/world/bentobox/border/commands/BorderColorCommandTest.java index 6d9e33f..dd5ea4a 100644 --- a/src/test/java/world/bentobox/border/commands/BorderColorCommandTest.java +++ b/src/test/java/world/bentobox/border/commands/BorderColorCommandTest.java @@ -91,6 +91,7 @@ protected void setUp() { // Settings Settings settings = new Settings(); when(addon.getSettings()).thenReturn(settings); + when(addon.getSettings(org.mockito.ArgumentMatchers.nullable(org.bukkit.World.class))).thenReturn(settings); ic = new BorderColorCommand(addon, ac, "color"); // Pre-populate the island field (canExecute sets it; execute depends on it) diff --git a/src/test/java/world/bentobox/border/commands/BorderTypeCommandTest.java b/src/test/java/world/bentobox/border/commands/BorderTypeCommandTest.java index 6258140..5f8d86f 100644 --- a/src/test/java/world/bentobox/border/commands/BorderTypeCommandTest.java +++ b/src/test/java/world/bentobox/border/commands/BorderTypeCommandTest.java @@ -106,6 +106,7 @@ protected void setUp() { // Settings Settings settings = new Settings(); when(addon.getSettings()).thenReturn(settings); + when(addon.getSettings(org.mockito.ArgumentMatchers.nullable(org.bukkit.World.class))).thenReturn(settings); ic = new BorderTypeCommand(addon, ac, "type"); diff --git a/src/test/java/world/bentobox/border/commands/IslandBorderCommandTest.java b/src/test/java/world/bentobox/border/commands/IslandBorderCommandTest.java index 0b97b43..e285a28 100644 --- a/src/test/java/world/bentobox/border/commands/IslandBorderCommandTest.java +++ b/src/test/java/world/bentobox/border/commands/IslandBorderCommandTest.java @@ -108,6 +108,7 @@ protected void setUp() { // Settings Settings settings = new Settings(); when(addon.getSettings()).thenReturn(settings); + when(addon.getSettings(org.mockito.ArgumentMatchers.nullable(org.bukkit.World.class))).thenReturn(settings); // Players Manager when(addon.getPlayers()).thenReturn(pm); diff --git a/src/test/java/world/bentobox/border/listeners/PlayerListenerTest.java b/src/test/java/world/bentobox/border/listeners/PlayerListenerTest.java index 5ee7391..ec4266f 100644 --- a/src/test/java/world/bentobox/border/listeners/PlayerListenerTest.java +++ b/src/test/java/world/bentobox/border/listeners/PlayerListenerTest.java @@ -1,5 +1,6 @@ package world.bentobox.border.listeners; +import static org.mockito.Mockito.mock; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -110,6 +111,7 @@ protected void setUp() { // Settings settings = new Settings(); when(addon.getSettings()).thenReturn(settings); + when(addon.getSettings(org.mockito.ArgumentMatchers.nullable(org.bukkit.World.class))).thenReturn(settings); // Locations when(to.getWorld()).thenReturn(world); @@ -340,6 +342,37 @@ void testOnPlayerLeaveIslandIslandEndReturnsTeleport() { } + /** + * Operators are free to walk outside the border. + */ + @Test + void testOnPlayerLeaveIslandOpIsNotMovedBack() { + when(iwm.isIslandNether(any())).thenReturn(true); + when(island.onIsland(any())).thenReturn(false); + when(player.isOp()).thenReturn(true); + settings.setReturnTeleport(true); + PlayerMoveEvent event = new PlayerMoveEvent(player, from, to); + pl.onPlayerLeaveIsland(event); + assertFalse(event.isCancelled()); + } + + /** + * Players with the bypass permission of the game mode are free to walk outside the border. + */ + @Test + void testOnPlayerLeaveIslandBypassPermission() { + GameModeAddon gm = mock(GameModeAddon.class); + when(gm.getPermissionPrefix()).thenReturn("boxed."); + when(iwm.getAddon(any())).thenReturn(Optional.of(gm)); + when(player.hasPermission("boxed.border.bypass")).thenReturn(true); + when(iwm.isIslandNether(any())).thenReturn(true); + when(island.onIsland(any())).thenReturn(false); + settings.setReturnTeleport(true); + PlayerMoveEvent event = new PlayerMoveEvent(player, from, to); + pl.onPlayerLeaveIsland(event); + assertFalse(event.isCancelled()); + } + /** * Test method for {@link world.bentobox.border.listeners.PlayerListener#onPlayerLeaveIsland(org.bukkit.event.player.PlayerMoveEvent)}. */ @@ -546,6 +579,7 @@ void testItemSpawnFarFromDeathIsNotTracked() { @Test void testOnPlayerDeathBounceBackDisabled() { settings.setBounceBack(false); + when(deathEvent.getPlayer()).thenReturn(player); pl.onPlayerDeath(deathEvent); verify(sch, never()).runTask(any(), any(Runnable.class)); } @@ -556,6 +590,7 @@ void testOnPlayerDeathBounceBackDisabled() { @Test void testOnPlayerDeathNoDrops() { when(deathEvent.getDrops()).thenReturn(new ArrayList<>()); + when(deathEvent.getPlayer()).thenReturn(player); pl.onPlayerDeath(deathEvent); verify(sch, never()).runTask(any(), any(Runnable.class)); } diff --git a/src/test/java/world/bentobox/border/listeners/ShowBarrierTest.java b/src/test/java/world/bentobox/border/listeners/ShowBarrierTest.java index 09c6e44..9016b24 100644 --- a/src/test/java/world/bentobox/border/listeners/ShowBarrierTest.java +++ b/src/test/java/world/bentobox/border/listeners/ShowBarrierTest.java @@ -59,6 +59,7 @@ protected void setUp() { settings = new Settings(); settings.setShowMaxBorder(false); when(addon.getSettings()).thenReturn(settings); + when(addon.getSettings(org.mockito.ArgumentMatchers.nullable(org.bukkit.World.class))).thenReturn(settings); // Island when(island.getGameMode()).thenReturn("bskyblock"); diff --git a/src/test/java/world/bentobox/border/listeners/ShowWorldBorderTest.java b/src/test/java/world/bentobox/border/listeners/ShowWorldBorderTest.java index 4455435..bb5f658 100644 --- a/src/test/java/world/bentobox/border/listeners/ShowWorldBorderTest.java +++ b/src/test/java/world/bentobox/border/listeners/ShowWorldBorderTest.java @@ -49,6 +49,7 @@ protected void setUp() { super.setUp(); settings = new Settings(); when(addon.getSettings()).thenReturn(settings); + when(addon.getSettings(org.mockito.ArgumentMatchers.nullable(org.bukkit.World.class))).thenReturn(settings); // Island when(island.getRange()).thenReturn(400);