Drastically improve @Handler, package registration is no longer needed

This commit is contained in:
tterrag1098 committed 2015-08-19 22:26:30 -04:00
1 parent 55ed6c7d47
commit 3d56149a25
12 files changed
+257 -251

No files matched your search

@@ -60,7 +60,6 @@ public class EnderCore implements IEnderMod {
public List<IConfigHandler> configs = Lists.newArrayList();
@SuppressWarnings("serial")
@EventHandler
@SneakyThrows
public void preInit(FMLPreInitializationEvent event) {
@@ -82,7 +81,7 @@ public class EnderCore implements IEnderMod {
}
ConfigHandler.instance().initialize(ConfigHandler.configFile);
Handlers.findPackages();
Handlers.preInit(event);
CompatRegistry.INSTANCE.handle(event);
OreDict.registerVanilla();
@@ -99,7 +98,7 @@ public class EnderCore implements IEnderMod {
c.initHook();
}
Handlers.register();
Handlers.register(event);
CompatRegistry.INSTANCE.handle(event);
ClientCommandHandler.instance.registerCommand(CommandReloadConfigs.CLIENT);
if (event.getSide().isServer()) {
@@ -2,18 +2,18 @@ package com.enderio.core.client.gui.bettermodlist;
import java.lang.reflect.Field;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import lombok.SneakyThrows;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.client.event.GuiOpenEvent;
import com.enderio.core.common.Handlers.Handler;
import cpw.mods.fml.client.GuiIngameModOptions;
import cpw.mods.fml.client.GuiModList;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
@Handler(HandlerType.FORGE)
@Handler
public class EventHandlerGui
{
private static Field _mainMenu, _parentScreen;
@@ -1,14 +1,14 @@
package com.enderio.core.client.handlers;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import lombok.Getter;
import com.enderio.core.common.Handlers.Handler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.ClientTickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
@Handler(HandlerType.FML)
@Handler
public class ClientHandler
{
@Getter
@@ -2,18 +2,18 @@ package com.enderio.core.client.handlers;
import java.util.Map;
import com.enderio.core.api.common.enchant.IAdvancedEnchant;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.StatCollector;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import com.enderio.core.api.common.enchant.IAdvancedEnchant;
import com.enderio.core.common.Handlers.Handler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
@Handler(HandlerType.FORGE)
@Handler
public class EnchantTooltipHandler
{
@SuppressWarnings("unchecked")
@@ -9,13 +9,12 @@ import org.lwjgl.input.Keyboard;
import com.enderio.core.EnderCore;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import static com.enderio.core.common.config.ConfigHandler.*;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
@Handler(HandlerType.FORGE)
import static com.enderio.core.common.config.ConfigHandler.*;
@Handler
public class OreDictTooltipHandler
{
@SubscribeEvent
@@ -24,7 +24,6 @@ import com.enderio.core.EnderCore;
import com.enderio.core.api.client.gui.IAdvancedTooltipProvider;
import com.enderio.core.api.client.gui.IResourceTooltipProvider;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import com.enderio.core.common.config.ConfigHandler;
import com.enderio.core.common.util.ItemUtil;
import com.google.common.collect.Lists;
@@ -33,7 +32,7 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import static com.enderio.core.common.config.ConfigHandler.showOredictTooltips;
@Handler(HandlerType.FORGE)
@Handler
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SpecialTooltipHandler {
@@ -1,6 +1,5 @@
package com.enderio.core.common;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
@@ -9,258 +8,273 @@ import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.experimental.UtilityClass;
import net.minecraftforge.common.MinecraftForge;
import org.apache.commons.lang3.ArrayUtils;
import com.enderio.core.IEnderMod;
import com.enderio.core.EnderCore;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import com.enderio.core.IEnderMod;
import com.enderio.core.common.Handlers.Handler.Inst;
import com.google.common.reflect.ClassPath;
import com.google.common.reflect.ClassPath.ClassInfo;
import static com.enderio.core.common.Handlers.Handler.Inst.*;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.LoaderState;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.discovery.ASMDataTable.ASMData;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.EventBus;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import static com.enderio.core.common.Handlers.Handler.Inst.*;
@UtilityClass
public class Handlers
{
public class Handlers {
/**
* New enum to represent handler types. Possible to use to figure out what
* type a method is without direct info.
*
* The order of the constants is the order they are tried. This is VERY
* important!
*/
@RequiredArgsConstructor
public enum HandlerType {
/**
* To be put on classes that are Forge/FML event handlers. If you are using this from another mod, be sure to implement {@link IEnderMod} on your
* {@code @Mod} class, or call {@code Handlers.addPackage("your.base.package")} so that this class can search your classes
* <p>
* Class must have either:<br>
* A public no args constructor (or lombok {@link NoArgsConstructor}) <b>OR</b><br>
* A static singleton object with field name {@code INSTANCE} (public or private). <b>OR</b><br>
* A static method with name <code>instance()</code> (public or private)
* Represents the {@link MinecraftForge#ORE_GEN_BUS}
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Handler
{
public enum HandlerType
{
/**
* Represents the {@link MinecraftForge#EVENT_BUS}
*/
FORGE,
FORGE_OREGEN("net.minecraftforge.event.terraingen.OreGenEvent", MinecraftForge.ORE_GEN_BUS),
/**
* Represents the {@link FMLCommonHandler#bus()}
*/
FML
}
/**
* Represents the {@link MinecraftForge#TERRAIN_GEN_BUS}
*/
FORGE_TERRAIN("net.minecraftforge.event.terraingen", MinecraftForge.TERRAIN_GEN_BUS),
public enum Inst
{
/**
* The default, will try all three methods, in the order {@link Inst#CONSTRUCTOR}, {@link Inst#FIELD}, {@link Inst#METHOD}
*/
AUTO,
/**
* Represents the {@link MinecraftForge#EVENT_BUS}
*/
FORGE("net.minecraftforge.event", MinecraftForge.EVENT_BUS),
/**
* The handler should be constructed from the default constructor of the class
*/
CONSTRUCTOR,
/**
* Represents the {@link FMLCommonHandler#bus()}
*/
FML("cpw.mods.fml", FMLCommonHandler.instance().bus());
/**
* The handler should be grabbed from the static {@code INSTANCE} field of the class
*/
FIELD,
public final String eventIdentifier;
public final EventBus bus;
}
/**
* The handler should be grabbed from the static {@code instance()} method of the class
*/
METHOD;
/**
* To be put on classes that are Forge/FML event handlers. If you are using
* this from another mod, be sure to implement {@link IEnderMod} on your
* {@code @Mod} class, or call
* {@code Handlers.addPackage("your.base.package")} so that this class can
* search your classes
* <p>
* Class must have either:<br>
* A public no args constructor (or lombok {@link NoArgsConstructor})
* <b>OR</b><br>
* A static singleton object with field name {@code INSTANCE} (public or
* private). <b>OR</b><br>
* A static method with name <code>instance()</code> (public or private)
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Handler {
@Deprecated
public enum HandlerType {
/**
* Represents the {@link MinecraftForge#EVENT_BUS}
*/
FORGE,
boolean matches(Inst other)
{
return this == AUTO || other == AUTO || other == this;
}
}
/**
* Array of buses to register this handler to. Leave blank for all.
*/
HandlerType[] value() default { HandlerType.FORGE, HandlerType.FML };
/**
* The method of getting your handler's instance. Defaults to {@link Inst#AUTO}
*/
Inst getInstFrom() default AUTO;
/**
* Represents the {@link FMLCommonHandler#bus()}
*/
FML
}
private static final Set<String> packageSet = new HashSet<String>();
public enum Inst {
/**
* The default, will try all three methods, in the order
* {@link Inst#CONSTRUCTOR}, {@link Inst#FIELD}, {@link Inst#METHOD}
*/
AUTO,
public void findPackages()
{
for (ModContainer mod : Loader.instance().getActiveModList())
{
if (mod.getMod() instanceof IEnderMod)
{
addPackage(getEnclosingPackage(mod.getMod()));
}
}
}
/**
* The handler should be constructed from the default constructor of the
* class
*/
CONSTRUCTOR,
private String getEnclosingPackage(Object obj)
{
Class<?> modClass = obj.getClass();
/**
* The handler should be grabbed from the static {@code INSTANCE} field of
* the class
*/
FIELD,
while (modClass.getComponentType() != null)
{
modClass = modClass.getComponentType();
}
/**
* The handler should be grabbed from the static {@code instance()} method
* of the class
*/
METHOD;
while (modClass.getEnclosingClass() != null)
{
modClass = modClass.getEnclosingClass();
}
String name = modClass.getName();
int lastDot = name.lastIndexOf('.');
return lastDot == -1 ? name : name.substring(0, lastDot);
boolean matches(Inst other) {
return this == AUTO || other == AUTO || other == this;
}
}
/**
* Registers a top level package to be searched for {@link Handler} classes. Not needed if your {@code @Mod} class implements {@link IEnderMod}
*
* @param packageName
* Array of buses to register this handler to. Leave blank for all.
*/
public void addPackage(String packageName)
{
if (Loader.instance().hasReachedState(LoaderState.INITIALIZATION))
{
throw new RuntimeException("This method must only be called in preinit");
}
EnderCore.logger.info("Adding package " + packageName + " to handler search.");
packageSet.add(packageName);
}
private boolean registered = false;
@Deprecated
HandlerType[] value() default { HandlerType.FORGE, HandlerType.FML };
/**
* For internal use only. Do not call. Callers will be sacked.
* The method of getting your handler's instance. Defaults to
* {@link Inst#AUTO}
*/
public void register()
{
if (registered)
{
throw new IllegalStateException("I warned you!");
}
Inst getInstFrom() default AUTO;
}
ClassPath classpath;
private static final Set<String> packageSet = new HashSet<String>();
try
{
classpath = ClassPath.from(EnderCore.class.getClassLoader());
}
catch (IOException e)
{
throw new RuntimeException(e);
}
private static Set<ASMData> annotations;
for (String packageName : packageSet)
{
Set<ClassInfo> classes = classpath.getTopLevelClassesRecursive(packageName);
public static void preInit(FMLPreInitializationEvent event) {
annotations = event.getAsmData().getAll(Handler.class.getName());
}
for (ClassInfo info : classes)
{
// if not client handler, or we are on client, continue
if (!info.getPackageName().contains("client") || FMLCommonHandler.instance().getEffectiveSide().isClient())
{
try
{
Class<?> c = info.load();
// private String getEnclosingPackage(Object obj) {
// Class<?> modClass = obj.getClass();
//
// while (modClass.getComponentType() != null) {
// modClass = modClass.getComponentType();
// }
//
// while (modClass.getEnclosingClass() != null) {
// modClass = modClass.getEnclosingClass();
// }
//
// String name = modClass.getName();
// int lastDot = name.lastIndexOf('.');
//
// return lastDot == -1 ? name : name.substring(0, lastDot);
// }
Annotation a = c.getAnnotation(Handler.class);
if (a != null)
{
registerHandler(c, (Handler) a);
}
}
catch (Throwable t)
{
EnderCore.logger.error(String.format("[Handlers] %s threw an error on load, skipping...", info.getName()));
t.printStackTrace();
}
}
else
{
EnderCore.logger.info(String.format("[Handlers] Skipping client class %s, we are on a dedicated server", info.getSimpleName()));
}
}
}
registered = true;
/**
* Registers a top level package to be searched for {@link Handler} classes.
* Not needed if your {@code @Mod} class implements {@link IEnderMod}
*
* @param packageName
*/
@Deprecated
public void addPackage(String packageName) {
if (Loader.instance().hasReachedState(LoaderState.INITIALIZATION)) {
throw new RuntimeException("This method must only be called in preinit");
}
private void registerHandler(Class<?> c, Handler handler) throws InstantiationException, IllegalAccessException
{
EnderCore.logger.info(String.format("[Handlers] Registering handler %s to busses: %s", c.getSimpleName(), Arrays.deepToString(handler.value())));
EnderCore.logger.info("Adding package " + packageName + " to handler search.");
packageSet.add(packageName);
}
HandlerType[] types = handler.value();
Object inst = tryInit(handler, c);
private boolean registered = false;
if (ArrayUtils.contains(types, HandlerType.FORGE))
MinecraftForge.EVENT_BUS.register(inst);
if (ArrayUtils.contains(types, HandlerType.FML))
FMLCommonHandler.instance().bus().register(inst);
/**
* For internal use only. Do not call. Callers will be sacked.
*
* @param event
*/
public void register(FMLInitializationEvent event) {
if (registered) {
throw new IllegalStateException("I warned you!");
}
private Object tryInit(Handler annot, Class<?> c)
{
Inst pref = annot.getInstFrom();
// Silence all exceptions to trickle down to next if statement.
// If all three fail, RuntimeException is thrown.
if (pref.matches(CONSTRUCTOR))
{
try
{
return c.newInstance();
}
catch (Exception e)
{}
for (ASMData data : annotations) {
String className = data.getClassName();
// if not client handler, or we are on client, continue
if (!className.contains("client") || FMLCommonHandler.instance().getEffectiveSide().isClient()) {
try {
Class<?> c = Class.forName(className);
Annotation a = c.getAnnotation(Handler.class);
if (a != null) {
registerHandler(c, data, (Handler) a);
}
} catch (Throwable t) {
EnderCore.logger.error(String.format("[Handlers] %s threw an error on load, skipping...", className));
t.printStackTrace();
}
if (pref.matches(FIELD))
{
try
{
Field inst = c.getDeclaredField("INSTANCE");
inst.setAccessible(true);
return inst.get(null);
}
catch (Exception e)
{}
}
if (pref.matches(METHOD))
{
try
{
Method inst = c.getDeclaredMethod("instance");
inst.setAccessible(true);
return inst.invoke(null);
}
catch (Exception e)
{}
}
throw new RuntimeException("Could not instantiate @Handler class " + c.getName() + " or access INSTANCE field or instance() method.");
} else {
EnderCore.logger.info(String.format("[Handlers] Skipping client class %s, we are on a dedicated server", className));
}
}
registered = true;
}
private void registerHandler(Class<?> c, ASMData data, Handler handler) throws InstantiationException, IllegalAccessException {
EnderCore.logger.info(String.format("[Handlers] Registering handler %s to busses: %s", c.getSimpleName(), Arrays.deepToString(handler.value())));
Object inst = tryInit(handler, c);
Method[] methods = c.getDeclaredMethods();
EnumSet<HandlerType> types = EnumSet.noneOf(HandlerType.class);
// Iterate over all methods to find those with @SubscribeEvent, then figure out what type that method is
for (Method m : methods) {
if (m.isAnnotationPresent(SubscribeEvent.class)) {
Class<?>[] params = m.getParameterTypes();
if (params.length >= 1) {
Class<?> param = params[0];
for (HandlerType type : HandlerType.values()) {
if (param.getName().contains(type.eventIdentifier)) {
types.add(type);
break;
}
}
}
}
}
for (HandlerType type : types) {
type.bus.register(inst);
}
}
private Object tryInit(Handler annot, Class<?> c) {
Inst pref = annot.getInstFrom();
// Silence all exceptions to trickle down to next if statement.
// If all three fail, RuntimeException is thrown.
if (pref.matches(CONSTRUCTOR)) {
try {
return c.newInstance();
} catch (Exception e) {
}
}
if (pref.matches(FIELD)) {
try {
Field inst = c.getDeclaredField("INSTANCE");
inst.setAccessible(true);
return inst.get(null);
} catch (Exception e) {
}
}
if (pref.matches(METHOD)) {
try {
Method inst = c.getDeclaredMethod("instance");
inst.setAccessible(true);
return inst.invoke(null);
} catch (Exception e) {
}
}
throw new RuntimeException("Could not instantiate @Handler class " + c.getName() + " or access INSTANCE field or instance() method.");
}
}
@@ -2,10 +2,9 @@ package com.enderio.core.common.config;
import java.io.File;
import net.minecraftforge.common.config.Configuration;
import com.enderio.core.EnderCore;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import com.enderio.core.common.Handlers.Handler.Inst;
import com.enderio.core.common.config.ConfigProcessor.IReloadCallback;
import com.enderio.core.common.config.JsonConfigReader.ModToken;
import com.enderio.core.common.config.annot.Comment;
@@ -18,9 +17,6 @@ import com.enderio.core.common.handlers.RightClickCropHandler.PlantInfo;
import com.enderio.core.common.tweaks.Tweak;
import com.enderio.core.common.tweaks.Tweaks;
import net.minecraftforge.common.config.Configuration;
@Handler(value = HandlerType.FML, getInstFrom = Inst.METHOD)
public class ConfigHandler extends AbstractConfigHandler implements ITweakConfigHandler, IReloadCallback {
private static final String sectionGeneral = Configuration.CATEGORY_GENERAL;
private static final String sectionEnchants = "enchants";
@@ -2,21 +2,23 @@ package com.enderio.core.common.handlers;
import java.util.Map;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import com.enderio.core.common.config.ConfigHandler;
import com.enderio.core.common.enchant.EnchantAutoSmelt;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.util.MathHelper;
import net.minecraftforge.event.terraingen.DecorateBiomeEvent;
import net.minecraftforge.event.terraingen.OreGenEvent;
import net.minecraftforge.event.world.BlockEvent;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.config.ConfigHandler;
import com.enderio.core.common.enchant.EnchantAutoSmelt;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
@Handler(HandlerType.FORGE)
@Handler
public class AutoSmeltHandler {
@SubscribeEvent
@@ -86,5 +88,4 @@ public class AutoSmeltHandler {
}
return -1;
}
}
@@ -11,7 +11,6 @@ import net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent;
import net.minecraftforge.oredict.OreDictionary;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import com.enderio.core.common.config.ConfigHandler;
import com.enderio.core.common.util.ItemUtil;
import com.google.common.collect.Lists;
@@ -19,7 +18,7 @@ import com.google.common.collect.Lists;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.registry.GameRegistry;
@Handler(HandlerType.FORGE)
@Handler
public class RightClickCropHandler
{
@NoArgsConstructor
@@ -3,11 +3,6 @@ package com.enderio.core.common.handlers;
import java.lang.reflect.Method;
import java.util.Map;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import com.enderio.core.common.enchant.EnchantXPBoost;
import com.enderio.core.common.util.Scheduler;
import lombok.SneakyThrows;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
@@ -22,10 +17,15 @@ import net.minecraft.world.World;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.world.BlockEvent.BreakEvent;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.enchant.EnchantXPBoost;
import com.enderio.core.common.util.Scheduler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.ReflectionHelper;
@Handler(HandlerType.FORGE)
@Handler
public class XPBoostHandler
{
private static final Method getExperiencePoints = ReflectionHelper.findMethod(EntityLivingBase.class, null,
@@ -8,7 +8,6 @@ import lombok.AllArgsConstructor;
import com.enderio.core.EnderCore;
import com.enderio.core.common.Handlers.Handler;
import com.enderio.core.common.Handlers.Handler.HandlerType;
import com.enderio.core.common.Handlers.Handler.Inst;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
@@ -22,7 +21,7 @@ import cpw.mods.fml.relauncher.SideOnly;
/**
* Convenience helper to schedule events to happen in the future.
*/
@Handler(value = HandlerType.FML, getInstFrom = Inst.METHOD)
@Handler(getInstFrom = Inst.METHOD)
public class Scheduler
{
@AllArgsConstructor