modularization, part 1
This commit is contained in:
@@ -0,0 +1,212 @@
|
||||
package draylar.omegaconfig;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import draylar.omegaconfig.api.Comment;
|
||||
import draylar.omegaconfig.api.Config;
|
||||
import draylar.omegaconfig.api.SyncableExclusionStrategy;
|
||||
import draylar.omegaconfig.exception.NoValidConstructorException;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import net.fabricmc.api.ModInitializer;
|
||||
import net.fabricmc.fabric.api.network.ServerSidePacketRegistry;
|
||||
import net.fabricmc.fabric.api.networking.v1.ServerLoginNetworking;
|
||||
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
|
||||
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.network.PacketByteBuf;
|
||||
import net.minecraft.util.Identifier;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
|
||||
public class OmegaConfig implements ModInitializer {
|
||||
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static final List<Config> REGISTERED_CONFIGURATIONS = new ArrayList<>();
|
||||
public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
|
||||
public static final Identifier CONFIG_SYNC_PACKET = new Identifier("omegaconfig", "sync");
|
||||
public static final Gson SYNC_ONLY_GSON = new GsonBuilder().addSerializationExclusionStrategy(new SyncableExclusionStrategy()).setPrettyPrinting().create();
|
||||
|
||||
@Override
|
||||
public void onInitialize() {
|
||||
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
|
||||
server.execute(() -> {
|
||||
PacketByteBuf packet = new PacketByteBuf(Unpooled.buffer());
|
||||
|
||||
// list of configurations that are synced
|
||||
CompoundTag root = new CompoundTag();
|
||||
ListTag configurations = new ListTag();
|
||||
|
||||
// Iterate over each configuration.
|
||||
// Find values that should be synced and send the value over.
|
||||
OmegaConfig.getRegisteredConfigurations().forEach(config -> {
|
||||
if(config.hasAnySyncable()) {
|
||||
configurations.add(config.writeSyncingTag());
|
||||
}
|
||||
});
|
||||
|
||||
// save to packet and send to user
|
||||
root.put("Configurations", configurations);
|
||||
packet.writeCompoundTag(root);
|
||||
handler.sendPacket(ServerPlayNetworking.createS2CPacket(CONFIG_SYNC_PACKET, packet));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public static <T extends Config> T register(Class<T> configClass) {
|
||||
try {
|
||||
// Attempt to instantiate a new instance of this class.
|
||||
T config = configClass.getDeclaredConstructor().newInstance();
|
||||
|
||||
// Exceptions will have been thrown at this point.
|
||||
// We want to provide access to the config as soon as it is created, so we:
|
||||
// 1. serialize to disk if the config does not already exist
|
||||
// 2. read from disk if it does exist
|
||||
if(!configExists(config)) {
|
||||
writeConfig(configClass, config);
|
||||
REGISTERED_CONFIGURATIONS.add(config);
|
||||
} else {
|
||||
try {
|
||||
// Read from the disk config file to populate the correct values into our config object.
|
||||
List<String> lines = Files.readAllLines(getConfigPath(config));
|
||||
lines.removeIf(line -> line.trim().startsWith("//"));
|
||||
StringBuilder res = new StringBuilder();
|
||||
lines.forEach(res::append);
|
||||
T object = GSON.fromJson(res.toString(), configClass);
|
||||
|
||||
// re-write the config to add new values
|
||||
writeConfig(configClass, object);
|
||||
REGISTERED_CONFIGURATIONS.add(object);
|
||||
return object;
|
||||
} catch (IOException ioException) {
|
||||
LOGGER.error(ioException);
|
||||
LOGGER.info(String.format("Read error, using default values for config %s.", configClass.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException exception) {
|
||||
throw new NoValidConstructorException();
|
||||
}
|
||||
}
|
||||
|
||||
private static <T extends Config> void writeConfig(Class<T> configClass, T instance) {
|
||||
// Write the config to disk with the default values.
|
||||
String json = GSON.toJson(instance);
|
||||
|
||||
// Cursed time.
|
||||
List<String> lines = new ArrayList<>(Arrays.asList(json.split("\n")));
|
||||
Map<Integer, String> insertions = new HashMap<>();
|
||||
Map<String, String> keyToComments = new HashMap<>();
|
||||
|
||||
// populate key -> comments map
|
||||
for(Field field : configClass.getDeclaredFields()) {
|
||||
addFieldComments(field, keyToComments);
|
||||
}
|
||||
|
||||
// get inner-class fields
|
||||
// TODO: recursively get inner classes?
|
||||
for(Class<?> innerClass : configClass.getDeclaredClasses()) {
|
||||
for(Field field : innerClass.getDeclaredFields()) {
|
||||
addFieldComments(field, keyToComments);
|
||||
}
|
||||
}
|
||||
|
||||
// Find areas we should insert comments into...
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String at = lines.get(i);
|
||||
|
||||
// Check if we should insert comment
|
||||
for (Map.Entry<String, String> entry : keyToComments.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
String comment = entry.getValue();
|
||||
|
||||
if (at.trim().startsWith(String.format("\"%s\"", key))) {
|
||||
insertions.put(i + insertions.size(), String.format("%s//%s", getStartingWhitespace(at), comment));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// insertions -> list
|
||||
insertions.forEach(lines::add);
|
||||
|
||||
// list -> string
|
||||
StringBuilder res = new StringBuilder();
|
||||
lines.forEach(str -> res.append(String.format("%s%n", str)));
|
||||
|
||||
try {
|
||||
Files.write(getConfigPath(instance), res.toString().getBytes());
|
||||
} catch (IOException ioException) {
|
||||
LOGGER.error(ioException);
|
||||
LOGGER.info(String.format("Write error, using default values for config %s.", configClass.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
private static void addFieldComments(Field field, Map<String, String> keyToComments) {
|
||||
String fieldName = field.getName();
|
||||
Annotation[] annotations = field.getDeclaredAnnotations();
|
||||
|
||||
// Find comment
|
||||
for (Annotation annotation : annotations) {
|
||||
if(annotation instanceof Comment) {
|
||||
keyToComments.put(fieldName, ((Comment) annotation).value());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a string with the left-side whitespace characters of the given input, up till the first non-whitespace character.
|
||||
*
|
||||
* <p>
|
||||
* " hello" -> " "
|
||||
* "p" -> ""
|
||||
* " p" -> " "
|
||||
*
|
||||
* @param input input to retrieve whitespaces from
|
||||
* @return starting whitespaces from the given input
|
||||
*/
|
||||
private static String getStartingWhitespace(String input) {
|
||||
int index = -1;
|
||||
|
||||
char[] chars = input.toCharArray();
|
||||
for(int i = 0; i < chars.length; i++) {
|
||||
char at = chars[i];
|
||||
|
||||
if(at != ' ') {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if(index != -1) {
|
||||
return input.substring(0, index);
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public static Path getConfigPath(Config config) {
|
||||
return Paths.get(FabricLoader.getInstance().getConfigDir().toString(), String.format("%s.json", config.getFileName()));
|
||||
}
|
||||
|
||||
public static boolean configExists(Config config) {
|
||||
return Files.exists(getConfigPath(config));
|
||||
}
|
||||
|
||||
public static List<Config> getRegisteredConfigurations() {
|
||||
return REGISTERED_CONFIGURATIONS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package draylar.omegaconfig.api;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.FIELD)
|
||||
public @interface Comment {
|
||||
String value() default "";
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package draylar.omegaconfig.api;
|
||||
|
||||
import draylar.omegaconfig.OmegaConfig;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.StringTag;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public interface Config {
|
||||
|
||||
/**
|
||||
* Writes this configuration file instance to disk.
|
||||
* Useful for saving modified values during runtime.
|
||||
*/
|
||||
default void save() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @return an instance of this Config class with all default values.
|
||||
*/
|
||||
default Config getDefault() {
|
||||
return null;
|
||||
}
|
||||
|
||||
default CompoundTag writeSyncingTag() {
|
||||
CompoundTag tag = new CompoundTag();
|
||||
tag.putString("ConfigName", getFileName());
|
||||
|
||||
// all config vs. individual fields
|
||||
if(Arrays.stream(getClass().getAnnotations()).anyMatch(annotation -> annotation instanceof Syncing)) {
|
||||
// write ALL fields to tag
|
||||
String json = OmegaConfig.GSON.toJson(this);
|
||||
tag.putString("Serialized", json);
|
||||
tag.putBoolean("AllSync", true);
|
||||
} else {
|
||||
// write all syncable fields to tag
|
||||
String json = OmegaConfig.SYNC_ONLY_GSON.toJson(this);
|
||||
tag.putString("Serialized", json);
|
||||
tag.putBoolean("AllSync", false);
|
||||
}
|
||||
|
||||
return tag;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if this {@link Config} has any values that should be synced to the client
|
||||
*/
|
||||
default boolean hasAnySyncable() {
|
||||
boolean hasSyncingField = Arrays.stream(getClass().getDeclaredFields()).anyMatch(field -> Arrays.stream(field.getDeclaredAnnotations()).anyMatch(annotation -> annotation instanceof Syncing));
|
||||
boolean classSyncs = Arrays.stream(getClass().getDeclaredAnnotations()).anyMatch(annotation -> annotation instanceof Syncing);
|
||||
return hasSyncingField | classSyncs;
|
||||
}
|
||||
|
||||
String getFileName();
|
||||
|
||||
@Nullable
|
||||
default String getModid() {
|
||||
return null;
|
||||
}
|
||||
|
||||
default boolean hasMenu() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package draylar.omegaconfig.api;
|
||||
|
||||
import com.google.gson.ExclusionStrategy;
|
||||
import com.google.gson.FieldAttributes;
|
||||
|
||||
public class SyncableExclusionStrategy implements ExclusionStrategy {
|
||||
|
||||
@Override
|
||||
public boolean shouldSkipField(FieldAttributes f) {
|
||||
return f.getAnnotations().stream().noneMatch(annotation -> annotation instanceof Syncing);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldSkipClass(Class<?> clazz) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package draylar.omegaconfig.api;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.FIELD, ElementType.TYPE})
|
||||
public @interface Syncing {
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package draylar.omegaconfig.exception;
|
||||
|
||||
public class NoValidConstructorException extends RuntimeException {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package draylar.omegaconfig.mixin;
|
||||
|
||||
import draylar.omegaconfig.OmegaConfig;
|
||||
import draylar.omegaconfig.api.Config;
|
||||
import draylar.omegaconfig.api.Syncing;
|
||||
import net.fabricmc.fabric.api.network.ClientSidePacketRegistry;
|
||||
import net.fabricmc.fabric.api.util.NbtType;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.client.RunArgs;
|
||||
import net.minecraft.client.gui.screen.Screen;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.Unique;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@Mixin(MinecraftClient.class)
|
||||
public class ClientMixin {
|
||||
|
||||
@Unique
|
||||
private final List<Config> savedClientConfig = new ArrayList<>(); // stored config from before sync is applied
|
||||
|
||||
@Inject(
|
||||
method = "<init>",
|
||||
at = @At("RETURN"))
|
||||
private void onReturn(RunArgs args, CallbackInfo ci) {
|
||||
ClientSidePacketRegistry.INSTANCE.register(OmegaConfig.CONFIG_SYNC_PACKET, (context, buffer) -> {
|
||||
CompoundTag tag = buffer.readCompoundTag();
|
||||
savedClientConfig.clear();
|
||||
|
||||
context.getTaskQueue().execute(() -> {
|
||||
if(tag != null && tag.contains("Configurations")) {
|
||||
ListTag list = tag.getList("Configurations", NbtType.COMPOUND);
|
||||
list.forEach(compound -> {
|
||||
CompoundTag syncedConfiguration = (CompoundTag) compound;
|
||||
String name = syncedConfiguration.getString("ConfigName");
|
||||
String json = syncedConfiguration.getString("Serialized");
|
||||
boolean allSync = syncedConfiguration.getBoolean("AllSync");
|
||||
|
||||
// find configuration class by name
|
||||
for (Config config : OmegaConfig.getRegisteredConfigurations()) {
|
||||
if (config.getFileName().equals(name)) {
|
||||
// bring values from server to object
|
||||
Config server = OmegaConfig.GSON.fromJson(json, config.getClass());
|
||||
|
||||
// deep-copy original config & save it for a restore later
|
||||
Config cachedClient = OmegaConfig.GSON.fromJson(OmegaConfig.GSON.toJson(config), config.getClass());
|
||||
savedClientConfig.add(cachedClient);
|
||||
|
||||
// locate all fields that differ between the client and server, assign values from server to client (this will mutate the stored object)
|
||||
for (Field field : server.getClass().getDeclaredFields()) {
|
||||
if(allSync || Arrays.stream(field.getAnnotations()).anyMatch(annotation -> annotation instanceof Syncing)) {
|
||||
try {
|
||||
field.setAccessible(true);
|
||||
Object serverValue = field.get(server);
|
||||
field.set(config, serverValue);
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Inject(
|
||||
method = "disconnect(Lnet/minecraft/client/gui/screen/Screen;)V",
|
||||
at = @At("RETURN"))
|
||||
private void restoreConfigurations(Screen screen, CallbackInfo ci) {
|
||||
for(Config config : savedClientConfig) {
|
||||
for(Config potentiallySynced : OmegaConfig.getRegisteredConfigurations()) {
|
||||
if(config.getFileName().equals(potentiallySynced.getFileName())) {
|
||||
boolean allConfigSyncs = Arrays.stream(config.getClass().getAnnotations()).anyMatch(annotation -> annotation instanceof Syncing);
|
||||
|
||||
// mutate object in registered configurations
|
||||
for (Field field : config.getClass().getDeclaredFields()) {
|
||||
if(allConfigSyncs || Arrays.stream(field.getAnnotations()).anyMatch(annotation -> annotation instanceof Syncing)) {
|
||||
try {
|
||||
field.setAccessible(true);
|
||||
Object preSyncValue = field.get(config);
|
||||
field.set(potentiallySynced, preSyncValue);
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
savedClientConfig.clear();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user