From 25497d310b427a52fc12db1f5d831c235a6a338b Mon Sep 17 00:00:00 2001 From: sinus Date: Sat, 1 Apr 2017 23:24:50 +0200 Subject: [PATCH] Adding config GUIs to the @Config based configuration System (#3735) Lots of internal API that modders should not touch. See test mods for example usages. --- .../client/gui/ForgeGuiFactory.java | 9 +- .../common/ForgeModContainer.java | 2 +- .../minecraftforge/common/config/Config.java | 12 +- .../common/config/ConfigCategory.java | 2 + .../common/config/ConfigElement.java | 58 ++ .../common/config/ConfigManager.java | 328 +++--- .../common/config/FieldWrapper.java | 396 ++++++++ .../common/config/IFieldWrapper.java | 35 + .../common/config/ITypeAdapter.java | 13 +- .../common/config/TypeAdapters.java | 951 +++++++++++++----- .../fml/client/DefaultGuiFactory.java | 63 ++ .../fml/client/FMLClientHandler.java | 1 + .../fml/client/FMLConfigGuiFactory.java | 15 +- .../minecraftforge/fml/client/GuiModList.java | 24 +- .../fml/client/IModGuiFactory.java | 37 +- .../fml/client/config/GuiConfig.java | 74 ++ .../fml/common/FMLModContainer.java | 2 +- .../net/minecraftforge/debug/ConfigTest.java | 62 +- .../assets/config_test/lang/en_US.lang | 4 + src/test/resources/mcmod.info | 16 + 20 files changed, 1665 insertions(+), 439 deletions(-) create mode 100644 src/main/java/net/minecraftforge/common/config/FieldWrapper.java create mode 100644 src/main/java/net/minecraftforge/common/config/IFieldWrapper.java create mode 100644 src/main/java/net/minecraftforge/fml/client/DefaultGuiFactory.java create mode 100644 src/test/resources/assets/config_test/lang/en_US.lang create mode 100644 src/test/resources/mcmod.info diff --git a/src/main/java/net/minecraftforge/client/gui/ForgeGuiFactory.java b/src/main/java/net/minecraftforge/client/gui/ForgeGuiFactory.java index 87cb063a34..17dab5725e 100644 --- a/src/main/java/net/minecraftforge/client/gui/ForgeGuiFactory.java +++ b/src/main/java/net/minecraftforge/client/gui/ForgeGuiFactory.java @@ -102,9 +102,16 @@ public class ForgeGuiFactory implements IModGuiFactory { @Override public void initialize(Minecraft minecraftInstance) {} + @Override - public Class mainConfigGuiClass() { return ForgeConfigGui.class; } + public boolean hasConfigGui() { return true; } + + @Override + public GuiScreen createConfigGui(GuiScreen parent) { return new ForgeConfigGui(parent); } + + @Override + public Class mainConfigGuiClass() { return null; } @Override public Set runtimeGuiCategories() { return null; } diff --git a/src/main/java/net/minecraftforge/common/ForgeModContainer.java b/src/main/java/net/minecraftforge/common/ForgeModContainer.java index 36c2cfd6fa..516a3b4dbf 100644 --- a/src/main/java/net/minecraftforge/common/ForgeModContainer.java +++ b/src/main/java/net/minecraftforge/common/ForgeModContainer.java @@ -428,7 +428,7 @@ public class ForgeModContainer extends DummyModContainer implements WorldAccessC NetworkRegistry.INSTANCE.register(this, this.getClass(), "*", evt.getASMHarvestedData()); ForgeNetworkHandler.registerChannel(this, evt.getSide()); - ConfigManager.load(this.getModId(), Config.Type.INSTANCE); + ConfigManager.sync(this.getModId(), Config.Type.INSTANCE); } @Subscribe diff --git a/src/main/java/net/minecraftforge/common/config/Config.java b/src/main/java/net/minecraftforge/common/config/Config.java index 35ba80c116..4d99980ea2 100644 --- a/src/main/java/net/minecraftforge/common/config/Config.java +++ b/src/main/java/net/minecraftforge/common/config/Config.java @@ -66,7 +66,7 @@ public @interface Config } @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.FIELD) + @Target({ElementType.FIELD, ElementType.TYPE}) public @interface LangKey { String value(); @@ -101,4 +101,14 @@ public @interface Config { String value(); } + + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.FIELD, ElementType.TYPE}) + public @interface RequiresMcRestart + {} + + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.FIELD, ElementType.TYPE}) + public @interface RequiresWorldRestart + {} } diff --git a/src/main/java/net/minecraftforge/common/config/ConfigCategory.java b/src/main/java/net/minecraftforge/common/config/ConfigCategory.java index 87b39f082d..e95b8adc61 100644 --- a/src/main/java/net/minecraftforge/common/config/ConfigCategory.java +++ b/src/main/java/net/minecraftforge/common/config/ConfigCategory.java @@ -348,6 +348,8 @@ public class ConfigCategory implements Map char type = prop.getType().getID(); write(out, pad1, String.valueOf(type), ":", propName, "=", prop.getString()); } + + prop.resetChangedState(); } if (children.size() > 0) diff --git a/src/main/java/net/minecraftforge/common/config/ConfigElement.java b/src/main/java/net/minecraftforge/common/config/ConfigElement.java index 4b6168659b..3da362a6ba 100644 --- a/src/main/java/net/minecraftforge/common/config/ConfigElement.java +++ b/src/main/java/net/minecraftforge/common/config/ConfigElement.java @@ -27,9 +27,14 @@ package net.minecraftforge.common.config; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Set; import java.util.regex.Pattern; +import com.google.common.base.Strings; +import com.google.common.collect.Lists; + import net.minecraftforge.fml.client.config.ConfigGuiType; +import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement; import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry; import net.minecraftforge.fml.client.config.GuiEditArrayEntries.IArrayEntry; import net.minecraftforge.fml.client.config.IConfigElement; @@ -360,4 +365,57 @@ public class ConfigElement implements IConfigElement { return isProperty ? prop.getMaxValue() : null; } + + /** + * Provides a ConfigElement derived from the annotation-based config system + * @param configClass the class which contains the configuration + * @return A ConfigElement based on the described category. + */ + public static IConfigElement from(Class configClass) + { + Config annotation = configClass.getAnnotation(Config.class); + if (annotation == null) + throw new RuntimeException(String.format("The class '%s' has no @Config annotation!", configClass.getName())); + + Configuration config = ConfigManager.getConfiguration(annotation.modid(), annotation.name()); + if (config == null) + { + String error = String.format("The configuration '%s' of mod '%s' isn't loaded with the ConfigManager!", annotation.name(), annotation.modid()); + throw new RuntimeException(error); + } + + String name = Strings.isNullOrEmpty(annotation.name()) ? annotation.modid() : annotation.name(); + String langKey = name; + Config.LangKey langKeyAnnotation = configClass.getAnnotation(Config.LangKey.class); + if (langKeyAnnotation != null) + { + langKey = langKeyAnnotation.value(); + } + + if (annotation.category().isEmpty()) + { + List elements = Lists.newArrayList(); + Set catNames = config.getCategoryNames(); + for (String catName : catNames) + { + if (catName.isEmpty()) + continue; + ConfigCategory category = config.getCategory(catName); + DummyCategoryElement element = new DummyCategoryElement(category.getName(), category.getLanguagekey(), new ConfigElement(category).getChildElements()); + element.setRequiresMcRestart(category.requiresMcRestart()); + element.setRequiresWorldRestart(category.requiresWorldRestart()); + elements.add(element); + } + + return new DummyCategoryElement(name, langKey, elements); + } + else + { + ConfigCategory category = config.getCategory(annotation.category()); + DummyCategoryElement element = new DummyCategoryElement(name, langKey, new ConfigElement(category).getChildElements()); + element.setRequiresMcRestart(category.requiresMcRestart()); + element.setRequiresWorldRestart(category.requiresWorldRestart()); + return element; + } + } } diff --git a/src/main/java/net/minecraftforge/common/config/ConfigManager.java b/src/main/java/net/minecraftforge/common/config/ConfigManager.java index 8f9f756d46..fe2062e527 100644 --- a/src/main/java/net/minecraftforge/common/config/ConfigManager.java +++ b/src/main/java/net/minecraftforge/common/config/ConfigManager.java @@ -22,27 +22,23 @@ package net.minecraftforge.common.config; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.Map.Entry; -import java.util.regex.Pattern; +import java.util.Set; import org.apache.logging.log4j.Level; import com.google.common.base.Joiner; +import com.google.common.base.Strings; +import com.google.common.base.Throwables; import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; +import com.google.common.collect.Sets; import net.minecraftforge.common.config.Config.Comment; import net.minecraftforge.common.config.Config.LangKey; import net.minecraftforge.common.config.Config.Name; -import net.minecraftforge.common.config.Config.RangeDouble; -import net.minecraftforge.common.config.Config.RangeInt; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.LoaderException; @@ -53,9 +49,9 @@ import net.minecraftforge.fml.common.discovery.asm.ModAnnotation.EnumHolder; public class ConfigManager { private static Map> asm_data = Maps.newHashMap(); - private static Map, ITypeAdapter> ADAPTERS = Maps.newHashMap(); - private static Map, ITypeAdapter.Map> MAP_ADAPTERS = Maps.newHashMap(); + static Map, ITypeAdapter> ADAPTERS = Maps.newHashMap(); private static Map CONFIGS = Maps.newHashMap(); + private static Map>> MOD_CONFIG_CLASSES = Maps.newHashMap(); static { @@ -93,8 +89,6 @@ public class ConfigManager private static void register(Class cls, ITypeAdapter adpt) { ADAPTERS.put(cls, adpt); - if (adpt instanceof ITypeAdapter.Map) - MAP_ADAPTERS.put(cls, (ITypeAdapter.Map)adpt); } public static void loadData(ASMDataTable data) @@ -116,8 +110,34 @@ public class ConfigManager map.put(type, target); } } - + + /** + * Bounces to sync(). + * TODO: remove + */ public static void load(String modid, Config.Type type) + { + sync(modid, type); + } + + /** + * Synchronizes configuration data between the file on disk, the {@code Configuration} object and the annotated + * mod classes containing the configuration variables. + * + * When first called, this method will try to load the configuration from disk. If this fails, because the file + * does not exist, it will be created with default values derived from the mods config classes variable default values + * and comments and ranges, as well as configuration names based on the appropriate annotations found in {@code @Config}. + * + * Note, that this method is being called by the {@link FMLModContaier}, so the mod needn't call it in init(). + * + * If this method is called after the initial load, it will check whether the values in the Configuration object differ + * from the values in the corresponding variables. If they differ, it will either overwrite the variables if the Configuration + * object is marked as changed (e.g. if it was changed with the ConfigGui) or otherwise overwrite the Configuration object's values. + * It then proceeds to saving the changes to disk. + * @param modid the mod's ID for which the configuration shall be loaded + * @param type the configuration type, currently always {@code Config.Type.INSTANCE} + */ + public static void sync(String modid, Config.Type type) { FMLLog.fine("Attempting to inject @Config classes into %s for type %s", modid, type); ClassLoader mcl = Loader.instance().getModClassLoader(); @@ -132,6 +152,11 @@ public class ConfigManager try { Class cls = Class.forName(targ.getClassName(), true, mcl); + + if (MOD_CONFIG_CLASSES.get(modid) == null) + MOD_CONFIG_CLASSES.put(modid, Sets.>newHashSet()); + MOD_CONFIG_CLASSES.get(modid).add(cls); + String name = (String)targ.getAnnotationInfo().get("name"); if (name == null) name = modid; @@ -141,15 +166,17 @@ public class ConfigManager File file = new File(configDir, name + ".cfg"); + boolean loading = false; Configuration cfg = CONFIGS.get(file.getAbsolutePath()); if (cfg == null) { cfg = new Configuration(file); cfg.load(); CONFIGS.put(file.getAbsolutePath(), cfg); + loading = true; } - createConfig(cfg, cls, modid, type == Config.Type.INSTANCE, category); + sync(cfg, cls, modid, category, loading, null); cfg.save(); @@ -161,160 +188,171 @@ public class ConfigManager } } } + + public static Class[] getModConfigClasses(String modid) + { + return MOD_CONFIG_CLASSES.get(modid).toArray(new Class[0]); + } // ======================================================= // INTERNAL // ======================================================= - private static void createConfig(Configuration cfg, Class cls, String modid, boolean isStatic, String category) + static Configuration getConfiguration(String modid, String name) { + if (Strings.isNullOrEmpty(name)) + name = modid; + File configDir = Loader.instance().getConfigDir(); + File configFile = new File(configDir, name + ".cfg"); + return CONFIGS.get(configFile.getAbsolutePath()); + } + + private static void sync(Configuration cfg, Class cls, String modid, String category, boolean loading, Object instance) { for (Field f : cls.getDeclaredFields()) { if (!Modifier.isPublic(f.getModifiers())) continue; - if (Modifier.isStatic(f.getModifiers()) != isStatic) + if (Modifier.isStatic(f.getModifiers()) != (instance == null)) continue; + + String comment = null; + Comment ca = f.getAnnotation(Comment.class); + if (ca != null) + comment = NEW_LINE.join(ca.value()); - createConfig(modid, category, cfg, f.getType(), f, null); - } - } + String langKey = modid + "." + (category.isEmpty() ? "" : category + ".") + f.getName().toLowerCase(Locale.ENGLISH); + LangKey la = f.getAnnotation(LangKey.class); + if (la != null) + langKey = la.value(); + + boolean requiresMcRestart = f.isAnnotationPresent(Config.RequiresMcRestart.class); + boolean requiresWorldRestart = f.isAnnotationPresent(Config.RequiresWorldRestart.class); - private static final Joiner NEW_LINE = Joiner.on('\n'); - private static final Joiner PIPE = Joiner.on('|'); - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static void createConfig(String modid, String category, Configuration cfg, Class ftype, Field f, Object instance) - { - Property prop = null; - - String comment = null; - Comment ca = f.getAnnotation(Comment.class); - if (ca != null) - comment = NEW_LINE.join(ca.value()); - - String langKey = modid + "." + category + "." + f.getName().toLowerCase(Locale.ENGLISH); - LangKey la = f.getAnnotation(LangKey.class); - if (la != null) - langKey = la.value(); - - ITypeAdapter adapter = ADAPTERS.get(ftype); - - if (adapter != null) - { - if (category.isEmpty()) - throw new RuntimeException("Can not specify a primitive field when the category is empty: " + f.getDeclaringClass() +"/" + f.getName()); - prop = adapter.getProp(cfg, category, f, instance, comment); - set(instance, f, adapter.getValue(prop)); - } - else if (ftype.getSuperclass() == Enum.class) - { - if (category.isEmpty()) - throw new RuntimeException("Can not specify a primitive field when the category is empty: " + f.getDeclaringClass() +"/" + f.getName()); - Enum enu = (Enum)get(instance, f); - prop = cfg.get(category, getName(f), enu.name(), comment); - prop.setValidationPattern(makePattern((Class)ftype)); - set(instance, f, Enum.valueOf((Class)ftype, prop.getString())); - } - else if (ftype == Map.class) - { - if (category.isEmpty()) - throw new RuntimeException("Can not specify a primitive field when the category is empty: " + f.getDeclaringClass() +"/" + f.getName()); - String sub = category + "." + getName(f).toLowerCase(Locale.ENGLISH); - Map m = (Map)get(instance, f); - ParameterizedType type = (ParameterizedType)f.getGenericType(); - Type mtype = type.getActualTypeArguments()[1]; - - cfg.getCategory(sub).setComment(comment); - - for (Entry e : m.entrySet()) + if (FieldWrapper.hasWrapperFor(f)) //Access the field { - ITypeAdapter.Map adpt = MAP_ADAPTERS.get(mtype); - - if (adpt != null) + if (Strings.isNullOrEmpty(category)) + throw new RuntimeException("An empty category may not contain anything but objects representing categories!"); + try { - prop = adpt.getProp(cfg, sub, e.getKey(), e.getValue()); + IFieldWrapper wrapper = FieldWrapper.get(instance, f, category); + ITypeAdapter adapt = wrapper.getTypeAdapter(); + Property.Type propType = adapt.getType(); + + for (String key : wrapper.getKeys()) + { + String suffix = key.replaceFirst(wrapper.getCategory() + ".", ""); + + boolean existed = exists(cfg, wrapper.getCategory(), suffix); + if (!existed || loading) //Creates keys in category specified by the wrapper if new ones are programaticaly added + { + Property property = property(cfg, wrapper.getCategory(), suffix, propType, adapt.isArrayAdapter()); + + adapt.setDefaultValue(property, wrapper.getValue(key)); + if (!existed) + adapt.setValue(property, wrapper.getValue(key)); + else + wrapper.setValue(key, adapt.getValue(property)); + } + else //If the key is not new, sync according to shoudlReadFromVar() + { + Property property = property(cfg, wrapper.getCategory(), suffix, propType, adapt.isArrayAdapter()); + Object propVal = adapt.getValue(property); + Object mapVal = wrapper.getValue(key); + if (shouldReadFromVar(property, propVal, mapVal)) + adapt.setValue(property, mapVal); + else + wrapper.setValue(key, propVal); + } + } + + + ConfigCategory confCat = cfg.getCategory(wrapper.getCategory()); + + for (Property property : confCat.getOrderedValues())//Are new keys in the Configuration object? + { + if (!wrapper.handlesKey(property.getName())) + continue; + + if (loading || !wrapper.hasKey(property.getName())) + { + Object value = wrapper.getTypeAdapter().getValue(property); + wrapper.setValue(confCat.getName() + "." + property.getName(), value); + } + } + + if (loading) //Doing this after the loops. The wrapper should set cosmetic stuff. + wrapper.setupConfiguration(cfg, comment, langKey, requiresMcRestart, requiresWorldRestart); + } - else if (mtype instanceof Class && ((Class)mtype).getSuperclass() == Enum.class) + catch (Exception e) //If anything goes wrong, add the errored field and class. { - prop = TypeAdapters.Str.getProp(cfg, sub, e.getKey(), ((Enum)e.getValue()).name()); - prop.setValidationPattern(makePattern((Class)mtype)); + String format = "Error syncing field '%s' of class '%s'!"; + String error = String.format(format, f.getName(), cls.getName()); + throw new RuntimeException(error, e); } - else - throw new RuntimeException("Unknown type in map! " + f.getDeclaringClass() + "/" + f.getName() + " " + mtype); - - prop.setLanguageKey(langKey + "." + e.getKey().toLowerCase(Locale.ENGLISH)); - + } + else if (f.getType().getSuperclass() != null && f.getType().getSuperclass().equals(Object.class)) //Descend the object tree + { + Object newInstance = null; + try + { + newInstance = f.get(instance); + } + catch (Exception e) + { + //This should never happen. Previous checks should eliminate this. + Throwables.propagate(e); + } + + String sub = (category.isEmpty() ? "" : category + ".") + getName(f).toLowerCase(Locale.ENGLISH); + ConfigCategory confCat = cfg.getCategory(sub); + confCat.setComment(comment); + confCat.setLanguageKey(langKey); + confCat.setRequiresMcRestart(requiresMcRestart); + confCat.setRequiresWorldRestart(requiresWorldRestart); + + sync(cfg, f.getType(), modid, sub, loading, newInstance); + } + else + { + String format = "Can't handle field '%s' of class '%s': Unknown type."; + String error = String.format(format, f.getName(), cls.getCanonicalName()); + throw new RuntimeException(error); } - prop = null; } - else if (ftype.getSuperclass() == Object.class) //Only support classes that are one level below Object. + } + + static final Joiner NEW_LINE = Joiner.on('\n'); + static final Joiner PIPE = Joiner.on('|'); + + private static Property property(Configuration cfg, String category, String property, Property.Type type, boolean isList) + { + Property prop = cfg.getCategory(category).get(property); + if (prop == null) { - String sub = (category.isEmpty() ? "" : category + ".") + getName(f).toLowerCase(Locale.ENGLISH); - cfg.getCategory(sub).setComment(comment); - Object sinst = get(instance, f); - for (Field sf : ftype.getDeclaredFields()) - { - if (!Modifier.isPublic(sf.getModifiers())) - continue; - - createConfig(modid, sub, cfg, sf.getType(), sf, sinst); - } + if (isList) + prop = new Property(property, new String[0], type); + else + prop = new Property(property, (String)null, type); + cfg.getCategory(category).put(property, prop); } - // TODO Lists ? other stuff - else - throw new RuntimeException("Unknown type in config! " + f.getDeclaringClass() + "/" + f.getName() + " " + ftype); - - - if (prop != null) + return prop; + } + + private static boolean exists(Configuration cfg, String category, String property) + { + return cfg.hasCategory(category) && cfg.getCategory(category).containsKey(property); + } + + private static boolean shouldReadFromVar(Property property, Object propValue, Object fieldValue) + { + if (!propValue.equals(fieldValue)) { - prop.setLanguageKey(langKey); - RangeInt ia = f.getAnnotation(RangeInt.class); - if (ia != null) - { - prop.setMinValue(ia.min()); - prop.setMaxValue(ia.max()); - if (comment != null) - prop.setComment(NEW_LINE.join(new String[]{comment, "Min: " + ia.min(), "Max: " + ia.max()})); - else - prop.setComment(NEW_LINE.join(new String[]{"Min: " + ia.min(), "Max: " + ia.max()})); - } - RangeDouble da = f.getAnnotation(RangeDouble.class); - if (da != null) - { - prop.setMinValue(da.min()); - prop.setMaxValue(da.max()); - if (comment != null) - prop.setComment(NEW_LINE.join(new String[]{comment, "Min: " + da.min(), "Max: " + da.max()})); - else - prop.setComment(NEW_LINE.join(new String[]{"Min: " + da.min(), "Max: " + da.max()})); - } - - //TODO List length values + if (property.hasChanged()) + return false; + else + return true; } - } - private static void set(Object instance, Field f, Object v) - { - try { - f.set(instance, v); - } catch (Exception e) { - e.printStackTrace(); - } - } - private static Object get(Object instance, Field f) - { - try { - return f.get(instance); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - @SuppressWarnings("rawtypes") - private static Pattern makePattern(Class cls) - { - List lst = Lists.newArrayList(); - for (Enum e : cls.getEnumConstants()) - lst.add(e.name()); - return Pattern.compile(PIPE.join(lst)); + return false; } private static String getName(Field f) diff --git a/src/main/java/net/minecraftforge/common/config/FieldWrapper.java b/src/main/java/net/minecraftforge/common/config/FieldWrapper.java new file mode 100644 index 0000000000..19272c5393 --- /dev/null +++ b/src/main/java/net/minecraftforge/common/config/FieldWrapper.java @@ -0,0 +1,396 @@ +package net.minecraftforge.common.config; + +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.regex.Pattern; +import java.util.Set; + +import com.google.common.base.Throwables; +import com.google.common.collect.Lists; + +import net.minecraftforge.common.config.Config.RangeDouble; +import net.minecraftforge.common.config.Config.RangeInt; + +import static net.minecraftforge.common.config.ConfigManager.*; + +public abstract class FieldWrapper implements IFieldWrapper +{ + protected String category, name; + + protected Field field; + protected Object instance; + + public FieldWrapper(String category, Field field, Object instance) + { + this.instance = instance; + this.field = field; + this.category = category; + this.name = field.getName(); + + if (field.isAnnotationPresent(Config.Name.class)) + this.name = field.getAnnotation(Config.Name.class).value(); + + this.field.setAccessible(true); // Just in case + } + + public static IFieldWrapper get(Object instance, Field field, String category) + { + if (ADAPTERS.get(field.getType()) != null) + return new PrimitiveWrapper(category, field, instance); + else if (Enum.class.isAssignableFrom(field.getType())) + return new EnumWrapper(category, field, instance); + else if (Map.class.isAssignableFrom(field.getType())) + return new MapWrapper(category, field, instance); + else if (field.getType().getSuperclass().equals(Object.class)) + throw new RuntimeException("Objects should not be handled by field wrappers"); + else + throw new IllegalArgumentException(String.format("Fields of type '%s' are not supported!", field.getType().getCanonicalName())); + } + + public static boolean hasWrapperFor(Field field) + { + if (ADAPTERS.get(field.getType()) != null) + return true; + else if (Enum.class.isAssignableFrom(field.getType())) + return true; + else if (Map.class.isAssignableFrom(field.getType())) + return true; + return false; + } + + private static class MapWrapper extends FieldWrapper + { + private Map theMap = null; + private Type mType; + + @SuppressWarnings("unchecked") + private MapWrapper(String category, Field field, Object instance) + { + super(category, field, instance); + + try + { + theMap = (Map) field.get(instance); + } + catch (ClassCastException cce) + { + throw new IllegalArgumentException(String.format("The map '%s' of class '%s' must have the key type String!", field.getName(), + field.getDeclaringClass().getCanonicalName()), cce); + } + catch (Exception e) + { + Throwables.propagate(e); + } + + ParameterizedType type = (ParameterizedType) field.getGenericType(); + mType = type.getActualTypeArguments()[1]; + + if (ADAPTERS.get(mType) == null && !Enum.class.isAssignableFrom((Class) mType)) + throw new IllegalArgumentException(String.format("The map '%s' of class '%s' has target values which are neither primitive nor an enum!", + field.getName(), field.getDeclaringClass().getCanonicalName())); + + } + + @Override + public ITypeAdapter getTypeAdapter() + { + ITypeAdapter adapter = ADAPTERS.get(mType); + if (adapter == null && Enum.class.isAssignableFrom((Class) mType)) + adapter = TypeAdapters.Str; + return adapter; + } + + @Override + public String[] getKeys() + { + Set keys = theMap.keySet(); + String[] keyArray = new String[keys.size()]; + + Iterator it = keys.iterator(); + for (int i = 0; i < keyArray.length; i++) + { + keyArray[i] = category + "." + name + "." + it.next(); + } + + return keyArray; + } + + @Override + public Object getValue(String key) + { + return theMap.get(key.replaceFirst(category + "." + name + ".", "")); + } + + @Override + public void setValue(String key, Object value) + { + String suffix = key.replaceFirst(category + "." + name + ".", ""); + theMap.put(suffix, value); + } + + @Override + public boolean hasKey(String name) + { + return theMap.containsKey(name); + } + + @Override + public boolean handlesKey(String name) + { + if (name == null) + return false; + return name.startsWith(category + "." + name + "."); + } + + @Override + public void setupConfiguration(Configuration cfg, String desc, String langKey, boolean reqMCRestart, boolean reqWorldRestart) + { + ConfigCategory confCat = cfg.getCategory(category); + confCat.setComment(desc); + confCat.setLanguageKey(langKey); + confCat.setRequiresMcRestart(reqMCRestart); + confCat.setRequiresWorldRestart(reqWorldRestart); + } + + @Override + public String getCategory() + { + return category + "." + name; + } + + } + + private static class EnumWrapper extends SingleValueFieldWrapper + { + + private EnumWrapper(String category, Field field, Object instance) + { + super(category, field, instance); + } + + @Override + public ITypeAdapter getTypeAdapter() + { + return TypeAdapters.Str; + } + + @Override + public Object getValue(String key) + { + if (!hasKey(key)) + throw new IllegalArgumentException("Unsupported Key!"); + + try + { + @SuppressWarnings("rawtypes") + Enum enu = (Enum) field.get(instance); + return enu.name(); + } + catch (Exception e) + { + Throwables.propagate(e); + } + return null; + } + + @Override + public void setValue(String key, Object value) + { + if (!hasKey(key)) + throw new IllegalArgumentException("Unsupported Key!"); + @SuppressWarnings({ "unchecked", "rawtypes" }) + Enum enu = Enum.valueOf((Class) field.getType(), (String) value); + try + { + field.set(instance, enu); + } + catch (Exception e) + { + Throwables.propagate(e); + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public void setupConfiguration(Configuration cfg, String desc, String langKey, boolean reqMCRestart, boolean reqWorldRestart) + { + super.setupConfiguration(cfg, desc, langKey, reqMCRestart, reqWorldRestart); + + Property prop = cfg.getCategory(this.category).get(this.name); // Will be setup in general by ConfigManager + + List lst = Lists.newArrayList(); + for (Enum e : ((Class) field.getType()).getEnumConstants()) + lst.add(e.name()); + + prop.setValidationPattern(Pattern.compile(PIPE.join(lst))); + prop.setValidValues(lst.toArray(new String[0])); + + String validValues = NEW_LINE.join(lst); + + if (desc != null) + prop.setComment(NEW_LINE.join(new String[] { desc, "Valid values:" }) + "\n" + validValues); + else + prop.setComment("Valid values:" + "\n" + validValues); + } + } + + private static class PrimitiveWrapper extends SingleValueFieldWrapper + { + + private PrimitiveWrapper(String category, Field field, Object instance) + { + super(category, field, instance); + } + + @Override + public ITypeAdapter getTypeAdapter() + { + return ADAPTERS.get(field.getType()); + } + + @Override + public Object getValue(String key) + { + if (!hasKey(key)) + throw new IllegalArgumentException("Unknown key!"); + try + { + return field.get(instance); + } + catch (Exception e) + { + Throwables.propagate(e); + } + return null; + } + + @Override + public void setValue(String key, Object value) + { + if (!hasKey(key)) + throw new IllegalArgumentException("Unknown key: " + key); + try + { + field.set(instance, value); + } + catch (Exception e) + { + Throwables.propagate(e); + } + } + + public void setupConfiguration(Configuration cfg, String desc, String langKey, boolean reqMCRestart, boolean reqWorldRestart) + { + super.setupConfiguration(cfg, desc, langKey, reqMCRestart, reqWorldRestart); + + Property prop = cfg.getCategory(this.category).get(this.name); + + RangeInt ia = field.getAnnotation(RangeInt.class); + if (ia != null) + { + prop.setMinValue(ia.min()); + prop.setMaxValue(ia.max()); + if (desc != null) + prop.setComment(NEW_LINE.join(new String[] { desc, "Min: " + ia.min(), "Max: " + ia.max() })); + else + prop.setComment(NEW_LINE.join(new String[] { "Min: " + ia.min(), "Max: " + ia.max() })); + } + + RangeDouble da = field.getAnnotation(RangeDouble.class); + if (da != null) + { + prop.setMinValue(da.min()); + prop.setMaxValue(da.max()); + if (desc != null) + prop.setComment(NEW_LINE.join(new String[] { desc, "Min: " + da.min(), "Max: " + da.max() })); + else + prop.setComment(NEW_LINE.join(new String[] { "Min: " + da.min(), "Max: " + da.max() })); + } + } + } + + private static abstract class SingleValueFieldWrapper extends FieldWrapper + { + private SingleValueFieldWrapper(String category, Field field, Object instance) + { + super(category, field, instance); + } + + @Override + public String[] getKeys() + { + return asArray(this.category + "." + this.name); + } + + @Override + public boolean hasKey(String name) + { + return (this.category + "." + this.name).equals(name); + } + + @Override + public boolean handlesKey(String name) + { + return hasKey(name); + } + + @Override + public void setupConfiguration(Configuration cfg, String desc, String langKey, boolean reqMCRestart, boolean reqWorldRestart) + { + Property prop = cfg.getCategory(this.category).get(this.name); // Will be setup in general by ConfigManager + + prop.setComment(desc); + prop.setLanguageKey(langKey); + prop.setRequiresMcRestart(reqMCRestart); + prop.setRequiresWorldRestart(reqWorldRestart); + } + + @Override + public String getCategory() + { + return category; + } + + } + + private static T[] asArray(T... in) + { + return in; + } + + public static class BeanEntry implements Entry + { + private K key; + private V value; + + public BeanEntry(K key, V value) + { + this.key = key; + this.value = value; + } + + @Override + public K getKey() + { + return key; + } + + @Override + public V getValue() + { + return value; + } + + @Override + public V setValue(V value) + { + throw new UnsupportedOperationException("This is a static bean."); + } + + } +} diff --git a/src/main/java/net/minecraftforge/common/config/IFieldWrapper.java b/src/main/java/net/minecraftforge/common/config/IFieldWrapper.java new file mode 100644 index 0000000000..4af7091fbb --- /dev/null +++ b/src/main/java/net/minecraftforge/common/config/IFieldWrapper.java @@ -0,0 +1,35 @@ +package net.minecraftforge.common.config; + +/** + * The objects are expected to get their wrapped field, the owning class, instance and category string on initialization. + */ +public interface IFieldWrapper +{ + + /** + * @return The type adapter to serialize the values returned by getValue. Null if non-primitive. + */ + public ITypeAdapter getTypeAdapter(); + + /** + * @param field the field about which to retrieve information + * @param instance The instance whose field shall be queried. + * @return a list of keys handled by this field + */ + public String[] getKeys(); + + public Object getValue(String key); + + public void setValue(String key, Object value); + + public boolean hasKey(String name); + + public boolean handlesKey(String name); + + public void setupConfiguration(Configuration cfg, String desc, String langKey, boolean reqMCRestart, boolean reqWorldRestart); + + /** + * @return the category name in which the entries should be saved. + */ + public String getCategory(); +} diff --git a/src/main/java/net/minecraftforge/common/config/ITypeAdapter.java b/src/main/java/net/minecraftforge/common/config/ITypeAdapter.java index dec99d121b..ed157a169d 100644 --- a/src/main/java/net/minecraftforge/common/config/ITypeAdapter.java +++ b/src/main/java/net/minecraftforge/common/config/ITypeAdapter.java @@ -18,16 +18,17 @@ */ package net.minecraftforge.common.config; -import java.lang.reflect.Field; +import net.minecraftforge.common.config.Property.Type; interface ITypeAdapter { - Property getProp(Configuration cfg, String category, Field field, Object instance, String comment); + void setDefaultValue(Property property, Object value); + + void setValue(Property property, Object value); Object getValue(Property prop); - public interface Map extends ITypeAdapter - { - Property getProp(Configuration cfg, String category, String name, Object value); - } + Type getType(); + + boolean isArrayAdapter(); } diff --git a/src/main/java/net/minecraftforge/common/config/TypeAdapters.java b/src/main/java/net/minecraftforge/common/config/TypeAdapters.java index 318183a26c..ea22999f49 100644 --- a/src/main/java/net/minecraftforge/common/config/TypeAdapters.java +++ b/src/main/java/net/minecraftforge/common/config/TypeAdapters.java @@ -19,7 +19,6 @@ package net.minecraftforge.common.config; -import java.lang.reflect.Field; //========================================================= // Run away thar' be dragons! //========================================================= @@ -32,6 +31,8 @@ import com.google.common.primitives.Floats; import com.google.common.primitives.Ints; import com.google.common.primitives.Shorts; +import net.minecraftforge.common.config.Property.Type; + class TypeAdapters { /* @@ -44,179 +45,453 @@ class TypeAdapters * int, int[], Integer, Integer[] * String, String[] */ - static ITypeAdapter bool = new TypeAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), getBoolean(instance, field), comment); - } + static ITypeAdapter bool = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return prop.getBoolean(); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValue((Boolean)value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValue((Boolean)value); + } + @Override + public Type getType() + { + return Type.BOOLEAN; + } + @Override + public boolean isArrayAdapter() + { + return false; + } }; - static ITypeAdapter boolA = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), (boolean[])getObject(instance, field), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, (boolean[])value, null); - } + static ITypeAdapter boolA = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return prop.getBooleanList(); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValues((boolean[])value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValues((boolean[])value); + } + @Override + public Type getType() + { + return Type.BOOLEAN; + } + @Override + public boolean isArrayAdapter() + { + return true; + } }; - static ITypeAdapter Bool = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), (Boolean)getObject(instance, field), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, (Boolean)value, null); - } + static ITypeAdapter Bool = new ITypeAdapter() { public Object getValue(Property prop) { return Boolean.valueOf(prop.getBoolean()); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValue((Boolean)value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValue((Boolean)value); + } + @Override + public Type getType() + { + return Type.BOOLEAN; + } + @Override + public boolean isArrayAdapter() + { + return false; + } }; - static ITypeAdapter BoolA = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), Booleans.toArray(Arrays.asList((Boolean[])getObject(instance, field))), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, (Boolean)value, null); - } + static ITypeAdapter BoolA = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return Booleans.asList(prop.getBooleanList()).toArray(new Boolean[prop.getBooleanList().length]); } - }; - static ITypeAdapter flt = new TypeAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), getFloat(instance, field), comment); + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValues(Booleans.toArray(Arrays.asList((Boolean[]) value))); } + @Override + public void setValue(Property property, Object value) + { + property.setValues(Booleans.toArray(Arrays.asList((Boolean[]) value))); + } + @Override + public Type getType() + { + return Type.BOOLEAN; + } + @Override + public boolean isArrayAdapter() + { + return true; + } + }; + static ITypeAdapter flt = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return (float)prop.getDouble(); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValue((Float)value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValue((Float)value); + } + @Override + public Type getType() + { + return Type.DOUBLE; + } + @Override + public boolean isArrayAdapter() + { + return false; + } }; - static ITypeAdapter fltA = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), Doubles.toArray(Floats.asList((float[])getObject(instance, field))), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, Doubles.toArray(Floats.asList((float[])value)), null); - } + static ITypeAdapter fltA = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return Floats.toArray(Doubles.asList(prop.getDoubleList())); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValues(Doubles.toArray(Floats.asList((float[])value))); + } + @Override + public void setValue(Property property, Object value) + { + property.setValues(Doubles.toArray(Floats.asList((float[])value))); + } + @Override + public Type getType() + { + return Type.DOUBLE; + } + @Override + public boolean isArrayAdapter() + { + return true; + } }; - static ITypeAdapter Flt = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), (Float)getObject(instance, field), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, (Float)value, null); - } + static ITypeAdapter Flt = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return Float.valueOf((float)prop.getDouble()); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValue((Float)value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValue((Float)value); + } + @Override + public Type getType() + { + return Type.DOUBLE; + } + @Override + public boolean isArrayAdapter() + { + return false; + } }; - static ITypeAdapter FltA = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), Doubles.toArray(Arrays.asList((Float[])getObject(instance, field))), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, Doubles.toArray(Arrays.asList((Float[])value)), null); - } + static ITypeAdapter FltA = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return Floats.asList(Floats.toArray(Doubles.asList(prop.getDoubleList()))).toArray(new Float[prop.getDoubleList().length]); } - }; - static ITypeAdapter dbl = new TypeAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), getDouble(instance, field), comment); + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValues(Doubles.toArray(Arrays.asList((Float[])value))); } - public Object getValue(Property prop) { + @Override + public void setValue(Property property, Object value) + { + property.setValues(Doubles.toArray(Arrays.asList((Float[])value))); + } + @Override + public Type getType() + { + return Type.DOUBLE; + } + @Override + public boolean isArrayAdapter() + { + return true; + } + }; + static ITypeAdapter dbl = new ITypeAdapter() { + @Override + public Object getValue(Property prop) + { return prop.getDouble(); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValue((Double)value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValue((Double)value); + } + @Override + public Type getType() + { + return Type.DOUBLE; + } + @Override + public boolean isArrayAdapter() + { + return false; + } }; - static ITypeAdapter dblA = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), (double[])getObject(instance, field), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, (double[])value, null); - } + static ITypeAdapter dblA = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return prop.getDoubleList(); } + + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValues((double[])value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValues((double[])value); + } + + @Override + public Type getType() + { + return Type.DOUBLE; + } + + @Override + public boolean isArrayAdapter() + { + return true; + } }; - static ITypeAdapter Dbl = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), (Double)getObject(instance, field), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, (Double)value, null); - } + static ITypeAdapter Dbl = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return Double.valueOf(prop.getDouble()); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValue((Double)value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValue((Double) value); + } + @Override + public Type getType() + { + return Type.DOUBLE; + } + @Override + public boolean isArrayAdapter() + { + return false; + } }; - static ITypeAdapter DblA = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), Doubles.toArray(Arrays.asList((Double[])getObject(instance, field))), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, Doubles.toArray(Arrays.asList((Double[])value)), null); - } + static ITypeAdapter DblA = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return Doubles.asList(prop.getDoubleList()).toArray(new Double[prop.getDoubleList().length]); } - }; - static ITypeAdapter byt = new TypeAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), getByte(instance, field), comment, Byte.MIN_VALUE, Byte.MAX_VALUE); + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValues(Doubles.toArray(Arrays.asList((Double[])value))); } - public Object getValue(Property prop) { + @Override + public void setValue(Property property, Object value) + { + property.setValues(Doubles.toArray(Arrays.asList((Double[])value))); + } + @Override + public Type getType() + { + return Type.DOUBLE; + } + @Override + public boolean isArrayAdapter() + { + return true; + } + }; + static ITypeAdapter byt = new ITypeAdapter() { + @Override + public Object getValue(Property prop) + { return (byte)prop.getInt(); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValue((Byte)value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValue((Byte)value); + } + @Override + public Type getType() + { + return Type.INTEGER; + } + @Override + public boolean isArrayAdapter() + { + return false; + } }; - static ITypeAdapter bytA = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), Ints.toArray(Bytes.asList((byte[])getObject(instance, field))), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, Ints.toArray(Bytes.asList((byte[])value)), null); - } + static ITypeAdapter bytA = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return Bytes.toArray(Ints.asList(prop.getIntList())); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValues(Ints.toArray(Bytes.asList((byte[])value))); + } + @Override + public void setValue(Property property, Object value) + { + property.setValues(Ints.toArray(Bytes.asList((byte[])value))); + } + @Override + public Type getType() + { + return Type.INTEGER; + } + @Override + public boolean isArrayAdapter() + { + return true; + } }; - static ITypeAdapter Byt = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), (Byte)getObject(instance, field), comment, Byte.MIN_VALUE, Byte.MAX_VALUE); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, (Byte)value, null, Byte.MIN_VALUE, Byte.MAX_VALUE); - } + static ITypeAdapter Byt = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return Byte.valueOf((byte)prop.getInt()); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValue((Byte)value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValue((Byte)value); + } + @Override + public Type getType() + { + return Type.INTEGER; + } + @Override + public boolean isArrayAdapter() + { + return false; + } }; - static ITypeAdapter BytA = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), Ints.toArray(Arrays.asList((Byte[])getObject(instance, field))), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, Ints.toArray(Arrays.asList((Byte[])value)), null); - } + static ITypeAdapter BytA = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return Bytes.asList(Bytes.toArray(Ints.asList(prop.getIntList()))).toArray(new Byte[prop.getIntList().length]); } - }; - static ITypeAdapter chr = new TypeAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), getChar(instance, field), comment, Character.MIN_VALUE, Character.MAX_VALUE); + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValues(Ints.toArray(Arrays.asList((Byte[]) value))); } + @Override + public void setValue(Property property, Object value) + { + property.setValues(Ints.toArray(Arrays.asList((Byte[]) value))); + } + @Override + public Type getType() + { + return Type.INTEGER; + } + @Override + public boolean isArrayAdapter() + { + return true; + } + }; + static ITypeAdapter chr = new ITypeAdapter() { + public Object getValue(Property prop) { return (char)prop.getInt(); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValue((Character)value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValue((Character)value); + } + @Override + public Type getType() + { + return Type.INTEGER; + } + @Override + public boolean isArrayAdapter() + { + return false; + } }; - static ITypeAdapter chrA = new MapAdapter() { + static ITypeAdapter chrA = new ITypeAdapter() { private int[] toPrim(char[] v) { if (v == null) return new int[0]; int[] ret = new int[v.length]; @@ -224,12 +499,7 @@ class TypeAdapters ret[x] = v[x]; return ret; } - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), toPrim((char[])getObject(instance, field)), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, toPrim((char[])value), null); - } + public Object getValue(Property prop) { int[] v = prop.getIntList(); char[] ret = new char[v.length]; @@ -237,19 +507,56 @@ class TypeAdapters ret[x] = (char)v[x]; return ret; } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValues(toPrim((char[])value)); + } + @Override + public void setValue(Property property, Object value) + { + property.setValues(toPrim((char[])value)); + } + + @Override + public Type getType() + { + return Type.INTEGER; + } + + @Override + public boolean isArrayAdapter() + { + return true; + } }; - static ITypeAdapter Chr = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), (Character)getObject(instance, field), comment, Character.MIN_VALUE, Character.MAX_VALUE); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, (Character)value, null, Character.MIN_VALUE, Character.MAX_VALUE); - } + static ITypeAdapter Chr = new ITypeAdapter() { + public Object getValue(Property prop) { return Character.valueOf((char)prop.getInt()); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValue((Character)value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValue((Character)value); + } + @Override + public Type getType() + { + return Type.INTEGER; + } + @Override + public boolean isArrayAdapter() + { + return false; + } }; - static ITypeAdapter ChrA = new MapAdapter() { + static ITypeAdapter ChrA = new ITypeAdapter() { private int[] toPrim(Character[] v) { if (v == null) return new int[0]; int[] ret = new int[v.length]; @@ -257,12 +564,7 @@ class TypeAdapters ret[x] = v[x] == null ? 0 : v[x]; return ret; } - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), toPrim((Character[])getObject(instance, field)), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, toPrim((Character[])value), null); - } + public Object getValue(Property prop) { int[] v = prop.getIntList(); Character[] ret = new Character[v.length]; @@ -270,44 +572,111 @@ class TypeAdapters ret[x] = Character.valueOf((char)v[x]); return ret; } - }; - static ITypeAdapter shrt = new TypeAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), getShort(instance, field), comment, Short.MIN_VALUE, Short.MAX_VALUE); + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValues(toPrim((Character[])value)); } + @Override + public void setValue(Property property, Object value) + { + property.setValues(toPrim((Character[]) value)); + } + + @Override + public Type getType() + { + return Type.INTEGER; + } + + @Override + public boolean isArrayAdapter() + { + return true; + } + + }; + static ITypeAdapter shrt = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return (short)prop.getInt(); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValue((Short)value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValue((Short)value); + } + @Override + public Type getType() + { + return Type.INTEGER; + } + @Override + public boolean isArrayAdapter() + { + return false; + } }; - static ITypeAdapter shrtA = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), Ints.toArray(Shorts.asList((short[])getObject(instance, field))), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, Ints.toArray(Shorts.asList((short[])value)), null); - } + static ITypeAdapter shrtA = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return Shorts.toArray(Ints.asList(prop.getIntList())); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValues(Ints.toArray(Shorts.asList((short[])value))); + } + @Override + public void setValue(Property property, Object value) + { + property.setValues(Ints.toArray(Shorts.asList((short[])value))); + } + @Override + public Type getType() + { + return Type.INTEGER; + } + @Override + public boolean isArrayAdapter() + { + return true; + } + }; - static ITypeAdapter Shrt = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), (Short)getObject(instance, field), comment, Short.MIN_VALUE, Short.MAX_VALUE); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, (Short)value, null, Short.MIN_VALUE, Short.MAX_VALUE); - } + static ITypeAdapter Shrt = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return Short.valueOf((short)prop.getInt()); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValue((Short)value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValue((Short)value); + } + @Override + public Type getType() + { + return Type.INTEGER; + } + @Override + public boolean isArrayAdapter() + { + return false; + } }; - static ITypeAdapter ShrtA = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), Ints.toArray(Arrays.asList((Short[])getObject(instance, field))), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, Ints.toArray(Arrays.asList((Short[])value)), null); - } + static ITypeAdapter ShrtA = new ITypeAdapter() { + @Override public Object getValue(Property prop) { int[] v = prop.getIntList(); Short[] ret = new Short[v.length]; @@ -315,153 +684,181 @@ class TypeAdapters ret[x] = Short.valueOf((short)v[x]); return ret; } - }; - static ITypeAdapter int_ = new TypeAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), getInt(instance, field), comment, Integer.MIN_VALUE, Integer.MAX_VALUE); + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValues(Ints.toArray(Arrays.asList((Short[])value))); } + @Override + public void setValue(Property property, Object value) + { + property.setValues(Ints.toArray(Arrays.asList((Short[])value))); + } + @Override + public Type getType() + { + return Type.INTEGER; + } + @Override + public boolean isArrayAdapter() + { + return true; + } + }; + static ITypeAdapter int_ = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return prop.getInt(); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValue((Integer)value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValue((Integer)value); + } + @Override + public Type getType() + { + return Type.INTEGER; + } + @Override + public boolean isArrayAdapter() + { + return false; + } }; - static ITypeAdapter intA = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), (int[])getObject(instance, field), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, (int[])value, null); - } + static ITypeAdapter intA = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return prop.getIntList(); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValues((int[])value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValues((int[])value); + } + @Override + public Type getType() + { + return Type.INTEGER; + } + @Override + public boolean isArrayAdapter() + { + return true; + } }; - static ITypeAdapter Int = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), (Integer)getObject(instance, field), comment, Integer.MIN_VALUE, Integer.MAX_VALUE); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, (Integer)value, null, Integer.MIN_VALUE, Integer.MAX_VALUE); - } + static ITypeAdapter Int = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return (Integer)prop.getInt(); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValue((Integer)value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValue((Integer)value); + } + @Override + public Type getType() + { + return Type.INTEGER; + } + @Override + public boolean isArrayAdapter() + { + return false; + } }; - static ITypeAdapter IntA = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), Ints.toArray(Arrays.asList((Integer[])getObject(instance, field))), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, Ints.toArray(Arrays.asList((Integer[])value)), null); - } + static ITypeAdapter IntA = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return Ints.asList(prop.getIntList()).toArray(new Integer[prop.getIntList().length]); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValues(Ints.toArray(Arrays.asList((Integer[])value))); + } + @Override + public void setValue(Property property, Object value) + { + property.setValues(Ints.toArray(Arrays.asList((Integer[])value))); + } + @Override + public Type getType() + { + return Type.INTEGER; + } + @Override + public boolean isArrayAdapter() + { + return true; + } }; - static ITypeAdapter.Map Str = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), (String)getObject(instance, field), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, (String)value, null); - } + static ITypeAdapter Str = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return prop.getString(); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValue((String)value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValue((String)value); + } + @Override + public Type getType() + { + return Type.STRING; + } + @Override + public boolean isArrayAdapter() + { + return false; + } }; - static ITypeAdapter StrA = new MapAdapter() { - public Property getProp(Configuration cfg, String category, Field field, Object instance, String comment) { - return cfg.get(category, getName(field), (String[])getObject(instance, field), comment); - } - public Property getProp(Configuration cfg, String category, String name, Object value) { - return cfg.get(category, name, (String[])value, null); - } + static ITypeAdapter StrA = new ITypeAdapter() { + @Override public Object getValue(Property prop) { return prop.getStringList(); } + @Override + public void setDefaultValue(Property property, Object value) + { + property.setDefaultValues((String[])value); + } + @Override + public void setValue(Property property, Object value) + { + property.setValues((String[])value); + } + @Override + public Type getType() + { + return Type.STRING; + } + @Override + public boolean isArrayAdapter() + { + return true; + } }; - - - private static abstract class TypeAdapter implements ITypeAdapter - { - public static boolean getBoolean(Object instance, Field f) - { - try { - return f.getBoolean(instance); - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - public static int getInt(Object instance, Field f) - { - try { - return f.getInt(instance); - } catch (Exception e) { - e.printStackTrace(); - } - return 0; - } - public static Object getObject(Object instance, Field f) - { - try { - return f.get(instance); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - public static byte getByte(Object instance, Field f) - { - try { - return f.getByte(instance); - } catch (Exception e) { - e.printStackTrace(); - } - return 0; - } - public static char getChar(Object instance, Field f) - { - try { - return f.getChar(instance); - } catch (Exception e) { - e.printStackTrace(); - } - return 0; - } - public static double getDouble(Object instance, Field f) - { - try { - return f.getDouble(instance); - } catch (Exception e) { - e.printStackTrace(); - } - return 0; - } - public static float getFloat(Object instance, Field f) - { - try { - return f.getFloat(instance); - } catch (Exception e) { - e.printStackTrace(); - } - return 0; - } - public static short getShort(Object instance, Field f) - { - try { - return f.getShort(instance); - } catch (Exception e) { - e.printStackTrace(); - } - return 0; - } - - public String getName(Field f) - { - if (f.isAnnotationPresent(Config.Name.class)) - return f.getAnnotation(Config.Name.class).value(); - return f.getName(); - } - } - private static abstract class MapAdapter extends TypeAdapter implements ITypeAdapter.Map {} } diff --git a/src/main/java/net/minecraftforge/fml/client/DefaultGuiFactory.java b/src/main/java/net/minecraftforge/fml/client/DefaultGuiFactory.java new file mode 100644 index 0000000000..a5b7f04686 --- /dev/null +++ b/src/main/java/net/minecraftforge/fml/client/DefaultGuiFactory.java @@ -0,0 +1,63 @@ +package net.minecraftforge.fml.client; + +import java.util.Set; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraftforge.fml.client.config.GuiConfig; +import net.minecraftforge.fml.common.ModContainer; + +public class DefaultGuiFactory implements IModGuiFactory +{ + + protected String modid, title; + protected Minecraft minecraft; + + protected DefaultGuiFactory(String modid, String title) + { + this.modid = modid; + this.title = title; + } + + @Override + public boolean hasConfigGui() + { + return true; + } + + @Override + public void initialize(Minecraft minecraftInstance) + { + this.minecraft = minecraftInstance; + } + + @Override + public GuiScreen createConfigGui(GuiScreen parentScreen) + { + return new GuiConfig(parentScreen, modid, title); + } + + @Deprecated + @Override + public Class mainConfigGuiClass() + { + return null; + } + + @Override + public Set runtimeGuiCategories() + { + return null; + } + + @Override + public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) + { + return null; + } + + public static IModGuiFactory forMod(ModContainer mod) + { + return new DefaultGuiFactory(mod.getModId(), mod.getName()); + } +} diff --git a/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java b/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java index 11821d7caf..828811cfca 100644 --- a/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java +++ b/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java @@ -371,6 +371,7 @@ public class FMLClientHandler implements IFMLSidedHandler String className = mc.getGuiClassName(); if (Strings.isNullOrEmpty(className)) { + guiFactories.put(mc, DefaultGuiFactory.forMod(mc)); continue; } try diff --git a/src/main/java/net/minecraftforge/fml/client/FMLConfigGuiFactory.java b/src/main/java/net/minecraftforge/fml/client/FMLConfigGuiFactory.java index 20c34abadd..661a5ae698 100644 --- a/src/main/java/net/minecraftforge/fml/client/FMLConfigGuiFactory.java +++ b/src/main/java/net/minecraftforge/fml/client/FMLConfigGuiFactory.java @@ -104,16 +104,29 @@ public class FMLConfigGuiFactory implements IModGuiFactory return list; } } + + + @Override + public boolean hasConfigGui() + { + return true; + } @Override public void initialize(Minecraft minecraftInstance) { } + @Override + public GuiScreen createConfigGui(GuiScreen parentScreen) + { + return new FMLConfigGuiScreen(parentScreen); + } + @Override public Class mainConfigGuiClass() { - return FMLConfigGuiScreen.class; + return null; } private static final Set fmlCategories = ImmutableSet.of(new RuntimeOptionCategoryElement("HELP", "FML")); diff --git a/src/main/java/net/minecraftforge/fml/client/GuiModList.java b/src/main/java/net/minecraftforge/fml/client/GuiModList.java index 9cc7da0e11..cd5a4604d2 100644 --- a/src/main/java/net/minecraftforge/fml/client/GuiModList.java +++ b/src/main/java/net/minecraftforge/fml/client/GuiModList.java @@ -282,7 +282,15 @@ public class GuiModList extends GuiScreen try { IModGuiFactory guiFactory = FMLClientHandler.instance().getGuiFactoryFor(selectedMod); - GuiScreen newScreen = guiFactory.mainConfigGuiClass().getConstructor(GuiScreen.class).newInstance(this); + GuiScreen newScreen = null; + try + { + newScreen = guiFactory.createConfigGui(this); + } + catch (AbstractMethodError error) + { + newScreen = guiFactory.mainConfigGuiClass().getConstructor(GuiScreen.class).newInstance(this); + } this.mc.displayGuiScreen(newScreen); } catch (Exception e) @@ -415,8 +423,18 @@ public class GuiModList extends GuiScreen IModGuiFactory guiFactory = FMLClientHandler.instance().getGuiFactoryFor(selectedMod); configModButton.visible = true; - configModButton.enabled = guiFactory != null && guiFactory.mainConfigGuiClass() != null; - + configModButton.enabled = false; + if (guiFactory != null) + { + try + { + configModButton.enabled = guiFactory.hasConfigGui(); + } + catch(AbstractMethodError error) + { + configModButton.enabled = guiFactory.mainConfigGuiClass() != null; + } + } lines.add(selectedMod.getMetadata().name); lines.add(String.format("Version: %s (%s)", selectedMod.getDisplayVersion(), selectedMod.getVersion())); lines.add(String.format("Mod ID: '%s' Mod State: %s", selectedMod.getModId(), Loader.instance().getModState(selectedMod))); diff --git a/src/main/java/net/minecraftforge/fml/client/IModGuiFactory.java b/src/main/java/net/minecraftforge/fml/client/IModGuiFactory.java index 340aa9c083..a7d16b667b 100644 --- a/src/main/java/net/minecraftforge/fml/client/IModGuiFactory.java +++ b/src/main/java/net/minecraftforge/fml/client/IModGuiFactory.java @@ -27,6 +27,11 @@ import net.minecraft.client.gui.GuiScreen; import javax.annotation.Nullable; +/** + * This is the interface you need to implement if you want to provide a customized config screen. + * {@link DefaultGuiFactory} provides a default implementation of this interface and will be used + * if the mod does not specify anything else. + */ public interface IModGuiFactory { /** * Called when instantiated to initialize with the active minecraft instance. @@ -34,6 +39,35 @@ public interface IModGuiFactory { * @param minecraftInstance the instance */ public void initialize(Minecraft minecraftInstance); + + /** + * If this method returns false, the config button in the mod list will be disabled + * @return true if this object provides a config gui screen, false otherwise + */ + public boolean hasConfigGui(); + + /** + * Return an initialized {@link GuiScreen}. This screen will be displayed + * when the "config" button is pressed in the mod list. It will + * have a single argument constructor - the "parent" screen, the same as all + * Minecraft GUIs. The expected behaviour is that this screen will replace the + * "mod list" screen completely, and will return to the mod list screen through + * the parent link, once the appropriate action is taken from the config screen. + * + * This config GUI is anticipated to provide configuration to the mod in a friendly + * visual way. It should not be abused to set internals such as IDs (they're gonna + * keep disappearing anyway), but rather, interesting behaviours. This config GUI + * is never run when a server game is running, and should be used to configure + * desired behaviours that affect server state. Costs, mod game modes, stuff like that + * can be changed here. + * + * @param parentScreen The screen to which must be returned when closing the + * returned screen. + * @return A class that will be instantiated on clicks on the config button + * or null if no GUI is desired. + */ + public GuiScreen createConfigGui(GuiScreen parentScreen); + /** * Return the name of a class extending {@link GuiScreen}. This class will * be instantiated when the "config" button is pressed in the mod list. It will @@ -52,12 +86,13 @@ public interface IModGuiFactory { * desired behaviours that affect server state. Costs, mod game modes, stuff like that * can be changed here. * + * @deprecated The method {@link IModGuiFactory.maingConfigGui(GuiScreen} is the recommended method. * @return A class that will be instantiated on clicks on the config button * or null if no GUI is desired. */ + @Deprecated public Class mainConfigGuiClass(); - /** * Return a list of the "runtime" categories this mod wishes to populate with * GUI elements. diff --git a/src/main/java/net/minecraftforge/fml/client/config/GuiConfig.java b/src/main/java/net/minecraftforge/fml/client/config/GuiConfig.java index d558474a9f..4bc8a5bdbc 100644 --- a/src/main/java/net/minecraftforge/fml/client/config/GuiConfig.java +++ b/src/main/java/net/minecraftforge/fml/client/config/GuiConfig.java @@ -25,6 +25,7 @@ import static net.minecraftforge.fml.client.config.GuiUtils.UNDO_CHAR; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; +import java.util.Comparator; import java.util.List; import net.minecraft.client.Minecraft; @@ -33,6 +34,8 @@ import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraft.util.text.TextComponentString; import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.config.ConfigElement; +import net.minecraftforge.common.config.ConfigManager; import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; @@ -80,6 +83,59 @@ public class GuiConfig extends GuiScreen protected HoverChecker undoHoverChecker; protected HoverChecker resetHoverChecker; protected HoverChecker checkBoxHoverChecker; + + /** + * This constructor handles the {@code @Config} configuration classes + * @param parentScreen the parent GuiScreen object + * @param mod the mod for which to create a screen + */ + public GuiConfig(GuiScreen parentScreen, String modid, String title) + { + this(parentScreen, modid, false, false, title, ConfigManager.getModConfigClasses(modid)); + } + + /** + * + * @param parentScreen the parrent GuiScreen object + * @param modID the mod ID for the mod whose config settings will be editted + * @param allRequireWorldRestart whether all config elements on this screen require a world restart + * @param allRequireMcRestart whether all config elements on this screen require a game restart + * @param title the desired title for this screen. For consistency it is recommended that you pass the path of the config file being + * edited. + * @param configClasses an array of classes annotated with {@code @Config} providing the configuration + */ + public GuiConfig(GuiScreen parentScreen, String modID, boolean allRequireWorldRestart, boolean allRequireMcRestart, String title, + Class... configClasses) + { + this(parentScreen, collectConfigElements(configClasses), modID, null, allRequireWorldRestart, allRequireMcRestart, title, null); + } + + private static List collectConfigElements(Class[] configClasses) + { + List toReturn; + if(configClasses.length == 1) + { + toReturn = ConfigElement.from(configClasses[0]).getChildElements(); + } + else + { + toReturn = new ArrayList(); + for(Class clazz : configClasses) + { + toReturn.add(ConfigElement.from(clazz)); + } + } + toReturn.sort(new Comparator(){ + + @Override + public int compare(IConfigElement e1, IConfigElement e2) + { + return I18n.format(e1.getLanguageKey()).compareTo(I18n.format(e2.getLanguageKey())); + } + + }); + return toReturn; + } /** * GuiConfig constructor that will use ConfigChangedEvent when editing is concluded. If a non-null value is passed for configID, @@ -167,7 +223,25 @@ public class GuiConfig extends GuiScreen this.entryList = new GuiConfigEntries(this, mc); this.initEntries = new ArrayList(entryList.listEntries); this.allRequireWorldRestart = allRequireWorldRestart; + IF:if (!allRequireWorldRestart) + { + for (IConfigElement element : configElements) + { + if (!element.requiresWorldRestart()); + break IF; + } + allRequireWorldRestart = true; + } this.allRequireMcRestart = allRequireMcRestart; + IF:if (!allRequireMcRestart) + { + for (IConfigElement element : configElements) + { + if (!element.requiresMcRestart()); + break IF; + } + allRequireMcRestart = true; + } this.modID = modID; this.configID = configID; this.isWorldRunning = mc.world != null; diff --git a/src/main/java/net/minecraftforge/fml/common/FMLModContainer.java b/src/main/java/net/minecraftforge/fml/common/FMLModContainer.java index 6b31a3cc1b..6b8166f7ef 100644 --- a/src/main/java/net/minecraftforge/fml/common/FMLModContainer.java +++ b/src/main/java/net/minecraftforge/fml/common/FMLModContainer.java @@ -617,7 +617,7 @@ public class FMLModContainer implements ModContainer } ProxyInjector.inject(this, event.getASMHarvestedData(), FMLCommonHandler.instance().getSide(), getLanguageAdapter()); AutomaticEventSubscriber.inject(this, event.getASMHarvestedData(), FMLCommonHandler.instance().getSide()); - ConfigManager.load(this.getModId(), Config.Type.INSTANCE); + ConfigManager.sync(this.getModId(), Config.Type.INSTANCE); processFieldAnnotations(event.getASMHarvestedData()); } diff --git a/src/test/java/net/minecraftforge/debug/ConfigTest.java b/src/test/java/net/minecraftforge/debug/ConfigTest.java index 55ef580cf3..db6f5c1c6c 100644 --- a/src/test/java/net/minecraftforge/debug/ConfigTest.java +++ b/src/test/java/net/minecraftforge/debug/ConfigTest.java @@ -1,21 +1,54 @@ package net.minecraftforge.debug; +import java.util.Map; +import java.util.Set; + +import com.google.common.base.Function; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Config; +import net.minecraftforge.common.config.ConfigManager; import net.minecraftforge.common.config.Config.*; +import net.minecraftforge.fml.client.IModGuiFactory; +import net.minecraftforge.fml.client.config.GuiConfig; +import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; @Mod(modid = ConfigTest.MODID, name = "ConfigTest", version = "1.0", acceptableRemoteVersions = "*") public class ConfigTest { public static final String MODID = "config_test"; - + @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { MinecraftForge.EVENT_BUS.register(this); } + + @Mod.EventHandler + public void init(FMLInitializationEvent event) { + System.out.println("Old: " + CONFIG_TYPES.bool); + CONFIG_TYPES.bool = !CONFIG_TYPES.bool; + System.out.println("New: " + CONFIG_TYPES.bool); + ConfigManager.sync(MODID, Type.INSTANCE); + System.out.println("After sync: " + CONFIG_TYPES.bool); + } + + @SubscribeEvent + public void onConfigChangedEvent(OnConfigChangedEvent event) { + if (event.getModID().equals(MODID)) + { + ConfigManager.sync(MODID, Type.INSTANCE); + } + } + @LangKey("config_test.config.types") @Config(modid = MODID, type = Type.INSTANCE, name = MODID + "_types") public static class CONFIG_TYPES { @@ -58,6 +91,7 @@ public class ConfigTest public String HeyLook = "I'm Inside!"; } } + @LangKey("config_test.config.annotations") @Config(modid = MODID) public static class CONFIG_ANNOTATIONS { @@ -79,6 +113,7 @@ public class ConfigTest public String HeyLook = "Go in!"; } } + @LangKey("config_test.config.subcats") @Config(modid = MODID, name = MODID + "_subcats", category = "") public static class CONFIG_SUBCATS { @@ -92,11 +127,34 @@ public class ConfigTest public static class SubCat { @Name("i_say") - public static String value; + public String value; public SubCat(String value) { this.value = value; } } } + + @LangKey("config_test.config.maps") + @Config(modid = MODID, name = MODID + "_map") + public static class CONFIG_MAP + { + @Name("map") + @RequiresMcRestart + public static Map theMap; + + static + { + theMap = Maps.newHashMap(); + for (int i = 0; i < 7; i++) + { + Integer[] array = new Integer[6]; + for (int x = 0; x < array.length; x++) + { + array[x] = i + x; + } + theMap.put("" + i, array); + } + } + } } diff --git a/src/test/resources/assets/config_test/lang/en_US.lang b/src/test/resources/assets/config_test/lang/en_US.lang new file mode 100644 index 0000000000..b215fad68d --- /dev/null +++ b/src/test/resources/assets/config_test/lang/en_US.lang @@ -0,0 +1,4 @@ +config_test.config.types=Field Types +config_test.config.annotations=Annotations +config_test.config.subcats=Subcategories +config_test.config.maps=Maps \ No newline at end of file diff --git a/src/test/resources/mcmod.info b/src/test/resources/mcmod.info new file mode 100644 index 0000000000..6fd11aa4ab --- /dev/null +++ b/src/test/resources/mcmod.info @@ -0,0 +1,16 @@ +[ +{ + "modid": "config_test", + "name": "ConfigTest", + "description": "Tests config", + "version": "1.0", + "mcversion": "", + "url": "", + "updateUrl": "", + "authorList": [""], + "credits": "", + "logoFile": "", + "screenshots": [], + "dependencies": [] +} +] \ No newline at end of file