From b2e9557b87b5005900df2a7119c7af29a624ef23 Mon Sep 17 00:00:00 2001 From: Christian Date: Wed, 26 Jun 2013 14:52:56 -0400 Subject: [PATCH] Changed to the EventHandler annotation universally, documentation and stuff. --- .../cpw/mods/fml/common/FMLModContainer.java | 53 +++++-- .../cpw/mods/fml/common/ILanguageAdapter.java | 15 +- fml/common/cpw/mods/fml/common/Mod.java | 149 ++++++++++++++++-- .../cpw/mods/fml/common/ModClassLoader.java | 2 +- .../cpw/mods/fml/common/SidedProxy.java | 23 +++ 5 files changed, 214 insertions(+), 28 deletions(-) diff --git a/fml/common/cpw/mods/fml/common/FMLModContainer.java b/fml/common/cpw/mods/fml/common/FMLModContainer.java index 657fc5f5e0..cfefbbee85 100644 --- a/fml/common/cpw/mods/fml/common/FMLModContainer.java +++ b/fml/common/cpw/mods/fml/common/FMLModContainer.java @@ -40,6 +40,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterators; +import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; @@ -83,7 +84,6 @@ public class FMLModContainer implements ModContainer private boolean overridesMetadata; private EventBus eventBus; private LoadController controller; - private Multimap, Object> annotations; private DefaultArtifactVersion processedVersion; private boolean isNetworkMod; @@ -107,6 +107,7 @@ public class FMLModContainer implements ModContainer private Certificate certificate; private String modLanguage; private ILanguageAdapter languageAdapter; + private ListMultimap,Method> eventMethods; public FMLModContainer(String className, File modSource, Map modDescriptor) { @@ -115,6 +116,7 @@ public class FMLModContainer implements ModContainer this.descriptor = modDescriptor; this.modLanguage = (String) modDescriptor.get("modLanguage"); this.languageAdapter = "scala".equals(modLanguage) ? new ILanguageAdapter.ScalaAdapter() : new ILanguageAdapter.JavaAdapter(); + this.eventMethods = ArrayListMultimap.create(); } private ILanguageAdapter getLanguageAdapter() @@ -312,10 +314,9 @@ public class FMLModContainer implements ModContainer } } - private Multimap, Object> gatherAnnotations(Class clazz) throws Exception + private Method gatherAnnotations(Class clazz) throws Exception { - Multimap,Object> anns = ArrayListMultimap.create(); - + Method factoryMethod = null; for (Method m : clazz.getDeclaredMethods()) { for (Annotation a : m.getAnnotations()) @@ -323,20 +324,47 @@ public class FMLModContainer implements ModContainer if (modTypeAnnotations.containsKey(a.annotationType())) { Class[] paramTypes = new Class[] { modTypeAnnotations.get(a.annotationType()) }; - if (Arrays.equals(m.getParameterTypes(), paramTypes)) { m.setAccessible(true); - anns.put(a.annotationType(), m); + eventMethods.put(modTypeAnnotations.get(a.annotationType()), m); } else { FMLLog.log(getModId(), Level.SEVERE,"The mod %s appears to have an invalid method annotation %s. This annotation can only apply to methods with argument types %s -it will not be called", getModId(), a.annotationType().getSimpleName(), Arrays.toString(paramTypes)); } } + else if (a.annotationType().equals(Mod.EventHandler.class)) + { + if (m.getParameterTypes().length == 1 && modAnnotationTypes.containsKey(m.getParameterTypes()[0])) + { + m.setAccessible(true); + eventMethods.put((Class) m.getParameterTypes()[1],m); + } + else + { + FMLLog.log(getModId(), Level.SEVERE,"The mod %s appears to have an invalid event annotation %s. This annotation can only apply to methods with recognized event arguments - it will not be called", getModId(), a.annotationType().getSimpleName()); + } + } + else if (a.annotationType().equals(Mod.InstanceFactory.class)) + { + if (Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0 && factoryMethod == null) + { + m.setAccessible(true); + factoryMethod = m; + } + else if (!(Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0)) + { + FMLLog.log(getModId(), Level.SEVERE, "The InstanceFactory annotation can only apply to a static method, taking zero arguments - it will be ignored on %s(%s)", m.getName(), Arrays.asList(m.getParameterTypes())); + } + else if (factoryMethod != null) + { + FMLLog.log(getModId(), Level.SEVERE, "The InstanceFactory annotation can only be used once, the application to %s(%s) will be ignored", m.getName(), Arrays.asList(m.getParameterTypes())); + } + } } } - return anns; + return factoryMethod; } private void processFieldAnnotations(ASMDataTable asmDataTable) throws Exception @@ -461,9 +489,9 @@ public class FMLModContainer implements ModContainer } } - annotations = gatherAnnotations(clazz); + Method factoryMethod = gatherAnnotations(clazz); isNetworkMod = FMLNetworkHandler.instance().registerNetworkMod(this, clazz, event.getASMHarvestedData()); - modInstance = getLanguageAdapter().getNewInstance(this,clazz, modClassLoader); + modInstance = getLanguageAdapter().getNewInstance(this,clazz, modClassLoader, factoryMethod); if (fingerprintNotPresent) { eventBus.post(new FMLFingerprintViolationEvent(source.isDirectory(), source, ImmutableSet.copyOf(this.sourceFingerprints), expectedFingerprint)); @@ -481,23 +509,20 @@ public class FMLModContainer implements ModContainer @Subscribe public void handleModStateEvent(FMLEvent event) { - Class annotation = modAnnotationTypes.get(event.getClass()); - if (annotation == null) + if (!eventMethods.containsKey(event.getClass())) { return; } try { - for (Object o : annotations.get(annotation)) + for (Method m : eventMethods.get(event.getClass())) { - Method m = (Method) o; m.invoke(modInstance, event); } } catch (Throwable t) { controller.errorOccurred(this, t); - Throwables.propagateIfPossible(t); } } diff --git a/fml/common/cpw/mods/fml/common/ILanguageAdapter.java b/fml/common/cpw/mods/fml/common/ILanguageAdapter.java index 4071cfb53b..d5b1c24384 100644 --- a/fml/common/cpw/mods/fml/common/ILanguageAdapter.java +++ b/fml/common/cpw/mods/fml/common/ILanguageAdapter.java @@ -9,14 +9,14 @@ import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.relauncher.Side; public interface ILanguageAdapter { - public Object getNewInstance(FMLModContainer container, Class objectClass, ClassLoader classLoader) throws Exception; + public Object getNewInstance(FMLModContainer container, Class objectClass, ClassLoader classLoader, Method factoryMarkedAnnotation) throws Exception; public boolean supportsStatics(); public void setProxy(Field target, Class proxyTarget, Object proxy) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException; public void setInternalProxies(ModContainer mod, Side side, ClassLoader loader); public static class ScalaAdapter implements ILanguageAdapter { @Override - public Object getNewInstance(FMLModContainer container, Class scalaObjectClass, ClassLoader classLoader) throws Exception + public Object getNewInstance(FMLModContainer container, Class scalaObjectClass, ClassLoader classLoader, Method factoryMarkedAnnotation) throws Exception { Class sObjectClass = Class.forName(scalaObjectClass.getName()+"$",true,classLoader); return sObjectClass.getField("MODULE$").get(null); @@ -163,9 +163,16 @@ public interface ILanguageAdapter { public static class JavaAdapter implements ILanguageAdapter { @Override - public Object getNewInstance(FMLModContainer container, Class objectClass, ClassLoader classLoader) throws Exception + public Object getNewInstance(FMLModContainer container, Class objectClass, ClassLoader classLoader, Method factoryMarkedMethod) throws Exception { - return objectClass.newInstance(); + if (factoryMarkedMethod != null) + { + return factoryMarkedMethod.invoke(null); + } + else + { + return objectClass.newInstance(); + } } @Override diff --git a/fml/common/cpw/mods/fml/common/Mod.java b/fml/common/cpw/mods/fml/common/Mod.java index f9d65388c3..44a686569a 100644 --- a/fml/common/cpw/mods/fml/common/Mod.java +++ b/fml/common/cpw/mods/fml/common/Mod.java @@ -5,7 +5,7 @@ * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html - * + * * Contributors: * cpw - implementation */ @@ -18,12 +18,57 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import net.minecraft.item.ItemBlock; +import net.minecraft.network.packet.Packet250CustomPayload; +import cpw.mods.fml.common.event.FMLFingerprintViolationEvent; +import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLInterModComms; +import cpw.mods.fml.common.event.FMLInterModComms.IMCEvent; +import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; +import cpw.mods.fml.common.event.FMLPreInitializationEvent; +import cpw.mods.fml.common.event.FMLServerAboutToStartEvent; +import cpw.mods.fml.common.event.FMLServerStartedEvent; +import cpw.mods.fml.common.event.FMLServerStartingEvent; +import cpw.mods.fml.common.event.FMLServerStoppedEvent; +import cpw.mods.fml.common.event.FMLServerStoppingEvent; +import cpw.mods.fml.common.event.FMLStateEvent; +import cpw.mods.fml.common.network.IPacketHandler; +import cpw.mods.fml.common.network.NetworkMod; +import cpw.mods.fml.common.registry.GameRegistry; /** - * The new mod style in FML 1.3 + * This defines a Mod to FML. + * Any class found with this annotation applied will be loaded as a Mod. The instance that is loaded will + * represent the mod to other Mods in the system. It will be sent various subclasses of {@link FMLEvent} + * at pre-defined times during the loading of the game, based on where you have applied the {@link EventHandler} + * annotation. + * + * This annotation is usually paired with a second annotation {@link NetworkMod}, which declares the + * network related properties of this mod. + * + *

This is a simple example of a Mod. It has the modId of "MyModId", the name of "My example mod", it is + * version 1.0, and depends on FML being loaded. It has the {@link NetworkMod} annotation as well, declaring it uses channel + * "MyModChannel" and {@link IPacketHandler} class PacketHandler. + *

{@code
+ * package mymod;
+ * // Declare that this is a mod with modId "MyModId", name "My example mod", version "1.0" and dependency on FML.
+ * {@literal @}Mod(modId="MyModId",name="My example mod",version="1.0",dependencies="required-after:FML")
+ * // Declare that this is a network mod using the {@link Packet250CustomPayload} channel "MyModChannel", required on the client if it's present
+ * // on the server, with {@link IPacketHandler} class PacketHandler.
+ * {@literal @}NetworkMod(channels = { "MyModChannel" }, clientSideRequired = true, serverSideRequired = false, packetHandler = PacketHandler.class)
+ * public class MyMod {
+ *      // Populate this field with the instance of the mod created by FML
+ *      {@literal @}Instance("MyModId")
+ *      public MyMod instance;
+ *
+ *      // Mark this method for receiving an {@link FMLEvent} (in this case, it's the {@link FMLPreInitializationEvent})
+ *      {@literal @}EventHandler public void preInit(FMLPreInitializationEvent event)
+ *      {
+ *          // Do stuff in pre-init phase (read config, create blocks and items, register them)
+ *      }
+ * }
+ * 
* * @author cpw * @@ -65,10 +110,14 @@ public @interface Mod * An optional bukkit plugin that will be injected into the bukkit plugin framework if * this mod is loaded into the FML framework and the bukkit coremod is present. * Instances of the bukkit plugin can be obtained via the {@link BukkitPluginRef} annotation on fields. + * + * This may be implemented by a bukkit integration. It is not provided with vanilla FML or MinecraftForge. + * * @return The name of the plugin to load for this mod */ String bukkitPlugin() default ""; /** + * NOT YET IMPLEMENTED.
* Mods that this mod will not load with. * An optional comma separated string of (+|-)(*|modid[@value]) which specify mods that * this mod will refuse to load with, resulting in the game failing to start. @@ -98,34 +147,82 @@ public @interface Mod * * @return A string listing modids to exclude from loading with this mod. */ + @Deprecated String modExclusionList() default ""; /** * Specifying this field allows for a mod to expect a signed jar with a fingerprint matching this value. * The fingerprint should be SHA-1 encoded, lowercase with ':' removed. An empty value indicates that * the mod is not expecting to be signed. * - * Any incorrectness of the fingerprint, be it missing or wrong, will result in the {@link FingerprintWarning} - * method firing prior to any other event on the mod. + * Any incorrectness of the fingerprint, be it missing or wrong, will result in the {@link FMLFingerprintViolationEvent} + * event firing prior to any other event on the mod. * * @return A certificate fingerprint that is expected for this mod. */ String certificateFingerprint() default ""; /** - * The language the mod is authored in. This will be used to control certain libraries being downloaded. + * The language the mod is authored in. This will be used to control certain compatibility behaviours for this mod. * Valid values are currently "java", "scala" * * @return The language the mod is authored in */ String modLanguage() default "java"; /** + * NOT YET IMPLEMENTED.
* An optional ASM hook class, that can be used to apply ASM to classes loaded from this mod. It is also given - * the ASM tree of the class declaring {@link Mod} to with what it will. + * the ASM tree of the class declaring {@link Mod} to do with what it will. * * @return The name of a class to be loaded and executed. Must implement {@link IASMHook}. */ + @Deprecated String asmHookClass() default ""; + /** + * Marks the associated method as handling an FML lifecycle event. + * The method must have a single parameter, one of the following types. This annotation + * replaces the multiple different annotations that previously were used. + * + * Current event classes. This first section is standard lifecycle events. They are dispatched + * at various phases as the game starts. Each event should have information useful to that + * phase of the lifecycle. They are fired in this order. + * + * These suggestions are mostly just suggestions on what to do in each event. + *
    + *
  • {@link FMLPreInitializationEvent} : Run before anything else. Read your config, create blocks, + * items, etc, and register them with the {@link GameRegistry}.
  • + *
  • {@link FMLInitializationEvent} : Do your mod setup. Build whatever data structures you care about. Register recipes, + * send {@link FMLInterModComms} messages to other mods.
  • + *
  • {@link FMLPostInitializationEvent} : Handle interaction with other mods, complete your setup based on this.
  • + *
+ *

These are the server lifecycle events. They are fired whenever a server is running, or about to run. Each time a server + * starts they will be fired in this sequence. + *

    + *
  • {@link FMLServerAboutToStartEvent} : Use if you need to handle something before the server has even been created.
  • + *
  • {@link FMLServerStartingEvent} : Do stuff you need to do to set up the server. register commands, tweak the server.
  • + *
  • {@link FMLServerStartedEvent} : Do what you need to with the running server.
  • + *
  • {@link FMLServerStoppingEvent} : Do what you need to before the server has started it's shutdown sequence.
  • + *
  • {@link FMLServerStoppedEvent} : Do whatever cleanup you need once the server has shutdown. Generally only useful + * on the integrated server.
  • + *
+ * The second set of events are more specialized, for receiving notification of specific + * information. + *
    + *
  • {@link FMLFingerprintViolationEvent} : Sent just before {@link FMLPreInitializationEvent} + * if something is wrong with your mod signature
  • + *
  • {@link IMCEvent} : Sent just after {@link FMLInitializationEvent} if you have IMC messages waiting + * from other mods
  • + *
+ * + * @author cpw + * + */ + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.METHOD) + public @interface EventHandler{} + + /** + * Deprecated for {@link EventHandler}
* Mark the designated method as to be called at if there is something wrong with the certificate fingerprint of * the mod's jar, or it is missing, or otherwise a problem. * @author cpw @@ -133,72 +230,90 @@ public @interface Mod */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) + @Deprecated public @interface FingerprintWarning {} /** + * Deprecated for {@link EventHandler}
* Mark the designated method as being called at the "pre-initialization" phase * @author cpw * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) + @Deprecated public @interface PreInit {} /** + * Deprecated for {@link EventHandler}
* Mark the designated method as being called at the "initialization" phase * @author cpw * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) + @Deprecated public @interface Init {} /** + * Deprecated for {@link EventHandler}
* Mark the designated method as being called at the "post-initialization" phase * @author cpw * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) + @Deprecated public @interface PostInit {} /** + * Deprecated for {@link EventHandler}
* Mark the designated method as being called at the "server-about-to-start" phase * @author cpw * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) + @Deprecated public @interface ServerAboutToStart {} /** + * Deprecated for {@link EventHandler}
* Mark the designated method as being called at the "server-starting" phase * @author cpw * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) + @Deprecated public @interface ServerStarting {} /** + * Deprecated for {@link EventHandler}
* Mark the designated method as being called at the "server-started" phase * @author cpw * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) + @Deprecated public @interface ServerStarted {} /** + * Deprecated for {@link EventHandler}
* Mark the designated method as being called at the "server-stopping" phase * @author cpw * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) + @Deprecated public @interface ServerStopping {} /** + * Deprecated for {@link EventHandler}
* Mark the designated method as being called at the "server-stopped" phase * @author cpw * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) + @Deprecated public @interface ServerStopped {} /** + * Deprecated for {@link EventHandler}
* Mark the designated method as the receiver for {@link FMLInterModComms} messages * Called between {@link Init} and {@link PostInit} * @author cpw @@ -206,9 +321,11 @@ public @interface Mod */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) + @Deprecated public @interface IMCCallback {} /** - * Populate the annotated field with the mod instance. + * Populate the annotated field with the mod instance based on the specified ModId. This can be used + * to retrieve instances of other mods. * @author cpw * */ @@ -234,12 +351,14 @@ public @interface Mod String value() default ""; } /** - * Populate the annotated field with an instance of the Block as specified + * NOT IMPLEMENTED AND SCHEDULED FOR REMOVAL.
+ * Populate the annotated field with an instance of the Block as specified. This never worked. It will be removed. * @author cpw * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) + @Deprecated public @interface Block { /** * The block's name @@ -251,12 +370,14 @@ public @interface Mod Class itemTypeClass() default ItemBlock.class; } /** - * Populate the annotated field with an Item + * NOT IMPLEMENTED AND SCHEDULED FOR REMOVAL.
+ * Populate the annotated field with an Item. This never worked. It will be removed. * @author cpw * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) + @Deprecated public @interface Item { /** * The name of the item @@ -267,4 +388,14 @@ public @interface Mod */ String typeClass(); } + + /** + * Mod instance factory method. Should return an instance of the mod. Applies only to static methods on the same class as {@link Mod}. + * @author cpw + * + */ + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.FIELD) + public @interface InstanceFactory { + } } diff --git a/fml/common/cpw/mods/fml/common/ModClassLoader.java b/fml/common/cpw/mods/fml/common/ModClassLoader.java index c517d5d33c..e1b9ed6e38 100644 --- a/fml/common/cpw/mods/fml/common/ModClassLoader.java +++ b/fml/common/cpw/mods/fml/common/ModClassLoader.java @@ -47,7 +47,7 @@ public class ModClassLoader extends URLClassLoader public void addFile(File modFile) throws MalformedURLException { - URL url = modFile.toURI().toURL(); + URL url = modFile.toURI().toURL(); mainClassLoader.addURL(url); } diff --git a/fml/common/cpw/mods/fml/common/SidedProxy.java b/fml/common/cpw/mods/fml/common/SidedProxy.java index 10f85783e3..a70ccf396d 100644 --- a/fml/common/cpw/mods/fml/common/SidedProxy.java +++ b/fml/common/cpw/mods/fml/common/SidedProxy.java @@ -18,6 +18,29 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** + * Sided proxies are loaded based on the specific environment they find themselves loaded into. + * They are used to ensure that client-specific code (such as GUIs) is only loaded into the game + * on the client side. + * It is applied to static fields of a class, anywhere in your mod code. FML will scan + * and load any classes with this annotation at mod construction time. + * + *

+ * This example will load a CommonProxy on the server side, and a ClientProxy on the client side. + * + *

{@code
+ *  public class MySidedProxyHolder {
+ *      {@literal @}SidedProxy(modId="MyModId",clientSide="mymod.ClientProxy", serverSide="mymod.CommonProxy")
+ *      public static CommonProxy proxy;
+ *  }
+ *
+ *  public class CommonProxy {
+ *      // Common or server stuff here that needs to be overridden on the client
+ *  }
+ *
+ *  public class ClientProxy extends CommonProxy {
+ *      // Override common stuff with client specific stuff here
+ *  }
+ * 
* @author cpw * */