Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
186 changes: 186 additions & 0 deletions src/main/java/com/wasteofplastic/invswitcher/GameModeRequests.java
Original file line number Diff line number Diff line change
@@ -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.
* <p>
* 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<String, Object> 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<String, Object> 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 <T> 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<T>(@NonNull T settings, @NonNull List<String> applied, @NonNull List<String> 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 <T> 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 <T> Result<T> apply(@NonNull T settings, @NonNull Map<String, Object> requests,
@NonNull Predicate<String> requestable) {
List<String> applied = new ArrayList<>();
List<String> 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> 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<Enum>) 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<Enum> type, String name) {
try {
return Enum.valueOf(type, name.toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException e) {
return null;
}
}
}
57 changes: 57 additions & 0 deletions src/main/java/com/wasteofplastic/invswitcher/InvSwitcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -35,6 +40,11 @@ public class InvSwitcher extends Addon {
private Store store;

private Settings settings;
private final Map<World, Settings> worldSettings = new HashMap<>();
/**
* How game modes are asked for the options they want
*/
BiFunction<GameModeAddon, String, Map<String, Object>> requester = GameModeRequests::ask;

private final Config<Settings> config = new Config<>(this, Settings.class);

Expand All @@ -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);
Expand Down Expand Up @@ -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<String, Object> requests = requester.apply(gm, getDescription().getName());
if (requests.isEmpty() || gm.getOverWorld() == null
|| settings.getIgnoreRequests().stream().anyMatch(name::equalsIgnoreCase)) {
continue;
}
GameModeRequests.Result<Settings> 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
Expand Down
40 changes: 39 additions & 1 deletion src/main/java/com/wasteofplastic/invswitcher/Settings.java
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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<String> 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<String> getIgnoreRequests() {
return ignoreRequests;
}
/**
* @param ignoreRequests names of the game modes whose requests are ignored
*/
public void setIgnoreRequests(Set<String> ignoreRequests) {
this.ignoreRequests = ignoreRequests;
}

/**
* @return the worlds
*/
Expand Down
Loading
Loading