This commit is contained in:
kento2 2026-09-01 01:43:45 +02:00
parent a365f70873
commit 0e8c48f570
39 changed files with 379 additions and 327 deletions

View file

@ -21,8 +21,9 @@ public record ScrowMessageStyle(
@Override
public Component ok(Component msg) {
return ComponentUtils.resolveURLS(prefix.append(Component.text("").color(NamedTextColor.GRAY))
.append(msg.colorIfAbsent(NamedTextColor.GRAY)));
return ComponentUtils.resolveURLS(
prefix.append(Component.text("").color(NamedTextColor.GRAY))
.append(msg.colorIfAbsent(NamedTextColor.GRAY)));
}
@Override

View file

@ -5,10 +5,7 @@ import org.bukkit.plugin.java.JavaPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import site.lab0x13.scrow.configurator.command.ConfiguratorCommand;
import site.lab0x13.scrow.configurator.configfile.ConfigFile;
import site.lab0x13.scrow.configurator.configfile.ConfigFileRegistry;
import site.lab0x13.scrow.configurator.storable.impl.VectorStorable;
import site.lab0x13.scrow.configurator.storable.impl.location.LocationStorable;
import java.io.IOException;
@ -18,19 +15,6 @@ public class ConfiguratorPlugin extends JavaPlugin {
@Override
public void onEnable() {
ConfigFile hotPotatoConfig = ConfigFile.of(this.getDataPath().resolve("config.json"));
ConfigFileRegistry.get().register(hotPotatoConfig);
var someVector = new VectorStorable();
var someLocation = new LocationStorable();
hotPotatoConfig.registerStorable("someVector", someVector);
hotPotatoConfig.registerStorable("someLocation", someLocation);
try {
hotPotatoConfig.load();
} catch (IOException e) {
throw new RuntimeException(e);
}
ScrowAPI.commands().register(ConfiguratorCommand.rootLiteral(ConfigFileRegistry.get()));
}

View file

@ -0,0 +1,40 @@
package site.lab0x13.scrow.configurator.action;
import de.kentoj.scrow.bukkit.command.ScrowBukkitCC;
import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.commands.model.argument.Argument;
import site.lab0x13.scrow.configurator.storable.Storable;
import java.util.List;
public abstract class SetAction<T> implements StorableAction<T, Storable<T>> {
private final Argument<ScrowBukkitCC, T> argument = argument();
protected abstract Argument<ScrowBukkitCC, T> argument();
protected abstract @Nullable Component valueToPrettyString(T value);
@Override
public String name() {
return "set";
}
@Override
public List<Argument<ScrowBukkitCC, ?>> arguments(Storable<T> __) {
return List.of(argument);
}
@Override
public boolean requiresValue() {
return false;
}
@Override
public void execute(Storable<T> storable, ScrowBukkitCC ctx) {
var parsedArg = ctx.getArgument(argument);
storable.value(parsedArg.value());
var prettyValue = valueToPrettyString(parsedArg.value());
var valueAsString = prettyValue != null ? prettyValue : Component.text(parsedArg.rawValue());
ctx.sender().sendMessage(ctx.style().ok("Set value to ").append(valueAsString));
}
}

View file

@ -11,9 +11,9 @@ import static java.util.Objects.*;
final class CheckLiteral {
private final Literal<ScrowBukkitCC> literal;
private final ConfigFile configFile;
private final ConfigFile<?> configFile;
public CheckLiteral(ConfigFile configFile) {
public CheckLiteral(ConfigFile<?> configFile) {
this.configFile = configFile;
this.literal = Literal.<ScrowBukkitCC>builder("check")
.withSyncExecutor(this::execute)

View file

@ -8,7 +8,7 @@ public final class ConfigLiteral {
private ConfigLiteral() {
}
public static Literal<ScrowBukkitCC> literal(ConfigFile cfg) {
public static Literal<ScrowBukkitCC> literal(ConfigFile<?> cfg) {
return Literal.<ScrowBukkitCC>builder(cfg.path().normalize().toString())
.withSubLiteral(new KeyLiteral(cfg).literal())
.withSubLiteral(new CheckLiteral(cfg).literal())

View file

@ -11,9 +11,9 @@ import site.lab0x13.scrow.configurator.action.StorableAction;
final class KeyLiteral {
private final Literal<ScrowBukkitCC> literal;
private final ConfigFile configFile;
private final ConfigFile<?> configFile;
KeyLiteral(ConfigFile configFile) {
KeyLiteral(ConfigFile<?> configFile) {
this.configFile = configFile;
literal = Literal.<ScrowBukkitCC>dynamic("key")
.withSubLiteralMetas(() -> configFile.allKeys().stream().map(LiteralMeta::of).toList())

View file

@ -1,28 +1,59 @@
package site.lab0x13.scrow.configurator.configfile;
import com.google.gson.JsonParser;
import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.configurator.storable.Storable;
import site.lab0x13.scrow.configurator.storable.complex.ComplexStorable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public interface ConfigFile extends Storable<Map<String, Storable<?>>> {
import static java.util.Objects.requireNonNull;
static ConfigFile of(Path path) {
return new ConfigFileImpl(path.normalize());
public abstract class ConfigFile<T> extends ComplexStorable<T> {
private final Path path;
public ConfigFile(Path path) {
this.path = path;
}
@Nullable Storable<?> getStorable(String key);
public void load() throws IOException {
this.loadJson(JsonParser.parseString(Files.readString(path)));
}
void registerStorable(String key, Storable<?> storable);
public void save() throws IOException {
Files.writeString(path, this.toJson().toString());
}
List<String> allKeys();
public Storable<?> getStorable(String key) {
Storable<?> cur = this;
for (var fieldName : key.split("\\.")) {
cur = cur.getSubField(fieldName);
if (cur == null) return null;
}
return cur;
}
void load() throws IOException;
public List<String> allKeys() {
var res = new ArrayList<String>();
addKeysRecursively(res, null, this);
return res;
}
void save() throws IOException;
private void addKeysRecursively(List<String> res, @Nullable String parentKey, Storable<?> storable) {
if (parentKey != null)
res.add(parentKey);
storable.subFieldNames().forEach(subFieldName -> {
var subKey = parentKey == null ? subFieldName : parentKey + "." + subFieldName;
addKeysRecursively(res, subKey, requireNonNull(storable.getSubField(subFieldName)));
});
}
Path path();
public Path path() {
return path;
}
}

View file

@ -1,83 +0,0 @@
package site.lab0x13.scrow.configurator.configfile;
import com.google.gson.JsonParser;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import site.lab0x13.scrow.configurator.storable.MapStorable;
import site.lab0x13.scrow.configurator.storable.Storable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import static java.util.Objects.requireNonNull;
class ConfigFileImpl extends MapStorable<Storable<?>> implements ConfigFile {
private static final Logger log = LoggerFactory.getLogger(ConfigFileImpl.class);
private final Path path;
ConfigFileImpl(Path path) {
this.path = path;
}
@Override
public @Nullable Storable<?> getStorable(String key) {
var index = key.indexOf(':');
if (index == -1)
return getSubField(key);
if (key.endsWith(":"))
return null;
var fieldName = key.substring(0, index);
Storable<?> storable = getSubField(fieldName);
if (storable == null)
return null;
for (String subFieldName : key.substring(index + 1).split(":")) {
if (subFieldName.isEmpty()) continue;
storable = storable.getSubField(subFieldName);
if (storable == null)
return null;
}
return storable;
}
@Override
public void registerStorable(String key, Storable<?> storable) {
registerEntry(key, (Storable<Object>) storable);
}
@Override
public List<String> allKeys() {
var res = new ArrayList<String>();
subFieldNames().forEach(key -> addKeysRecursively(res, key, requireNonNull(getSubField(key))));
return res;
}
private void addKeysRecursively(List<String> result, String key, Storable<?> storable) {
result.add(key);
storable.subFieldNames().forEach(subKey ->
addKeysRecursively(result, key + ":" + subKey, requireNonNull(storable.getSubField(subKey))));
}
@Override
public void load() throws IOException {
if (!Files.exists(this.path)) return;
var json = Files.readString(this.path());
this.loadJson(JsonParser.parseString(json));
}
@Override
public void save() throws IOException {
Files.createDirectories(this.path().getParent());
Files.writeString(this.path(), this.toJson().toString());
}
@Override
public Path path() {
return path;
}
}

View file

@ -1,34 +1,33 @@
package site.lab0x13.scrow.configurator.configfile;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
public class ConfigFileRegistry {
private static final Logger log = LoggerFactory.getLogger(ConfigFileRegistry.class);
private static final ConfigFileRegistry instance = new ConfigFileRegistry();
public static ConfigFileRegistry get() {
return instance;
}
private final Map<String, ConfigFile> configFiles = new HashMap<>();
private final Map<String, ConfigFile<?>> configFiles = new HashMap<>();
public void register(ConfigFile configFile) {
var oldValue = configFiles.put(configFile.path().toString(), configFile);
if (oldValue != null)
log.warn("Overwriting old config with same path '{}'", configFile.path());
private ConfigFileRegistry() {
}
public Map<String, ConfigFile> allConfigs() {
public <S> void register(ConfigFile<S> configFile, S defaultValue) {
configFile.value(defaultValue);
configFiles.put(configFile.path().normalize().toString(), configFile);
}
public Map<String, ConfigFile<?>> allConfigs() {
return new HashMap<>(configFiles);
}
public @Nullable ConfigFile getConfigFile(String path) {
public @Nullable ConfigFile<?> getConfigFile(String path) {
return configFiles.get(path);
}
}

View file

@ -1,36 +1,46 @@
package site.lab0x13.scrow.configurator.storable;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.configurator.action.StorableAction;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.function.Supplier;
public abstract class AbstractStorable<T> implements Storable<T> {
private final List<ValueChangeSubscriber> subscribers = new ArrayList<>();
private final Supplier<T> defaultValue;
protected T value = null;
private final List<StorableAction<?, ?>> actions = new ArrayList<>();
private final List<ValueRequirement<T>> requirements = new ArrayList<>();
private @Nullable T value = null;
protected AbstractStorable(Supplier<T> defaultValue) {
this.defaultValue = defaultValue;
public AbstractStorable() {
actions.addAll(Storable.super.actions());
}
protected AbstractStorable(T defaultValue) {
this(() -> defaultValue);
}
protected abstract JsonElement toJsonSafe();
protected abstract void loadJsonSafe(JsonElement json);
protected void requireValue(Predicate<T> predicate, String error) {
requirements.add(new ValueRequirement<>(predicate, error));
}
protected void addAction(StorableAction<?, ?> action) {
actions.add(action);
}
@Override
public void subscribe(ValueChangeSubscriber subscriber) {
subscribers.add(subscriber);
}
@Override
public List<StorableAction<?, ?>> actions() {
return actions;
}
@Override
public @Nullable T value() {
return value;
@ -38,10 +48,15 @@ public abstract class AbstractStorable<T> implements Storable<T> {
@Override
public void value(@Nullable T value) {
this.value = value != null ? value : defaultValue.get();
setValueSilently(value);
subscribers.forEach(ValueChangeSubscriber::notifyValueChange);
}
@Override
public void setValueSilently(@Nullable T value) {
this.value = value;
}
@Override
public @Nullable String checkValue() {
for (var requirement : requirements) {
@ -50,4 +65,20 @@ public abstract class AbstractStorable<T> implements Storable<T> {
}
return null;
}
@Override
public void loadJson(JsonElement json) {
if (json == null || json.isJsonNull()) {
value(null);
return;
}
loadJsonSafe(json);
}
@Override
public JsonElement toJson() {
if (value == null)
return JsonNull.INSTANCE;
return toJsonSafe();
}
}

View file

@ -9,6 +9,10 @@ import java.util.Map;
public class MapStorable<V> extends ComplexStorable<Map<String, V>> {
public MapStorable() {
value(new HashMap<>());
}
public <S> void registerEntry(String name, Storable<S> storable) {
fieldRegistry().registerField(name, storable, map -> (S) map.get(name));
}

View file

@ -2,12 +2,13 @@ package site.lab0x13.scrow.configurator.storable;
import com.google.gson.JsonElement;
import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.configurator.action.StorableAction;
import site.lab0x13.scrow.configurator.action.GlobalSetJsonAction;
import site.lab0x13.scrow.configurator.action.GlobalShowAction;
import site.lab0x13.scrow.configurator.action.StorableAction;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public interface Storable<T> {
@ -15,6 +16,11 @@ public interface Storable<T> {
void value(@Nullable T value);
/**
* Set value without notifying subscribers
*/
void setValueSilently(@Nullable T value);
JsonElement toJson();
void loadJson(JsonElement json);

View file

@ -4,15 +4,13 @@ import com.google.gson.JsonElement;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.function.Supplier;
public abstract class WrappedStorable<R, T> extends AbstractStorable<T> {
private final Storable<R> realStorable;
private boolean skipUpdates = false;
public WrappedStorable(Storable<R> realStorable, Supplier<T> defaultValue) {
super(defaultValue);
public WrappedStorable(Storable<R> realStorable) {
this.realStorable = realStorable;
realStorable.subscribe(() -> {
if (realStorable.value() == null)
@ -22,10 +20,6 @@ public abstract class WrappedStorable<R, T> extends AbstractStorable<T> {
});
}
public WrappedStorable(Storable<R> realStorable, T defaultValue) {
this(realStorable, () -> defaultValue);
}
abstract protected T wrap(R real);
abstract protected R unwrap(T value);
@ -44,12 +38,12 @@ public abstract class WrappedStorable<R, T> extends AbstractStorable<T> {
}
@Override
public JsonElement toJson() {
public JsonElement toJsonSafe() {
return realStorable.toJson();
}
@Override
public void loadJson(JsonElement json) {
public void loadJsonSafe(JsonElement json) {
realStorable.loadJson(json);
}

View file

@ -6,12 +6,14 @@ import site.lab0x13.scrow.configurator.storable.Storable;
public abstract class ComplexStorable<T> extends SubFieldedStorable<T> {
protected ComplexStorable(T defaultValue) {
super(defaultValue);
public ComplexStorable() {
this.registerFields(fieldRegistry());
}
protected abstract void registerFields(FieldRegistry<T> registry);
@Override
public JsonElement toJson() {
public JsonElement toJsonSafe() {
var obj = new JsonObject();
fieldRegistry().subFields().forEach((subFieldName, subField) -> {
var v = (Storable<Object>) subField.storable();
@ -21,14 +23,9 @@ public abstract class ComplexStorable<T> extends SubFieldedStorable<T> {
}
@Override
public void loadJson(JsonElement json) {
if (json == null) {
value(null);
return;
}
public void loadJsonSafe(JsonElement json) {
var obj = json.getAsJsonObject();
skipUpdates(() -> fieldRegistry().subFields().forEach((subFieldName, subField) ->
subField.storable().loadJson(obj.get(subFieldName))));
updateValue();
fieldRegistry().subFields().forEach((subFieldName, subField) ->
subField.storable().loadJson(obj.get(subFieldName)));
}
}

View file

@ -2,6 +2,7 @@ package site.lab0x13.scrow.configurator.storable.complex;
import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.configurator.storable.Storable;
import site.lab0x13.scrow.configurator.storable.list.ListStorable;
import java.util.HashMap;
import java.util.Map;
@ -9,10 +10,19 @@ import java.util.function.Function;
public class FieldRegistry<T> {
private final Storable<T> parent;
private final Map<String, Field<T, ?>> subFields = new HashMap<>();
private final Runnable onFieldRegister;
public FieldRegistry(Storable<T> parent, Runnable onFieldRegister) {
this.parent = parent;
this.onFieldRegister = onFieldRegister;
}
public <S> void registerField(String name, Storable<S> storable, Function<T, S> getter) {
subFields.put(name, new Field<>(storable, getter));
parent.subscribe(() -> storable.setValueSilently(getter.apply(parent.value())));
storable.subscribe(onFieldRegister::run);
}
public Map<String, Field<T, ?>> subFields() {

View file

@ -2,57 +2,20 @@ package site.lab0x13.scrow.configurator.storable.complex;
import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.configurator.storable.AbstractStorable;
import site.lab0x13.scrow.configurator.storable.Action;
import site.lab0x13.scrow.configurator.storable.Storable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public abstract class SubFieldedStorable<T> extends AbstractStorable<T> {
private final FieldRegistry<T> fieldRegistry = new FieldRegistry<>();
private boolean skipUpdates = false;
public SubFieldedStorable(T defaultValue) {
super(defaultValue);
this.registerFields(fieldRegistry);
fieldRegistry.subFields().values().forEach(f -> f.storable().subscribe(this::updateValue));
}
protected abstract void registerFields(FieldRegistry<T> registry);
private final FieldRegistry<T> fieldRegistry = new FieldRegistry<>(this, this::onFieldRegister);
protected abstract T construct(FieldReader<T> reader);
/**
* Run action without updating the value
*/
protected void skipUpdates(Action action) {
try {
skipUpdates = true;
action.apply();
} finally {
skipUpdates = false;
}
}
protected void updateValue() {
if (skipUpdates)
return;
super.value(construct(new FieldReader<>(fieldRegistry)));
}
@Override
public void value(@Nullable T value) {
super.value(value);
if (value == null) {
// reset if null
skipUpdates(() -> fieldRegistry.subFields().values().forEach(f -> f.storable().value(null)));
} else {
skipUpdates(() -> fieldRegistry.subFields().values().forEach(_field -> {
var field = (Field<T, Object>) _field;
field.storable().value(field.getter().apply(value));
}));
}
private void onFieldRegister() {
this.setValueSilently(construct(new FieldReader<>(fieldRegistry)));
}
@Override

View file

@ -8,7 +8,7 @@ import site.lab0x13.scrow.configurator.storable.primitive.LongStorable;
import java.time.Duration;
public class DurationStorable extends ComplexStorable<Duration> {
public final class DurationStorable extends ComplexStorable<Duration> {
@Override
protected void registerFields(FieldRegistry<Duration> registry) {

View file

@ -6,7 +6,7 @@ import site.lab0x13.scrow.configurator.storable.complex.FieldReader;
import site.lab0x13.scrow.configurator.storable.complex.FieldRegistry;
import site.lab0x13.scrow.configurator.storable.primitive.DoubleStorable;
public class VectorStorable extends ComplexStorable<Vector> {
public final class VectorStorable extends ComplexStorable<Vector> {
@Override
protected void registerFields(FieldRegistry<Vector> registry) {

View file

@ -1,16 +1,21 @@
package site.lab0x13.scrow.configurator.storable.impl;
package site.lab0x13.scrow.configurator.storable.impl.component;
import de.kentoj.scrow.bukkit.command.ScrowBukkitCC;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import site.lab0x13.scrow.commands.model.argument.Argument;
import site.lab0x13.scrow.commands.model.argument.types.StringArgumentType;
import site.lab0x13.scrow.configurator.action.SetAction;
import site.lab0x13.scrow.configurator.storable.WrappedStorable;
import site.lab0x13.scrow.configurator.storable.primitive.StringStorable;
public class MiniMessageStorable extends WrappedStorable<String, Component> {
public final class ComponentStorable extends WrappedStorable<String, Component> {
private static final MiniMessage miniMessage = MiniMessage.miniMessage();
public MiniMessageStorable() {
public ComponentStorable() {
super(new StringStorable());
addAction(new SetComponentAction());
}
@Override

View file

@ -0,0 +1,21 @@
package site.lab0x13.scrow.configurator.storable.impl.component;
import de.kentoj.scrow.bukkit.command.ScrowBukkitCC;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import site.lab0x13.scrow.commands.model.argument.Argument;
import site.lab0x13.scrow.commands.model.argument.types.StringArgumentType;
import site.lab0x13.scrow.configurator.action.SetAction;
class SetComponentAction extends SetAction<String> {
@Override
protected Argument<ScrowBukkitCC, String> argument() {
return Argument.builder("miniMessage", new StringArgumentType<ScrowBukkitCC>())
.build();
}
@Override
protected Component valueToPrettyString(String value) {
return MiniMessage.miniMessage().deserialize(value);
}
}

View file

@ -1,27 +1,18 @@
package site.lab0x13.scrow.configurator.storable.impl.location;
import org.bukkit.Location;
import site.lab0x13.scrow.configurator.action.StorableAction;
import site.lab0x13.scrow.configurator.storable.complex.ComplexStorable;
import site.lab0x13.scrow.configurator.storable.primitive.DoubleStorable;
import site.lab0x13.scrow.configurator.storable.primitive.FloatStorable;
import site.lab0x13.scrow.configurator.storable.primitive.PrimitiveStorable;
import site.lab0x13.scrow.configurator.storable.complex.FieldReader;
import site.lab0x13.scrow.configurator.storable.complex.FieldRegistry;
import site.lab0x13.scrow.configurator.storable.impl.world.WorldStorable;
import site.lab0x13.scrow.configurator.storable.primitive.DoubleStorable;
import site.lab0x13.scrow.configurator.storable.primitive.FloatStorable;
import java.util.ArrayList;
import java.util.List;
public final class LocationStorable extends ComplexStorable<Location> {
public class LocationStorable extends ComplexStorable<Location> {
private final List<StorableAction<?, ?>> actions;
public LocationStorable(Location defaultValue) {
super(defaultValue);
actions = new ArrayList<>(super.actions());
actions.add(new LocationPickCurrentAction());
actions.add(new LocationTeleportAction());
public LocationStorable() {
addAction(new LocationPickCurrentAction());
addAction(new LocationTeleportAction());
}
@Override
@ -34,11 +25,6 @@ public class LocationStorable extends ComplexStorable<Location> {
registry.registerField("pitch", new FloatStorable(), Location::getPitch);
}
@Override
public List<StorableAction<?, ?>> actions() {
return actions;
}
@Override
protected Location construct(FieldReader<Location> reader) {
return new Location(

View file

@ -1,38 +1,21 @@
package site.lab0x13.scrow.configurator.storable.impl.world;
import de.kentoj.scrow.bukkit.command.ScrowBukkitCC;
import net.kyori.adventure.text.Component;
import org.bukkit.World;
import site.lab0x13.scrow.commands.bukkit.type.WorldArgumentType;
import site.lab0x13.scrow.commands.model.argument.Argument;
import site.lab0x13.scrow.configurator.action.StorableAction;
import site.lab0x13.scrow.configurator.storable.Storable;
import site.lab0x13.scrow.configurator.action.SetAction;
import java.util.List;
class SetWorldAction implements StorableAction<World, Storable<World>> {
private final Argument<ScrowBukkitCC, World> arg =
Argument.builder("world", new WorldArgumentType<ScrowBukkitCC>()).build();
class SetWorldAction extends SetAction<World> {
@Override
public String name() {
return "set";
protected Component valueToPrettyString(World value) {
return Component.text(value.getName() + "(" + value.getUID() + ")");
}
@Override
public List<Argument<ScrowBukkitCC, ?>> arguments(Storable<World> __) {
return List.of(arg);
}
@Override
public boolean requiresValue() {
return false;
}
@Override
public void execute(Storable<World> node, ScrowBukkitCC ctx) {
World world = ctx.getArg(arg);
node.value(world);
ctx.sender().sendMessage(ctx.style().ok("Set world to " + world.getName() + "(" + world.getUID() + ")"));
protected Argument<ScrowBukkitCC, World> argument() {
return Argument.builder("world", new WorldArgumentType<ScrowBukkitCC>()).build();
}
}

View file

@ -9,12 +9,12 @@ import site.lab0x13.scrow.configurator.storable.primitive.StringStorable;
import java.util.ArrayList;
import java.util.List;
public class WorldStorable extends WrappedStorable<String, World> {
public final class WorldStorable extends WrappedStorable<String, World> {
private final List<StorableAction<?, ?>> actions;
public WorldStorable(World defaultValue) {
super(new StringStorable(), defaultValue);
public WorldStorable() {
super(new StringStorable());
actions = new ArrayList<>(super.actions());
actions.add(new SetWorldAction());
}

View file

@ -2,7 +2,6 @@ package site.lab0x13.scrow.configurator.storable.list;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import site.lab0x13.scrow.configurator.action.StorableAction;
import site.lab0x13.scrow.configurator.storable.AbstractStorable;
@ -13,22 +12,25 @@ import java.util.List;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import static java.util.Objects.requireNonNull;
public class ListStorable<S> extends AbstractStorable<List<S>> {
private final Supplier<Storable<S>> newElementSupplier;
private final List<StorableAction<?, ?>> actions;
private final List<Storable<S>> _value = new ArrayList<>();
private final List<Storable<S>> _value;
public ListStorable(Supplier<Storable<S>> newElementSupplier) {
super(new ArrayList<>());
this.newElementSupplier = newElementSupplier;
_value = new ArrayList<>();
value(new ArrayList<>());
actions = super.actions();
actions.add(new ListExpandAction<>());
}
@Override
public void value(@Nullable List<S> value) {
super.value(value != null ? value : new ArrayList<>());
}
@Override
public List<StorableAction<?, ?>> actions() {
return actions;
@ -39,26 +41,34 @@ public class ListStorable<S> extends AbstractStorable<List<S>> {
*/
public Storable<S> expandList() {
var newElement = newElementSupplier.get();
newElement.subscribe(() -> value(_value.stream().map(Storable::value).toList()));
newElement.subscribe(this::updateValue);
_value.add(newElement);
updateValue();
return newElement;
}
public void deleteAt(int index) {
_value.remove(index);
updateValue();
}
@Override
public JsonElement toJson() {
public JsonElement toJsonSafe() {
var out = new JsonArray();
_value.forEach(storable -> out.add(storable.toJson()));
return out;
}
@Override
public void loadJson(JsonElement json) {
if (json == null) {
_value.clear();
return;
}
public void loadJsonSafe(JsonElement json) {
var in = json.getAsJsonArray();
in.forEach(jsonElement -> expandList().loadJson(jsonElement));
_value.clear();
in.forEach(jsonElement -> {
var element = newElementSupplier.get();
element.loadJson(jsonElement);
_value.add(element);
});
updateValue();
}
@Override
@ -70,6 +80,16 @@ public class ListStorable<S> extends AbstractStorable<List<S>> {
@Override
public @Nullable Storable<?> getSubField(String name) {
return _value.get(Integer.parseInt(name));
int index;
try {
index = Integer.parseInt(name);
} catch (NumberFormatException _) {
return null;
}
return _value.get(index);
}
private void updateValue() {
setValueSilently(_value.stream().map(Storable::value).toList());
}
}

View file

@ -2,9 +2,13 @@ package site.lab0x13.scrow.configurator.storable.primitive;
import com.google.gson.JsonPrimitive;
public class BooleanStorable extends PrimitiveStorable<Boolean>{
public final class BooleanStorable extends PrimitiveStorable<Boolean>{
public BooleanStorable(boolean defaultValue) {
super(defaultValue, JsonPrimitive::new, JsonPrimitive::getAsBoolean);
}
public BooleanStorable() {
super(false, JsonPrimitive::new, JsonPrimitive::getAsBoolean);
this(false);
}
}

View file

@ -2,9 +2,13 @@ package site.lab0x13.scrow.configurator.storable.primitive;
import com.google.gson.JsonPrimitive;
public class ByteStorable extends PrimitiveStorable<Byte>{
public final class ByteStorable extends PrimitiveStorable<Byte>{
public ByteStorable(byte defaultValue) {
super(defaultValue, JsonPrimitive::new, JsonPrimitive::getAsByte);
}
public ByteStorable() {
super((byte)0, JsonPrimitive::new, JsonPrimitive::getAsByte);
this((byte) 0);
}
}

View file

@ -2,9 +2,13 @@ package site.lab0x13.scrow.configurator.storable.primitive;
import com.google.gson.JsonPrimitive;
public class DoubleStorable extends PrimitiveStorable<Double>{
public final class DoubleStorable extends PrimitiveStorable<Double>{
public DoubleStorable(double defaultValue) {
super(defaultValue, JsonPrimitive::new, JsonPrimitive::getAsDouble);
}
public DoubleStorable() {
super(0D, JsonPrimitive::new, JsonPrimitive::getAsDouble);
this(0);
}
}

View file

@ -2,9 +2,13 @@ package site.lab0x13.scrow.configurator.storable.primitive;
import com.google.gson.JsonPrimitive;
public class FloatStorable extends PrimitiveStorable<Float>{
public final class FloatStorable extends PrimitiveStorable<Float>{
public FloatStorable(float defaultValue) {
super(defaultValue, JsonPrimitive::new, JsonPrimitive::getAsFloat);
}
public FloatStorable() {
super(0F, JsonPrimitive::new, JsonPrimitive::getAsFloat);
this(0);
}
}

View file

@ -2,9 +2,12 @@ package site.lab0x13.scrow.configurator.storable.primitive;
import com.google.gson.JsonPrimitive;
public class IntStorable extends PrimitiveStorable<Integer>{
public final class IntStorable extends PrimitiveStorable<Integer>{
public IntStorable(int defaultValue) {
super(defaultValue, JsonPrimitive::new, JsonPrimitive::getAsInt);
}
public IntStorable() {
super(0, JsonPrimitive::new, JsonPrimitive::getAsInt);
this(0);
}
}

View file

@ -2,9 +2,13 @@ package site.lab0x13.scrow.configurator.storable.primitive;
import com.google.gson.JsonPrimitive;
public class LongStorable extends PrimitiveStorable<Long> {
public final class LongStorable extends PrimitiveStorable<Long> {
public LongStorable(long defaultValue) {
super(defaultValue, JsonPrimitive::new, JsonPrimitive::getAsLong);
}
public LongStorable() {
super(0L, JsonPrimitive::new, JsonPrimitive::getAsLong);
this(0);
}
}

View file

@ -13,9 +13,9 @@ import java.util.function.Function;
public class PrimitiveStorable<V> extends AbstractStorable<V> {
private final V defaultValue;
private final Function<V, JsonPrimitive> serializer;
private final Function<JsonPrimitive, V> deserializer;
private final V defaultValue;
public PrimitiveStorable(V defaultValue, Function<V, JsonPrimitive> serializer, Function<JsonPrimitive, V> deserializer) {
this.defaultValue = defaultValue;
@ -24,23 +24,13 @@ public class PrimitiveStorable<V> extends AbstractStorable<V> {
}
@Override
public JsonElement toJson() {
if (value() == null)
return JsonNull.INSTANCE;
public JsonElement toJsonSafe() {
return serializer.apply(value());
}
@Override
public void loadJson(JsonElement json) {
if (json == null || json.isJsonNull())
value(defaultValue);
else
value(deserializer.apply(json.getAsJsonPrimitive()));
}
@Override
public void value(@Nullable V value) {
super.value(value == null ? defaultValue : value);
public void loadJsonSafe(JsonElement json) {
value(deserializer.apply(json.getAsJsonPrimitive()));
}
@Override

View file

@ -1,10 +1,22 @@
package site.lab0x13.scrow.configurator.storable.primitive;
import com.google.gson.JsonPrimitive;
import site.lab0x13.scrow.configurator.action.StorableAction;
import java.util.List;
public final class StringStorable extends PrimitiveStorable<String>{
public StringStorable(String defaultValue) {
super(defaultValue, JsonPrimitive::new, JsonPrimitive::getAsString);
}
public class StringStorable extends PrimitiveStorable<String>{
public StringStorable() {
super("", JsonPrimitive::new, JsonPrimitive::getAsString);
this("");
}
@Override
public List<StorableAction<?, ?>> actions() {
return super.actions();
}
}

View file

@ -4,7 +4,9 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import site.lab0x13.scrow.configurator.configfile.ConfigFileRegistry;
import site.lab0x13.scrow.extraction.config.ExtractionConfig;
import site.lab0x13.scrow.extraction.config.ExtractionConfigStorable;
public class ExtractionPlugin extends JavaPlugin {
@ -18,6 +20,7 @@ public class ExtractionPlugin extends JavaPlugin {
@Override
public void onEnable() {
_plugin = this;
ExtractionConfig.registerAndLoad(this);
var config = new ExtractionConfigStorable(this.getDataPath().resolve("config.json"));
ConfigFileRegistry.get().register(config, ExtractionConfig.defaultConfig());
}
}

View file

@ -4,6 +4,7 @@ import net.kyori.adventure.text.Component;
import org.bukkit.Location;
import site.lab0x13.scrow.extraction.extractionpoint.ExtractionPoint;
import java.util.ArrayList;
import java.util.List;
public record ArenaConfig(
@ -12,4 +13,7 @@ public record ArenaConfig(
List<Location> spawnLocations,
List<ExtractionPoint> extractionPoints
) {
public static ArenaConfig defaultConfig() {
return new ArenaConfig("", Component.empty(), new ArrayList<>(), new ArrayList<>());
}
}

View file

@ -3,9 +3,9 @@ package site.lab0x13.scrow.extraction.config;
import site.lab0x13.scrow.configurator.storable.complex.ComplexStorable;
import site.lab0x13.scrow.configurator.storable.complex.FieldReader;
import site.lab0x13.scrow.configurator.storable.complex.FieldRegistry;
import site.lab0x13.scrow.configurator.storable.impl.MiniMessageStorable;
import site.lab0x13.scrow.configurator.storable.list.ListStorable;
import site.lab0x13.scrow.configurator.storable.impl.component.ComponentStorable;
import site.lab0x13.scrow.configurator.storable.impl.location.LocationStorable;
import site.lab0x13.scrow.configurator.storable.list.ListStorable;
import site.lab0x13.scrow.configurator.storable.primitive.StringStorable;
public class ArenaConfigStorable extends ComplexStorable<ArenaConfig> {
@ -13,9 +13,12 @@ public class ArenaConfigStorable extends ComplexStorable<ArenaConfig> {
@Override
protected void registerFields(FieldRegistry<ArenaConfig> registry) {
registry.registerField("id", new StringStorable(), ArenaConfig::id);
registry.registerField("name", new MiniMessageStorable(), ArenaConfig::name);
registry.registerField("spawnLocations", new ListStorable<>(LocationStorable::new), ArenaConfig::spawnLocations);
registry.registerField("extractionPoints", new ListStorable<>(ExtractionPointStorable::new), ArenaConfig::extractionPoints);
registry.registerField("name", new ComponentStorable(), ArenaConfig::name);
registry.registerField("spawnLocations",
new ListStorable<>(LocationStorable::new), ArenaConfig::spawnLocations);
registry.registerField("extractionPoints",
new ListStorable<>(ExtractionPointStorable::new),
ArenaConfig::extractionPoints);
}
@Override

View file

@ -1,32 +1,27 @@
package site.lab0x13.scrow.extraction.config;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.ApiStatus;
import site.lab0x13.scrow.configurator.configfile.ConfigFile;
import site.lab0x13.scrow.configurator.configfile.ConfigFileRegistry;
import site.lab0x13.scrow.configurator.storable.impl.DurationStorable;
import site.lab0x13.scrow.configurator.storable.list.ListStorable;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
public record ExtractionConfig(
List<ArenaConfig> arenas,
Duration extractionDuration
) {
private static ExtractionConfig instance;
public final class ExtractionConfig {
private ExtractionConfig() {
public static ExtractionConfig defaultConfig() {
return new ExtractionConfig(
new ArrayList<>(),
Duration.ofMillis(100)
);
}
public static final ListStorable<ArenaConfig> arenas = new ListStorable<>(ArenaConfigStorable::new);
public static final DurationStorable extractionDuration = new DurationStorable();
public ExtractionConfig {
instance = this;
}
public static void registerAndLoad(Plugin plugin) {
var configFile = ConfigFile.of(plugin.getDataPath().resolve("config.json"));
ConfigFileRegistry.get().register(configFile);
{
configFile.registerStorable("arenas", arenas);
configFile.registerStorable("extractionDuration", extractionDuration);
}
try {
configFile.load();
} catch (IOException e) {
throw new RuntimeException("failed loading config", e);
}
public static ExtractionConfig get() {
return instance;
}
}

View file

@ -0,0 +1,29 @@
package site.lab0x13.scrow.extraction.config;
import site.lab0x13.scrow.configurator.configfile.ConfigFile;
import site.lab0x13.scrow.configurator.storable.complex.FieldReader;
import site.lab0x13.scrow.configurator.storable.complex.FieldRegistry;
import site.lab0x13.scrow.configurator.storable.impl.DurationStorable;
import site.lab0x13.scrow.configurator.storable.list.ListStorable;
import java.nio.file.Path;
public class ExtractionConfigStorable extends ConfigFile<ExtractionConfig> {
public ExtractionConfigStorable(Path path) {
super(path);
}
@Override
protected void registerFields(FieldRegistry<ExtractionConfig> registry) {
registry.registerField("arenas", new ListStorable<>(ArenaConfigStorable::new), ExtractionConfig::arenas);
registry.registerField("extractionDuration", new DurationStorable(), ExtractionConfig::extractionDuration);
}
@Override
protected ExtractionConfig construct(FieldReader<ExtractionConfig> reader) {
return new ExtractionConfig(
reader.read("arenas"),
reader.read("extractionDuration")
);
}
}

View file

@ -3,6 +3,7 @@ package site.lab0x13.scrow.extraction.extractionpoint;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import site.lab0x13.scrow.extraction.compass.CompassTarget;
import site.lab0x13.scrow.extraction.config.ExtractionConfig;
import java.util.HashMap;
import java.util.Map;

View file

@ -7,7 +7,6 @@ import site.lab0x13.scrow.extraction.config.ExtractionConfig;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import static java.util.Objects.requireNonNull;
@ -28,12 +27,12 @@ public class ExtractionProgress {
private final List<Consumer<Double>> changeSubscribers = new ArrayList<>();
private final long requiredMs;
/**
* System.currentTimeMillis() at first click (in this attempt to extract)
* or < 0 if extracting hasn't been attempted recently.
* System.currentTimeMillis() at first click (in this attempt to extract)
* or < 0 if extracting hasn't been attempted recently.
*/
private long clickingSince = -1;
/**
* System.currentTimeMillis() at last click
* System.currentTimeMillis() at last click
*/
private long lastClickMs = 0;
@ -45,7 +44,7 @@ public class ExtractionProgress {
}
public ExtractionProgress() {
this(requireNonNull(ExtractionConfig.extractionDuration.value()));
this(ExtractionConfig.get().extractionDuration());
}
public void advanceExtraction() {
@ -57,6 +56,7 @@ public class ExtractionProgress {
/* reset if not called again for a while */
new BukkitRunnable() {
final long lastClickMsAtStart = lastClickMs;
@Override
public void run() {
if (lastClickMsAtStart == lastClickMs)