diff --git a/src/main/java/com/wasteofplastic/invswitcher/GameModeRequests.java b/src/main/java/com/wasteofplastic/invswitcher/GameModeRequests.java
new file mode 100644
index 0000000..7dadace
--- /dev/null
+++ b/src/main/java/com/wasteofplastic/invswitcher/GameModeRequests.java
@@ -0,0 +1,186 @@
+package com.wasteofplastic.invswitcher;
+
+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/com/wasteofplastic/invswitcher/InvSwitcher.java b/src/main/java/com/wasteofplastic/invswitcher/InvSwitcher.java
index 894cb33..63c93c1 100644
--- a/src/main/java/com/wasteofplastic/invswitcher/InvSwitcher.java
+++ b/src/main/java/com/wasteofplastic/invswitcher/InvSwitcher.java
@@ -3,6 +3,11 @@
import java.util.HashSet;
import java.util.Objects;
+import java.util.function.BiFunction;
+import world.bentobox.bentobox.api.addons.GameModeAddon;
+import java.util.stream.Stream;
+import java.util.Map;
+import java.util.HashMap;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@@ -35,6 +40,11 @@ public class InvSwitcher extends Addon {
private Store store;
private Settings settings;
+ private final Map worldSettings = new HashMap<>();
+ /**
+ * How game modes are asked for the options they want
+ */
+ BiFunction> requester = GameModeRequests::ask;
private final Config config = new Config<>(this, Settings.class);
@@ -59,6 +69,8 @@ public void allLoaded() {
.map(Bukkit::getWorld)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
+ // Game modes may ask for options in their own worlds
+ loadRequests();
if (worlds.isEmpty()) {
logWarning("Did not hook into any worlds - disabling addon!");
this.setState(State.DISABLED);
@@ -251,6 +263,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 options and the admin allows that.
+ * @param world a world, may be null
+ * @return settings for the world
+ */
+ public Settings getSettings(World world) {
+ return world == null ? settings : worldSettings.getOrDefault(world, settings);
+ }
+
+ /**
+ * Options a game mode may ask for. Money and the economy are server-wide, and the worlds
+ * and request settings are the admin's alone.
+ */
+ static boolean isRequestable(String path) {
+ return path.startsWith("options.") && !path.endsWith(".money");
+ }
+
+ /**
+ * Asks every game mode which options it needs and works out the settings for its worlds.
+ */
+ void loadRequests() {
+ worldSettings.clear();
+ if (!settings.isAllowRequests()) {
+ return;
+ }
+ for (GameModeAddon gm : getPlugin().getAddonsManager().getGameModeAddons()) {
+ String name = gm.getDescription().getName();
+ Map requests = requester.apply(gm, getDescription().getName());
+ if (requests.isEmpty() || gm.getOverWorld() == null
+ || settings.getIgnoreRequests().stream().anyMatch(name::equalsIgnoreCase)) {
+ continue;
+ }
+ GameModeRequests.Result result = GameModeRequests.apply(settings, requests,
+ InvSwitcher::isRequestable);
+ result.refused().forEach(r -> logWarning(name + " asked for something that cannot be done: " + r));
+ log(name + " asked for these options in its worlds: "
+ + (result.applied().isEmpty() ? "none that differ from the config" : String.join(", ", result.applied())));
+ // The nether and end are picked up by name with the other worlds
+ worlds.add(gm.getOverWorld());
+ Stream.of(gm.getOverWorld(), gm.getNetherWorld(), gm.getEndWorld()).filter(Objects::nonNull)
+ .forEach(w -> worldSettings.put(w, result.settings()));
+ }
+ }
+
/**
* Get the hooked worlds
* @return the worlds
diff --git a/src/main/java/com/wasteofplastic/invswitcher/Settings.java b/src/main/java/com/wasteofplastic/invswitcher/Settings.java
index e2da52c..2274eba 100644
--- a/src/main/java/com/wasteofplastic/invswitcher/Settings.java
+++ b/src/main/java/com/wasteofplastic/invswitcher/Settings.java
@@ -46,7 +46,7 @@ public class Settings implements ConfigObject {
@ConfigEntry(path = "options.money")
private boolean money = false;
- @ConfigComment("Switch inventories based on island. Only applies if players own more than one island.")
+ @ConfigComment("Switch inventories based on island. Only applies if players own or are team members of more than one island.")
@ConfigComment("Each sub-option controls whether that aspect is switched per-island.")
@ConfigComment("The world-level option must also be true for the island option to have any effect.")
@ConfigEntry(path = "options.islands.active")
@@ -98,6 +98,44 @@ public class Settings implements ConfigObject {
@ConfigEntry(path = "economy.debug")
private boolean economyDebug = false;
+ @ConfigComment("")
+ @ConfigComment("Game modes can ask for the options they need in their own worlds, so that you do not")
+ @ConfigComment("have to set them up by hand. A game mode that asks is hooked into automatically and the")
+ @ConfigComment("options it asks for apply in its worlds only. Nothing in this file is changed and other")
+ @ConfigComment("worlds keep the options 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. Their worlds then use the options")
+ @ConfigComment("above, and only if they are in the worlds list.")
+ @ConfigEntry(path = "game-mode-requests.ignore")
+ private Set ignoreRequests = new HashSet<>();
+
+ /**
+ * @return true if game modes may ask for options in their own worlds
+ */
+ public boolean isAllowRequests() {
+ return allowRequests;
+ }
+ /**
+ * @param allowRequests true if game modes may ask for options 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;
+ }
+
/**
* @return the worlds
*/
diff --git a/src/main/java/com/wasteofplastic/invswitcher/Store.java b/src/main/java/com/wasteofplastic/invswitcher/Store.java
index c71d913..c4f7db5 100644
--- a/src/main/java/com/wasteofplastic/invswitcher/Store.java
+++ b/src/main/java/com/wasteofplastic/invswitcher/Store.java
@@ -96,7 +96,7 @@ public Store(InvSwitcher addon) {
/**
* Compute the storage key for a player based on their current location.
* Returns "worldName/islandId" if per-island mode is active and the player
- * owns multiple concurrent islands, otherwise returns just "worldName".
+ * belongs to multiple concurrent islands, otherwise returns just "worldName".
* @param player - player
* @param world - world
* @return storage key
@@ -130,11 +130,11 @@ String getStorageKey(Player player, World world, Location location, Island islan
}
String overworldName = getOverworldName(world);
- if (!addon.getSettings().isIslandsActive()) {
+ if (!addon.getSettings(world).isIslandsActive()) {
return overworldName;
}
- // Check if player owns multiple concurrent islands in this world
+ // Check if player belongs to multiple concurrent islands in this world
World overworld = Util.getWorld(world);
int count = addon.getIslands().getNumberOfConcurrentIslands(player.getUniqueId(),
Objects.requireNonNull(overworld));
@@ -143,8 +143,7 @@ String getStorageKey(Player player, World world, Location location, Island islan
}
// If a specific island was provided, use it
- if (island != null && island.getOwner() != null
- && island.getOwner().equals(player.getUniqueId())) {
+ if (island != null && isOnTeam(island, player.getUniqueId())) {
return overworldName + "/" + island.getUniqueId();
}
@@ -163,7 +162,7 @@ String getStorageKey(Player player, World world, Location location, Island islan
Optional islandOpt = addon.getIslands().getIslandAt(location);
if (islandOpt.isPresent()) {
Island loc = islandOpt.get();
- if (loc.getOwner() != null && loc.getOwner().equals(player.getUniqueId())) {
+ if (isOnTeam(loc, player.getUniqueId())) {
return overworldName + "/" + loc.getUniqueId();
}
}
@@ -173,13 +172,25 @@ String getStorageKey(Player player, World world, Location location, Island islan
return (current != null) ? current : overworldName;
}
+ /**
+ * Checks if a player is the owner or a team member of an island. Per-island switching
+ * applies to every island a player belongs to, not only the ones they own, so that team
+ * members get the island's inventory, advancements, etc. too.
+ * @param island - island
+ * @param uuid - player's UUID
+ * @return true if the player is a member or higher on the island
+ */
+ public static boolean isOnTeam(Island island, UUID uuid) {
+ return island.getMemberSet().contains(uuid);
+ }
+
/**
* Get the overworld name from any world by stripping nether/end suffixes.
* @param world - world
* @return overworld name
*/
private String getOverworldName(World world) {
- if (!addon.getWorlds().contains(world)) {
+ if (world == null || !addon.getWorlds().contains(world)) {
return DEFAULT_WORLD_KEY;
}
return (world.getName().replace(THE_END, "")).replace(NETHER, "");
@@ -268,7 +279,7 @@ public void getInventory(Player player, World world, Island island) {
}
// Each option uses the island key or the world key based on its island sub-setting
- Settings settings = addon.getSettings();
+ Settings settings = addon.getSettings(world);
if (settings.isInventory()) {
String k = settings.isIslandsInventory() ? islandLoadKey : worldKey;
player.getInventory().setContents(store.getInventory(k).toArray(new ItemStack[0]));
@@ -412,7 +423,7 @@ private InventoryStorage getInv(Player player) {
*/
public void storeInventory(Player player, World world) {
storeAndSave(player, world, false);
- clearPlayer(player);
+ clearPlayer(player, world);
// Done!
}
@@ -433,7 +444,7 @@ public void storeAndSave(Player player, World world, boolean shutdown) {
// world they were last in, even after they log out.
store.setLastKey(islandKey);
// Each option saves to the island key or the world key based on its island sub-setting
- Settings settings = addon.getSettings();
+ Settings settings = addon.getSettings(world);
if (settings.isInventory()) {
String k = settings.isIslandsInventory() ? islandKey : worldKey;
List contents = Arrays.asList(player.getInventory().getContents());
@@ -489,7 +500,7 @@ public void storeAndSave(Player player, World world, boolean shutdown) {
* @param world - current world
*/
public void syncEnderChest(Player player, World world) {
- Settings settings = addon.getSettings();
+ Settings settings = addon.getSettings(world);
if (!settings.isEnderChest() || player == null || world == null) {
return;
}
@@ -615,32 +626,32 @@ private void getStat(Statistic s, InventoryStorage store, Player player, String
}
}
- private void clearPlayer(Player player) {
- if (this.addon.getSettings().isInventory())
+ private void clearPlayer(Player player, World world) {
+ if (addon.getSettings(world).isInventory())
{
// Clear the player's inventory
player.getInventory().clear();
}
- if (this.addon.getSettings().isExperience())
+ if (addon.getSettings(world).isExperience())
{
// Reset experience
setTotalExperience(player, 0);
}
- if (this.addon.getSettings().isAdvancements())
+ if (addon.getSettings(world).isAdvancements())
{
// Reset advancements
resetAdv(player);
}
- if (this.addon.getSettings().isEnderChest())
+ if (addon.getSettings(world).isEnderChest())
{
// Reset enderchest
player.getEnderChest().clear();
}
- if (this.addon.getSettings().isStatistics())
+ if (addon.getSettings(world).isStatistics())
{
// Reset Statistics
Arrays.stream(Statistic.values()).forEach(s ->
@@ -763,7 +774,7 @@ public void saveOnShutdown() {
*/
String getStorageKeyForEvent(Player player, World world, Island island) {
String overworldName = getOverworldName(world);
- if (!addon.getSettings().isIslandsActive()) {
+ if (!addon.getSettings(world).isIslandsActive()) {
return overworldName;
}
World overworld = Util.getWorld(world);
@@ -774,8 +785,8 @@ String getStorageKeyForEvent(Player player, World world, Island island) {
if (count <= 1) {
return overworldName;
}
- // Only use island-specific key if the player owns the island
- if (island != null && island.getOwner() != null && island.getOwner().equals(player.getUniqueId())) {
+ // Only use island-specific key if the player is on the island's team
+ if (island != null && isOnTeam(island, player.getUniqueId())) {
return overworldName + "/" + island.getUniqueId();
}
return overworldName;
@@ -793,7 +804,7 @@ public void clearStoredInventoryForWorld(Player player, World world, Island isla
InventoryStorage store = getInv(player);
String key = getStorageKeyForEvent(player, world, island);
String worldKey = getOverworldName(world);
- Settings settings = addon.getSettings();
+ Settings settings = addon.getSettings(world);
if (settings.isInventory()) {
String k = settings.isIslandsInventory() ? key : worldKey;
store.setInventory(k, Collections.emptyList());
@@ -813,7 +824,7 @@ public void clearStoredEnderChestForWorld(Player player, World world, Island isl
InventoryStorage store = getInv(player);
String key = getStorageKeyForEvent(player, world, island);
String worldKey = getOverworldName(world);
- Settings settings = addon.getSettings();
+ Settings settings = addon.getSettings(world);
if (settings.isEnderChest()) {
String k = settings.isIslandsEnderChest() ? key : worldKey;
store.setEnderChest(k, Collections.emptyList());
@@ -833,7 +844,7 @@ public void clearStoredExpForWorld(Player player, World world, Island island) {
InventoryStorage store = getInv(player);
String key = getStorageKeyForEvent(player, world, island);
String worldKey = getOverworldName(world);
- Settings settings = addon.getSettings();
+ Settings settings = addon.getSettings(world);
if (settings.isExperience()) {
String k = settings.isIslandsExperience() ? key : worldKey;
store.setExp(k, 0);
@@ -854,7 +865,7 @@ public void clearStoredHealthForWorld(Player player, World world, Island island)
InventoryStorage store = getInv(player);
String key = getStorageKeyForEvent(player, world, island);
String worldKey = getOverworldName(world);
- Settings settings = addon.getSettings();
+ Settings settings = addon.getSettings(world);
if (settings.isHealth()) {
String k = settings.isIslandsHealth() ? key : worldKey;
store.getHealth().remove(k);
@@ -874,7 +885,7 @@ public void clearStoredFoodForWorld(Player player, World world, Island island) {
InventoryStorage store = getInv(player);
String key = getStorageKeyForEvent(player, world, island);
String worldKey = getOverworldName(world);
- Settings settings = addon.getSettings();
+ Settings settings = addon.getSettings(world);
if (settings.isFood()) {
String k = settings.isIslandsFood() ? key : worldKey;
store.setFood(k, 20);
@@ -895,7 +906,7 @@ public void clearStoredMoneyForWorld(Player player, World world, Island island)
InventoryStorage store = getInv(player);
String key = getStorageKeyForEvent(player, world, island);
String worldKey = getOverworldName(world);
- Settings settings = addon.getSettings();
+ Settings settings = addon.getSettings(world);
if (settings.isMoney()) {
String k = settings.isIslandsMoney() ? key : worldKey;
store.setMoney(k, 0D);
@@ -987,7 +998,7 @@ public String getMoneyKey(OfflinePlayer player, World world) {
return null;
}
String overworldName = getOverworldName(world);
- Settings settings = addon.getSettings();
+ Settings settings = addon.getSettings(world);
if (!settings.isIslandsActive() || !settings.isIslandsMoney()) {
return overworldName;
}
diff --git a/src/main/java/com/wasteofplastic/invswitcher/listeners/PlayerListener.java b/src/main/java/com/wasteofplastic/invswitcher/listeners/PlayerListener.java
index 5b3e3e7..bb8ac43 100644
--- a/src/main/java/com/wasteofplastic/invswitcher/listeners/PlayerListener.java
+++ b/src/main/java/com/wasteofplastic/invswitcher/listeners/PlayerListener.java
@@ -20,6 +20,7 @@
import org.bukkit.entity.Player;
import com.wasteofplastic.invswitcher.InvSwitcher;
+import com.wasteofplastic.invswitcher.Store;
import world.bentobox.bentobox.api.events.island.IslandEnterEvent;
import world.bentobox.bentobox.api.events.player.PlayerBaseEvent;
@@ -81,13 +82,13 @@ public void onWorldEnter(final PlayerChangedWorldEvent event) {
}
/**
- * Handles inventory switching when a player enters an island they own.
- * Only triggers when per-island switching is enabled and the player owns multiple islands.
+ * Handles inventory switching when a player enters an island they own or are a team member of.
+ * Only triggers when per-island switching is enabled and the player belongs to multiple islands.
* @param event - event
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onIslandEnter(IslandEnterEvent event) {
- if (!addon.getSettings().isIslandsActive()) {
+ if (!addon.getSettings(event.getIsland().getWorld()).isIslandsActive()) {
return;
}
@@ -103,12 +104,12 @@ public void onIslandEnter(IslandEnterEvent event) {
Island island = event.getIsland();
- // Only switch if the player owns the island they're entering
- if (island.getOwner() == null || !island.getOwner().equals(player.getUniqueId())) {
+ // Only switch if the player is on the team of the island they're entering
+ if (!Store.isOnTeam(island, player.getUniqueId())) {
return;
}
- // Only switch if player owns multiple islands (otherwise key is the same)
+ // Only switch if player belongs to multiple islands (otherwise key is the same)
World overworld = Util.getWorld(world);
int count = addon.getIslands().getNumberOfConcurrentIslands(
player.getUniqueId(), Objects.requireNonNull(overworld));
@@ -163,7 +164,7 @@ public void onPlayerJoin(final PlayerJoinEvent event) {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerRespawn(PlayerRespawnEvent event) {
- if (!addon.getSettings().isIslandsActive()) {
+ if (!addon.getSettings(event.getRespawnLocation().getWorld()).isIslandsActive()) {
return;
}
@@ -212,7 +213,7 @@ public void onPlayerQuit(final PlayerQuitEvent event) {
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onEnderChestClose(final InventoryCloseEvent event) {
- if (!addon.getSettings().isEnderChest()) {
+ if (!addon.getSettings(event.getPlayer().getWorld()).isEnderChest()) {
return;
}
if (event.getInventory().getType() != InventoryType.ENDER_CHEST) {
@@ -259,7 +260,7 @@ private void closeOpenContainer(Player player) {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerResetInventory(PlayerResetInventoryEvent event) {
// If we are not switching inventories, let BentoBox perform its own reset.
- if (!addon.getSettings().isInventory()) return;
+ if (!addon.getSettings(event.getWorld()).isInventory()) return;
if (!shouldInterceptPlayerReset(event)) return;
event.setCancelled(true);
Player player = Bukkit.getPlayer(event.getPlayerUUID());
@@ -276,7 +277,7 @@ public void onPlayerResetInventory(PlayerResetInventoryEvent event) {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerResetEnderChest(PlayerResetEnderChestEvent event) {
// If we are not switching ender chests, let BentoBox perform its own reset.
- if (!addon.getSettings().isEnderChest()) return;
+ if (!addon.getSettings(event.getWorld()).isEnderChest()) return;
if (!shouldInterceptPlayerReset(event)) return;
event.setCancelled(true);
Player player = Bukkit.getPlayer(event.getPlayerUUID());
@@ -293,7 +294,7 @@ public void onPlayerResetEnderChest(PlayerResetEnderChestEvent event) {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerResetExp(PlayerResetExpEvent event) {
// If we are not switching experience, let BentoBox perform its own reset.
- if (!addon.getSettings().isExperience()) return;
+ if (!addon.getSettings(event.getWorld()).isExperience()) return;
if (!shouldInterceptPlayerReset(event)) return;
event.setCancelled(true);
Player player = Bukkit.getPlayer(event.getPlayerUUID());
@@ -311,7 +312,7 @@ public void onPlayerResetExp(PlayerResetExpEvent event) {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerResetHealth(PlayerResetHealthEvent event) {
// If we are not switching health, let BentoBox perform its own reset.
- if (!addon.getSettings().isHealth()) return;
+ if (!addon.getSettings(event.getWorld()).isHealth()) return;
if (!shouldInterceptPlayerReset(event)) return;
event.setCancelled(true);
Player player = Bukkit.getPlayer(event.getPlayerUUID());
@@ -328,7 +329,7 @@ public void onPlayerResetHealth(PlayerResetHealthEvent event) {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerResetHunger(PlayerResetHungerEvent event) {
// If we are not switching food, let BentoBox perform its own reset.
- if (!addon.getSettings().isFood()) return;
+ if (!addon.getSettings(event.getWorld()).isFood()) return;
if (!shouldInterceptPlayerReset(event)) return;
event.setCancelled(true);
Player player = Bukkit.getPlayer(event.getPlayerUUID());
diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml
index ab91c16..ccf77bd 100755
--- a/src/main/resources/config.yml
+++ b/src/main/resources/config.yml
@@ -35,7 +35,7 @@ options:
# or in a different world. If another economy plugin is present, worlds InvSwitcher does
# not manage are passed through to it; if not, InvSwitcher handles every world itself.
money: false
- # Switch inventories based on island. Only applies if players own more than one island.
+ # Switch inventories based on island. Only applies if players own or are team members of more than one island.
# Each sub-option controls whether that aspect is switched per-island.
# The world-level option must also be true for the island option to have any effect.
islands:
@@ -69,3 +69,14 @@ economy:
# Log every economy transaction (deposit/withdraw/balance) to the console for troubleshooting.
# Verbose - only enable while diagnosing a problem.
debug: false
+#
+# Game modes can ask for the options they need in their own worlds, so that you do not
+# have to set them up by hand. A game mode that asks is hooked into automatically and the
+# options it asks for apply in its worlds only. Nothing in this file is changed and other
+# worlds keep the options 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. Their worlds then use the options
+ # above, and only if they are in the worlds list.
+ ignore: []
diff --git a/src/test/java/com/wasteofplastic/invswitcher/InvSwitcherTest.java b/src/test/java/com/wasteofplastic/invswitcher/InvSwitcherTest.java
index b042572..5633346 100644
--- a/src/test/java/com/wasteofplastic/invswitcher/InvSwitcherTest.java
+++ b/src/test/java/com/wasteofplastic/invswitcher/InvSwitcherTest.java
@@ -6,6 +6,7 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -226,6 +227,63 @@ void testAllLoadedNoWorlds() {
verify(plugin, never()).log("Hooking into the following worlds:");
}
+ private world.bentobox.bentobox.api.addons.GameModeAddon requestingGameMode(World gmWorld) {
+ world.bentobox.bentobox.api.addons.GameModeAddon gm = mock(world.bentobox.bentobox.api.addons.GameModeAddon.class);
+ when(gm.getDescription()).thenReturn(new AddonDescription.Builder("bentobox", "Boxed", "1").build());
+ when(gm.getOverWorld()).thenReturn(gmWorld);
+ addon.requester = (g, n) -> g == gm && n.equals("InvSwitcher")
+ ? java.util.Map.of("options.islands.advancements", true, "options.money", true, "worlds", "x")
+ : java.util.Map.of();
+ when(am.getGameModeAddons()).thenReturn(java.util.List.of(gm));
+ return gm;
+ }
+
+ /**
+ * A game mode's request applies in its own worlds only, and hooks the addon into them.
+ */
+ @Test
+ void testGameModeRequest() {
+ try (MockedStatic mockedBukkit = mockStatic(Bukkit.class, Mockito.RETURNS_MOCKS)) {
+ when(Bukkit.getWorld(anyString())).thenReturn(null);
+ World gmWorld = mock(World.class);
+ when(gmWorld.getName()).thenReturn("boxed_world");
+ requestingGameMode(gmWorld);
+ addon.onLoad();
+ addon.getSettings().setWorlds(Collections.emptySet());
+ addon.allLoaded();
+ // Hooked in without being in the worlds list
+ assertTrue(addon.getWorlds().contains(gmWorld));
+ // The option is on in the game mode's world and still off everywhere else
+ assertTrue(addon.getSettings(gmWorld).isIslandsAdvancements());
+ org.junit.jupiter.api.Assertions.assertFalse(addon.getSettings().isIslandsAdvancements());
+ org.junit.jupiter.api.Assertions.assertFalse(addon.getSettings(world).isIslandsAdvancements());
+ // Money and the worlds list cannot be asked for
+ org.junit.jupiter.api.Assertions.assertFalse(addon.getSettings(gmWorld).isMoney());
+ verify(plugin).log("[InvSwitcher] Boxed asked for these options in its worlds: options.islands.advancements: true");
+ verify(plugin, times(2)).logWarning(org.mockito.ArgumentMatchers.contains("asked for something that cannot be done"));
+ }
+ }
+
+ /**
+ * The admin can ignore requests from a game mode, or from all of them.
+ */
+ @Test
+ void testGameModeRequestIgnored() {
+ World gmWorld = mock(World.class);
+ requestingGameMode(gmWorld);
+ addon.onLoad();
+ addon.getSettings().setWorlds(Collections.emptySet());
+ addon.getSettings().setIgnoreRequests(Set.of("boxed"));
+ addon.allLoaded();
+ org.junit.jupiter.api.Assertions.assertFalse(addon.getSettings(gmWorld).isIslandsAdvancements());
+ assertEquals(State.DISABLED, addon.getState());
+
+ addon.getSettings().setIgnoreRequests(Collections.emptySet());
+ addon.getSettings().setAllowRequests(false);
+ addon.loadRequests();
+ org.junit.jupiter.api.Assertions.assertFalse(addon.getSettings(gmWorld).isIslandsAdvancements());
+ }
+
/**
* Test method for {@link com.wasteofplastic.invswitcher.InvSwitcher#getStore()}.
*/
diff --git a/src/test/java/com/wasteofplastic/invswitcher/StoreTest.java b/src/test/java/com/wasteofplastic/invswitcher/StoreTest.java
index 3c1ca15..b60cc1d 100644
--- a/src/test/java/com/wasteofplastic/invswitcher/StoreTest.java
+++ b/src/test/java/com/wasteofplastic/invswitcher/StoreTest.java
@@ -1,5 +1,6 @@
package com.wasteofplastic.invswitcher;
+import com.google.common.collect.ImmutableSet;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -131,6 +132,7 @@ void setUp() {
// Settings
sets = new Settings();
when(addon.getSettings()).thenReturn(sets);
+ when(addon.getSettings(org.mockito.ArgumentMatchers.nullable(org.bukkit.World.class))).thenReturn(sets);
// Addon
when(addon.getLogger()).thenReturn(logger);
@@ -401,6 +403,7 @@ void testGetStorageKeyMultipleIslandsOnOwnIsland() {
sets.setIslandsActive(true);
Island island = mock(Island.class);
when(island.getOwner()).thenReturn(playerUUID);
+ when(island.getMemberSet()).thenReturn(ImmutableSet.of(playerUUID));
when(island.getUniqueId()).thenReturn("island-123");
Location loc = mock(Location.class);
when(player.getLocation()).thenReturn(loc);
@@ -415,12 +418,35 @@ void testGetStorageKeyMultipleIslandsOnOwnIsland() {
}
}
+ @Test
+ void testGetStorageKeyMultipleIslandsOnTeamIsland() {
+ // The player is a team member, not the owner. They still get the island's key.
+ sets.setIslandsActive(true);
+ Island island = mock(Island.class);
+ UUID owner = UUID.randomUUID();
+ when(island.getOwner()).thenReturn(owner);
+ when(island.getMemberSet()).thenReturn(ImmutableSet.of(owner, playerUUID));
+ when(island.getUniqueId()).thenReturn("team-island");
+ Location loc = mock(Location.class);
+ when(player.getLocation()).thenReturn(loc);
+
+ try (MockedStatic utilities = Mockito.mockStatic(Util.class)) {
+ utilities.when(() -> Util.getWorld(world)).thenReturn(world);
+ when(islandsManager.getNumberOfConcurrentIslands(playerUUID, world)).thenReturn(2);
+ when(islandsManager.getIslandAt(loc)).thenReturn(Optional.of(island));
+
+ assertEquals("world/team-island", s.getStorageKey(player, world));
+ assertEquals("world/team-island", s.getStorageKeyForEvent(player, world, island));
+ }
+ }
+
@Test
void testGetStorageKeyMultipleIslandsOnOtherPlayerIsland() {
sets.setIslandsActive(true);
Island island = mock(Island.class);
UUID otherPlayer = UUID.randomUUID();
when(island.getOwner()).thenReturn(otherPlayer);
+ when(island.getMemberSet()).thenReturn(ImmutableSet.of(otherPlayer));
Location loc = mock(Location.class);
when(player.getLocation()).thenReturn(loc);
@@ -440,6 +466,7 @@ void testGetStorageKeyWithSpecificIsland() {
sets.setIslandsActive(true);
Island island = mock(Island.class);
when(island.getOwner()).thenReturn(playerUUID);
+ when(island.getMemberSet()).thenReturn(ImmutableSet.of(playerUUID));
when(island.getUniqueId()).thenReturn("island-456");
try (MockedStatic utilities = Mockito.mockStatic(Util.class)) {
@@ -512,6 +539,7 @@ void testUpgradeWorldKeyToIsland() {
Island oldIsland = mock(Island.class);
when(oldIsland.getOwner()).thenReturn(playerUUID);
+ when(oldIsland.getMemberSet()).thenReturn(ImmutableSet.of(playerUUID));
when(oldIsland.getUniqueId()).thenReturn("island-primary");
try (MockedStatic utilities = Mockito.mockStatic(Util.class);
@@ -552,10 +580,12 @@ void testFullScenarioSingleToMultipleIslands() {
Island primaryIsland = mock(Island.class);
when(primaryIsland.getOwner()).thenReturn(playerUUID);
+ when(primaryIsland.getMemberSet()).thenReturn(ImmutableSet.of(playerUUID));
when(primaryIsland.getUniqueId()).thenReturn("island-primary");
Island newIsland = mock(Island.class);
when(newIsland.getOwner()).thenReturn(playerUUID);
+ when(newIsland.getMemberSet()).thenReturn(ImmutableSet.of(playerUUID));
when(newIsland.getUniqueId()).thenReturn("island-new");
Location loc = mock(Location.class);
@@ -880,6 +910,7 @@ void testGetStorageKeyForEventMultipleIslandsOwner() {
sets.setIslandsActive(true);
Island island = mock(Island.class);
when(island.getOwner()).thenReturn(playerUUID);
+ when(island.getMemberSet()).thenReturn(ImmutableSet.of(playerUUID));
when(island.getUniqueId()).thenReturn("island-abc");
try (MockedStatic mockedUtil = mockStatic(Util.class)) {
mockedUtil.when(() -> Util.getWorld(world)).thenReturn(world);
@@ -899,6 +930,7 @@ void testGetStorageKeyForEventMultipleIslandsNotOwner() {
Island island = mock(Island.class);
UUID otherOwner = UUID.randomUUID();
when(island.getOwner()).thenReturn(otherOwner); // player is NOT the owner
+ when(island.getMemberSet()).thenReturn(ImmutableSet.of(otherOwner));
try (MockedStatic mockedUtil = mockStatic(Util.class)) {
mockedUtil.when(() -> Util.getWorld(world)).thenReturn(world);
when(islandsManager.getNumberOfConcurrentIslands(playerUUID, world)).thenReturn(2);
diff --git a/src/test/java/com/wasteofplastic/invswitcher/economy/InvEconomyTest.java b/src/test/java/com/wasteofplastic/invswitcher/economy/InvEconomyTest.java
index 3720d68..d1474aa 100644
--- a/src/test/java/com/wasteofplastic/invswitcher/economy/InvEconomyTest.java
+++ b/src/test/java/com/wasteofplastic/invswitcher/economy/InvEconomyTest.java
@@ -103,6 +103,7 @@ void setUp() {
sets.setIslandsActive(false);
sets.setImportExistingBalances(false);
when(addon.getSettings()).thenReturn(sets);
+ when(addon.getSettings(org.mockito.ArgumentMatchers.nullable(org.bukkit.World.class))).thenReturn(sets);
when(addon.getLogger()).thenReturn(logger);
when(addon.getIslands()).thenReturn(islandsManager);
diff --git a/src/test/java/com/wasteofplastic/invswitcher/listeners/PlayerListenerTest.java b/src/test/java/com/wasteofplastic/invswitcher/listeners/PlayerListenerTest.java
index 00c8123..5f36684 100644
--- a/src/test/java/com/wasteofplastic/invswitcher/listeners/PlayerListenerTest.java
+++ b/src/test/java/com/wasteofplastic/invswitcher/listeners/PlayerListenerTest.java
@@ -1,5 +1,6 @@
package com.wasteofplastic.invswitcher.listeners;
+import com.google.common.collect.ImmutableSet;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -108,6 +109,7 @@ void setUp() {
when(addon.getStore()).thenReturn(store);
when(addon.getWorlds()).thenReturn(Set.of(world));
when(addon.getSettings()).thenReturn(settings);
+ when(addon.getSettings(org.mockito.ArgumentMatchers.nullable(org.bukkit.World.class))).thenReturn(settings);
when(addon.getIslands()).thenReturn(islandsManager);
pl = new PlayerListener(addon);
}
@@ -231,6 +233,7 @@ void testOnIslandEnterNotOwner() {
when(settings.isIslandsActive()).thenReturn(true);
UUID otherOwner = UUID.randomUUID();
when(island.getOwner()).thenReturn(otherOwner);
+ when(island.getMemberSet()).thenReturn(ImmutableSet.of(otherOwner));
IslandEnterEvent event = new IslandEnterEvent(island, playerUUID, false, null, island, null);
try (MockedStatic mockedBukkit = mockStatic(Bukkit.class)) {
mockedBukkit.when(() -> Bukkit.getPlayer(playerUUID)).thenReturn(player);
@@ -243,6 +246,7 @@ void testOnIslandEnterNotOwner() {
void testOnIslandEnterSingleIsland() {
when(settings.isIslandsActive()).thenReturn(true);
when(island.getOwner()).thenReturn(playerUUID);
+ when(island.getMemberSet()).thenReturn(ImmutableSet.of(playerUUID));
IslandEnterEvent event = new IslandEnterEvent(island, playerUUID, false, null, island, null);
try (MockedStatic mockedBukkit = mockStatic(Bukkit.class);
@@ -259,6 +263,7 @@ void testOnIslandEnterSingleIsland() {
void testOnIslandEnterMultipleIslandsSameKey() {
when(settings.isIslandsActive()).thenReturn(true);
when(island.getOwner()).thenReturn(playerUUID);
+ when(island.getMemberSet()).thenReturn(ImmutableSet.of(playerUUID));
when(island.getUniqueId()).thenReturn("island-1");
// Current key already matches
@@ -281,6 +286,7 @@ void testOnIslandEnterMultipleIslandsSameKey() {
void testOnIslandEnterMultipleIslandsDifferentKey() {
when(settings.isIslandsActive()).thenReturn(true);
when(island.getOwner()).thenReturn(playerUUID);
+ when(island.getMemberSet()).thenReturn(ImmutableSet.of(playerUUID));
when(island.getUniqueId()).thenReturn("island-2");
when(store.getStorageKey(player, world, island)).thenReturn("world/island-2");
@@ -697,6 +703,7 @@ void testWorldEnterWithOpenEnderChestDoesNotSyncToDestination() {
void testCloseOpenContainerOnIslandEnter() {
when(settings.isIslandsActive()).thenReturn(true);
when(island.getOwner()).thenReturn(playerUUID);
+ when(island.getMemberSet()).thenReturn(ImmutableSet.of(playerUUID));
when(island.getUniqueId()).thenReturn("island-2");
when(store.getStorageKey(player, world, island)).thenReturn("world/island-2");
when(store.getCurrentKey(player)).thenReturn("world/island-1");