WOW 😲 such broken. Many brokes.

This commit is contained in:
cpw authored and LexManos committed 2018-09-05 11:40:47 -07:00
1 parent c1f0e1b68f
commit f942eb184a
266 files changed
+1717 -4018

No files matched your search

@@ -19,14 +19,61 @@
package net.minecraftforge.fml;
import net.minecraftforge.common.ForgeVersion;
import net.minecraftforge.fml.common.MinecraftDummyContainer;
import com.electronwill.nightconfig.core.path.PathConfig;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.loading.moddiscovery.IModInfo;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
public class DefaultModContainers
{
static {
PathConfig minecraftmod;
PathConfig forgemod;
try
{
minecraftmod = PathConfig.of(Paths.get(DefaultModContainers.class.getClassLoader().getResource("minecraftmod.toml").toURI()));
forgemod = PathConfig.of(Paths.get(DefaultModContainers.class.getClassLoader().getResource("forgemod.toml").toURI()));
minecraftmod.load();
forgemod.load();
}
catch (URISyntaxException | NullPointerException e)
{
throw new RuntimeException("Missing toml configs for minecraft and forge!", e);
}
minecraftModInfo = new ModInfo(null, minecraftmod);
forgeModInfo = new ModInfo(null, forgemod);
}
private static final IModInfo minecraftModInfo;
private static final IModInfo forgeModInfo;
// no construction
private DefaultModContainers() {}
public static final ModContainer MINECRAFT = new MinecraftDummyContainer(ForgeVersion.mcVersion);
}
public static List<IModInfo> getModInfos()
{
return Arrays.asList(minecraftModInfo, forgeModInfo);
}
public static final ModContainer MINECRAFT = new ModContainer(minecraftModInfo)
{
@Override
public boolean matches(Object mod)
{
return mod == this;
}
@Override
public Object getMod()
{
return this;
}
};
}
@@ -51,9 +51,13 @@ public class LaunchTesting
Configurator.setRootLevel(Level.DEBUG);
final MarkerFilter classloadingFilter = MarkerFilter.createFilter("CLASSLOADING", Filter.Result.DENY, Filter.Result.NEUTRAL);
final MarkerFilter launchpluginFilter = MarkerFilter.createFilter("LAUNCHPLUGIN", Filter.Result.DENY, Filter.Result.NEUTRAL);
final MarkerFilter axformFilter= MarkerFilter.createFilter("AXFORM", Filter.Result.DENY, Filter.Result.NEUTRAL);
final MarkerFilter eventbusFilter = MarkerFilter.createFilter("EVENTBUS", Filter.Result.DENY, Filter.Result.NEUTRAL);
final LoggerContext logcontext = LoggerContext.getContext(false);
// logcontext.getConfiguration().addFilter(classloadingFilter);
logcontext.getConfiguration().addFilter(classloadingFilter);
logcontext.getConfiguration().addFilter(launchpluginFilter);
logcontext.getConfiguration().addFilter(axformFilter);
logcontext.getConfiguration().addFilter(eventbusFilter);
logcontext.updateLoggers();
hackNatives();
Launcher.main("--launchTarget", "devfmlclient","--gameDir", "projects/run",
@@ -0,0 +1,62 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.loading.ModList;
import java.util.function.Supplier;
public enum LifecycleEventProvider
{
LOAD(()->new LifecycleEvent(ModLoadingStage.BEGIN)),
PREINIT(()->new LifecycleEvent(ModLoadingStage.PREINIT));
public void dispatch(final ModList target) {
target.dispatchLifeCycleEvent(this.event.get());
}
private final Supplier<? extends LifecycleEvent> event;
LifecycleEventProvider(Supplier<? extends LifecycleEvent> e)
{
event = e;
}
public static class LifecycleEvent extends Event {
private final ModLoadingStage stage;
public LifecycleEvent(ModLoadingStage stage)
{
this.stage = stage;
}
public ModLoadingStage fromStage()
{
return this.stage;
}
public ModLoadingStage toStage()
{
return ModLoadingStage.values()[this.stage.ordinal()+1];
}
}
}
@@ -17,11 +17,9 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.eventhandler;
package net.minecraftforge.fml;
public interface IEventListener
public enum ModLoadingStage
{
void invoke(Event event);
ERROR, BEGIN, CONSTRUCT, PREINIT, INIT, POSTINIT, COMPLETE
}
@@ -0,0 +1,68 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml;
import net.minecraft.client.Minecraft;
import net.minecraft.server.dedicated.DedicatedServer;
import net.minecraftforge.api.Side;
import net.minecraftforge.fml.loading.FMLEnvironment;
import java.util.function.Function;
import java.util.function.Supplier;
public enum SidedProvider
{
DATAFIXER(c->c.get().getDataFixer(), s->s.get().getDataFixer());
private static Supplier<Minecraft> client;
private static Supplier<DedicatedServer> server;
public static void setClient(Supplier<Minecraft> client)
{
SidedProvider.client = client;
}
public static void setServer(Supplier<DedicatedServer> server)
{
SidedProvider.server = server;
}
private final Function<Supplier<Minecraft>, ?> clientSide;
private final Function<Supplier<DedicatedServer>, ?> serverSide;
SidedProvider(Function<Supplier<Minecraft>,?> clientSide, Function<Supplier<DedicatedServer>,?> serverSide)
{
this.clientSide = clientSide;
this.serverSide = serverSide;
}
@SuppressWarnings("unchecked")
public <T> T get() {
if (FMLEnvironment.side == Side.CLIENT) {
return (T)this.clientSide.apply(client);
}
else if (FMLEnvironment.side == Side.SERVER) {
return (T)this.serverSide.apply(server);
}
else {
throw new IllegalArgumentException("THREE SIDES? WUT?");
}
}
}
@@ -1,50 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml;
import com.electronwill.nightconfig.core.conversion.Converter;
import java.net.MalformedURLException;
import java.net.URL;
public final class TomlConverters
{
public static class StringToURL implements Converter<URL, String> {
@Override
public URL convertToField(String value)
{
try
{
return new URL(value);
}
catch (MalformedURLException e)
{
throw new RuntimeException("Invalid URL specified", e);
}
}
@Override
public String convertFromField(URL value)
{
return value.toString();
}
}
}
@@ -0,0 +1,122 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.versioning.ComparableVersion;
import javax.annotation.Nullable;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class VersionChecker
{
public enum Status
{
PENDING(),
FAILED(),
UP_TO_DATE(),
OUTDATED(3, true),
AHEAD(),
BETA(),
BETA_OUTDATED(6, true);
final int sheetOffset;
final boolean draw, animated;
Status()
{
this(0, false, false);
}
Status(int sheetOffset)
{
this(sheetOffset, true, false);
}
Status(int sheetOffset, boolean animated)
{
this(sheetOffset, true, animated);
}
Status(int sheetOffset, boolean draw, boolean animated)
{
this.sheetOffset = sheetOffset;
this.draw = draw;
this.animated = animated;
}
public int getSheetOffset()
{
return sheetOffset;
}
public boolean shouldDraw()
{
return draw;
}
public boolean isAnimated()
{
return animated;
}
}
public static class CheckResult
{
public final Status status;
@Nullable
public final ComparableVersion target;
public final Map<ComparableVersion, String> changes;
@Nullable
public final String url;
private CheckResult(Status status, @Nullable ComparableVersion target, @Nullable Map<ComparableVersion, String> changes, @Nullable String url)
{
this.status = status;
this.target = target;
this.changes = changes == null ? Collections.<ComparableVersion, String>emptyMap() : Collections.unmodifiableMap(changes);
this.url = url;
}
}
public static void startVersionCheck()
{
}
// Gather a list of mods that have opted in to this update system by providing a URL.
public static Map<ModContainer, URL> gatherMods()
{
Map<ModContainer, URL> ret = new HashMap<>();
return ret;
}
private static Map<ModContainer, CheckResult> results = new ConcurrentHashMap<>();
public static CheckResult getResult(ModContainer mod)
{
return new CheckResult(Status.PENDING, null, null, null);
}
}
@@ -20,15 +20,21 @@
package net.minecraftforge.fml.client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.IReloadableResourceManager;
import net.minecraft.client.resources.IResourcePack;
import net.minecraft.client.resources.data.MetadataSerializer;
import net.minecraftforge.common.ForgeVersion;
import net.minecraftforge.fml.LifecycleEventProvider;
import net.minecraftforge.fml.SidedProvider;
import net.minecraftforge.fml.VersionChecker;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.loading.FMLLoader;
import org.lwjgl.input.Mouse;
import java.io.IOException;
import java.util.List;
public class ClientModLoader
@@ -40,8 +46,9 @@ public class ClientModLoader
* @param mcResourceManager
* @param metadataSerializer_
*/
public static void begin(Minecraft minecraft, List<IResourcePack> defaultResourcePacks, IReloadableResourceManager mcResourceManager, MetadataSerializer metadataSerializer_)
public static void begin(final Minecraft minecraft, final List<IResourcePack> defaultResourcePacks, final IReloadableResourceManager mcResourceManager, MetadataSerializer metadataSerializer_)
{
SidedProvider.setClient(()->minecraft);
SplashProgress.start();
FMLLoader.getModLoader().loadMods();
minecraft.refreshResources();
@@ -52,9 +59,9 @@ public class ClientModLoader
SplashProgress.finish();
}
public static ForgeVersion.Status checkForUpdates()
public static VersionChecker.Status checkForUpdates()
{
return ForgeVersion.Status.UP_TO_DATE;
return VersionChecker.Status.UP_TO_DATE;
}
public static void complete()
@@ -62,4 +69,30 @@ public class ClientModLoader
GlStateManager.disableTexture2D();
GlStateManager.enableTexture2D();
}
// If the startup screen has a notification on it, render that instead of the loading screen
public static boolean drawNotificationOverProgressScreen(final Minecraft client, final ScaledResolution scaledResolution) throws IOException
{
if (client.currentScreen instanceof GuiNotification)
{
int width = scaledResolution.getScaledWidth();
int height = scaledResolution.getScaledHeight();
int mouseX = Mouse.getX() * width / client.displayWidth;
int mouseZ = height - Mouse.getY() * height / client.displayHeight - 1;
client.currentScreen.drawScreen(mouseX, mouseZ, 0);
client.currentScreen.handleInput();
return true;
}
else
{
return false;
}
}
public static boolean isErrored()
{
return false;
}
}
@@ -109,7 +109,7 @@ import net.minecraftforge.fml.common.ModMetadata;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
import net.minecraftforge.fml.common.StartupQuery;
import net.minecraftforge.fml.common.WrongMinecraftVersionException;
import net.minecraftforge.fml.common.eventhandler.EventBus;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.common.network.FMLNetworkEvent;
import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler;
import net.minecraftforge.fml.common.toposort.ModSortingException;
@@ -118,8 +118,6 @@ import net.minecraftforge.registries.GameData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.FormattedMessage;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
@@ -179,9 +177,6 @@ public class FMLClientHandler implements IFMLSidedHandler
private DummyModContainer optifineContainer;
@Deprecated // TODO remove in 1.13. mods are referencing this to get around client-only dependencies in old Forge versions
private MissingModsException modsMissing;
private boolean loading = true;
@Nullable
@@ -583,15 +578,6 @@ public class FMLClientHandler implements IFMLSidedHandler
return client.getIntegratedServer();
}
/**
* TODO remove in 1.13
*/
@Deprecated
public void displayMissingMods(Object modMissingPacket)
{
// showGuiScreen(new GuiModsMissingForServer(modMissingPacket));
}
/**
* If the client is in the midst of loading, we disable saving so that custom settings aren't wiped out
*/
@@ -894,7 +880,7 @@ public class FMLClientHandler implements IFMLSidedHandler
}
@Override
public void fireNetRegistrationEvent(EventBus bus, NetworkManager manager, Set<String> channelSet, String channel, Side side)
public void fireNetRegistrationEvent(IEventBus bus, NetworkManager manager, Set<String> channelSet, String channel, Side side)
{
if (side == Side.CLIENT)
{
@@ -930,7 +916,6 @@ public class FMLClientHandler implements IFMLSidedHandler
throw new RuntimeException("Unknown INetHandler: " + net);
}
private SetMultimap<String,ResourceLocation> missingTextures = HashMultimap.create();
private Set<String> badTextureDomains = Sets.newHashSet();
private Table<String, String, Set<ResourceLocation>> brokenTextures = HashBasedTable.create();
@@ -1043,6 +1028,7 @@ public class FMLClientHandler implements IFMLSidedHandler
return DISALLOWED_CHAR_MATCHER.removeFrom(StringUtils.stripControlCodes(message));
}
public void logMissingTextureErrors() {}
@Override
public void reloadRenderers()
{
@@ -0,0 +1,147 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.client;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.collect.Table;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.AbstractResourcePack;
import net.minecraft.client.resources.FallbackResourceManager;
import net.minecraft.client.resources.IResourcePack;
import net.minecraft.client.resources.SimpleReloadableResourceManager;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.FMLContainerHolder;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class TextureTracker
{
private static final SetMultimap<String,ResourceLocation> missingTextures = HashMultimap.create();
private static final Set<String> badTextureDomains = Sets.newHashSet();
private static final Table<String, String, Set<ResourceLocation>> brokenTextures = HashBasedTable.create();
public static void trackMissingTexture(ResourceLocation resourceLocation)
{
badTextureDomains.add(resourceLocation.getResourceDomain());
missingTextures.put(resourceLocation.getResourceDomain(),resourceLocation);
}
public static void trackBrokenTexture(ResourceLocation resourceLocation, String error)
{
badTextureDomains.add(resourceLocation.getResourceDomain());
Set<ResourceLocation> badType = brokenTextures.get(resourceLocation.getResourceDomain(), error);
if (badType == null)
{
badType = Sets.newHashSet();
brokenTextures.put(resourceLocation.getResourceDomain(), MoreObjects.firstNonNull(error, "Unknown error"), badType);
}
badType.add(resourceLocation);
}
public static void logMissingTextureErrors()
{
if (missingTextures.isEmpty() && brokenTextures.isEmpty())
{
return;
}
Logger logger = LogManager.getLogger("TEXTURE ERRORS");
logger.error(Strings.repeat("+=", 25));
logger.error("The following texture errors were found.");
Map<String,FallbackResourceManager> resManagers = ObfuscationReflectionHelper.getPrivateValue(SimpleReloadableResourceManager.class, (SimpleReloadableResourceManager)Minecraft.getMinecraft().getResourceManager(), "domainResourceManagers", "field_110548"+"_a");
for (String resourceDomain : badTextureDomains)
{
Set<ResourceLocation> missing = missingTextures.get(resourceDomain);
logger.error(Strings.repeat("=", 50));
logger.error(" DOMAIN {}", resourceDomain);
logger.error(Strings.repeat("-", 50));
logger.error(" domain {} is missing {} texture{}",resourceDomain, missing.size(),missing.size()!=1 ? "s" : "");
FallbackResourceManager fallbackResourceManager = resManagers.get(resourceDomain);
if (fallbackResourceManager == null)
{
logger.error(" domain {} is missing a resource manager - it is probably a side-effect of automatic texture processing", resourceDomain);
}
else
{
List<IResourcePack> resPacks = ObfuscationReflectionHelper.getPrivateValue(FallbackResourceManager.class, fallbackResourceManager, "resourcePacks","field_110540"+"_a");
logger.error(" domain {} has {} location{}:",resourceDomain, resPacks.size(), resPacks.size() != 1 ? "s" :"");
for (IResourcePack resPack : resPacks)
{
if (resPack instanceof FMLContainerHolder) {
FMLContainerHolder containerHolder = (FMLContainerHolder) resPack;
ModContainer fmlContainer = containerHolder.getFMLContainer();
logger.error(" mod {} resources at {}", fmlContainer.getModId(), fmlContainer.getSource().getPath());
}
else if (resPack instanceof AbstractResourcePack)
{
AbstractResourcePack resourcePack = (AbstractResourcePack) resPack;
File resPath = ObfuscationReflectionHelper.getPrivateValue(AbstractResourcePack.class, resourcePack, "resourcePackFile","field_110597"+"_b");
logger.error(" resource pack at path {}",resPath.getPath());
}
else
{
logger.error(" unknown resourcepack type {} : {}", resPack.getClass().getName(), resPack.getPackName());
}
}
}
logger.error(Strings.repeat("-", 25));
if (missingTextures.containsKey(resourceDomain)) {
logger.error(" The missing resources for domain {} are:", resourceDomain);
for (ResourceLocation rl : missing) {
logger.error(" {}", rl.getResourcePath());
}
logger.error(Strings.repeat("-", 25));
}
if (!brokenTextures.containsRow(resourceDomain))
{
logger.error(" No other errors exist for domain {}", resourceDomain);
}
else
{
logger.error(" The following other errors were reported for domain {}:",resourceDomain);
Map<String, Set<ResourceLocation>> resourceErrs = brokenTextures.row(resourceDomain);
for (String error: resourceErrs.keySet())
{
logger.error(Strings.repeat("-", 25));
logger.error(" Problem: {}", error);
for (ResourceLocation rl : resourceErrs.get(error))
{
logger.error(" {}",rl.getResourcePath());
}
}
}
logger.error(Strings.repeat("=", 50));
}
logger.error(Strings.repeat("+=", 25));
}
}
@@ -25,7 +25,6 @@ import static net.minecraftforge.fml.client.config.GuiUtils.UNDO_CHAR;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@@ -43,7 +42,7 @@ import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEve
import net.minecraftforge.fml.client.event.ConfigChangedEvent.PostConfigChangedEvent;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.eventhandler.Event.Result;
import net.minecraftforge.eventbus.api.Event.Result;
import org.lwjgl.input.Keyboard;
@@ -19,8 +19,8 @@
package net.minecraftforge.fml.client.event;
import net.minecraftforge.fml.common.eventhandler.Event;
import net.minecraftforge.fml.common.eventhandler.Event.HasResult;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.eventbus.api.Event.HasResult;
import javax.annotation.Nullable;
@@ -36,7 +36,7 @@ import javax.annotation.Nullable;
* @author bspkrs
*/
@HasResult
public class ConfigChangedEvent extends Event
public class ConfigChangedEvent extends net.minecraftforge.eventbus.api.Event
{
private final String modID;
private final boolean isWorldRunning;
@@ -1,246 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common;
import java.io.File;
import java.net.URL;
import java.security.cert.Certificate;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraftforge.fml.StringUtils;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.DefaultArtifactVersion;
import net.minecraftforge.fml.common.versioning.VersionRange;
import com.google.common.collect.ImmutableList;
import com.google.common.eventbus.EventBus;
import javax.annotation.Nullable;
public class DummyModContainer implements ModContainer
{
private ModMetadata md;
private ArtifactVersion processedVersion;
private String label;
private int classVersion;
public DummyModContainer(ModMetadata md)
{
this.md = md;
}
public DummyModContainer(String label)
{
this.label = label;
}
public DummyModContainer()
{
}
@Override
public void bindMetadata(MetadataCollection mc)
{
}
@Override
public List<ArtifactVersion> getDependants()
{
return Collections.emptyList();
}
@Override
public List<ArtifactVersion> getDependencies()
{
return Collections.emptyList();
}
@Override
public Set<ArtifactVersion> getRequirements()
{
return Collections.emptySet();
}
@Override
public ModMetadata getMetadata()
{
return md;
}
@Override
public Object getMod()
{
return null;
}
@Override
public String getModId()
{
return md.modId;
}
@Override
public String getPrefix()
{
return StringUtils.toLowerCase(getModId());
}
@Override
public String getName()
{
return md.name;
}
@Override
public String getSortingRules()
{
return "";
}
@Override
public File getSource()
{
return null;
}
@Override
public String getVersion()
{
return md.version;
}
@Override
public boolean matches(Object mod)
{
return false;
}
@Override
public void setEnabledState(boolean enabled)
{
}
@Override
public boolean registerBus(EventBus bus, LoadController controller)
{
return false;
}
@Override
public ArtifactVersion getProcessedVersion()
{
if (processedVersion == null)
{
processedVersion = new DefaultArtifactVersion(getModId(), getVersion());
}
return processedVersion;
}
@Override
public boolean isImmutable()
{
return false;
}
@Override
public String getDisplayVersion()
{
return md.version;
}
@Override
public VersionRange acceptableMinecraftVersionRange()
{
return Loader.instance().getMinecraftModContainer().getStaticVersionRange();
}
@Override
@Nullable
public Certificate getSigningCertificate()
{
return null;
}
@Override
public String toString()
{
return md != null ? getModId() : "Dummy Container ("+label+") @" + System.identityHashCode(this);
}
@Override
public Map<String, String> getCustomModProperties()
{
return EMPTY_PROPERTIES;
}
@Override
public Class<?> getCustomResourcePackClass()
{
return null;
}
@Override
public Map<String, String> getSharedModDescriptor()
{
return null;
}
@Override
public Disableable canBeDisabled()
{
return Disableable.NEVER;
}
@Override
public String getGuiClassName()
{
return null;
}
@Override
public List<String> getOwnedPackages()
{
return ImmutableList.of();
}
@Override
public boolean shouldLoadInEnvironment()
{
return true;
}
@Override
public URL getUpdateUrl()
{
return null;
}
@Override
public void setClassVersion(int classVersion)
{
this.classVersion = classVersion;
}
@Override
public int getClassVersion()
{
return this.classVersion;
}
}
@@ -54,7 +54,7 @@ import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.CompoundDataFixer;
import net.minecraftforge.fml.client.BrandingControl;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.EventBus;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
@@ -102,7 +102,7 @@ public class FMLCommonHandler
private List<String> brandingsNoMC;
private Set<SaveHandler> handlerSet = Collections.newSetFromMap(new MapMaker().weakKeys().<SaveHandler,Boolean>makeMap());
private WeakReference<SaveHandler> handlerToCheck;
private EventBus eventBus = MinecraftForge.EVENT_BUS;
private IEventBus eventBus = MinecraftForge.EVENT_BUS;
private volatile CountDownLatch exitLatch = null;
private FMLCommonHandler()
@@ -115,7 +115,7 @@ public class FMLCommonHandler
* @return the event bus
*/
@Deprecated
public EventBus bus()
public IEventBus bus()
{
return eventBus;
}
@@ -1,776 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Config;
import net.minecraftforge.common.config.ConfigManager;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.Mod.Metadata;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import net.minecraftforge.fml.common.discovery.ModCandidate;
import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData;
import net.minecraftforge.fml.common.event.FMLConstructionEvent;
import net.minecraftforge.fml.common.event.FMLEvent;
import net.minecraftforge.fml.common.event.FMLFingerprintViolationEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.DefaultArtifactVersion;
import net.minecraftforge.fml.common.versioning.DependencyParser;
import net.minecraftforge.fml.common.versioning.VersionParser;
import net.minecraftforge.fml.common.versioning.VersionRange;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import net.minecraftforge.fml.relauncher.Side;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.function.Function;
import com.google.common.base.Strings;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import javax.annotation.Nullable;
import static net.minecraftforge.fml.Logging.CORE;
public class FMLModContainer implements ModContainer
{
private Object modInstance;
private File source;
private ModMetadata modMetadata;
private String className;
private Map<String, Object> descriptor;
private boolean enabled = true;
private String internalVersion;
private boolean overridesMetadata;
private EventBus eventBus;
private LoadController controller;
private DefaultArtifactVersion processedVersion;
private String annotationDependencies;
private VersionRange minecraftAccepted;
private boolean fingerprintNotPresent;
private Set<String> sourceFingerprints;
private Certificate certificate;
private String modLanguage;
private ILanguageAdapter languageAdapter;
private Disableable disableability;
private ListMultimap<Class<? extends FMLEvent>, Method> eventMethods;
private Map<String, String> customModProperties;
private ModCandidate candidate;
private URL updateJSONUrl;
private int classVersion;
private Logger modLog;
public FMLModContainer(String className, ModCandidate container, Map<String, Object> modDescriptor)
{
this.className = className;
this.source = container.getModContainer();
this.candidate = container;
this.descriptor = modDescriptor;
this.eventMethods = ArrayListMultimap.create();
this.modLanguage = (String)modDescriptor.get("modLanguage");
String languageAdapterType = (String)modDescriptor.get("modLanguageAdapter");
if (Strings.isNullOrEmpty(languageAdapterType))
{
this.languageAdapter = "scala".equals(modLanguage) ? new ILanguageAdapter.ScalaAdapter() : new ILanguageAdapter.JavaAdapter();
}
else
{
// Delay loading of the adapter until the mod is on the classpath, in case the mod itself contains it.
this.languageAdapter = null;
FMLLog.log.trace("Using custom language adapter {} for {} (modid: {})", languageAdapterType, this.className, getModId());
}
sanityCheckModId();
modLog = LogManager.getLogger(getModId());
}
public FMLModContainer(ModInfo info, String className, ClassLoader modClassLoader)
{
try
{
final Class<?> aClass = Class.forName(className, true, modClassLoader);
LogManager.getLogger("FML").error("Loaded {} with {}", aClass, aClass.getClassLoader());
}
catch (ClassNotFoundException e)
{
LogManager.getLogger("FML").error(CORE, "Failed to load class {}", className, e);
throw new RuntimeException(e);
}
}
private void sanityCheckModId()
{
String modid = (String)this.descriptor.get("modid");
if (Strings.isNullOrEmpty(modid))
{
throw new IllegalArgumentException("The modId is null or empty");
}
if (modid.length() > 64)
{
throw new IllegalArgumentException(String.format("The modId %s is longer than the maximum of 64 characters.", modid));
}
if (!modid.equals(modid.toLowerCase(Locale.ENGLISH)))
{
throw new IllegalArgumentException(String.format("The modId %s must be all lowercase.", modid));
}
}
private ILanguageAdapter getLanguageAdapter()
{
if (languageAdapter == null)
{
try
{
languageAdapter = (ILanguageAdapter)Class.forName((String)descriptor.get("modLanguageAdapter"), true, Loader.instance().getModClassLoader()).newInstance();
}
catch (Exception ex)
{
FMLLog.log.error("Error constructing custom mod language adapter referenced by {} (modid: {})", getModId(), ex);
throw new RuntimeException(ex);
}
}
return languageAdapter;
}
@Override
public String getModId()
{
return (String)descriptor.get("modid");
}
@Override
public String getName()
{
return modMetadata.name;
}
@Override
public String getVersion()
{
return internalVersion;
}
@Override
public File getSource()
{
return source;
}
@Override
public ModMetadata getMetadata()
{
return modMetadata;
}
@Override
public void bindMetadata(MetadataCollection mc)
{
modMetadata = mc.getMetadataForId(getModId(), descriptor);
if (descriptor.containsKey("useMetadata"))
{
overridesMetadata = !((Boolean)descriptor.get("useMetadata"));
}
if (overridesMetadata || !modMetadata.useDependencyInformation)
{
annotationDependencies = (String)descriptor.get("dependencies");
DependencyParser dependencyParser = new DependencyParser(getModId(), FMLCommonHandler.instance().getSide());
DependencyParser.DependencyInfo info = dependencyParser.parseDependencies(annotationDependencies);
info.dependants.addAll(Loader.instance().getInjectedBefore(getModId()));
info.dependencies.addAll(Loader.instance().getInjectedAfter(getModId()));
modMetadata.requiredMods = info.requirements;
modMetadata.dependencies = info.dependencies;
modMetadata.dependants = info.dependants;
modLog.trace("Parsed dependency info : Requirements: {} After:{} Before:{}", info.requirements, info.dependencies, info.dependants);
}
else
{
modLog.trace("Using mcmod dependency info : {} {} {}", modMetadata.requiredMods, modMetadata.dependencies, modMetadata.dependants);
}
if (Strings.isNullOrEmpty(modMetadata.name))
{
modLog.info("Mod {} is missing the required element 'name'. Substituting {}", getModId(), getModId());
modMetadata.name = getModId();
}
internalVersion = (String)descriptor.get("version");
if (Strings.isNullOrEmpty(internalVersion))
{
Properties versionProps = searchForVersionProperties();
if (versionProps != null)
{
internalVersion = versionProps.getProperty(getModId() + ".version");
modLog.debug("Found version {} for mod {} in version.properties, using", internalVersion, getModId());
}
}
if (Strings.isNullOrEmpty(internalVersion) && !Strings.isNullOrEmpty(modMetadata.version))
{
modLog.warn("Mod {} is missing the required element 'version' and a version.properties file could not be found. Falling back to metadata version {}", getModId(), modMetadata.version);
internalVersion = modMetadata.version;
}
if (Strings.isNullOrEmpty(internalVersion))
{
modLog.warn("Mod {} is missing the required element 'version' and no fallback can be found. Substituting '1.0'.", getModId());
modMetadata.version = internalVersion = "1.0";
}
String mcVersionString = (String)descriptor.get("acceptedMinecraftVersions");
if ("[1.12]".equals(mcVersionString))
mcVersionString = "[1.12,1.12.2]";
if ("[1.12.1]".equals(mcVersionString) || "[1.12,1.12.1]".equals(mcVersionString))
mcVersionString = "[1.12,1.12.2]";
if (!Strings.isNullOrEmpty(mcVersionString))
{
minecraftAccepted = VersionParser.parseRange(mcVersionString);
}
else
{
minecraftAccepted = Loader.instance().getMinecraftModContainer().getStaticVersionRange();
}
String jsonURL = (String)descriptor.get("updateJSON");
if (!Strings.isNullOrEmpty(jsonURL))
{
try
{
this.updateJSONUrl = new URL(jsonURL);
}
catch (MalformedURLException e)
{
modLog.debug("Specified json URL invalid: {}", jsonURL);
}
}
}
@Nullable
public Properties searchForVersionProperties()
{
try
{
modLog.debug("Attempting to load the file version.properties from {} to locate a version number for {}", getSource().getName(), getModId());
Properties version = null;
if (getSource().isFile())
{
ZipFile source = new ZipFile(getSource());
ZipEntry versionFile = source.getEntry("version.properties");
if (versionFile != null)
{
version = new Properties();
InputStream sourceInputStream = source.getInputStream(versionFile);
try
{
version.load(sourceInputStream);
}
finally
{
IOUtils.closeQuietly(sourceInputStream);
}
}
source.close();
}
else if (getSource().isDirectory())
{
File propsFile = new File(getSource(), "version.properties");
if (propsFile.exists() && propsFile.isFile())
{
version = new Properties();
try (FileInputStream fis = new FileInputStream(propsFile))
{
version.load(fis);
}
}
}
return version;
}
catch (IOException e)
{
modLog.trace("Failed to find a usable version.properties file");
return null;
}
}
@Override
public void setEnabledState(boolean enabled)
{
this.enabled = enabled;
}
@Override
public Set<ArtifactVersion> getRequirements()
{
return modMetadata.requiredMods;
}
@Override
public List<ArtifactVersion> getDependencies()
{
return modMetadata.dependencies;
}
@Override
public List<ArtifactVersion> getDependants()
{
return modMetadata.dependants;
}
@Override
public String getSortingRules()
{
return ((overridesMetadata || !modMetadata.useDependencyInformation) ? Strings.nullToEmpty(annotationDependencies) : modMetadata.printableSortingRules());
}
@Override
public boolean matches(Object mod)
{
return mod == modInstance;
}
@Override
public Object getMod()
{
return modInstance;
}
@Override
public boolean registerBus(EventBus bus, LoadController controller)
{
if (this.enabled)
{
modLog.debug("Enabling mod {}", getModId());
this.eventBus = bus;
this.controller = controller;
eventBus.register(this);
return true;
}
else
{
return false;
}
}
@Nullable
@SuppressWarnings("unchecked")
private Method gatherAnnotations(Class<?> clazz) throws Exception
{
Method factoryMethod = null;
for (Method m : clazz.getDeclaredMethods())
{
for (Annotation a : m.getAnnotations())
{
if (a.annotationType().equals(Mod.EventHandler.class))
{
if (m.getParameterTypes().length == 1 && FMLEvent.class.isAssignableFrom(m.getParameterTypes()[0]))
{
m.setAccessible(true);
eventMethods.put((Class<? extends FMLEvent>)m.getParameterTypes()[0], m);
}
else
{
modLog.error("The mod {} appears to have an invalid event annotation {}. 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))
{
modLog.error("The InstanceFactory annotation can only apply to a static method, taking zero arguments - it will be ignored on {}({})", m.getName(), Arrays.asList(m.getParameterTypes()));
}
else if (factoryMethod != null)
{
modLog.error("The InstanceFactory annotation can only be used once, the application to {}({}) will be ignored", m.getName(), Arrays.asList(m.getParameterTypes()));
}
}
}
}
return factoryMethod;
}
private void processFieldAnnotations(ASMDataTable asmDataTable) throws Exception
{
SetMultimap<String, ASMData> annotations = asmDataTable.getAnnotationsFor(this);
parseSimpleFieldAnnotation(annotations, Instance.class.getName(), ModContainer::getMod);
parseSimpleFieldAnnotation(annotations, Metadata.class.getName(), ModContainer::getMetadata);
}
private void parseSimpleFieldAnnotation(SetMultimap<String, ASMData> annotations, String annotationClassName, Function<ModContainer, Object> retriever) throws IllegalAccessException
{
Set<ASMDataTable.ASMData> mods = annotations.get(Mod.class.getName());
String[] annName = annotationClassName.split("\\.");
String annotationName = annName[annName.length - 1];
for (ASMData targets : annotations.get(annotationClassName))
{
String targetMod = (String)targets.getAnnotationInfo().get("value");
String owner = (String)targets.getAnnotationInfo().get("owner");
if (Strings.isNullOrEmpty(owner))
{
owner = ASMDataTable.getOwnerModID(mods, targets);
if (Strings.isNullOrEmpty(owner))
{
FMLLog.bigWarning("Could not determine owning mod for @{} on {} for mod {}", annotationClassName, targets.getClassName(), this.getModId());
continue;
}
}
if (!this.getModId().equals(owner))
{
FMLLog.log.debug("Skipping @{} injection for {}.{} since it is not for mod {}", annotationClassName, targets.getClassName(), targets.getObjectName(), this.getModId());
continue;
}
Field f = null;
Object injectedMod = null;
ModContainer mc = this;
boolean isStatic = false;
Class<?> clz = modInstance.getClass();
if (!Strings.isNullOrEmpty(targetMod))
{
if (Loader.isModLoaded(targetMod))
{
mc = Loader.instance().getIndexedModList().get(targetMod);
}
else
{
mc = null;
}
}
if (mc != null)
{
try
{
clz = Class.forName(targets.getClassName(), true, Loader.instance().getModClassLoader());
f = clz.getDeclaredField(targets.getObjectName());
f.setAccessible(true);
isStatic = Modifier.isStatic(f.getModifiers());
injectedMod = retriever.apply(mc);
}
catch (ReflectiveOperationException e)
{
modLog.warn("Attempting to load @{} in class {} for {} and failing", annotationName, targets.getClassName(), mc.getModId(), e);
}
}
if (f != null)
{
Object target = null;
if (!isStatic)
{
target = modInstance;
if (!modInstance.getClass().equals(clz))
{
modLog.warn("Unable to inject @{} in non-static field {}.{} for {} as it is NOT the primary mod instance", annotationName, targets.getClassName(), targets.getObjectName(), mc.getModId());
continue;
}
}
f.set(target, injectedMod);
}
}
}
@Subscribe
public void constructMod(FMLConstructionEvent event)
{
try
{
ModClassLoader modClassLoader = event.getModClassLoader();
modClassLoader.addFile(source);
modClassLoader.clearNegativeCacheFor(candidate.getClassList());
//Only place I could think to add this...
MinecraftForge.preloadCrashClasses(event.getASMHarvestedData(), getModId(), candidate.getClassList());
Class<?> clazz = Class.forName(className, true, modClassLoader);
Certificate[] certificates = clazz.getProtectionDomain().getCodeSource().getCertificates();
ImmutableList<String> certList = CertificateHelper.getFingerprints(certificates);
sourceFingerprints = ImmutableSet.copyOf(certList);
String expectedFingerprint = (String)descriptor.get("certificateFingerprint");
fingerprintNotPresent = true;
if (expectedFingerprint != null && !expectedFingerprint.isEmpty())
{
if (!sourceFingerprints.contains(expectedFingerprint))
{
Level warnLevel = Level.ERROR;
if (source.isDirectory())
{
warnLevel = Level.TRACE;
}
modLog.log(warnLevel, "The mod {} is expecting signature {} for source {}, however there is no signature matching that description", getModId(), expectedFingerprint, source.getName());
}
else
{
certificate = certificates[certList.indexOf(expectedFingerprint)];
fingerprintNotPresent = false;
}
}
@SuppressWarnings("unchecked")
List<Map<String, Object>> props = (List<Map<String, Object>>)descriptor.get("customProperties");
if (props != null)
{
com.google.common.collect.ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
for (Map<String, Object> p : props)
{
builder.put((String)p.get("k"), (String)p.get("v"));
}
customModProperties = builder.build();
}
else
{
customModProperties = EMPTY_PROPERTIES;
}
Boolean hasDisableableFlag = (Boolean)descriptor.get("canBeDeactivated");
boolean hasReverseDepends = !event.getReverseDependencies().get(getModId()).isEmpty();
if (hasDisableableFlag != null && hasDisableableFlag)
{
disableability = hasReverseDepends ? Disableable.DEPENDENCIES : Disableable.YES;
}
else
{
disableability = hasReverseDepends ? Disableable.DEPENDENCIES : Disableable.RESTART;
}
Method factoryMethod = gatherAnnotations(clazz);
modInstance = getLanguageAdapter().getNewInstance(this, clazz, modClassLoader, factoryMethod);
NetworkRegistry.INSTANCE.register(this, clazz, (String)(descriptor.containsKey("acceptableRemoteVersions") ? descriptor.get("acceptableRemoteVersions") : null), event.getASMHarvestedData());
if (fingerprintNotPresent)
{
eventBus.post(new FMLFingerprintViolationEvent(source.isDirectory(), source, ImmutableSet.copyOf(this.sourceFingerprints), expectedFingerprint));
}
ProxyInjector.inject(this, event.getASMHarvestedData(), FMLCommonHandler.instance().getSide(), getLanguageAdapter());
AutomaticEventSubscriber.inject(this, event.getASMHarvestedData(), FMLCommonHandler.instance().getSide());
ConfigManager.sync(this.getModId(), Config.Type.INSTANCE);
processFieldAnnotations(event.getASMHarvestedData());
}
catch (Throwable e)
{
controller.errorOccurred(this, e);
}
}
@Subscribe
public void handleModStateEvent(FMLEvent event)
{
if (!eventMethods.containsKey(event.getClass()))
{
return;
}
try
{
for (Method m : eventMethods.get(event.getClass()))
{
m.invoke(modInstance, event);
}
}
catch (Throwable t)
{
controller.errorOccurred(this, t);
}
}
@Override
public ArtifactVersion getProcessedVersion()
{
if (processedVersion == null)
{
processedVersion = new DefaultArtifactVersion(getModId(), getVersion());
}
return processedVersion;
}
@Override
public boolean isImmutable()
{
return false;
}
@Override
public String getDisplayVersion()
{
return modMetadata.version;
}
@Override
public VersionRange acceptableMinecraftVersionRange()
{
return minecraftAccepted;
}
@Override
public Certificate getSigningCertificate()
{
return certificate;
}
@Override
public String toString()
{
return "FMLMod:" + getModId() + "{" + getVersion() + "}";
}
@Override
public Map<String, String> getCustomModProperties()
{
return customModProperties;
}
@Override
public Class<?> getCustomResourcePackClass()
{
try
{
return getSource().isDirectory() ? Class.forName("net.minecraftforge.fml.client.FMLFolderResourcePack", true, getClass().getClassLoader()) : Class.forName("net.minecraftforge.fml.client.FMLFileResourcePack", true, getClass().getClassLoader());
}
catch (ClassNotFoundException e)
{
return null;
}
}
@Override
public Map<String, String> getSharedModDescriptor()
{
Map<String, String> descriptor = Maps.newHashMap();
descriptor.put("modsystem", "FML");
descriptor.put("id", getModId());
descriptor.put("version", getDisplayVersion());
descriptor.put("name", getName());
descriptor.put("url", modMetadata.url);
descriptor.put("authors", modMetadata.getAuthorList());
descriptor.put("description", modMetadata.description);
return descriptor;
}
@Override
public Disableable canBeDisabled()
{
return disableability;
}
@Override
public String getGuiClassName()
{
return (String)descriptor.get("guiFactory");
}
@Override
public List<String> getOwnedPackages()
{
return candidate.getContainedPackages();
}
private boolean isTrue(Boolean value)
{
if (value == null)
{
return false;
}
return value;
}
@Override
public boolean shouldLoadInEnvironment()
{
boolean clientSideOnly = isTrue((Boolean)descriptor.get("clientSideOnly"));
boolean serverSideOnly = isTrue((Boolean)descriptor.get("serverSideOnly"));
if (clientSideOnly && serverSideOnly)
{
throw new RuntimeException("Mod annotation claims to be both client and server side only!");
}
Side side = FMLCommonHandler.instance().getSide();
if (clientSideOnly && side != Side.CLIENT)
{
FMLLog.log.info("Disabling mod {} it is client side only.", getModId());
return false;
}
if (serverSideOnly && side != Side.SERVER)
{
FMLLog.log.info("Disabling mod {} it is server side only.", getModId());
return false;
}
return true;
}
@Override
public URL getUpdateUrl()
{
return updateJSONUrl;
}
@Override
public void setClassVersion(int classVersion)
{
this.classVersion = classVersion;
}
@Override
public int getClassVersion()
{
return this.classVersion;
}
}
@@ -28,7 +28,7 @@ import net.minecraft.network.NetworkManager;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.IThreadListener;
import net.minecraftforge.common.util.CompoundDataFixer;
import net.minecraftforge.fml.common.eventhandler.EventBus;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.relauncher.Side;
public interface IFMLSidedHandler
@@ -65,7 +65,7 @@ public interface IFMLSidedHandler
INetHandler getClientPlayHandler();
void fireNetRegistrationEvent(EventBus bus, NetworkManager manager, Set<String> channelSet, String channel, Side side);
void fireNetRegistrationEvent(IEventBus bus, NetworkManager manager, Set<String> channelSet, String channel, Side side);
boolean shouldAllowPlayerLogins();
@@ -23,10 +23,9 @@ import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import net.minecraftforge.fml.javafmlmod.FMLModContainer;
import net.minecraftforge.fml.relauncher.Side;
import org.apache.logging.log4j.Level;
public interface ILanguageAdapter {
Object getNewInstance(FMLModContainer container, Class<?> objectClass, ClassLoader classLoader, Method factoryMarkedAnnotation) throws Exception;
boolean supportsStatics();
@@ -1,240 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common;
import java.io.File;
import java.net.URL;
import java.security.cert.Certificate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.VersionRange;
import com.google.common.eventbus.EventBus;
import javax.annotation.Nullable;
public class InjectedModContainer implements ModContainer
{
private File source;
public final ModContainer wrappedContainer;
public InjectedModContainer(ModContainer mc, File source)
{
this.source = source != null ? source : new File("minecraft.jar");
this.wrappedContainer = mc;
}
@Override
public String getModId()
{
return wrappedContainer.getModId();
}
@Override
public String getName()
{
return wrappedContainer.getName();
}
@Override
public String getVersion()
{
return wrappedContainer.getVersion();
}
@Override
public File getSource()
{
return source;
}
@Override
public ModMetadata getMetadata()
{
return wrappedContainer.getMetadata();
}
@Override
public void bindMetadata(MetadataCollection mc)
{
wrappedContainer.bindMetadata(mc);
}
@Override
public void setEnabledState(boolean enabled)
{
wrappedContainer.setEnabledState(enabled);
}
@Override
public Set<ArtifactVersion> getRequirements()
{
return wrappedContainer.getRequirements();
}
@Override
public List<ArtifactVersion> getDependencies()
{
return wrappedContainer.getDependencies();
}
@Override
public List<ArtifactVersion> getDependants()
{
return wrappedContainer.getDependants();
}
@Override
public String getSortingRules()
{
return wrappedContainer.getSortingRules();
}
@Override
public boolean registerBus(EventBus bus, LoadController controller)
{
return wrappedContainer.registerBus(bus, controller);
}
@Override
public boolean matches(Object mod)
{
return wrappedContainer.matches(mod);
}
@Override
public Object getMod()
{
return wrappedContainer.getMod();
}
@Override
public ArtifactVersion getProcessedVersion()
{
return wrappedContainer.getProcessedVersion();
}
@Override
public boolean isImmutable()
{
return true;
}
@Override
public String getDisplayVersion()
{
return wrappedContainer.getDisplayVersion();
}
@Override
public VersionRange acceptableMinecraftVersionRange()
{
return wrappedContainer.acceptableMinecraftVersionRange();
}
@Nullable
public WorldAccessContainer getWrappedWorldAccessContainer()
{
if (wrappedContainer instanceof WorldAccessContainer)
{
return (WorldAccessContainer) wrappedContainer;
}
else
{
return null;
}
}
@Override
@Nullable
public Certificate getSigningCertificate()
{
return wrappedContainer.getSigningCertificate();
}
@Override
public String toString()
{
return "Wrapped{"+wrappedContainer.toString()+"}";
}
@Override
public Map<String, String> getCustomModProperties()
{
return wrappedContainer.getCustomModProperties();
}
@Override
public Class<?> getCustomResourcePackClass()
{
return wrappedContainer.getCustomResourcePackClass();
}
@Override
public Map<String, String> getSharedModDescriptor()
{
return wrappedContainer.getSharedModDescriptor();
}
@Override
public Disableable canBeDisabled()
{
return wrappedContainer.canBeDisabled();
}
@Override
public String getGuiClassName()
{
return wrappedContainer.getGuiClassName();
}
@Override
public List<String> getOwnedPackages()
{
return wrappedContainer.getOwnedPackages();
}
@Override
public boolean shouldLoadInEnvironment()
{
return true;
}
@Override
public URL getUpdateUrl()
{
return wrappedContainer.getUpdateUrl();
}
@Override
public void setClassVersion(int classVersion)
{
wrappedContainer.setClassVersion(classVersion);
}
@Override
public int getClassVersion()
{
return wrappedContainer.getClassVersion();
}
}
@@ -1,39 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common;
import com.google.common.eventbus.EventBus;
public class MCPDummyContainer extends DummyModContainer {
public MCPDummyContainer(ModMetadata metadata) {
super(metadata);
}
@Override
public boolean registerBus(EventBus bus, LoadController controller) {
return true;
}
@Override
public Disableable canBeDisabled()
{
return Disableable.YES;
}
}
@@ -1,85 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common;
import java.io.File;
import java.security.cert.Certificate;
import com.google.common.eventbus.EventBus;
import net.minecraftforge.fml.common.versioning.VersionParser;
import net.minecraftforge.fml.common.versioning.VersionRange;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler;
import net.minecraftforge.fml.relauncher.Side;
import javax.annotation.Nullable;
public class MinecraftDummyContainer extends DummyModContainer
{
private VersionRange staticRange;
public MinecraftDummyContainer(String actualMCVersion)
{
super(new ModMetadata());
getMetadata().modId = "minecraft";
getMetadata().name = "Minecraft";
getMetadata().version = actualMCVersion;
staticRange = VersionParser.parseRange("["+actualMCVersion+"]");
}
@Override
public boolean isImmutable()
{
return true;
}
@Override
public File getSource()
{
return new File("minecraft.jar");
}
@Override
public boolean registerBus(EventBus bus, LoadController controller)
{
return true;
}
public VersionRange getStaticVersionRange()
{
return staticRange;
}
@Override
@Nullable
public Certificate getSigningCertificate()
{
if (FMLLaunchHandler.side() != Side.CLIENT)
return null;
try
{
Class<?> cbr = Class.forName("net.minecraft.client.ClientBrandRetriever", false, getClass().getClassLoader());
Certificate[] certificates = cbr.getProtectionDomain().getCodeSource().getCertificates();
return certificates != null ? certificates[0] : null;
}
catch (Exception ignored){} // Errors don't matter just return null.
return null;
}
}
@@ -1,256 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import net.minecraftforge.fml.common.asm.transformers.ModAPITransformer;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import net.minecraftforge.fml.common.discovery.ModCandidate;
import net.minecraftforge.fml.common.discovery.ModDiscoverer;
import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.DefaultArtifactVersion;
import net.minecraftforge.fml.common.versioning.VersionParser;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
public class ModAPIManager {
public static final ModAPIManager INSTANCE = new ModAPIManager();
@SuppressWarnings("unused")
private ModAPITransformer transformer;
private ASMDataTable dataTable;
private Map<String,APIContainer> apiContainers;
private static class APIContainer extends DummyModContainer {
private List<ArtifactVersion> referredMods;
private ArtifactVersion ownerMod;
private ArtifactVersion ourVersion;
private String providedAPI;
private File source;
private String version;
private Set<String> currentReferents;
private Set<String> packages;
private boolean selfReferenced;
public APIContainer(String providedAPI, String apiVersion, File source, ArtifactVersion ownerMod)
{
this.providedAPI = providedAPI;
this.version = apiVersion;
this.ownerMod = ownerMod;
this.ourVersion = new DefaultArtifactVersion(providedAPI, apiVersion);
this.referredMods = Lists.newArrayList();
this.source = source;
this.currentReferents = Sets.newHashSet();
this.packages = Sets.newHashSet();
}
@Override
public File getSource()
{
return source;
}
@Override
public String getVersion()
{
return version;
}
@Override
public String getName()
{
return "API: "+providedAPI;
}
@Override
public String getModId()
{
return providedAPI;
}
@Override
public List<ArtifactVersion> getDependants()
{
return referredMods;
}
@Override
public List<ArtifactVersion> getDependencies()
{
return selfReferenced ? ImmutableList.<ArtifactVersion>of() : ImmutableList.of(ownerMod);
}
@Override
public ArtifactVersion getProcessedVersion()
{
return ourVersion;
}
public void validate(String providedAPI, String apiOwner, String apiVersion)
{
if (Loader.instance().getModClassLoader().containsSource(this.getSource())) {
FMLLog.bigWarning("The API {} from source {} is loaded from an incompatible classloader. THIS WILL NOT WORK!", providedAPI, this.getSource().getAbsolutePath());
}
// TODO Compare this annotation data to the one we first found. Maybe barf if there is inconsistency?
}
@Override
public String toString()
{
return "APIContainer{"+providedAPI+":"+version+"}";
}
public void addAPIReference(String embedded)
{
if (currentReferents.add(embedded))
{
referredMods.add(VersionParser.parseVersionReference(embedded));
}
}
public void addOwnedPackage(String apiPackage)
{
packages.add(apiPackage);
}
public void addAPIReferences(List<String> candidateIds)
{
for (String modId : candidateIds)
{
addAPIReference(modId);
}
}
void markSelfReferenced()
{
selfReferenced = true;
}
}
public void registerDataTableAndParseAPI(ASMDataTable dataTable)
{
this.dataTable = dataTable;
Set<ASMData> apiList = dataTable.getAll("net.minecraftforge.fml.common.API");
apiContainers = Maps.newHashMap();
for (ASMData data : apiList)
{
Map<String, Object> annotationInfo = data.getAnnotationInfo();
String apiPackage = data.getClassName().substring(0,data.getClassName().indexOf(".package-info"));
String providedAPI = (String) annotationInfo.get("provides");
String apiOwner = (String) annotationInfo.get("owner");
String apiVersion = (String) annotationInfo.get("apiVersion");
APIContainer container = apiContainers.get(providedAPI);
if (container == null)
{
container = new APIContainer(providedAPI, apiVersion, data.getCandidate().getModContainer(), VersionParser.parseVersionReference(apiOwner));
apiContainers.put(providedAPI, container);
}
else
{
container.validate(providedAPI, apiOwner, apiVersion);
}
container.addOwnedPackage(apiPackage);
for (ModContainer mc : data.getCandidate().getContainedMods())
{
String embeddedIn = mc.getModId();
if (container.currentReferents.contains(embeddedIn))
{
continue;
}
FMLLog.log.debug("Found API {} (owned by {} providing {}) embedded in {}",apiPackage, apiOwner, providedAPI, embeddedIn);
if (!embeddedIn.equals(apiOwner))
{
container.addAPIReference(embeddedIn);
}
}
}
for (APIContainer container : apiContainers.values())
{
for (String pkg : container.packages)
{
Set<ModCandidate> candidates = dataTable.getCandidatesFor(pkg);
for (ModCandidate candidate : candidates)
{
List<String> candidateIds = candidate.getContainedMods().stream().map(ModContainer::getModId).collect(Collectors.toCollection(ArrayList::new));
if (!candidateIds.contains(container.ownerMod.getLabel()) && !container.currentReferents.containsAll(candidateIds))
{
FMLLog.log.info("Found mod(s) {} containing declared API package {} (owned by {}) without associated API reference",candidateIds, pkg, container.ownerMod);
container.addAPIReferences(candidateIds);
}
}
}
if (apiContainers.containsKey(container.ownerMod.getLabel()))
{
ArtifactVersion owner = container.ownerMod;
do
{
APIContainer parent = apiContainers.get(owner.getLabel());
if (parent == container)
{
FMLLog.log.trace("APIContainer {} is it's own parent. skipping", owner);
container.markSelfReferenced();
break;
}
FMLLog.log.trace("Removing upstream parent {} from {}", parent.ownerMod.getLabel(), container);
container.currentReferents.remove(parent.ownerMod.getLabel());
container.referredMods.remove(parent.ownerMod);
owner = parent.ownerMod;
}
while (apiContainers.containsKey(owner.getLabel()));
}
FMLLog.log.debug("Creating API container dummy for API {}: owner: {}, dependents: {}", container.providedAPI, container.ownerMod, container.referredMods);
}
}
public void manageAPI(ModClassLoader modClassLoader, ModDiscoverer discoverer)
{
registerDataTableAndParseAPI(discoverer.getASMTable());
transformer = modClassLoader.addModAPITransformer(dataTable);
}
public void injectAPIModContainers(List<ModContainer> mods, Map<String, ModContainer> nameLookup)
{
mods.addAll(apiContainers.values());
nameLookup.putAll(apiContainers);
}
public void cleanupAPIContainers(List<ModContainer> mods)
{
mods.removeAll(apiContainers.values());
}
public boolean hasAPI(String modId)
{
return apiContainers.containsKey(modId);
}
public Iterable<? extends ModContainer> getAPIList()
{
return apiContainers.values();
}
}
@@ -19,20 +19,13 @@
package net.minecraftforge.fml.common;
import java.io.File;
import java.net.URL;
import java.security.cert.Certificate;
import java.util.List;
import net.minecraftforge.fml.LifecycleEventProvider;
import net.minecraftforge.fml.ModLoadingStage;
import net.minecraftforge.fml.loading.moddiscovery.IModInfo;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.VersionRange;
import com.google.common.collect.ImmutableMap;
import com.google.common.eventbus.EventBus;
import javax.annotation.Nullable;
import java.util.function.Consumer;
/**
* The container that wraps around mods in the system.
@@ -47,125 +40,82 @@ import javax.annotation.Nullable;
*
*/
public interface ModContainer
public abstract class ModContainer
{
public static enum Disableable {
YES, RESTART, NEVER, DEPENDENCIES;
protected final String modId;
protected final IModInfo modInfo;
protected ModLoadingStage modLoadingStage;
protected final Map<ModLoadingStage, Consumer<LifecycleEventProvider.LifecycleEvent>> triggerMap;
public ModContainer(IModInfo info)
{
this.modId = info.getModId();
this.modInfo = info;
this.triggerMap = new HashMap<>();
this.modLoadingStage = ModLoadingStage.BEGIN;
}
/**
* The globally unique modid for this mod
* @return the modid for this mod
*/
String getModId();
String getPrefix();
public final String getModId()
{
return modId;
}
/**
* A human readable name
* @return the resource prefix for the mod
*/
String getName();
public final String getPrefix()
{
return modId;
}
/**
* A human readable version identifier
* @return The current loading stage for this mod
*/
String getVersion();
public ModLoadingStage getCurrentState()
{
return modLoadingStage;
}
/**
* The location on the file system which this mod came from
* Transition the mod to this event if possible.
* @param event to transition to
*/
File getSource();
public final void transitionState(LifecycleEventProvider.LifecycleEvent event)
{
if (modLoadingStage != event.fromStage())
{
try
{
triggerMap.getOrDefault(modLoadingStage, e->{}).accept(event);
modLoadingStage = event.toStage();
}
catch (RuntimeException e)
{
modLoadingStage = ModLoadingStage.ERROR;
}
}
}
/**
* The metadata for this mod
* @return the modinfo used to create this mod instance
*/
ModMetadata getMetadata();
public IModInfo getModInfo()
{
return modInfo;
}
/**
* Attach this mod to it's metadata from the supplied metadata collection
*/
void bindMetadata(MetadataCollection mc);
/**
* Set the enabled/disabled state of this mod
*/
void setEnabledState(boolean enabled);
/**
* A list of the modids that this mod requires loaded prior to loading
*/
Set<ArtifactVersion> getRequirements();
/**
* A list of modids that should be loaded prior to this one. The special
* value <strong>*</strong> indicates to load <em>after</em> any other mod.
*/
List<ArtifactVersion> getDependencies();
/**
* A list of modids that should be loaded <em>after</em> this one. The
* special value <strong>*</strong> indicates to load <em>before</em> any
* other mod.
*/
List<ArtifactVersion> getDependants();
/**
* A representative string encapsulating the sorting preferences for this
* mod
*/
String getSortingRules();
/**
* Register the event bus for the mod and the controller for error handling
* Returns if this bus was successfully registered - disabled mods and other
* mods that don't need real events should return false and avoid further
* processing
* Does this mod match the supplied mod?
*
* @param bus
* @param controller
* @param mod to compare
* @return if the mod matches
*/
boolean registerBus(EventBus bus, LoadController controller);
public abstract boolean matches(Object mod);
/**
* Does this mod match the supplied mod
*
* @param mod
* @return the mod object instance
*/
boolean matches(Object mod);
/**
* Get the actual mod object
*/
Object getMod();
ArtifactVersion getProcessedVersion();
boolean isImmutable();
String getDisplayVersion();
VersionRange acceptableMinecraftVersionRange();
@Nullable
Certificate getSigningCertificate();
public static final Map<String,String> EMPTY_PROPERTIES = ImmutableMap.of();
Map<String,String> getCustomModProperties();
public Class<?> getCustomResourcePackClass();
Map<String, String> getSharedModDescriptor();
Disableable canBeDisabled();
String getGuiClassName();
List<String> getOwnedPackages();
boolean shouldLoadInEnvironment();
URL getUpdateUrl();
void setClassVersion(int classVersion);
int getClassVersion();
public abstract Object getMod();
}
@@ -25,6 +25,7 @@ import java.util.Map;
import net.minecraftforge.fml.common.discovery.ModCandidate;
import net.minecraftforge.fml.common.discovery.asm.ASMModParser;
import net.minecraftforge.fml.javafmlmod.FMLModContainer;
import net.minecraftforge.fml.loading.moddiscovery.ModAnnotation;
import org.objectweb.asm.Type;
@@ -42,7 +42,7 @@ import static org.objectweb.asm.Type.getMethodDescriptor;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.eventhandler.Event;
import net.minecraftforge.eventbus.api.Event;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
@@ -104,7 +104,7 @@ public class EventSubscriptionTransformer implements IClassTransformer
// Yes, this recursively loads classes until we get this base class. THIS IS NOT A ISSUE. Coremods should handle re-entry just fine.
// If they do not this a COREMOD issue NOT a Forge/LaunchWrapper issue.
Class<?> parent = this.getClass().getClassLoader().loadClass(classNode.superName.replace('/', '.'));
if (!Event.class.isAssignableFrom(parent))
if (!net.minecraftforge.eventbus.api.Event.class.isAssignableFrom(parent))
{
return false;
}
@@ -24,7 +24,7 @@ import java.security.CodeSource;
import java.security.cert.Certificate;
import java.util.Properties;
import net.minecraftforge.fml.common.FMLModContainer;
import net.minecraftforge.fml.javafmlmod.FMLModContainer;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.ModMetadata;
import net.minecraftforge.fml.common.LoaderState.ModState;
@@ -1,196 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.eventhandler;
import static org.objectweb.asm.Opcodes.*;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import net.minecraftforge.fml.common.ModContainer;
import org.apache.logging.log4j.ThreadContext;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import com.google.common.collect.Maps;
public class ASMEventHandler implements IEventListener
{
private static int IDs = 0;
private static final String HANDLER_DESC = Type.getInternalName(IEventListener.class);
private static final String HANDLER_FUNC_DESC = Type.getMethodDescriptor(IEventListener.class.getDeclaredMethods()[0]);
private static final ASMClassLoader LOADER = new ASMClassLoader();
private static final HashMap<Method, Class<?>> cache = Maps.newHashMap();
private static final boolean GETCONTEXT = Boolean.parseBoolean(System.getProperty("fml.LogContext", "false"));
private final IEventListener handler;
private final SubscribeEvent subInfo;
private ModContainer owner;
private String readable;
private java.lang.reflect.Type filter = null;
@Deprecated
public ASMEventHandler(Object target, Method method, ModContainer owner) throws Exception
{
this(target, method, owner, false);
}
public ASMEventHandler(Object target, Method method, ModContainer owner, boolean isGeneric) throws Exception
{
this.owner = owner;
if (Modifier.isStatic(method.getModifiers()))
handler = (IEventListener)createWrapper(method).newInstance();
else
handler = (IEventListener)createWrapper(method).getConstructor(Object.class).newInstance(target);
subInfo = method.getAnnotation(SubscribeEvent.class);
readable = "ASM: " + target + " " + method.getName() + Type.getMethodDescriptor(method);
if (isGeneric)
{
java.lang.reflect.Type type = method.getGenericParameterTypes()[0];
if (type instanceof ParameterizedType)
{
filter = ((ParameterizedType)type).getActualTypeArguments()[0];
}
}
}
@SuppressWarnings("rawtypes")
@Override
public void invoke(Event event)
{
if (GETCONTEXT)
ThreadContext.put("mod", owner == null ? "" : owner.getName());
if (handler != null)
{
if (!event.isCancelable() || !event.isCanceled() || subInfo.receiveCanceled())
{
if (filter == null || filter == ((IGenericEvent)event).getGenericType())
{
handler.invoke(event);
}
}
}
if (GETCONTEXT)
ThreadContext.remove("mod");
}
public EventPriority getPriority()
{
return subInfo.priority();
}
public Class<?> createWrapper(Method callback)
{
if (cache.containsKey(callback))
{
return cache.get(callback);
}
ClassWriter cw = new ClassWriter(0);
MethodVisitor mv;
boolean isStatic = Modifier.isStatic(callback.getModifiers());
String name = getUniqueName(callback);
String desc = name.replace('.', '/');
String instType = Type.getInternalName(callback.getDeclaringClass());
String eventType = Type.getInternalName(callback.getParameterTypes()[0]);
/*
System.out.println("Name: " + name);
System.out.println("Desc: " + desc);
System.out.println("InstType: " + instType);
System.out.println("Callback: " + callback.getName() + Type.getMethodDescriptor(callback));
System.out.println("Event: " + eventType);
*/
cw.visit(V1_6, ACC_PUBLIC | ACC_SUPER, desc, null, "java/lang/Object", new String[]{ HANDLER_DESC });
cw.visitSource(".dynamic", null);
{
if (!isStatic)
cw.visitField(ACC_PUBLIC, "instance", "Ljava/lang/Object;", null, null).visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC, "<init>", isStatic ? "()V" : "(Ljava/lang/Object;)V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
if (!isStatic)
{
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(ALOAD, 1);
mv.visitFieldInsn(PUTFIELD, desc, "instance", "Ljava/lang/Object;");
}
mv.visitInsn(RETURN);
mv.visitMaxs(2, 2);
mv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC, "invoke", HANDLER_FUNC_DESC, null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
if (!isStatic)
{
mv.visitFieldInsn(GETFIELD, desc, "instance", "Ljava/lang/Object;");
mv.visitTypeInsn(CHECKCAST, instType);
}
mv.visitVarInsn(ALOAD, 1);
mv.visitTypeInsn(CHECKCAST, eventType);
mv.visitMethodInsn(isStatic ? INVOKESTATIC : INVOKEVIRTUAL, instType, callback.getName(), Type.getMethodDescriptor(callback), false);
mv.visitInsn(RETURN);
mv.visitMaxs(2, 2);
mv.visitEnd();
}
cw.visitEnd();
Class<?> ret = LOADER.define(name, cw.toByteArray());
cache.put(callback, ret);
return ret;
}
private String getUniqueName(Method callback)
{
return String.format("%s_%d_%s_%s_%s", getClass().getName(), IDs++,
callback.getDeclaringClass().getSimpleName(),
callback.getName(),
callback.getParameterTypes()[0].getSimpleName());
}
private static class ASMClassLoader extends ClassLoader
{
private ASMClassLoader()
{
super(ASMClassLoader.class.getClassLoader());
}
public Class<?> define(String name, byte[] data)
{
return defineClass(name, data, 0, data.length);
}
}
public String toString()
{
return readable;
}
}
@@ -1,30 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.eventhandler;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(value = RUNTIME)
@Target(value = TYPE)
public @interface Cancelable{}
@@ -1,166 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.eventhandler;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.base.Preconditions;
/**
* Base Event class that all other events are derived from
*/
public class Event
{
@Retention(value = RUNTIME)
@Target(value = TYPE)
public @interface HasResult{}
public enum Result
{
DENY,
DEFAULT,
ALLOW
}
private boolean isCanceled = false;
private Result result = Result.DEFAULT;
private static ListenerList listeners = new ListenerList();
private EventPriority phase = null;
public Event()
{
setup();
}
/**
* Determine if this function is cancelable at all.
* @return If access to setCanceled should be allowed
*
* Note:
* Events with the Cancelable annotation will have this method automatically added to return true.
*/
public boolean isCancelable()
{
return false;
}
/**
* Determine if this event is canceled and should stop executing.
* @return The current canceled state
*/
public boolean isCanceled()
{
return isCanceled;
}
/**
* Sets the cancel state of this event. Note, not all events are cancelable, and any attempt to
* invoke this method on an event that is not cancelable (as determined by {@link #isCancelable}
* will result in an {@link UnsupportedOperationException}.
*
* The functionality of setting the canceled state is defined on a per-event bases.
*
* @param cancel The new canceled value
*/
public void setCanceled(boolean cancel)
{
if (!isCancelable())
{
throw new UnsupportedOperationException(
"Attempted to call Event#setCanceled() on a non-cancelable event of type: "
+ this.getClass().getCanonicalName()
);
}
isCanceled = cancel;
}
/**
* Determines if this event expects a significant result value.
*
* Note:
* Events with the HasResult annotation will have this method automatically added to return true.
*/
public boolean hasResult()
{
return false;
}
/**
* Returns the value set as the result of this event
*/
public Result getResult()
{
return result;
}
/**
* Sets the result value for this event, not all events can have a result set, and any attempt to
* set a result for a event that isn't expecting it will result in a IllegalArgumentException.
*
* The functionality of setting the result is defined on a per-event bases.
*
* @param value The new result
*/
public void setResult(Result value)
{
result = value;
}
/**
* Called by the base constructor, this is used by ASM generated
* event classes to setup various functionality such as the listener list.
*/
protected void setup()
{
}
/**
* Returns a ListenerList object that contains all listeners
* that are registered to this event.
*
* @return Listener List
*/
public ListenerList getListenerList()
{
return listeners;
}
@Nullable
public EventPriority getPhase()
{
return this.phase;
}
public void setPhase(@Nonnull EventPriority value)
{
Preconditions.checkNotNull(value, "setPhase argument must not be null");
int prev = phase == null ? -1 : phase.ordinal();
Preconditions.checkArgument(prev < value.ordinal(), "Attempted to set event phase to %s when already %s", value, phase);
phase = value;
}
}
@@ -1,210 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.eventhandler;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nonnull;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Sets;
import com.google.common.reflect.TypeToken;
public class EventBus implements IEventExceptionHandler
{
private static int maxID = 0;
private ConcurrentHashMap<Object, ArrayList<IEventListener>> listeners = new ConcurrentHashMap<Object, ArrayList<IEventListener>>();
private Map<Object,ModContainer> listenerOwners = new MapMaker().weakKeys().weakValues().makeMap();
private final int busID = maxID++;
private IEventExceptionHandler exceptionHandler;
private boolean shutdown;
public EventBus()
{
ListenerList.resize(busID + 1);
exceptionHandler = this;
}
public EventBus(@Nonnull IEventExceptionHandler handler)
{
this();
Preconditions.checkNotNull(handler, "EventBus exception handler can not be null");
exceptionHandler = handler;
}
public void register(Object target)
{
if (listeners.containsKey(target))
{
return;
}
ModContainer activeModContainer = Loader.instance().activeModContainer();
if (activeModContainer == null)
{
FMLLog.log.error("Unable to determine registrant mod for {}. This is a critical error and should be impossible", target, new Throwable());
activeModContainer = Loader.instance().getMinecraftModContainer();
}
listenerOwners.put(target, activeModContainer);
boolean isStatic = target.getClass() == Class.class;
@SuppressWarnings("unchecked")
Set<? extends Class<?>> supers = isStatic ? Sets.newHashSet((Class<?>)target) : TypeToken.of(target.getClass()).getTypes().rawTypes();
for (Method method : (isStatic ? (Class<?>)target : target.getClass()).getMethods())
{
if (isStatic && !Modifier.isStatic(method.getModifiers()))
continue;
else if (!isStatic && Modifier.isStatic(method.getModifiers()))
continue;
for (Class<?> cls : supers)
{
try
{
Method real = cls.getDeclaredMethod(method.getName(), method.getParameterTypes());
if (real.isAnnotationPresent(SubscribeEvent.class))
{
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length != 1)
{
throw new IllegalArgumentException(
"Method " + method + " has @SubscribeEvent annotation, but requires " + parameterTypes.length +
" arguments. Event handler methods must require a single argument."
);
}
Class<?> eventType = parameterTypes[0];
if (!Event.class.isAssignableFrom(eventType))
{
throw new IllegalArgumentException("Method " + method + " has @SubscribeEvent annotation, but takes a argument that is not an Event " + eventType);
}
register(eventType, target, real, activeModContainer);
break;
}
}
catch (NoSuchMethodException e)
{
; // Eat the error, this is not unexpected
}
}
}
}
private void register(Class<?> eventType, Object target, Method method, final ModContainer owner)
{
try
{
Constructor<?> ctr = eventType.getConstructor();
ctr.setAccessible(true);
Event event = (Event)ctr.newInstance();
final ASMEventHandler asm = new ASMEventHandler(target, method, owner, IGenericEvent.class.isAssignableFrom(eventType));
IEventListener listener = asm;
if (IContextSetter.class.isAssignableFrom(eventType))
{
listener = new IEventListener()
{
@Override
public void invoke(Event event)
{
ModContainer old = Loader.instance().activeModContainer();
Loader.instance().setActiveModContainer(owner);
((IContextSetter)event).setModContainer(owner);
asm.invoke(event);
Loader.instance().setActiveModContainer(old);
}
};
}
event.getListenerList().register(busID, asm.getPriority(), listener);
ArrayList<IEventListener> others = listeners.computeIfAbsent(target, k -> new ArrayList<>());
others.add(listener);
}
catch (Exception e)
{
FMLLog.log.error("Error registering event handler: {} {} {}", owner, eventType, method, e);
}
}
public void unregister(Object object)
{
ArrayList<IEventListener> list = listeners.remove(object);
if(list == null)
return;
for (IEventListener listener : list)
{
ListenerList.unregisterAll(busID, listener);
}
}
public boolean post(Event event)
{
if (shutdown) return false;
IEventListener[] listeners = event.getListenerList().getListeners(busID);
int index = 0;
try
{
for (; index < listeners.length; index++)
{
listeners[index].invoke(event);
}
}
catch (Throwable throwable)
{
exceptionHandler.handleException(this, event, listeners, index, throwable);
Throwables.throwIfUnchecked(throwable);
throw new RuntimeException(throwable);
}
return event.isCancelable() && event.isCanceled();
}
public void shutdown()
{
FMLLog.log.warn("EventBus {} shutting down - future events will not be posted.", busID);
shutdown = true;
}
@Override
public void handleException(EventBus bus, Event event, IEventListener[] listeners, int index, Throwable throwable)
{
FMLLog.log.error("Exception caught during firing event {}:", event, throwable);
FMLLog.log.error("Index: {} Listeners:", index);
for (int x = 0; x < listeners.length; x++)
{
FMLLog.log.error("{}: {}", x, listeners[x]);
}
}
}
@@ -1,42 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.eventhandler;
public enum EventPriority implements IEventListener
{
/*Priority of event listeners, listeners will be sorted with respect to this priority level.
*
* Note:
* Due to using a ArrayList in the ListenerList,
* these need to stay in a contiguous index starting at 0. {Default ordinal}
*/
HIGHEST, //First to execute
HIGH,
NORMAL,
LOW,
LOWEST //Last to execute
;
@Override
public void invoke(Event event)
{
event.setPhase(this);
}
}
@@ -1,31 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.eventhandler;
import net.minecraftforge.fml.common.ModContainer;
//Instructs event handlers to set the active mod container.
//This has a major performance impact so use sparingly.
//Note: The context IS NOT thread aware as this would be ungodly slow.
//So This should ONLY be used for Forge mod lifecycle events.
public interface IContextSetter
{
default void setModContainer(ModContainer mod){};
}
@@ -1,35 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.eventhandler;
public interface IEventExceptionHandler
{
/**
* Fired when a EventListener throws an exception for the specified event on the event bus.
* After this function returns, the original Throwable will be propagated upwards.
*
* @param bus The bus the event is being fired on
* @param event The event that is being fired
* @param listeners All listeners that are listening for this event, in order
* @param index Index for the current listener being fired.
* @param throwable The throwable being thrown
*/
void handleException(EventBus bus, Event event, IEventListener[] listeners, int index, Throwable throwable);
}
@@ -1,27 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.eventhandler;
import java.lang.reflect.Type;
public interface IGenericEvent<T>
{
Type getGenericType();
}
@@ -1,278 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.eventhandler;
import java.util.*;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import javax.annotation.Nullable;
public class ListenerList
{
private static ImmutableList<ListenerList> allLists = ImmutableList.of();
private static int maxSize = 0;
@Nullable
private ListenerList parent;
private ListenerListInst[] lists = new ListenerListInst[0];
public ListenerList()
{
this(null);
}
public ListenerList(@Nullable ListenerList parent)
{
// parent needs to be set before resize !
this.parent = parent;
extendMasterList(this);
resizeLists(maxSize);
}
private synchronized static void extendMasterList(ListenerList inst)
{
ImmutableList.Builder<ListenerList> builder = ImmutableList.builder();
builder.addAll(allLists);
builder.add(inst);
allLists = builder.build();
}
public static void resize(int max)
{
if (max <= maxSize)
{
return;
}
for (ListenerList list : allLists)
{
list.resizeLists(max);
}
maxSize = max;
}
public void resizeLists(int max)
{
if (parent != null)
{
parent.resizeLists(max);
}
if (lists.length >= max)
{
return;
}
ListenerListInst[] newList = new ListenerListInst[max];
int x = 0;
for (; x < lists.length; x++)
{
newList[x] = lists[x];
}
for(; x < max; x++)
{
if (parent != null)
{
newList[x] = new ListenerListInst(parent.getInstance(x));
}
else
{
newList[x] = new ListenerListInst();
}
}
lists = newList;
}
public static void clearBusID(int id)
{
for (ListenerList list : allLists)
{
list.lists[id].dispose();
}
}
protected ListenerListInst getInstance(int id)
{
return lists[id];
}
public IEventListener[] getListeners(int id)
{
return lists[id].getListeners();
}
public void register(int id, EventPriority priority, IEventListener listener)
{
lists[id].register(priority, listener);
}
public void unregister(int id, IEventListener listener)
{
lists[id].unregister(listener);
}
public static void unregisterAll(int id, IEventListener listener)
{
for (ListenerList list : allLists)
{
list.unregister(id, listener);
}
}
private class ListenerListInst
{
private boolean rebuild = true;
private IEventListener[] listeners;
private ArrayList<ArrayList<IEventListener>> priorities;
private ListenerListInst parent;
private List<ListenerListInst> children;
private ListenerListInst()
{
int count = EventPriority.values().length;
priorities = new ArrayList<ArrayList<IEventListener>>(count);
for (int x = 0; x < count; x++)
{
priorities.add(new ArrayList<IEventListener>());
}
}
public void dispose()
{
for (ArrayList<IEventListener> listeners : priorities)
{
listeners.clear();
}
priorities.clear();
parent = null;
listeners = null;
if (children != null)
children.clear();
}
private ListenerListInst(ListenerListInst parent)
{
this();
this.parent = parent;
this.parent.addChild(this);
}
/**
* Returns a ArrayList containing all listeners for this event,
* and all parent events for the specified priority.
*
* The list is returned with the listeners for the children events first.
*
* @param priority The Priority to get
* @return ArrayList containing listeners
*/
public ArrayList<IEventListener> getListeners(EventPriority priority)
{
ArrayList<IEventListener> ret = new ArrayList<IEventListener>(priorities.get(priority.ordinal()));
if (parent != null)
{
ret.addAll(parent.getListeners(priority));
}
return ret;
}
/**
* Returns a full list of all listeners for all priority levels.
* Including all parent listeners.
*
* List is returned in proper priority order.
*
* Automatically rebuilds the internal Array cache if its information is out of date.
*
* @return Array containing listeners
*/
public IEventListener[] getListeners()
{
if (shouldRebuild()) buildCache();
return listeners;
}
protected boolean shouldRebuild()
{
return rebuild;// || (parent != null && parent.shouldRebuild());
}
protected void forceRebuild()
{
this.rebuild = true;
if (this.children != null)
{
for (ListenerListInst child : this.children)
child.forceRebuild();
}
}
private void addChild(ListenerListInst child)
{
if (this.children == null)
this.children = Lists.newArrayList();
this.children.add(child);
}
/**
* Rebuild the local Array of listeners, returns early if there is no work to do.
*/
private void buildCache()
{
if(parent != null && parent.shouldRebuild())
{
parent.buildCache();
}
ArrayList<IEventListener> ret = new ArrayList<IEventListener>();
for (EventPriority value : EventPriority.values())
{
List<IEventListener> listeners = getListeners(value);
if (listeners.size() > 0)
{
ret.add(value); //Add the priority to notify the event of it's current phase.
ret.addAll(listeners);
}
}
listeners = ret.toArray(new IEventListener[ret.size()]);
rebuild = false;
}
public void register(EventPriority priority, IEventListener listener)
{
priorities.get(priority.ordinal()).add(listener);
this.forceRebuild();
}
public void unregister(IEventListener listener)
{
for(ArrayList<IEventListener> list : priorities)
{
if (list.remove(listener))
{
this.forceRebuild();
}
}
}
}
}
@@ -1,34 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.eventhandler;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.*;
import static java.lang.annotation.ElementType.*;
@Retention(value = RUNTIME)
@Target(value = METHOD)
public @interface SubscribeEvent
{
EventPriority priority() default EventPriority.NORMAL;
boolean receiveCanceled() default false;
}
@@ -19,7 +19,7 @@
package net.minecraftforge.fml.common.gameevent;
import net.minecraftforge.fml.common.eventhandler.Event;
import net.minecraftforge.eventbus.api.Event;
public class InputEvent extends Event {
public static class MouseInputEvent extends InputEvent {}
@@ -23,7 +23,7 @@ import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.eventhandler.Event;
import net.minecraftforge.eventbus.api.Event;
import javax.annotation.Nonnull;
@@ -22,10 +22,11 @@ package net.minecraftforge.fml.common.gameevent;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.eventhandler.Event;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.relauncher.Side;
public class TickEvent extends Event {
public class TickEvent extends net.minecraftforge.eventbus.api.Event
{
public enum Type {
WORLD, PLAYER, CLIENT, SERVER, RENDER;
}
@@ -29,8 +29,8 @@ import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.eventhandler.EventBus;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.network.internal.FMLProxyPacket;
import net.minecraftforge.fml.relauncher.Side;
@@ -50,7 +50,7 @@ import javax.annotation.Nullable;
*/
public class FMLEventChannel {
private EnumMap<Side, FMLEmbeddedChannel> channels;
private EventBus eventBus;
private IEventBus eventBus;
/*
* This is done this way so that the CLIENT specific code in the factory only loads on the client
@@ -100,7 +100,7 @@ public class FMLEventChannel {
FMLEventChannel(String name)
{
this.channels = NetworkRegistry.INSTANCE.newChannel(name, new NetworkEventFiringHandler(this));
this.eventBus = new EventBus();
this.eventBus = IEventBus.create();
}
/**
@@ -27,7 +27,7 @@ import net.minecraft.network.INetHandler;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.network.play.INetHandlerPlayServer;
import net.minecraftforge.fml.common.eventhandler.Event;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.common.network.internal.FMLProxyPacket;
import net.minecraftforge.fml.relauncher.Side;
@@ -242,7 +242,8 @@ public class FMLNetworkEvent<T extends INetHandler> extends Event {
* @author cpw
*
*/
public static class CustomNetworkEvent extends Event {
public static class CustomNetworkEvent extends net.minecraftforge.eventbus.api.Event
{
private final Object wrappedEvent;
public CustomNetworkEvent(Object wrappedEvent)
{
@@ -30,6 +30,7 @@ import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.LoaderException;
import net.minecraftforge.fml.javafmlmod.FMLModContainer;
import net.minecraftforge.fml.relauncher.Side;
public final class DependencyParser
@@ -182,7 +183,7 @@ public final class DependencyParser
}
// TODO 1.13: throw these exceptions instead of logging them
/** Based on {@link net.minecraftforge.fml.common.FMLModContainer#sanityCheckModId()} */
/** Based on {@link FMLModContainer#sanityCheckModId()} */
private static void sanityCheckModId(String modId, String dep, String depModId)
{
if (Strings.isNullOrEmpty(depModId))
@@ -17,16 +17,15 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.loading;
package net.minecraftforge.fml.javafmlmod;
import net.minecraftforge.fml.common.FMLModContainer;
import net.minecraftforge.fml.javafmlmod.FMLModContainer;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import net.minecraftforge.fml.loading.IModLanguageProvider;
import net.minecraftforge.fml.loading.moddiscovery.IModInfo;
import net.minecraftforge.fml.loading.moddiscovery.ScanResult;
import org.objectweb.asm.Type;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
@@ -53,9 +52,9 @@ public class FMLJavaModLanguageProvider implements IModLanguageProvider
}
@Override
public ModContainer loadMod(final ModInfo info, final ClassLoader modClassLoader)
public ModContainer loadMod(final IModInfo info, final ClassLoader modClassLoader, final ScanResult scanResults)
{
return new FMLModContainer(info, className, modClassLoader);
return new FMLModContainer(info, className, modClassLoader, scanResults);
}
}
@@ -0,0 +1,120 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.javafmlmod;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;
import net.minecraftforge.fml.LifecycleEventProvider;
import net.minecraftforge.fml.ModLoadingStage;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.loading.FMLLoader;
import net.minecraftforge.fml.loading.moddiscovery.IModInfo;
import net.minecraftforge.fml.loading.moddiscovery.ScanResult;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.stream.Collectors;
import org.objectweb.asm.Type;
import static net.minecraftforge.fml.Logging.LOADING;
public class FMLModContainer extends ModContainer
{
private static final Logger LOGGER = LogManager.getLogger("FML");
private final ScanResult scanResults;
private Object modInstance;
private final Class<?> modClass;
public FMLModContainer(IModInfo info, String className, ClassLoader modClassLoader, ScanResult scanResults)
{
super(info);
this.scanResults = scanResults;
triggerMap.put(ModLoadingStage.BEGIN, this::constructMod);
triggerMap.put(ModLoadingStage.PREINIT, this::preinitMod);
try
{
modClass = Class.forName(className, true, modClassLoader);
LOGGER.error(LOADING,"Loaded modclass {} with {}", modClass.getName(), modClass.getClassLoader());
}
catch (ClassNotFoundException e)
{
LOGGER.error(LOADING, "Failed to load class {}", className, e);
throw new RuntimeException(e);
}
}
private void preinitMod(LifecycleEventProvider.LifecycleEvent lifecycleEvent)
{
List<Pair<String, String>> instanceFields = scanResults.getAnnotations().stream().
filter(a -> Objects.equals(a.getAnnotationType(), Type.getType(Instance.class)) &&
Objects.equals(a.getClassType(), Type.getType(modClass))).
map(a->Pair.of(a.getMemberName(), (String)a.getAnnotationData().get("value"))).
collect(Collectors.toList());
instanceFields.forEach(p->{
try
{
final Field field = modClass.getDeclaredField(p.getLeft());
field.setAccessible(true);
field.set(modInstance, FMLLoader.getModLoader().getModList().getModObjectById(p.getRight()).get());
}
catch (NoSuchFieldException | IllegalAccessException e)
{
LOGGER.error(LOADING, "Unable to set field {} to mod with ID {}", p.getLeft(), p.getRight(), e);
}
});
}
private void constructMod(LifecycleEventProvider.LifecycleEvent event)
{
try
{
LOGGER.debug(LOADING, "Loading mod instance {} of type {}", getModId(), modClass.getName());
this.modInstance = modClass.newInstance();
LOGGER.debug(LOADING, "Loaded mod instance {} of type {}", getModId(), modClass.getName());
}
catch (InstantiationException | IllegalAccessException e)
{
LOGGER.error("Failed to create mod instance. ModID: {}, class {}", getModId(), modClass.getName(), e);
throw new RuntimeException("Failed to create mod instance", e);
}
}
@Override
public boolean matches(Object mod)
{
return mod == modInstance;
}
@Override
public Object getMod()
{
return modInstance;
}
}
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml;
package net.minecraftforge.fml.loading;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
@@ -22,12 +22,13 @@ package net.minecraftforge.fml.loading;
import cpw.mods.modlauncher.api.IEnvironment;
import cpw.mods.modlauncher.api.ILaunchHandlerService;
import cpw.mods.modlauncher.api.ITransformingClassLoader;
import net.minecraft.client.main.Main;
import net.minecraftforge.api.Side;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import static net.minecraftforge.fml.Logging.CORE;
@@ -41,6 +42,13 @@ public class FMLDevClientLaunchProvider extends FMLCommonLaunchHandler implement
return "devfmlclient";
}
private static final List<String> SKIPPACKAGES = Arrays.asList(
"joptsimple.", "org.lwjgl.", "com.mojang.", "com.google.",
"org.apache.commons.", "io.netty.", "net.minecraftforge.fml.loading.",
"net.minecraftforge.eventbus.", "it.unimi.dsi.fastutil.", "net.minecraftforge.api.",
"paulscode.sound.", "com.ibm.icu.", "sun.", "gnu.trove.", "com.electronwill.nightconfig."
);
@Override
public Path[] identifyTransformationTargets()
{
@@ -62,7 +70,7 @@ public class FMLDevClientLaunchProvider extends FMLCommonLaunchHandler implement
return () -> {
fmlLog.debug(CORE, "Launching minecraft in {} with arguments {}", launchClassLoader, arguments);
super.beforeStart(launchClassLoader);
launchClassLoader.setTargetPackageFilter(cn -> !cn.startsWith("net.minecraftforge.fml.loading."));
launchClassLoader.addTargetPackageFilter(cn -> SKIPPACKAGES.stream().noneMatch(cn::startsWith));
Class.forName("net.minecraft.client.main.Main", true, launchClassLoader.getInstance()).getMethod("main", String[].class).invoke(null, (Object)arguments);
return null;
};
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml;
package net.minecraftforge.fml.loading;
import net.minecraftforge.api.Side;
import net.minecraftforge.fml.loading.FMLLoader;
@@ -54,6 +54,7 @@ public class FMLLoader
private static ILaunchPluginService accessTransformer;
private static ModDiscoverer modDiscoverer;
private static ICoreModProvider coreModProvider;
private static ILaunchPluginService eventBus;
private static LanguageLoadingProvider languageLoadingProvider;
private static Side side;
private static ModList modList;
@@ -70,6 +71,8 @@ public class FMLLoader
fmlLog.error(CORE,"Found incompatible ModLauncher specification : {}, version {} from {}", modLauncherPackage.getSpecificationVersion(), modLauncherPackage.getImplementationVersion(), modLauncherPackage.getImplementationVendor());
throw new IncompatibleEnvironmentException("Incompatible modlauncher found "+modLauncherPackage.getSpecificationVersion());
}
fmlLog.debug(CORE, "Initializing modjar URL handler");
URL.setURLStreamHandlerFactory(p->p.equals("modjar") ? new ModJarURLHandler() : null);
accessTransformer = environment.findLaunchPlugin("accesstransformer").orElseThrow(()-> new IncompatibleEnvironmentException("Missing AccessTransformer, cannot run"));
@@ -80,6 +83,15 @@ public class FMLLoader
throw new IncompatibleEnvironmentException("Incompatible accesstransformer found "+atPackage.getSpecificationVersion());
}
eventBus = environment.findLaunchPlugin("eventbus").orElseThrow(()-> new IncompatibleEnvironmentException("Missing EventBus, cannot run"));
final Package eventBusPackage = eventBus.getClass().getPackage();
fmlLog.debug(CORE,"FML found EventBus version : {}", eventBusPackage.getImplementationVersion());
if (!eventBusPackage.isCompatibleWith("1.0")) {
fmlLog.error(CORE,"Found incompatible EventBus specification : {}, version {} from {}", eventBusPackage.getSpecificationVersion(), eventBusPackage.getImplementationVersion(), eventBusPackage.getImplementationVendor());
throw new IncompatibleEnvironmentException("Incompatible eventbus found "+eventBusPackage.getSpecificationVersion());
}
final ArrayList<ICoreModProvider> coreModProviders = new ArrayList<>();
ServiceLoader.load(ICoreModProvider.class).forEach(coreModProviders::add);
@@ -20,19 +20,16 @@
package net.minecraftforge.fml.loading;
import cpw.mods.modlauncher.api.IEnvironment;
import cpw.mods.modlauncher.api.ILaunchHandlerService;
import cpw.mods.modlauncher.api.ITransformationService;
import cpw.mods.modlauncher.api.ITransformer;
import cpw.mods.modlauncher.api.IncompatibleEnvironmentException;
import joptsimple.ArgumentAcceptingOptionSpec;
import joptsimple.OptionSpecBuilder;
import net.minecraftforge.fml.FMLConfig;
import net.minecraftforge.fml.common.FMLPaths;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
@@ -20,11 +20,9 @@
package net.minecraftforge.fml.loading;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import net.minecraftforge.fml.loading.moddiscovery.IModInfo;
import net.minecraftforge.fml.loading.moddiscovery.ScanResult;
import java.util.List;
import java.util.function.Consumer;
/**
@@ -40,6 +38,6 @@ public interface IModLanguageProvider
Consumer<ScanResult> getFileVisitor();
interface IModLanguageLoader {
ModContainer loadMod(ModInfo info, ClassLoader modClassLoader);
ModContainer loadMod(IModInfo info, ClassLoader modClassLoader, ScanResult scanResults);
}
}
@@ -0,0 +1,54 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.loading;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.nio.file.Files;
public class ModJarURLHandler extends URLStreamHandler
{
// modjar:///modid!path/to/file
@Override
protected URLConnection openConnection(URL url) throws IOException {
return new URLConnection(url) {
private String modpath;
private String modid;
@Override
public void connect() throws IOException
{
final String path = url.getPath();
final String[] parts = path.split("!");
if (parts.length!=2) throw new IOException("Illegal URL format "+path);
modid = parts[0];
modpath = parts[1];
}
@Override
public InputStream getInputStream() throws IOException
{
return Files.newInputStream(FMLLoader.getModLoader().getModList().getModFileById(modid).getFile().findResource(modpath));
}
};
}
}
@@ -19,14 +19,22 @@
package net.minecraftforge.fml.loading;
import com.google.common.collect.Multimap;
import net.minecraftforge.fml.LifecycleEventProvider;
import net.minecraftforge.fml.ModLoadingStage;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.loading.moddiscovery.BackgroundScanHandler;
import net.minecraftforge.fml.loading.moddiscovery.IModFileInfo;
import net.minecraftforge.fml.loading.moddiscovery.IModInfo;
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
@@ -34,44 +42,74 @@ import java.util.stream.Collectors;
*/
public class ModList
{
private final List<ModFile> modFiles;
private final List<ModFileInfo> modFiles;
private final List<ModInfo> sortedList;
private final Map<String, ModFileInfo> fileById;
private BackgroundScanHandler scanner;
private List<ModContainer> mods;
private Map<String, ModContainer> indexedMods;
public ModList(final List<ModFile> modFiles, final List<ModInfo> sortedList)
{
this.modFiles = modFiles;
this.modFiles = modFiles.stream().map(ModFile::getModFileInfo).map(ModFileInfo.class::cast).collect(Collectors.toList());
this.sortedList = sortedList;
this.fileById = this.modFiles.stream().map(ModFileInfo::getMods).flatMap(Collection::stream).
map(ModInfo.class::cast).
collect(Collectors.toMap(ModInfo::getModId, ModInfo::getOwningFile));
}
public void addCoreMods()
{
modFiles.stream().map(ModFile::getCoreMods).flatMap(List::stream).forEach(FMLLoader.getCoreModProvider()::addCoreMod);
modFiles.stream().map(ModFileInfo::getFile).map(ModFile::getCoreMods).flatMap(List::stream).forEach(FMLLoader.getCoreModProvider()::addCoreMod);
}
public void addAccessTransformers()
{
modFiles.forEach(mod -> mod.getAccessTransformer().ifPresent(path -> FMLLoader.addAccessTransformer(path, mod)));
modFiles.stream().map(ModFileInfo::getFile).forEach(mod -> mod.getAccessTransformer().ifPresent(path -> FMLLoader.addAccessTransformer(path, mod)));
}
public void addForScanning(BackgroundScanHandler backgroundScanHandler)
{
this.scanner = backgroundScanHandler;
backgroundScanHandler.setModList(this);
modFiles.forEach(backgroundScanHandler::submitForScanning);
modFiles.stream().map(ModFileInfo::getFile).forEach(backgroundScanHandler::submitForScanning);
}
public List<ModFile> getModFiles()
public List<ModFileInfo> getModFiles()
{
return modFiles;
}
public Path findResource(final String className)
{
for (final ModFile mf : modFiles) {
final Path resource = mf.findResource(className);
for (ModFileInfo mf : modFiles) {
final Path resource = mf.getFile().findResource(className);
if (resource != null) return resource;
}
return null;
}
public ModFileInfo getModFileById(String modid)
{
return this.fileById.get(modid);
}
public void dispatchLifeCycleEvent(LifecycleEventProvider.LifecycleEvent lifecycleEvent) {
this.mods.parallelStream().forEach(m->m.transitionState(lifecycleEvent));
final List<ModContainer> erroredContainers = this.mods.stream().filter(m -> m.getCurrentState() == ModLoadingStage.ERROR).collect(Collectors.toList());
if (!erroredContainers.isEmpty()) {
throw new RuntimeException("Errored containers found!");
}
}
public void setLoadedMods(List<ModContainer> modContainers)
{
this.mods = modContainers;
this.indexedMods = modContainers.stream().collect(Collectors.toMap(ModContainer::getModId, Function.identity()));
}
public Optional<Object> getModObjectById(String modId)
{
return Optional.ofNullable(this.indexedMods.get(modId));
}
}
@@ -19,7 +19,9 @@
package net.minecraftforge.fml.loading;
import net.minecraftforge.fml.LifecycleEventProvider;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
import java.util.Collection;
import java.util.List;
@@ -49,6 +51,12 @@ public class ModLoader
}
public void loadMods() {
final List<ModContainer> collect = modList.getModFiles().stream().map(mf -> mf.buildMods(this.modClassLoader)).flatMap(Collection::stream).collect(Collectors.toList());
modList.setLoadedMods(modList.getModFiles().stream().
map(ModFileInfo::getFile).
map(mf -> mf.buildMods(this.modClassLoader)).
flatMap(Collection::stream).collect(Collectors.toList()));
LifecycleEventProvider.LOAD.dispatch(modList);
LifecycleEventProvider.PREINIT.dispatch(modList);
}
}
@@ -22,6 +22,7 @@ package net.minecraftforge.fml.loading;
import org.apache.logging.log4j.LogManager;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
@@ -35,25 +36,6 @@ public class ModLoadingClassLoader extends SecureClassLoader
{
static {
ClassLoader.registerAsParallelCapable();
// We use a custom URL format : modjar:modid!/path/in/jarfile
URL.setURLStreamHandlerFactory(protocol -> "modjar".equals(protocol) ? new URLStreamHandler() {
@Override
protected URLConnection openConnection(URL url) throws IOException {
return new URLConnection(url) {
@Override
public void connect()
{
url.get
}
};
}
@Override
protected void parseURL(URL u, String spec, int start, int limit)
{
}
} : null);
}
private ModLoader modLoader;
@@ -19,13 +19,13 @@
package net.minecraftforge.fml.loading;
import net.minecraftforge.common.ForgeVersion;
import net.minecraftforge.fml.DefaultModContainers;
import net.minecraftforge.fml.Java9BackportUtils;
import net.minecraftforge.fml.Logging;
import net.minecraftforge.fml.common.DuplicateModsFoundException;
import net.minecraftforge.fml.common.MissingModsException;
import net.minecraftforge.fml.common.toposort.TopologicalSort;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.loading.moddiscovery.IModInfo;
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import org.apache.logging.log4j.LogManager;
@@ -35,6 +35,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -61,21 +62,21 @@ public class ModSorter
}
private void sort() {
final TopologicalSort.DirectedGraph<ModInfo> topoGraph = new TopologicalSort.DirectedGraph<>();
final TopologicalSort.DirectedGraph<IModInfo> topoGraph = new TopologicalSort.DirectedGraph<>();
modFiles.stream().map(ModFile::getModInfos).
flatMap(Collection::stream).forEach(topoGraph::addNode);
modFiles.stream().map(ModFile::getModInfos).
flatMap(Collection::stream).map(ModInfo::getDependencies).flatMap(Collection::stream).forEach(dep->addDependency(topoGraph, dep));
flatMap(Collection::stream).map(IModInfo::getDependencies).flatMap(Collection::stream).forEach(dep->addDependency(topoGraph, dep));
}
private void addDependency(TopologicalSort.DirectedGraph<ModInfo> topoGraph, ModInfo.ModVersion dep)
private void addDependency(TopologicalSort.DirectedGraph<IModInfo> topoGraph, IModInfo.ModVersion dep)
{
}
private void buildUniqueList()
{
final Stream<ModInfo> modInfos = modFiles.stream().map(ModFile::getModInfos).flatMap(Collection::stream);
final Map<String, List<ModInfo>> modIds = modInfos.collect(Collectors.groupingBy(ModInfo::getModId));
final Stream<ModInfo> modInfos = modFiles.stream().map(ModFile::getModInfos).flatMap(Collection::stream).map(ModInfo.class::cast);
final Map<String, List<ModInfo>> modIds = modInfos.collect(Collectors.groupingBy(IModInfo::getModId));
// TODO: make this figure out dupe handling better
final List<Map.Entry<String, List<ModInfo>>> dupedMods = modIds.entrySet().stream().filter(e -> e.getValue().size() > 1).collect(Collectors.toList());
@@ -90,14 +91,14 @@ public class ModSorter
private void verifyDependencyVersions()
{
final Map<String, ArtifactVersion> modVersions = Stream.concat(modFiles.stream().map(ModFile::getModInfos).
flatMap(Collection::stream), ForgeVersion.getModInfos().stream()).collect(Collectors.toMap(ModInfo::getModId, ModInfo::getVersion));
final Map<ModInfo, List<ModInfo.ModVersion>> modVersionDependencies = modFiles.stream().
flatMap(Collection::stream), DefaultModContainers.getModInfos().stream()).collect(Collectors.toMap(IModInfo::getModId, IModInfo::getVersion));
final Map<IModInfo, List<IModInfo.ModVersion>> modVersionDependencies = modFiles.stream().
map(ModFile::getModInfos).flatMap(Collection::stream).
collect(Collectors.groupingBy(Function.identity(), Java9BackportUtils.flatMapping(e -> e.getDependencies().stream(), Collectors.toList())));
final Set<ModInfo.ModVersion> mandatoryModVersions = modVersionDependencies.values().stream().flatMap(Collection::stream).
final Set<IModInfo.ModVersion> mandatoryModVersions = modVersionDependencies.values().stream().flatMap(Collection::stream).
filter(mv -> mv.isMandatory() && mv.getSide().isCorrectSide()).collect(Collectors.toSet());
LogManager.getLogger("FML").debug(LOADING, "Found {} mandatory requirements", mandatoryModVersions.size());
final Set<ModInfo.ModVersion> missingVersions = mandatoryModVersions.stream().filter(mv->this.modVersionMatches(mv, modVersions)).collect(Collectors.toSet());
final Set<IModInfo.ModVersion> missingVersions = mandatoryModVersions.stream().filter(mv->this.modVersionMatches(mv, modVersions)).collect(Collectors.toSet());
LogManager.getLogger("FML").debug(LOADING, "Found {} mandatory mod requirements missing", missingVersions.size());
if (!missingVersions.isEmpty()) {
@@ -105,7 +106,7 @@ public class ModSorter
}
}
private boolean modVersionMatches(final ModInfo.ModVersion mv, final Map<String, ArtifactVersion> modVersions)
private boolean modVersionMatches(final IModInfo.ModVersion mv, final Map<String, ArtifactVersion> modVersions)
{
return !modVersions.containsKey(mv.getModId()) || !mv.getVersionRange().containsVersion(modVersions.get(mv.getModId()));
}
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml;
package net.minecraftforge.fml.loading;
import com.google.common.collect.ImmutableMap;
import net.minecraftforge.common.ForgeVersion;
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml;
package net.minecraftforge.fml.loading;
import org.apache.commons.lang3.text.StrSubstitutor;
@@ -17,21 +17,23 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.eventhandler;
package net.minecraftforge.fml.loading.moddiscovery;
import java.lang.reflect.Type;
import com.electronwill.nightconfig.core.UnmodifiableConfig;
import net.minecraftforge.fml.common.versioning.VersionRange;
public class GenericEvent<T> extends Event implements IGenericEvent<T>
import java.net.URL;
import java.util.List;
public interface IModFileInfo
{
private Class<T> type;
protected GenericEvent(Class<T> type)
{
this.type = type;
}
List<IModInfo> getMods();
@Override
public Type getGenericType()
{
return type;
}
UnmodifiableConfig getConfig();
URL getUpdateURL(IModFileInfo modFileInfo);
String getModLoader();
VersionRange getModLoaderVersion();
}
@@ -0,0 +1,107 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.loading.moddiscovery;
import com.electronwill.nightconfig.core.UnmodifiableConfig;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.VersionRange;
import net.minecraftforge.fml.loading.FMLEnvironment;
import java.util.List;
public interface IModInfo
{
VersionRange UNBOUNDED = VersionRange.createFromVersionSpec("");
IModFileInfo getOwningFile();
String getModId();
ArtifactVersion getVersion();
List<ModVersion> getDependencies();
UnmodifiableConfig getModConfig();
enum Ordering {
BEFORE, AFTER, NONE
}
enum DependencySide {
CLIENT, SERVER, BOTH;
public boolean isCorrectSide()
{
return this == BOTH || FMLEnvironment.side.name().equals(this.name());
}
}
class ModVersion {
private IModInfo owner;
private final String modId;
private final VersionRange versionRange;
private final boolean mandatory;
private final Ordering ordering;
private final DependencySide side;
ModVersion(final IModInfo owner, final UnmodifiableConfig config) {
this.owner = owner;
this.modId = config.get("modId");
this.versionRange = config.getOptional("versionRange").map(String.class::cast).
map(VersionRange::createFromVersionSpec).orElse(UNBOUNDED);
this.mandatory = config.get("mandatory");
this.ordering = config.getOptional("ordering").map(String.class::cast).
map(Ordering::valueOf).orElse(Ordering.NONE);
this.side = config.getOptional("side").map(String.class::cast).
map(DependencySide::valueOf).orElse(DependencySide.BOTH);
}
public String getModId()
{
return modId;
}
public VersionRange getVersionRange()
{
return versionRange;
}
public boolean isMandatory()
{
return mandatory;
}
public Ordering getOrdering()
{
return ordering;
}
public DependencySide getSide()
{
return side;
}
public void setOwner(final IModInfo owner)
{
this.owner = owner;
}
}
}
@@ -21,9 +21,9 @@ package net.minecraftforge.fml.loading.moddiscovery;
public class InvalidModFileException extends RuntimeException
{
private final ModFile.ModFileInfo modFileInfo;
private final IModFileInfo modFileInfo;
public InvalidModFileException(String message, ModFile.ModFileInfo modFileInfo)
public InvalidModFileException(String message, IModFileInfo modFileInfo)
{
super(message);
this.modFileInfo = modFileInfo;
@@ -70,10 +70,10 @@ public class ModDiscoverer {
}
}
fmlLog.debug(SCAN,"Found {} mod files with {} mods", mods::size, ()->mods.stream().mapToInt(mf -> mf.getModInfos().size()).sum());
final ModList sortedMods = ModSorter.sort(mods);
sortedMods.addCoreMods();
sortedMods.addAccessTransformers();
sortedMods.addForScanning(backgroundScanHandler);
final ModList modList = ModSorter.sort(mods);
modList.addCoreMods();
modList.addAccessTransformers();
modList.addForScanning(backgroundScanHandler);
return backgroundScanHandler;
}
}
@@ -19,24 +19,14 @@
package net.minecraftforge.fml.loading.moddiscovery;
import com.electronwill.nightconfig.core.UnmodifiableConfig;
import com.electronwill.nightconfig.core.file.FileConfig;
import com.google.common.collect.ImmutableMap;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.fml.StringUtils;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.versioning.DefaultArtifactVersion;
import net.minecraftforge.fml.common.versioning.VersionRange;
import net.minecraftforge.fml.loading.FMLLoader;
import net.minecraftforge.fml.loading.IModLanguageProvider;
import net.minecraftforge.fml.loading.ModLoadingClassLoader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -84,7 +74,7 @@ public class ModFile
public List<ModContainer> buildMods(ModLoadingClassLoader modClassLoader)
{
return getScanResult().getTargets().entrySet().stream().
map(e->e.getValue().loadMod(this.modInfoMap.get(e.getKey()), modClassLoader)).collect(Collectors.toList());
map(e->e.getValue().loadMod(this.modInfoMap.get(e.getKey()), modClassLoader, getScanResult())).collect(Collectors.toList());
}
public enum Type {
@@ -94,8 +84,8 @@ public class ModFile
private final Type modFileType;
private final Manifest manifest;
private final IModLocator locator;
private ModFileInfo modFileInfo;
private Map<String, ModInfo> modInfoMap;
private IModFileInfo modFileInfo;
private Map<String, IModInfo> modInfoMap;
private ScanResult fileScanResult;
private CompletableFuture<ScanResult> futureScanResult;
private List<CoreModFile> coreMods;
@@ -125,7 +115,7 @@ public class ModFile
return filePath;
}
public List<ModInfo> getModInfos() {
public List<IModInfo> getModInfos() {
return modFileInfo.getMods();
}
@@ -135,12 +125,12 @@ public class ModFile
public boolean identifyMods() {
this.modFileInfo = ModFileParser.readModList(this);
if (this.modFileInfo == null) return false;
fmlLog.debug(LOADING,"Loading mod file {} with language {}", this.getFilePath(), this.modFileInfo.modLoader);
this.modInfoMap = this.getModInfos().stream().collect(Collectors.toMap(ModInfo::getModId, Function.identity()));
fmlLog.debug(LOADING,"Loading mod file {} with language {}", this.getFilePath(), this.modFileInfo.getModLoader());
this.modInfoMap = this.getModInfos().stream().collect(Collectors.toMap(IModInfo::getModId, Function.identity()));
this.coreMods = ModFileParser.getCoreMods(this);
this.coreMods.forEach(mi-> fmlLog.debug(LOADING,"Found coremod {}", mi.getPath()));
this.accessTransformer = locator.findPath(this, "META-INF", "accesstransformer.cfg");
this.loader = FMLLoader.getLanguageLoadingProvider().findLanguage(this.modFileInfo.modLoader, this.modFileInfo.modLoaderVersion);
this.loader = FMLLoader.getLanguageLoadingProvider().findLanguage(this.modFileInfo.getModLoader(), this.modFileInfo.getModLoaderVersion());
return true;
}
@@ -193,53 +183,7 @@ public class ModFile
return locator;
}
public ModFileInfo getModFileInfo() {
public IModFileInfo getModFileInfo() {
return modFileInfo;
}
public static class ModFileInfo {
private final UnmodifiableConfig config;
private final ModFile modFile;
private final URL updateJSONURL;
private final URL issueURL;
private final String modLoader;
private final VersionRange modLoaderVersion;
private final List<ModInfo> mods;
private final Map<String,Object> properties;
public ModFileInfo(final ModFile modFile, final UnmodifiableConfig config)
{
this.modFile = modFile;
this.config = config;
this.modLoader = config.<String>getOptional("modLoader").
orElseThrow(()->new InvalidModFileException("Missing ModLoader in file", this));
this.modLoaderVersion = config.<String>getOptional("loaderVersion").
map(VersionRange::createFromVersionSpec).
orElseThrow(()->new InvalidModFileException("Missing ModLoader version in file", this));
this.properties = config.<UnmodifiableConfig>getOptional("properties").
map(UnmodifiableConfig::valueMap).orElse(Collections.emptyMap());
this.modFile.setFileProperties(this.properties);
final ArrayList<UnmodifiableConfig> modConfigs = config.getOrElse("mods", ArrayList::new);
if (modConfigs.isEmpty()) {
throw new InvalidModFileException("Missing mods list", this);
}
this.mods = modConfigs.stream().map(mi-> new ModInfo(this, mi)).collect(Collectors.toList());
this.updateJSONURL = config.<String>getOptional("updateJSONURL").map(StringUtils::toURL).orElse(null);
this.issueURL = config.<String>getOptional("issueTrackerURL").map(StringUtils::toURL).orElse(null);
}
public List<ModInfo> getMods()
{
return mods;
}
public ModFile getFile()
{
return this.modFile;
}
public UnmodifiableConfig getConfig()
{
return this.config;
}
}
}
@@ -0,0 +1,99 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.loading.moddiscovery;
import com.electronwill.nightconfig.core.UnmodifiableConfig;
import net.minecraftforge.fml.common.versioning.VersionRange;
import net.minecraftforge.fml.loading.StringUtils;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ModFileInfo implements IModFileInfo
{
private final UnmodifiableConfig config;
private final ModFile modFile;
private final URL updateJSONURL;
private final URL issueURL;
private final String modLoader;
private final VersionRange modLoaderVersion;
private final List<IModInfo> mods;
private final Map<String,Object> properties;
ModFileInfo(final ModFile modFile, final UnmodifiableConfig config)
{
this.modFile = modFile;
this.config = config;
this.modLoader = config.<String>getOptional("modLoader").
orElseThrow(()->new InvalidModFileException("Missing ModLoader in file", this));
this.modLoaderVersion = config.<String>getOptional("loaderVersion").
map(VersionRange::createFromVersionSpec).
orElseThrow(()->new InvalidModFileException("Missing ModLoader version in file", this));
this.properties = config.<UnmodifiableConfig>getOptional("properties").
map(UnmodifiableConfig::valueMap).orElse(Collections.emptyMap());
this.modFile.setFileProperties(this.properties);
final ArrayList<UnmodifiableConfig> modConfigs = config.getOrElse("mods", ArrayList::new);
if (modConfigs.isEmpty()) {
throw new InvalidModFileException("Missing mods list", this);
}
this.mods = modConfigs.stream().map(mi-> new ModInfo(this, mi)).collect(Collectors.toList());
this.updateJSONURL = config.<String>getOptional("updateJSONURL").map(StringUtils::toURL).orElse(null);
this.issueURL = config.<String>getOptional("issueTrackerURL").map(StringUtils::toURL).orElse(null);
}
@Override
public List<IModInfo> getMods()
{
return mods;
}
public ModFile getFile()
{
return this.modFile;
}
@Override
public UnmodifiableConfig getConfig()
{
return this.config;
}
@Override
public URL getUpdateURL(IModFileInfo modFileInfo)
{
return this.updateJSONURL;
}
@Override
public String getModLoader()
{
return modLoader;
}
@Override
public VersionRange getModLoaderVersion()
{
return modLoaderVersion;
}
}
@@ -22,7 +22,6 @@ package net.minecraftforge.fml.loading.moddiscovery;
import com.electronwill.nightconfig.core.path.PathConfig;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.text.StrSubstitutor;
import java.io.IOException;
import java.lang.reflect.Type;
@@ -37,7 +36,7 @@ import static net.minecraftforge.fml.Logging.LOADING;
import static net.minecraftforge.fml.Logging.fmlLog;
public class ModFileParser {
public static ModFile.ModFileInfo readModList(final ModFile modFile) {
public static IModFileInfo readModList(final ModFile modFile) {
fmlLog.debug(LOADING,"Parsing mod file candidate {}", modFile.getFilePath());
final Path modsjson = modFile.getLocator().findPath(modFile, "META-INF", "mods.toml");
if (!Files.exists(modsjson)) {
@@ -47,12 +46,12 @@ public class ModFileParser {
return loadModFile(modFile, modsjson);
}
public static ModFile.ModFileInfo loadModFile(final ModFile file, final Path modsjson)
public static IModFileInfo loadModFile(final ModFile file, final Path modsjson)
{
final PathConfig pathConfig = PathConfig.builder(modsjson).build();
pathConfig.load();
pathConfig.close();
return new ModFile.ModFileInfo(file, pathConfig);
return new ModFileInfo(file, pathConfig);
}
protected static List<CoreModFile> getCoreMods(final ModFile modFile) {
@@ -20,36 +20,29 @@
package net.minecraftforge.fml.loading.moddiscovery;
import com.electronwill.nightconfig.core.UnmodifiableConfig;
import net.minecraftforge.fml.FMLEnvironment;
import net.minecraftforge.fml.StringSubstitutor;
import net.minecraftforge.fml.StringUtils;
import net.minecraftforge.fml.loading.StringSubstitutor;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.DefaultArtifactVersion;
import net.minecraftforge.fml.common.versioning.VersionRange;
import net.minecraftforge.fml.loading.IModLanguageProvider;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
public class ModInfo {
public class ModInfo implements IModInfo {
private static final DefaultArtifactVersion DEFAULT_VERSION = new DefaultArtifactVersion("1");
public static final VersionRange UNBOUNDED = VersionRange.createFromVersionSpec("");
private final ModFile.ModFileInfo owningFile;
private final ModFileInfo owningFile;
private final String modId;
private final ArtifactVersion version;
private final String displayName;
private final String description;
private final List<ModInfo.ModVersion> dependencies;
private final List<IModInfo.ModVersion> dependencies;
private final Map<String,Object> properties;
private final UnmodifiableConfig modConfig;
public ModInfo(final ModFile.ModFileInfo owningFile, final UnmodifiableConfig modConfig)
public ModInfo(final ModFileInfo owningFile, final UnmodifiableConfig modConfig)
{
this.owningFile = owningFile;
this.modConfig = modConfig;
@@ -71,84 +64,29 @@ public class ModInfo {
}
public ModFile getOwningFile() {
return owningFile.getFile();
@Override
public ModFileInfo getOwningFile() {
return owningFile;
}
@Override
public String getModId() {
return modId;
}
@Override
public ArtifactVersion getVersion() {
return version;
}
public List<ModInfo.ModVersion> getDependencies() {
@Override
public List<IModInfo.ModVersion> getDependencies() {
return this.dependencies;
}
public enum Ordering {
BEFORE, AFTER, NONE
@Override
public UnmodifiableConfig getModConfig() {
return this.modConfig;
}
public enum DependencySide {
CLIENT, SERVER, BOTH;
public boolean isCorrectSide()
{
return this == BOTH || FMLEnvironment.side.name().equals(this.name());
}
}
public static class ModVersion {
private ModInfo owner;
private final String modId;
private final VersionRange versionRange;
private final boolean mandatory;
private final Ordering ordering;
private final DependencySide side;
ModVersion(final ModInfo owner, final UnmodifiableConfig config) {
this.owner = owner;
this.modId = config.get("modId");
this.versionRange = config.getOptional("versionRange").map(String.class::cast).
map(VersionRange::createFromVersionSpec).orElse(UNBOUNDED);
this.mandatory = config.get("mandatory");
this.ordering = config.getOptional("ordering").map(String.class::cast).
map(Ordering::valueOf).orElse(Ordering.NONE);
this.side = config.getOptional("side").map(String.class::cast).
map(DependencySide::valueOf).orElse(DependencySide.BOTH);
}
public String getModId()
{
return modId;
}
public VersionRange getVersionRange()
{
return versionRange;
}
public boolean isMandatory()
{
return mandatory;
}
public Ordering getOrdering()
{
return ordering;
}
public DependencySide getSide()
{
return side;
}
public void setOwner(final ModInfo owner)
{
this.owner = owner;
}
}
}
@@ -19,7 +19,7 @@
package net.minecraftforge.fml.loading.moddiscovery;
import net.minecraftforge.fml.StringUtils;
import net.minecraftforge.fml.loading.StringUtils;
import net.minecraftforge.fml.common.FMLPaths;
import java.io.IOException;
@@ -20,8 +20,6 @@
package net.minecraftforge.fml.loading.moddiscovery;
import com.google.common.collect.Multimap;
import net.minecraftforge.fml.loading.FMLJavaModLanguageProvider;
import net.minecraftforge.fml.loading.IModLanguageProvider;
import org.objectweb.asm.Type;
@@ -66,7 +64,6 @@ public class ScanResult {
return modTargets;
}
public static class ClassData {
private final Type clazz;
private final Type parent;
@@ -111,6 +108,5 @@ public class ScanResult {
public static ScanResult.AnnotationData fromModAnnotation(final Type clazz, final ModAnnotation annotation) {
return new AnnotationData(annotation.asmType, clazz, annotation.member, annotation.values);
}
}
}
@@ -37,13 +37,13 @@ import net.minecraft.util.IThreadListener;
import net.minecraft.util.text.translation.LanguageMap;
import net.minecraft.world.storage.SaveFormatOld;
import net.minecraftforge.common.util.CompoundDataFixer;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.IFMLSidedHandler;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.StartupQuery;
import net.minecraftforge.fml.common.eventhandler.EventBus;
import net.minecraftforge.fml.common.network.FMLNetworkEvent;
import net.minecraftforge.fml.relauncher.Side;
@@ -305,7 +305,7 @@ public class FMLServerHandler implements IFMLSidedHandler
}
@Override
public void fireNetRegistrationEvent(EventBus bus, NetworkManager manager, Set<String> channelSet, String channel, Side side)
public void fireNetRegistrationEvent(IEventBus bus, NetworkManager manager, Set<String> channelSet, String channel, Side side)
{
bus.post(new FMLNetworkEvent.CustomPacketRegistrationEvent<NetHandlerPlayServer>(manager, channelSet, channel, side, NetHandlerPlayServer.class));
}