diff --git a/src/main/java/slimeknights/mantle/common/IRegisterUtil.java b/src/main/java/slimeknights/mantle/common/IRegisterUtil.java index 0b48c48..09171d1 100644 --- a/src/main/java/slimeknights/mantle/common/IRegisterUtil.java +++ b/src/main/java/slimeknights/mantle/common/IRegisterUtil.java @@ -77,7 +77,7 @@ public interface IRegisterUtil { * @param block Block to get item block * @return Registered item block */ - default BlockItem registerItemBlock(IForgeRegistry registry, Block block) { + default BlockItem registerBlockItem(IForgeRegistry registry, Block block) { BlockItem itemBlock = new BlockItem(block, new Item.Properties()); return this.register(registry, itemBlock, block.getRegistryName()); } @@ -90,7 +90,7 @@ public interface IRegisterUtil { * @param group Group for the item block * @return Registered item block */ - default BlockItem registerItemBlock(IForgeRegistry registry, Block block, ItemGroup group) { + default BlockItem registerBlockItem(IForgeRegistry registry, Block block, ItemGroup group) { BlockItem itemBlock = new BlockItem(block, new Item.Properties().group(group)); return this.register(registry, itemBlock, block.getRegistryName()); } @@ -102,7 +102,7 @@ public interface IRegisterUtil { * @param itemBlock Item block instance to register * @return Registered item block */ - default T registerItemBlock(IForgeRegistry registry, T itemBlock) { + default T registerBlockItem(IForgeRegistry registry, T itemBlock) { return this.register(registry, itemBlock, itemBlock.getBlock().getRegistryName()); } @@ -144,9 +144,9 @@ public interface IRegisterUtil { * @param blocks Blocks needing item blocks * @return Registered item blocks */ - default List registerItemBlocks(IForgeRegistry registry, List blocks) { + default List registerBlockItems(IForgeRegistry registry, List blocks) { return blocks.stream().map((block) -> { - return this.registerItemBlock(registry, block); + return this.registerBlockItem(registry, block); }).collect(Collectors.toList()); } @@ -158,9 +158,9 @@ public interface IRegisterUtil { * @param group Group for the item blocks * @return Registered item blocks */ - default List registerItemBlocks(IForgeRegistry registry, List blocks, ItemGroup group) { + default List registerBlockItems(IForgeRegistry registry, List blocks, ItemGroup group) { return blocks.stream().map((block) -> { - return this.registerItemBlock(registry, block, group); + return this.registerBlockItem(registry, block, group); }).collect(Collectors.toList()); } @@ -172,9 +172,9 @@ public interface IRegisterUtil { * @param constructor ItemBlock constructor * @return Registered item block */ - default List registerItemBlocks(IForgeRegistry registry, List blocks, Function constructor) { + default List registerBlockItems(IForgeRegistry registry, List blocks, Function constructor) { return blocks.stream().map((block) -> { - return this.registerItemBlock(registry, constructor.apply(block)); + return this.registerBlockItem(registry, constructor.apply(block)); }).collect(Collectors.toList()); } } diff --git a/src/main/java/slimeknights/mantle/pulsar/config/IConfiguration.java b/src/main/java/slimeknights/mantle/pulsar/config/IConfiguration.java index 4350ab4..0eb3304 100644 --- a/src/main/java/slimeknights/mantle/pulsar/config/IConfiguration.java +++ b/src/main/java/slimeknights/mantle/pulsar/config/IConfiguration.java @@ -1,9 +1,9 @@ package slimeknights.mantle.pulsar.config; -import javax.annotation.ParametersAreNonnullByDefault; - import slimeknights.mantle.pulsar.pulse.PulseMeta; +import javax.annotation.ParametersAreNonnullByDefault; + /** * Interface for config handlers. * @@ -12,34 +12,34 @@ import slimeknights.mantle.pulsar.pulse.PulseMeta; @ParametersAreNonnullByDefault public interface IConfiguration { - /** - * Perform any configuration loading required. - */ - void load(); + /** + * Perform any configuration loading required. + */ + void load(); - /** - * Perform anything after all pulses have been registered. - */ - void postLoad(); + /** + * Perform anything after all pulses have been registered. + */ + void postLoad(); - /** - * Gets whether the given module is enabled in the config. - * - * @param meta The pulse metadata. - * @return Whether the module is enabled. - */ - boolean isModuleEnabled(PulseMeta meta); + /** + * Gets whether the given module is enabled in the config. + * + * @param meta The pulse metadata. + * @return Whether the module is enabled. + */ + boolean isModuleEnabled(PulseMeta meta); - /** - * Perform any action whenever a new pulse get's registered. - * - * @param meta The pulse metadata. - * @return Whether the module is enabled. - */ - void addPulse(PulseMeta meta); + /** + * Perform any action whenever a new pulse get's registered. + * + * @param meta The pulse metadata. + * @return Whether the module is enabled. + */ + void addPulse(PulseMeta meta); - /** - * Flush configuration to disk/database/whatever. - */ - void flush(); + /** + * Flush configuration to disk/database/whatever. + */ + void flush(); } diff --git a/src/main/java/slimeknights/mantle/pulsar/config/PulsarConfig.java b/src/main/java/slimeknights/mantle/pulsar/config/PulsarConfig.java index 547729f..9fe4ca8 100644 --- a/src/main/java/slimeknights/mantle/pulsar/config/PulsarConfig.java +++ b/src/main/java/slimeknights/mantle/pulsar/config/PulsarConfig.java @@ -7,7 +7,6 @@ import net.minecraftforge.fml.loading.FMLPaths; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import slimeknights.mantle.pulsar.control.PulseManager; -import slimeknights.mantle.pulsar.internal.Configuration; import slimeknights.mantle.pulsar.pulse.PulseMeta; import javax.annotation.Nonnull; @@ -16,70 +15,70 @@ import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; -public class PulsarConfig implements IConfiguration -{ - private static final Logger LOGGER = LogManager.getLogger(); +public class PulsarConfig implements IConfiguration { - private final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder(); - private ForgeConfigSpec SPEC = this.BUILDER.build(); + private static final Logger LOGGER = LogManager.getLogger(); - private final CommentedFileConfig config; + private final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder(); + private ForgeConfigSpec SPEC = this.BUILDER.build(); - private final String description; + private final CommentedFileConfig config; - private boolean builderPushed; - private boolean configBuilt; - private final Map modules = new LinkedHashMap<>(); + private final String description; - /** - * Creates the config to be used later. - * - * Do NOT make this the same as the overall mod configuration; it will clobber it! - * - * @param confName The config file name (without path or .toml suffix) - * @param description The description for the group that the config entries will be placed in. - */ - public PulsarConfig(String confName, String description) { - this.config = this.createConfig(FMLPaths.CONFIGDIR.get(), confName); - this.description = description.toLowerCase(Locale.US); - this.builderPushed = false; - this.configBuilt = false; - this.BUILDER.push(this.description); + private boolean configBuilt; + private final Map modules = new LinkedHashMap<>(); + + /** + * Creates the config to be used later. + * + * Do NOT make this the same as the overall mod configuration; it will clobber it! + * + * @param confName The config file name (without path or .toml suffix) + * @param description The description for the group that the config entries will be placed in. + */ + public PulsarConfig(String confName, String description) { + this.config = this.createConfig(FMLPaths.CONFIGDIR.get(), confName); + this.description = description.toLowerCase(Locale.US); + this.configBuilt = false; + this.BUILDER.push(this.description); + } + + @Override + public void load() { + } + + @Override + public void postLoad() { + if (!this.configBuilt) { + this.BUILDER.pop(); + this.SPEC = this.BUILDER.build(); + this.SPEC.setConfig(this.config); } - @Override - public void load() {} + this.configBuilt = true; + } - @Override - public void postLoad() { - if(!this.configBuilt) { - this.BUILDER.pop(); - this.SPEC = this.BUILDER.build(); - this.SPEC.setConfig(this.config); - } + @Override + public boolean isModuleEnabled(@Nonnull PulseMeta meta) { + ForgeConfigSpec.BooleanValue entry = this.modules.get(meta.getId()); - this.configBuilt = true; + if (entry == null) { + this.modules.put(meta.getId(), this.BUILDER.comment(meta.getDescription()).worldRestart().define(meta.getId(), meta.isDefaultEnabled())); + return meta.isEnabled(); } - - @Override - public boolean isModuleEnabled(@Nonnull PulseMeta meta) { - ForgeConfigSpec.BooleanValue entry = this.modules.get(meta.getId()); - - if (entry == null) { - this.modules.put(meta.getId(), this.BUILDER.comment(meta.getDescription()).worldRestart().define(meta.getId(), meta.isDefaultEnabled())); - return meta.isEnabled(); - } else { - return entry.get(); - } + else { + return entry.get(); } + } - @Override - public void addPulse(@Nonnull PulseMeta meta) { - ForgeConfigSpec.BooleanValue entry = this.modules.get(meta.getId()); - if (entry == null) { - this.modules.put(meta.getId(), this.BUILDER.comment(meta.getDescription()).worldRestart().define(meta.getId(), meta.isDefaultEnabled())); - } + @Override + public void addPulse(@Nonnull PulseMeta meta) { + ForgeConfigSpec.BooleanValue entry = this.modules.get(meta.getId()); + if (entry == null) { + this.modules.put(meta.getId(), this.BUILDER.comment(meta.getDescription()).worldRestart().define(meta.getId(), meta.isDefaultEnabled())); } + } /*@Override public boolean isModuleEnabled(ForgeConfigSpec.BooleanValue configValue) { @@ -93,17 +92,17 @@ public class PulsarConfig implements IConfiguration return value; }*/ - @Override - public void flush() { - this.config.save(); - } + @Override + public void flush() { + this.config.save(); + } - public CommentedFileConfig createConfig(Path configBasePath, String configName) { - final Path configPath = configBasePath.resolve(String.format("%s.toml", configName)); - final CommentedFileConfig configData = CommentedFileConfig.builder(configPath).sync().autosave().writingMode(WritingMode.REPLACE).build(); - LOGGER.debug(PulseManager.CONFIG, "Built TOML config for {}", configPath.toString()); - configData.load(); - LOGGER.debug(PulseManager.CONFIG, "Loaded TOML config file {}", configPath.toString()); - return configData; - } + public CommentedFileConfig createConfig(Path configBasePath, String configName) { + final Path configPath = configBasePath.resolve(String.format("%s.toml", configName)); + final CommentedFileConfig configData = CommentedFileConfig.builder(configPath).sync().autosave().writingMode(WritingMode.REPLACE).build(); + LOGGER.debug(PulseManager.CONFIG, "Built TOML config for {}", configPath.toString()); + configData.load(); + LOGGER.debug(PulseManager.CONFIG, "Loaded TOML config file {}", configPath.toString()); + return configData; + } } diff --git a/src/main/java/slimeknights/mantle/pulsar/control/PulseManager.java b/src/main/java/slimeknights/mantle/pulsar/control/PulseManager.java index 28f21a4..a403190 100644 --- a/src/main/java/slimeknights/mantle/pulsar/control/PulseManager.java +++ b/src/main/java/slimeknights/mantle/pulsar/control/PulseManager.java @@ -1,8 +1,6 @@ package slimeknights.mantle.pulsar.control; import net.minecraft.util.ResourceLocation; -import net.minecraftforge.common.ForgeConfigSpec.BooleanValue; - import net.minecraftforge.eventbus.EventBus; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.SubscribeEvent; @@ -14,15 +12,6 @@ import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLModContainer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; - -import java.lang.reflect.Field; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -import javax.annotation.ParametersAreNonnullByDefault; - import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; import slimeknights.mantle.pulsar.config.IConfiguration; @@ -35,6 +24,13 @@ import slimeknights.mantle.pulsar.internal.CrashHandler; import slimeknights.mantle.pulsar.pulse.Pulse; import slimeknights.mantle.pulsar.pulse.PulseMeta; +import javax.annotation.ParametersAreNonnullByDefault; +import java.lang.reflect.Field; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + /** * Manager class for a given mods Pulses. * @@ -50,268 +46,289 @@ import slimeknights.mantle.pulsar.pulse.PulseMeta; @ParametersAreNonnullByDefault public class PulseManager { - private Logger log; - private final boolean useConfig; + private Logger log; + private final boolean useConfig; - private static final Map> ALL_PULSES = new HashMap<>(); - private final Map pulses = new LinkedHashMap<>(); - private final Map allPulses = new LinkedHashMap<>(); - // Use the Google @Subscribe to avoid confusion/breaking changes. - private final Flightpath flightpath = new Flightpath(new AnnotationLocator(SubscribeEvent.class)); + private static final Map> ALL_PULSES = new HashMap<>(); + private final Map pulses = new LinkedHashMap<>(); + private final Map allPulses = new LinkedHashMap<>(); + // Use the Google @Subscribe to avoid confusion/breaking changes. + private final Flightpath flightpath = new Flightpath(new AnnotationLocator(SubscribeEvent.class)); - private boolean blockNewRegistrations = false; - private boolean configLoaded = false; - private IConfiguration conf; - private String id; + private boolean blockNewRegistrations = false; + private boolean configLoaded = false; + private IConfiguration conf; + private String id; - public static final Marker CONFIG = MarkerManager.getMarker("PULSARCONFIG"); + public static final Marker CONFIG = MarkerManager.getMarker("PULSARCONFIG"); - /** - * Configuration-using constructor. - * - * This form creates a PulseManager that supports configuration of Pulses by file. - * - * @param configName The config file name. - */ - public PulseManager(String configName) { - this.init(); - this.useConfig = true; - this.conf = new Configuration(configName, this.log); + /** + * Configuration-using constructor. + * + * This form creates a PulseManager that supports configuration of Pulses by file. + * + * @param configName The config file name. + */ + public PulseManager(String configName) { + this.init(); + this.useConfig = true; + this.conf = new Configuration(configName, this.log); + } + + /** + * Custom configuration-using constructor. + * + * Don't like JSON? Heathen. Lets you handle configuration, to whatever media you like - File, database, death star. + * Whatever really. See {@link slimeknights.mantle.pulsar.config.IConfiguration}. + * + * @param config Configuration handler. + */ + public PulseManager(IConfiguration config) { + this.init(); + this.useConfig = true; + this.conf = config; + } + + /** + * Shared initialiser code between all the constructors. + */ + private void init() { + String modId = ModLoadingContext.get().getActiveContainer().getNamespace(); + this.id = modId; + this.log = LogManager.getLogger("Pulsar-" + modId); + this.flightpath.setExceptionHandler(new BusExceptionHandler(modId)); + CrashReportExtender.registerCrashCallable(new CrashHandler(modId, this)); + // regsister our pulse loader so it can be found by the static method + ALL_PULSES.put(modId, this.pulses); + // Attach us to the mods FML bus + this.attachToContainerEventBus(this); + } + + /** + * Overrides Pulsars default behaviour when a pulse emits an exception. See Flightpath's documentation. + * + * @param handler The Flightpath-compatible exception handler to use. + */ + public void setPulseExceptionHandler(IExceptionHandler handler) { + this.flightpath.setExceptionHandler(handler); + } + + /** + * Register a new Pulse with the manager. + * + * This CANNOT be done after preinit has been invoked. + * + * @param pulse The Pulse to register. + */ + public void registerPulse(Object pulse) { + if (this.blockNewRegistrations) { + throw new RuntimeException("A mod tried to register a plugin after preinit! Pulse: " + + pulse); + } + if (!this.configLoaded) { + this.conf.load(); + + this.configLoaded = true; } - /** - * Custom configuration-using constructor. - * - * Don't like JSON? Heathen. Lets you handle configuration, to whatever media you like - File, database, death star. - * Whatever really. See {@link slimeknights.mantle.pulsar.config.IConfiguration}. - * - * @param config Configuration handler. - */ - public PulseManager(IConfiguration config) { - this.init(); - this.useConfig = true; - this.conf = config; + String id, description, deps, pulseDeps; + boolean forced, enabled, defaultEnabled, missingDeps = false; + + try { + Pulse p = pulse.getClass().getAnnotation(Pulse.class); + id = p.id(); + description = p.description(); + deps = p.modsRequired(); + pulseDeps = p.pulsesRequired(); + forced = p.forced(); + enabled = p.defaultEnable(); + defaultEnabled = p.defaultEnable(); + } + catch (NullPointerException ex) { + throw new RuntimeException("Could not parse @Pulse annotation for Pulse: " + pulse); } - /** - * Shared initialiser code between all the constructors. - */ - private void init() { - String modId = ModLoadingContext.get().getActiveContainer().getNamespace(); - this.id = modId; - this.log = LogManager.getLogger("Pulsar-" + modId); - this.flightpath.setExceptionHandler(new BusExceptionHandler(modId)); - CrashReportExtender.registerCrashCallable(new CrashHandler(modId, this)); - // regsister our pulse loader so it can be found by the static method - ALL_PULSES.put(modId, this.pulses); - // Attach us to the mods FML bus - this.attachToContainerEventBus(this); + // Work around Java not allowing default-null fields. + if (description.equals("")) { + description = null; } - /** - * Overrides Pulsars default behaviour when a pulse emits an exception. See Flightpath's documentation. - * - * @param handler The Flightpath-compatible exception handler to use. - */ - public void setPulseExceptionHandler(IExceptionHandler handler) { - this.flightpath.setExceptionHandler(handler); - } - - /** - * Register a new Pulse with the manager. - * - * This CANNOT be done after preinit has been invoked. - * - * @param pulse The Pulse to register. - */ - public void registerPulse(Object pulse) { - if (this.blockNewRegistrations) throw new RuntimeException("A mod tried to register a plugin after preinit! Pulse: " - + pulse); - if (!this.configLoaded) { - this.conf.load(); - - this.configLoaded = true; + if (!deps.equals("")) { + String[] parsedDeps = deps.split(";"); + for (String s : parsedDeps) { + if (!ModList.get().isLoaded(s)) { + this.log.info("Skipping Pulse " + id + "; missing dependency: " + s); + missingDeps = true; + enabled = false; + break; } + } + } - String id, description, deps, pulseDeps; - boolean forced, enabled, defaultEnabled, missingDeps = false; + PulseMeta meta = new PulseMeta(id, description, forced, enabled, defaultEnabled); + meta.setMissingDeps(missingDeps || !this.hasRequiredPulses(meta, pulseDeps)); - try { - Pulse p = pulse.getClass().getAnnotation(Pulse.class); - id = p.id(); - description = p.description(); - deps = p.modsRequired(); - pulseDeps = p.pulsesRequired(); - forced = p.forced(); - enabled = p.defaultEnable(); - defaultEnabled = p.defaultEnable(); - } catch (NullPointerException ex) { - throw new RuntimeException("Could not parse @Pulse annotation for Pulse: " + pulse); + if (meta.isForced() || !this.useConfig) { + this.allPulses.put(pulse, meta); + } + else { + this.conf.addPulse(meta); + this.allPulses.put(pulse, meta); + } + } + + /** + * Helper to attach a given object to the mod container event bus. + * + * @param obj Object to register. + */ + private void attachToContainerEventBus(Object obj) { + ModContainer cnt = ModLoadingContext.get().getActiveContainer(); + this.log.debug("Attaching [" + obj + "] to event bus for container [" + cnt + "]"); + try { + FMLModContainer mc = (FMLModContainer) cnt; + Field ebf = mc.getClass().getDeclaredField("eventBus"); + + boolean access = ebf.isAccessible(); + ebf.setAccessible(true); + EventBus eb = (EventBus) ebf.get(mc); + ebf.setAccessible(access); + + eb.register(obj); + } + catch (NoSuchFieldException nsfe) { + throw new RuntimeException("Pulsar >> Incompatible FML mod container (missing eventBus field) - wrong Forge version?"); + } + catch (IllegalAccessException iae) { + throw new RuntimeException("Pulsar >> Security Manager blocked access to eventBus on mod container. Cannot continue."); + } + catch (ClassCastException cce) { + throw new RuntimeException("Pulsar >> Something in the mod container had the wrong type? " + cce.getMessage()); + } + } + + /** + * Internal (but public for EventBus use) handler for events. + * + * DO NOT CALL THIS DIRECTLY! Let EventBus handle it. + * + * @param evt An event object. + */ + @SubscribeEvent + public void propagateEvent(Event evt) { + if (evt instanceof FMLCommonSetupEvent) { + this.preInit((FMLCommonSetupEvent) evt); + } + // We use individual buses due to the EventBus class using a Set rather than a List, thus losing the ordering. + // This trick is shamelessly borrowed from FML. + this.flightpath.post(evt); + } + + private boolean getEnabledFromConfig(PulseMeta meta) { + if (meta.isForced() || !this.useConfig) { + return true; // Forced or no config set. + } + + return this.conf.isModuleEnabled(meta); + } + + private void preInit(FMLCommonSetupEvent evt) { + if (!this.blockNewRegistrations) { + this.conf.flush(); // First init call, so flush config + } + this.blockNewRegistrations = true; + } + + private boolean hasRequiredPulses(PulseMeta meta, String deps) { + if (!deps.equals("")) { + String[] parsedDeps = deps.split(";"); + for (String s : parsedDeps) { + if (!this.isPulseLoaded(s)) { + this.log.info("Skipping Pulse " + meta.getId() + "; missing pulse: " + s); + return false; } - - // Work around Java not allowing default-null fields. - if (description.equals("")) description = null; - - if (!deps.equals("")) { - String[] parsedDeps = deps.split(";"); - for (String s : parsedDeps) { - if (!ModList.get().isLoaded(s)) { - this.log.info("Skipping Pulse " + id + "; missing dependency: " + s); - missingDeps = true; - enabled = false; - break; - } - } - } - - PulseMeta meta = new PulseMeta(id, description, forced, enabled, defaultEnabled); - meta.setMissingDeps(missingDeps || !this.hasRequiredPulses(meta, pulseDeps)); - - this.conf.addPulse(meta); - this.allPulses.put(pulse, meta); + } } + return true; + } - /** - * Helper to attach a given object to the mod container event bus. - * - * @param obj Object to register. - */ - private void attachToContainerEventBus(Object obj) { - ModContainer cnt = ModLoadingContext.get().getActiveContainer(); - this.log.debug("Attaching [" + obj + "] to event bus for container [" + cnt + "]"); - try { - FMLModContainer mc = (FMLModContainer)cnt; - Field ebf = mc.getClass().getDeclaredField("eventBus"); - - boolean access = ebf.isAccessible(); - ebf.setAccessible(true); - EventBus eb = (EventBus)ebf.get(mc); - ebf.setAccessible(access); - - eb.register(obj); - } catch (NoSuchFieldException nsfe) { - throw new RuntimeException("Pulsar >> Incompatible FML mod container (missing eventBus field) - wrong Forge version?"); - } catch (IllegalAccessException iae) { - throw new RuntimeException("Pulsar >> Security Manager blocked access to eventBus on mod container. Cannot continue."); - } catch (ClassCastException cce) { - throw new RuntimeException("Pulsar >> Something in the mod container had the wrong type? " + cce.getMessage()); - } + /** + * Check if a given Pulse ID is loaded in this manager. + * + * @param pulseId The ID to check. If it contains : treats the ID as a resource location and checks the global list + * @return Whether the ID was present. + */ + public boolean isPulseLoaded(String pulseId) { + // if it has a colon, assume its a namespaced ID + if (pulseId.contains(":")) { + return isPulseLoadedGlobal(pulseId); } + return isPulseLoaded(this.pulses, pulseId); + } - /** - * Internal (but public for EventBus use) handler for events. - * - * DO NOT CALL THIS DIRECTLY! Let EventBus handle it. - * - * @param evt An event object. - */ - @SubscribeEvent - public void propagateEvent(Event evt) { - if (evt instanceof FMLCommonSetupEvent) - this.preInit((FMLCommonSetupEvent) evt); - // We use individual buses due to the EventBus class using a Set rather than a List, thus losing the ordering. - // This trick is shamelessly borrowed from FML. - this.flightpath.post(evt); + /** + * Check if a given Pulse ID is loaded in any manager. + * + * @param pulseId Resource location string to check. Domain is the mod ID, path is the pulse ID + * @return Whether the ID was present. + */ + public static boolean isPulseLoadedGlobal(String pulseId) { + ResourceLocation loc = new ResourceLocation(pulseId); + Map pulses = ALL_PULSES.get(loc.getNamespace()); + if (pulses != null) { + return isPulseLoaded(pulses, loc.getPath()); } + return false; + } - private boolean getEnabledFromConfig(PulseMeta meta) { - if (meta.isForced() || !this.useConfig) return true; // Forced or no config set. - - return this.conf.isModuleEnabled(meta); - } - - private void preInit(FMLCommonSetupEvent evt) { - if (!this.blockNewRegistrations) - this.conf.flush(); // First init call, so flush config - this.blockNewRegistrations = true; - } - - private boolean hasRequiredPulses(PulseMeta meta, String deps) { - if (!deps.equals("")) { - String[] parsedDeps = deps.split(";"); - for (String s : parsedDeps) { - if (!this.isPulseLoaded(s)) { - this.log.info("Skipping Pulse " + meta.getId() + "; missing pulse: " + s); - return false; - } - } - } + /** + * Checks whether a pulse is loaded in the given pulse manager + * + * @param pulseId The ID to check. + * @return Whether the ID was present. + */ + private static boolean isPulseLoaded(Map pulses, String pulseId) { + for (Map.Entry entry : pulses.entrySet()) { + if (entry.getValue().getId().equalsIgnoreCase(pulseId)) { return true; + } + } + return false; + } + + public Collection getAllPulseMetadata() { + return this.pulses.values(); + } + + @Override + public String toString() { + return "PulseManager[" + this.id + "]"; + } + + /** + * Enable or Disable all Pulses registered + * + * This MUST be called after you register all your pulses using registerPulse and must be called BEFORE preinit + */ + public void enablePulses() { + if (this.blockNewRegistrations) { + throw new RuntimeException("A mod tried to enable their plugins after preinit!"); } - /** - * Check if a given Pulse ID is loaded in this manager. - * - * @param pulseId The ID to check. If it contains : treats the ID as a resource location and checks the global list - * @return Whether the ID was present. - */ - public boolean isPulseLoaded(String pulseId) { - // if it has a colon, assume its a namespaced ID - if(pulseId.contains(":")) { - return isPulseLoadedGlobal(pulseId); - } - return isPulseLoaded(this.pulses, pulseId); + if (this.configLoaded) { + this.conf.postLoad(); } - /** - * Check if a given Pulse ID is loaded in any manager. - * - * @param pulseId Resource location string to check. Domain is the mod ID, path is the pulse ID - * @return Whether the ID was present. - */ - public static boolean isPulseLoadedGlobal(String pulseId) { - ResourceLocation loc = new ResourceLocation(pulseId); - Map pulses = ALL_PULSES.get(loc.getNamespace()); - if(pulses != null) { - return isPulseLoaded(pulses, loc.getPath()); - } - return false; - } - - /** - * Checks whether a pulse is loaded in the given pulse manager - * - * @param pulseId The ID to check. - * @return Whether the ID was present. - */ - private static boolean isPulseLoaded(Map pulses, String pulseId) { - for(Map.Entry entry : pulses.entrySet()) { - if (entry.getValue().getId().equalsIgnoreCase(pulseId)) { - return true; - } - } - return false; - } - - public Collection getAllPulseMetadata() { - return this.pulses.values(); - } - - @Override - public String toString() { - return "PulseManager[" + this.id + "]"; - } - /** - * Enable or Disable all Pulses registered - * - * This MUST be called after you register all your pulses using registerPulse and must be called BEFORE preinit - */ - public void enablePulses() { - if(this.blockNewRegistrations) throw new RuntimeException("A mod tried to enable their plugins after preinit!"); - - if(this.configLoaded) - this.conf.postLoad(); - - for (Map.Entry entry : this.allPulses.entrySet()) { - PulseMeta meta = entry.getValue(); - Object pulse = entry.getKey(); - - meta.setEnabled(this.getEnabledFromConfig(meta)); - - if (meta.isEnabled()) { - this.pulses.put(pulse, meta); - this.flightpath.register(pulse); - } - } + for (Map.Entry entry : this.allPulses.entrySet()) { + PulseMeta meta = entry.getValue(); + Object pulse = entry.getKey(); + + meta.setEnabled(this.getEnabledFromConfig(meta)); + + if (meta.isEnabled()) { + this.pulses.put(pulse, meta); + this.flightpath.register(pulse); + } } + } } diff --git a/src/main/java/slimeknights/mantle/pulsar/debug/EventSpy.java b/src/main/java/slimeknights/mantle/pulsar/debug/EventSpy.java index 59f31e3..b9fec72 100644 --- a/src/main/java/slimeknights/mantle/pulsar/debug/EventSpy.java +++ b/src/main/java/slimeknights/mantle/pulsar/debug/EventSpy.java @@ -3,11 +3,9 @@ package slimeknights.mantle.pulsar.debug; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.ModLoadingContext; - import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; - import slimeknights.mantle.pulsar.pulse.Pulse; /** @@ -16,19 +14,19 @@ import slimeknights.mantle.pulsar.pulse.Pulse; * @author Arkan */ @SuppressWarnings("unused") -@Pulse(id="EventSpy", description="we iz in ur buses, monitorin ur eventz", forced=true) +@Pulse(id = "EventSpy", description = "we iz in ur buses, monitorin ur eventz", forced = true) public class EventSpy { - private final Logger log = LogManager.getLogger("EventSpy/" + ModLoadingContext.get().getActiveContainer().getNamespace()); + private final Logger log = LogManager.getLogger("EventSpy/" + ModLoadingContext.get().getActiveContainer().getNamespace()); - @SubscribeEvent - public void receive(Event evt) { - this.log.info("Received event: " + evt); - } + @SubscribeEvent + public void receive(Event evt) { + this.log.info("Received event: " + evt); + } - @SubscribeEvent - public void preInit(final FMLCommonSetupEvent evt) { - this.log.info("Example preInit hit"); - } + @SubscribeEvent + public void preInit(final FMLCommonSetupEvent evt) { + this.log.info("Example preInit hit"); + } } diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/Airdrop.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/Airdrop.java index 8c9c2da..9445755 100755 --- a/src/main/java/slimeknights/mantle/pulsar/flightpath/Airdrop.java +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/Airdrop.java @@ -16,4 +16,6 @@ import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented -public @interface Airdrop {} +public @interface Airdrop { + +} diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/Flightpath.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/Flightpath.java index 938f9aa..8558c90 100755 --- a/src/main/java/slimeknights/mantle/pulsar/flightpath/Flightpath.java +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/Flightpath.java @@ -1,116 +1,121 @@ package slimeknights.mantle.pulsar.flightpath; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -import javax.annotation.ParametersAreNonnullByDefault; - import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.IGenericEvent; import slimeknights.mantle.pulsar.flightpath.lib.AnnotationLocator; import slimeknights.mantle.pulsar.flightpath.lib.BlackholeExceptionHandler; +import javax.annotation.ParametersAreNonnullByDefault; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.LinkedHashMap; +import java.util.Map; + /** * Flightpath - an ordered event bus implementation. * * @author Arkan */ @ParametersAreNonnullByDefault -@SuppressWarnings({"unused","unchecked"}) +@SuppressWarnings({ "unused", "unchecked" }) public class Flightpath { - private final ISubscriberLocator locator; - // Note we *MUST* use a linked map, otherwise order is lost. - private final LinkedHashMap, Map>> subscribers = new LinkedHashMap, Map>>(); - // Anything that manipulates state *MUST* acquire this lock. It prevents awkward issues when iterating. - private final Object lock = new Object(); + private final ISubscriberLocator locator; + // Note we *MUST* use a linked map, otherwise order is lost. + private final LinkedHashMap, Map>> subscribers = new LinkedHashMap, Map>>(); + // Anything that manipulates state *MUST* acquire this lock. It prevents awkward issues when iterating. + private final Object lock = new Object(); - private IExceptionHandler exceptionHandler = new BlackholeExceptionHandler(); + private IExceptionHandler exceptionHandler = new BlackholeExceptionHandler(); - /** - * Generates a plain old Flightpath, using the default @Airdrop annotation. - */ - public Flightpath() { - this.locator = new AnnotationLocator(Airdrop.class); + /** + * Generates a plain old Flightpath, using the default @Airdrop annotation. + */ + public Flightpath() { + this.locator = new AnnotationLocator(Airdrop.class); + } + + /** + * Generates a Flightpath using a different locator implementation. + * + * Pass a custom constructed instance of AnnotationLocator to use alternative annotations. + * + * @param locator The locator to be applied to new objects. + */ + public Flightpath(ISubscriberLocator locator) { + this.locator = locator; + } + + /** + * Used to change exception handling behaviour. + * + * @param handler The handler to use. + */ + public void setExceptionHandler(IExceptionHandler handler) { + synchronized (this.lock) { + this.exceptionHandler = handler; } + } - /** - * Generates a Flightpath using a different locator implementation. - * - * Pass a custom constructed instance of AnnotationLocator to use alternative annotations. - * - * @param locator The locator to be applied to new objects. - */ - public Flightpath(ISubscriberLocator locator) { - this.locator = locator; + /** + * Registers a given object onto the bus. + * + * @param obj Object to attach to the bus. + */ + public void register(Object obj) { + synchronized (this.lock) { + if (this.subscribers.containsKey(obj)) { + return; // Nothing to do. + } + this.subscribers.put(obj, this.locator.findSubscribers(obj)); } + } - /** - * Used to change exception handling behaviour. - * - * @param handler The handler to use. - */ - public void setExceptionHandler(IExceptionHandler handler) { - synchronized (this.lock) { - this.exceptionHandler = handler; - } - } + /** + * Posts the given event on the bus. + * + * By default this blackholes exceptions. If you need different behaviour, see setExceptionHandler. + * + * @param evt The event to post. + */ + public void post(Event evt) { + synchronized (this.lock) { + for (Map.Entry, Map>> ent : this.subscribers.entrySet()) { + for (Map.Entry, Map> obj : ent.getValue().entrySet()) { + if (!obj.getKey().isAssignableFrom(evt.getClass())) { + continue; + } + for (Map.Entry objEnt : obj.getValue().entrySet()) { + Method m = objEnt.getKey(); + Type filter = objEnt.getValue(); - /** - * Registers a given object onto the bus. - * - * @param obj Object to attach to the bus. - */ - public void register(Object obj) { - synchronized (this.lock) { - if (this.subscribers.containsKey(obj)) return; // Nothing to do. - this.subscribers.put(obj, this.locator.findSubscribers(obj)); - } - } - - /** - * Posts the given event on the bus. - * - * By default this blackholes exceptions. If you need different behaviour, see setExceptionHandler. - * - * @param evt The event to post. - */ - public void post(Event evt) { - synchronized (this.lock) { - for (Map.Entry, Map>> ent : this.subscribers.entrySet()) { - for (Map.Entry, Map> obj: ent.getValue().entrySet()) { - if (!obj.getKey().isAssignableFrom(evt.getClass())) continue; - for(Map.Entry objEnt : obj.getValue().entrySet()){ - Method m = objEnt.getKey(); - Type filter = objEnt.getValue(); - - try { - if (filter == null || filter == ((IGenericEvent)evt).getGenericType()) { - boolean access = m.isAccessible(); - m.setAccessible(true); - m.invoke(ent.getKey(), evt); - m.setAccessible(access); - } - } catch(InvocationTargetException ex) { - // thrown when a method throws an exception, so use that exception instead of the wrapper for a better stacktrace - if(ex.getTargetException() instanceof Exception) { - this.exceptionHandler.handle((Exception)ex.getTargetException()); - } else { - this.exceptionHandler.handle(ex); - } - } catch (Exception ex) { - // all other exceptions, this means something when wrong with the reflection - this.exceptionHandler.handle(ex); - } - } - } + try { + if (filter == null || filter == ((IGenericEvent) evt).getGenericType()) { + boolean access = m.isAccessible(); + m.setAccessible(true); + m.invoke(ent.getKey(), evt); + m.setAccessible(access); + } } - this.exceptionHandler.flush(); + catch (InvocationTargetException ex) { + // thrown when a method throws an exception, so use that exception instead of the wrapper for a better stacktrace + if (ex.getTargetException() instanceof Exception) { + this.exceptionHandler.handle((Exception) ex.getTargetException()); + } + else { + this.exceptionHandler.handle(ex); + } + } + catch (Exception ex) { + // all other exceptions, this means something when wrong with the reflection + this.exceptionHandler.handle(ex); + } + } } + } + this.exceptionHandler.flush(); } + } } diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/IExceptionHandler.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/IExceptionHandler.java index 782a05a..41f69a9 100755 --- a/src/main/java/slimeknights/mantle/pulsar/flightpath/IExceptionHandler.java +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/IExceptionHandler.java @@ -10,16 +10,16 @@ import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault public interface IExceptionHandler { - /** - * Handle a given exception. - * - * @param ex The exception (duh) - */ - void handle(Exception ex); + /** + * Handle a given exception. + * + * @param ex The exception (duh) + */ + void handle(Exception ex); - /** - * Called after all methods have been invoked for cleanup or coalescing. - */ - void flush(); + /** + * Called after all methods have been invoked for cleanup or coalescing. + */ + void flush(); } diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/ISubscriberLocator.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/ISubscriberLocator.java index 64d6f03..b67e0d2 100755 --- a/src/main/java/slimeknights/mantle/pulsar/flightpath/ISubscriberLocator.java +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/ISubscriberLocator.java @@ -1,12 +1,10 @@ package slimeknights.mantle.pulsar.flightpath; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.util.Map; -import java.util.Set; - import javax.annotation.Nonnull; import javax.annotation.ParametersAreNonnullByDefault; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.Map; /** * Interface for defining custom subscriber scanners. @@ -14,7 +12,7 @@ import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault public interface ISubscriberLocator { - @Nonnull - Map, Map> findSubscribers(Object obj); + @Nonnull + Map, Map> findSubscribers(Object obj); } diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/AnnotationLocator.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/AnnotationLocator.java index e84e9b0..dec67e7 100755 --- a/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/AnnotationLocator.java +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/AnnotationLocator.java @@ -1,19 +1,16 @@ package slimeknights.mantle.pulsar.flightpath.lib; +import net.minecraftforge.eventbus.api.IGenericEvent; +import slimeknights.mantle.pulsar.flightpath.ISubscriberLocator; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; -import java.util.Set; - -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -import net.minecraftforge.eventbus.api.IGenericEvent; -import slimeknights.mantle.pulsar.flightpath.ISubscriberLocator; /** * Default implementation of ISubscriberLocator @@ -23,39 +20,42 @@ import slimeknights.mantle.pulsar.flightpath.ISubscriberLocator; @ParametersAreNonnullByDefault public class AnnotationLocator implements ISubscriberLocator { - private final Class annotation; + private final Class annotation; - public AnnotationLocator(Class annotation) { - this.annotation = annotation; - } + public AnnotationLocator(Class annotation) { + this.annotation = annotation; + } - @Override - public @Nonnull Map, Map> findSubscribers(Object obj) { - Map, Map> methods = new HashMap, Map>(); + @Override + public @Nonnull + Map, Map> findSubscribers(Object obj) { + Map, Map> methods = new HashMap, Map>(); - for (Method m : obj.getClass().getMethods()) { - if (m.isAnnotationPresent(this.annotation) && m.getParameterTypes().length == 1) { - Class param = m.getParameterTypes()[0]; + for (Method m : obj.getClass().getMethods()) { + if (m.isAnnotationPresent(this.annotation) && m.getParameterTypes().length == 1) { + Class param = m.getParameterTypes()[0]; - Type filter = null; + Type filter = null; - if(IGenericEvent.class.isAssignableFrom(param)) { - Type type = m.getGenericParameterTypes()[0]; + if (IGenericEvent.class.isAssignableFrom(param)) { + Type type = m.getGenericParameterTypes()[0]; - if (type instanceof ParameterizedType) { - filter = ((ParameterizedType) type).getActualTypeArguments()[0]; + if (type instanceof ParameterizedType) { + filter = ((ParameterizedType) type).getActualTypeArguments()[0]; - if (filter instanceof ParameterizedType) { - filter = ((ParameterizedType) filter).getRawType(); - } - } - } - - if (!methods.containsKey(param)) methods.put(param, new HashMap()); - methods.get(param).put(m, filter); + if (filter instanceof ParameterizedType) { + filter = ((ParameterizedType) filter).getRawType(); } + } } - return methods; + if (!methods.containsKey(param)) { + methods.put(param, new HashMap()); + } + methods.get(param).put(m, filter); + } } + + return methods; + } } diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/BlackholeExceptionHandler.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/BlackholeExceptionHandler.java index ad47b95..afc6555 100755 --- a/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/BlackholeExceptionHandler.java +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/BlackholeExceptionHandler.java @@ -1,9 +1,9 @@ package slimeknights.mantle.pulsar.flightpath.lib; -import javax.annotation.ParametersAreNonnullByDefault; - import slimeknights.mantle.pulsar.flightpath.IExceptionHandler; +import javax.annotation.ParametersAreNonnullByDefault; + /** * Default exception handler when Flightpath has been asked to ignore errors. * @@ -12,14 +12,14 @@ import slimeknights.mantle.pulsar.flightpath.IExceptionHandler; @ParametersAreNonnullByDefault public class BlackholeExceptionHandler implements IExceptionHandler { - @Override - public void handle(Exception ex) { - // NO-OP - } + @Override + public void handle(Exception ex) { + // NO-OP + } - @Override - public void flush() { - // NO-OP - } + @Override + public void flush() { + // NO-OP + } } diff --git a/src/main/java/slimeknights/mantle/pulsar/internal/BusExceptionHandler.java b/src/main/java/slimeknights/mantle/pulsar/internal/BusExceptionHandler.java index d406291..6b93232 100644 --- a/src/main/java/slimeknights/mantle/pulsar/internal/BusExceptionHandler.java +++ b/src/main/java/slimeknights/mantle/pulsar/internal/BusExceptionHandler.java @@ -2,41 +2,40 @@ package slimeknights.mantle.pulsar.internal; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import slimeknights.mantle.pulsar.flightpath.IExceptionHandler; import javax.annotation.ParametersAreNonnullByDefault; -import slimeknights.mantle.pulsar.flightpath.IExceptionHandler; - /** * Custom exception catcher that logs events. */ @ParametersAreNonnullByDefault public final class BusExceptionHandler implements IExceptionHandler { - private final String id; - private final Logger logger; + private final String id; + private final Logger logger; - /** - * @param id Mod ID to include in exception raises. - */ - public BusExceptionHandler(String id) { - this.id = id; - this.logger = LogManager.getLogger(id + "-Pulsar-Flightpath"); - } + /** + * @param id Mod ID to include in exception raises. + */ + public BusExceptionHandler(String id) { + this.id = id; + this.logger = LogManager.getLogger(id + "-Pulsar-Flightpath"); + } - @Override - public void handle(Exception ex) { - this.logger.error("Exception caught from a pulse on flightpath for mod ID " + this.id + ": ", ex); - // if its a runtime exception, we can just throw it as is - if(ex instanceof RuntimeException) { - throw (RuntimeException)ex; - } - throw new Error(ex); + @Override + public void handle(Exception ex) { + this.logger.error("Exception caught from a pulse on flightpath for mod ID " + this.id + ": ", ex); + // if its a runtime exception, we can just throw it as is + if (ex instanceof RuntimeException) { + throw (RuntimeException) ex; } + throw new Error(ex); + } - @Override - public void flush() { - // NO-OP - } + @Override + public void flush() { + // NO-OP + } } diff --git a/src/main/java/slimeknights/mantle/pulsar/internal/Configuration.java b/src/main/java/slimeknights/mantle/pulsar/internal/Configuration.java index fcab490..bcbcbad 100644 --- a/src/main/java/slimeknights/mantle/pulsar/internal/Configuration.java +++ b/src/main/java/slimeknights/mantle/pulsar/internal/Configuration.java @@ -5,9 +5,12 @@ import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; - import org.apache.logging.log4j.Logger; +import slimeknights.mantle.pulsar.config.IConfiguration; +import slimeknights.mantle.pulsar.pulse.PulseMeta; +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -18,12 +21,6 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; -import javax.annotation.Nonnull; -import javax.annotation.ParametersAreNonnullByDefault; - -import slimeknights.mantle.pulsar.config.IConfiguration; -import slimeknights.mantle.pulsar.pulse.PulseMeta; - /** * Default Gson Configuration helper. * @@ -32,194 +29,207 @@ import slimeknights.mantle.pulsar.pulse.PulseMeta; @ParametersAreNonnullByDefault public class Configuration implements IConfiguration { - private static final int CONFIG_LEVEL = 1; + private static final int CONFIG_LEVEL = 1; - private static final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private final String confPath; - private final Logger logger; + private static final Gson gson = new GsonBuilder().setPrettyPrinting().create(); + private final String confPath; + private final Logger logger; + + private Map modules; + + /** + * Creates a new Configuration object. + * + * Do NOT make this the same as the overall mod configuration; it will clobber it! + * + * @param confName The config file name (without path or .json suffix) + * @param logger The logger to send debug info to. + */ + public Configuration(String confName, Logger logger) { + this.confPath = Paths.get("config", confName + ".json").toString(); + this.logger = logger; + } + + @Override + public void load() { + this.getModulesFromJson(); + } + + @Override + public void postLoad() { + } + + @Override + public boolean isModuleEnabled(@Nonnull PulseMeta meta) { + ConfigEntry entry = this.modules.get(meta.getId()); + if (entry == null) { + return meta.isEnabled(); + } + else { + return entry.getEnabled(); + } + } + + @Override + public void addPulse(@Nonnull PulseMeta meta) { + ConfigEntry entry = this.modules.get(meta.getId()); + + if (entry == null) { + this.modules.put(meta.getId(), new ConfigEntry(meta.isDefaultEnabled(), meta.getDescription())); + } + } + + @Override + public void flush() { + this.writeModulesToJson(); + } + + private void getModulesFromJson() { + // Step 1: Does the file exist? + File f = new File(this.confPath); + if (!f.exists()) { + this.logger.info("Couldn't find config file; will generate a new one later."); + this.modules = new HashMap(); + return; + } + + // Step 2: File exists. Let's make sure it's usable. + if (!(f.canRead() && f.canWrite())) { + throw new FileNotReadWritableException("Could not read/write Pulsar config: " + this.confPath); + } + + // Step 3: Good enough. Read it. + try { + try { + this.modules = this.parseV1Config(f); + } + catch (Exception ex) { + this.logger.warn("Failed to parse " + f.getName() + " using the v1 parser; trying the v0 parser."); + Map conf = this.parseV0Config(f); + this.logger.info("Found valid v0 configuration. Upgrading it."); + this.modules = conf; + this.writeModulesToJson(); + this.logger.info("Upgrade complete! Config is now in v1 format."); + } + } + catch (Exception ex) { + this.logger.warn("Invalid config file. Discarding."); + ex.printStackTrace(); + this.modules = new HashMap(); + } + } + + private Map parseV0Config(File f) throws Exception { + try { + JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(f))); + Map m = gson.fromJson(reader, new TypeToken>() { + }.getType()); // NASTY! + if (m == null) { + throw new NullPointerException("Gson returned null."); + } + Map out = new HashMap(); + for (Map.Entry e : m.entrySet()) { + out.put(e.getKey(), new ConfigEntry(e.getValue())); + } + return out; + } + catch (FileNotFoundException fnfe) { + throw new RuntimeException("This shouldn't be possible... " + fnfe); + } + } + + private Map parseV1Config(File f) throws Exception { + try { + JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(f))); + GsonConfig c = gson.fromJson(reader, GsonConfig.class); + if (c.getConfigVersion() > 1) { + throw new RuntimeException("Pulsar config is from a newer version! Remove it! " + f.getAbsolutePath()); + } + if (c.getModules() == null) { + throw new IllegalArgumentException("Not a valid GsonConfig. Try v0 parsing."); + } + return c.getModules(); + } + catch (FileNotFoundException fnfe) { + throw new RuntimeException("This shouldn't be possible... " + fnfe); + } + } + + private void writeModulesToJson() { + try { + JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(new File(this.confPath)))); + writer.setIndent(" "); + GsonConfig out = new GsonConfig(CONFIG_LEVEL, this.modules); + gson.toJson(out, GsonConfig.class, writer); + writer.close(); + } + catch (Exception ex) { + this.logger.warn("Could not write config? " + this.confPath); + } + } + + /** + * Internal exception for an unreadable/unwritable config. + */ + private static class FileNotReadWritableException extends RuntimeException { + + public FileNotReadWritableException(String message) { + super(message); + } + } + + /** + * Internal data holder, for use in the map and JSON. + */ + private static class ConfigEntry { + + private Boolean enabled; + private String description = null; + + public ConfigEntry(Boolean enabled) { + this.enabled = enabled; + } + + public ConfigEntry(Boolean enabled, String description) { + this(enabled); + this.description = description; + } + + public Boolean getEnabled() { + return this.enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + public String getDescription() { + return this.description; + } + } + + /** + * Internal representation of a version 1+ config file. + */ + private static class GsonConfig { + + private int CONFIG_VERSION = 0; private Map modules; - /** - * Creates a new Configuration object. - * - * Do NOT make this the same as the overall mod configuration; it will clobber it! - * - * @param confName The config file name (without path or .json suffix) - * @param logger The logger to send debug info to. - */ - public Configuration(String confName, Logger logger) { - this.confPath = Paths.get("config", confName+ ".json").toString(); - this.logger = logger; + public GsonConfig(int version, Map modules) { + this.CONFIG_VERSION = version; + this.modules = modules; } - @Override - public void load() { - this.getModulesFromJson(); + public int getConfigVersion() { + return this.CONFIG_VERSION; } - @Override - public void postLoad() {} - - @Override - public boolean isModuleEnabled(@Nonnull PulseMeta meta) { - ConfigEntry entry = this.modules.get(meta.getId()); - if (entry == null) { - return meta.isEnabled(); - } else { - return entry.getEnabled(); - } + public Map getModules() { + return this.modules; } - @Override - public void addPulse(@Nonnull PulseMeta meta) { - ConfigEntry entry = this.modules.get(meta.getId()); - - if (entry == null) { - this.modules.put(meta.getId(), new ConfigEntry(meta.isDefaultEnabled(), meta.getDescription())); - } - } - - @Override - public void flush() { - this.writeModulesToJson(); - } - - private void getModulesFromJson() { - // Step 1: Does the file exist? - File f = new File(this.confPath); - if (!f.exists()) { - this.logger.info("Couldn't find config file; will generate a new one later."); - this.modules = new HashMap(); - return; - } - - // Step 2: File exists. Let's make sure it's usable. - if (!(f.canRead() && f.canWrite())) { - throw new FileNotReadWritableException("Could not read/write Pulsar config: " + this.confPath); - } - - // Step 3: Good enough. Read it. - try { - try { - this.modules = this.parseV1Config(f); - } catch (Exception ex) { - this.logger.warn("Failed to parse " + f.getName() + " using the v1 parser; trying the v0 parser."); - Map conf = this.parseV0Config(f); - this.logger.info("Found valid v0 configuration. Upgrading it."); - this.modules = conf; - this.writeModulesToJson(); - this.logger.info("Upgrade complete! Config is now in v1 format."); - } - } catch (Exception ex) { - this.logger.warn("Invalid config file. Discarding."); - ex.printStackTrace(); - this.modules = new HashMap(); - } - } - - private Map parseV0Config(File f) throws Exception { - try { - JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(f))); - Map m = gson.fromJson(reader, new TypeToken>(){}.getType()); // NASTY! - if (m == null) { - throw new NullPointerException("Gson returned null."); - } - Map out = new HashMap(); - for (Map.Entry e : m.entrySet()) { - out.put(e.getKey(), new ConfigEntry(e.getValue())); - } - return out; - } catch (FileNotFoundException fnfe) { - throw new RuntimeException("This shouldn't be possible... " + fnfe); - } - } - - private Map parseV1Config(File f) throws Exception { - try { - JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(f))); - GsonConfig c = gson.fromJson(reader, GsonConfig.class); - if (c.getConfigVersion() > 1) throw new RuntimeException("Pulsar config is from a newer version! Remove it! " + f.getAbsolutePath()); - if (c.getModules() == null) throw new IllegalArgumentException("Not a valid GsonConfig. Try v0 parsing."); - return c.getModules(); - } catch (FileNotFoundException fnfe) { - throw new RuntimeException("This shouldn't be possible... " + fnfe); - } - } - - private void writeModulesToJson() { - try { - JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(new File(this.confPath)))); - writer.setIndent(" "); - GsonConfig out = new GsonConfig(CONFIG_LEVEL, this.modules); - gson.toJson(out, GsonConfig.class, writer); - writer.close(); - } catch (Exception ex) { - this.logger.warn("Could not write config? " + this.confPath); - } - } - - /** - * Internal exception for an unreadable/unwritable config. - */ - private static class FileNotReadWritableException extends RuntimeException { - public FileNotReadWritableException(String message) { - super(message); - } - } - - /** - * Internal data holder, for use in the map and JSON. - */ - private static class ConfigEntry { - - private Boolean enabled; - private String description = null; - - public ConfigEntry(Boolean enabled) { - this.enabled = enabled; - } - - public ConfigEntry(Boolean enabled, String description) { - this(enabled); - this.description = description; - } - - public Boolean getEnabled() { - return this.enabled; - } - - public void setEnabled(Boolean enabled) { - this.enabled = enabled; - } - - public String getDescription() { - return this.description; - } - } - - /** - * Internal representation of a version 1+ config file. - */ - private static class GsonConfig { - - private int CONFIG_VERSION = 0; - - private Map modules; - - public GsonConfig(int version, Map modules) { - this.CONFIG_VERSION = version; - this.modules = modules; - } - - public int getConfigVersion() { - return this.CONFIG_VERSION; - } - - public Map getModules() { - return this.modules; - } - - } + } } diff --git a/src/main/java/slimeknights/mantle/pulsar/internal/CrashHandler.java b/src/main/java/slimeknights/mantle/pulsar/internal/CrashHandler.java index 4adf21f..464449c 100644 --- a/src/main/java/slimeknights/mantle/pulsar/internal/CrashHandler.java +++ b/src/main/java/slimeknights/mantle/pulsar/internal/CrashHandler.java @@ -1,7 +1,6 @@ package slimeknights.mantle.pulsar.internal; import net.minecraftforge.fml.common.ICrashCallable; - import slimeknights.mantle.pulsar.control.PulseManager; import slimeknights.mantle.pulsar.pulse.PulseMeta; @@ -12,39 +11,41 @@ import slimeknights.mantle.pulsar.pulse.PulseMeta; */ public class CrashHandler implements ICrashCallable { - private String id; - private PulseManager manager; + private String id; + private PulseManager manager; - public CrashHandler(String modId, PulseManager manager) { - this.id = "Pulsar/" + modId + " loaded Pulses"; - this.manager = manager; - } + public CrashHandler(String modId, PulseManager manager) { + this.id = "Pulsar/" + modId + " loaded Pulses"; + this.manager = manager; + } - @Override - public String getLabel() { - return this.id; - } + @Override + public String getLabel() { + return this.id; + } - @Override - public String call() throws Exception { - String out = "\n"; - for (PulseMeta meta : this.manager.getAllPulseMetadata()) { - String state = getStateFromMeta(meta); - out += "\t\t- " + meta.getId() + " (" + state + ")\n"; // Yes, yes, manual indenting, I know... - } - return out; + @Override + public String call() throws Exception { + String out = "\n"; + for (PulseMeta meta : this.manager.getAllPulseMetadata()) { + String state = getStateFromMeta(meta); + out += "\t\t- " + meta.getId() + " (" + state + ")\n"; // Yes, yes, manual indenting, I know... } + return out; + } - private static String getStateFromMeta(PulseMeta meta) { - if (meta.isForced()) { - return "Enabled/Forced"; - } else { - if (meta.isEnabled()) { - return "Enabled/Not Forced"; - } else { - return "Disabled/Not Forced"; - } - } + private static String getStateFromMeta(PulseMeta meta) { + if (meta.isForced()) { + return "Enabled/Forced"; } + else { + if (meta.isEnabled()) { + return "Enabled/Not Forced"; + } + else { + return "Disabled/Not Forced"; + } + } + } } diff --git a/src/main/java/slimeknights/mantle/pulsar/pulse/Pulse.java b/src/main/java/slimeknights/mantle/pulsar/pulse/Pulse.java index b9f7c9a..005dc81 100644 --- a/src/main/java/slimeknights/mantle/pulsar/pulse/Pulse.java +++ b/src/main/java/slimeknights/mantle/pulsar/pulse/Pulse.java @@ -15,38 +15,38 @@ import java.lang.annotation.Target; * @author Arkan */ @Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) +@Target({ ElementType.TYPE }) @Documented public @interface Pulse { - /** - * @return This Pulses UID - Much like FML mods have mod IDs. - */ - String id(); + /** + * @return This Pulses UID - Much like FML mods have mod IDs. + */ + String id(); - /** - * @return This Pulses description, human-readable for config files. Can be blank. - */ - String description() default ""; + /** + * @return This Pulses description, human-readable for config files. Can be blank. + */ + String description() default ""; - /** - * @return Dependant mod IDs, seperated by ; as in FML. Skips checks when undefined. - */ - String modsRequired() default ""; + /** + * @return Dependant mod IDs, seperated by ; as in FML. Skips checks when undefined. + */ + String modsRequired() default ""; - /** - * @return Dependeant Pulse IDs, seperated by ; . Skips checks when undefined. - */ - String pulsesRequired() default ""; + /** + * @return Dependeant Pulse IDs, seperated by ; . Skips checks when undefined. + */ + String pulsesRequired() default ""; - /** - * @return Whether this Pulse is mandatory or not (true -> mandatory). - */ - boolean forced() default false; + /** + * @return Whether this Pulse is mandatory or not (true -> mandatory). + */ + boolean forced() default false; - /** - * @return Whether a configurable Pulse should be enabled by default. Ignored where forced = true. - */ - boolean defaultEnable() default true; + /** + * @return Whether a configurable Pulse should be enabled by default. Ignored where forced = true. + */ + boolean defaultEnable() default true; } diff --git a/src/main/java/slimeknights/mantle/pulsar/pulse/PulseMeta.java b/src/main/java/slimeknights/mantle/pulsar/pulse/PulseMeta.java index 8cb5ca4..0cd1730 100644 --- a/src/main/java/slimeknights/mantle/pulsar/pulse/PulseMeta.java +++ b/src/main/java/slimeknights/mantle/pulsar/pulse/PulseMeta.java @@ -11,43 +11,43 @@ import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault public class PulseMeta { - private String id, description; - private boolean forced, enabled, defaultEnabled; - private boolean missingDeps = false; + private String id, description; + private boolean forced, enabled, defaultEnabled; + private boolean missingDeps = false; - public PulseMeta(String id, @Nullable String description, boolean forced, boolean enabled, boolean defaultEnabled) { - this.id = id; - this.description = description; - this.forced = forced; - this.enabled = enabled; - this.defaultEnabled = defaultEnabled; - } + public PulseMeta(String id, @Nullable String description, boolean forced, boolean enabled, boolean defaultEnabled) { + this.id = id; + this.description = description; + this.forced = forced; + this.enabled = enabled; + this.defaultEnabled = defaultEnabled; + } - public String getId() { - return this.id; - } + public String getId() { + return this.id; + } - public String getDescription() { - return this.description; - } + public String getDescription() { + return this.description; + } - public boolean isForced() { - return !this.missingDeps && this.forced; - } + public boolean isForced() { + return !this.missingDeps && this.forced; + } - public boolean isEnabled() { - return !this.missingDeps && this.enabled; - } + public boolean isEnabled() { + return !this.missingDeps && this.enabled; + } - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } - public void setMissingDeps(boolean missing) { - this.missingDeps = missing; - } + public void setMissingDeps(boolean missing) { + this.missingDeps = missing; + } - public boolean isDefaultEnabled() { - return this.defaultEnabled; - } + public boolean isDefaultEnabled() { + return this.defaultEnabled; + } } diff --git a/src/main/resources/META-INF/mantle_deobf_at.cfg b/src/main/resources/META-INF/mantle_deobf_at.cfg index dd69613..7388f56 100644 --- a/src/main/resources/META-INF/mantle_deobf_at.cfg +++ b/src/main/resources/META-INF/mantle_deobf_at.cfg @@ -1,14 +1,12 @@ # Mantle -- Access Transformer # GuiContainer -public net.minecraft.client.gui.inventory.GuiContainer xSize -public net.minecraft.client.gui.inventory.GuiContainer ySize -public net.minecraft.client.gui.inventory.GuiContainer guiTop -public net.minecraft.client.gui.inventory.GuiContainer guiLeft -public net.minecraft.client.gui.inventory.GuiContainer drawSlot(Lnet/minecraft/inventory/Slot;)V -public net.minecraft.client.gui.inventory.GuiContainer isMouseOverSlot(Lnet/minecraft/inventory/Slot;II)Z -# GuiScreen -public net.minecraft.client.gui.GuiScreen buttonList +public net.minecraft.client.gui.screen.inventory.ContainerScreen xSize +public net.minecraft.client.gui.screen.inventory.ContainerScreen ySize +public net.minecraft.client.gui.screen.inventory.ContainerScreen guiTop +public net.minecraft.client.gui.screen.inventory.ContainerScreen guiLeft +public net.minecraft.client.gui.screen.inventory.ContainerScreen drawSlot(Lnet/minecraft/inventory/container/Slot;)V +public net.minecraft.client.gui.screen.inventory.ContainerScreen isMouseOverSlot(Lnet/minecraft/inventory/container/Slot;DD)Z -# Block -public net.minecraft.block.Block displayOnCreativeTab +# Screen +public net.minecraft.client.gui.screen.Screen buttons # buttons \ No newline at end of file