summaryrefslogtreecommitdiff
path: root/src/SMAPI
diff options
context:
space:
mode:
Diffstat (limited to 'src/SMAPI')
-rw-r--r--src/SMAPI/Framework/Content/AssetName.cs16
-rw-r--r--src/SMAPI/Framework/ContentCoordinator.cs19
-rw-r--r--src/SMAPI/Framework/ContentManagers/ModContentManager.cs6
-rw-r--r--src/SMAPI/Framework/ContentPack.cs6
-rw-r--r--src/SMAPI/Framework/ModHelpers/ModContentHelper.cs6
-rw-r--r--src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs4
-rw-r--r--src/SMAPI/Framework/ModLoading/ModResolver.cs23
-rw-r--r--src/SMAPI/Framework/Models/SConfig.cs10
-rw-r--r--src/SMAPI/Framework/Reflection/IInterfaceProxyFactory.cs17
-rw-r--r--src/SMAPI/Framework/Reflection/InterfaceProxyFactory.cs10
-rw-r--r--src/SMAPI/Framework/Reflection/OriginalInterfaceProxyBuilder.cs118
-rw-r--r--src/SMAPI/Framework/Reflection/OriginalInterfaceProxyFactory.cs57
-rw-r--r--src/SMAPI/Framework/SCore.cs17
-rw-r--r--src/SMAPI/Framework/Translator.cs3
-rw-r--r--src/SMAPI/SMAPI.config.json6
-rw-r--r--src/SMAPI/Utilities/CaseInsensitivePathCache.cs124
16 files changed, 254 insertions, 188 deletions
diff --git a/src/SMAPI/Framework/Content/AssetName.cs b/src/SMAPI/Framework/Content/AssetName.cs
index 4c691b9a..148354a1 100644
--- a/src/SMAPI/Framework/Content/AssetName.cs
+++ b/src/SMAPI/Framework/Content/AssetName.cs
@@ -119,25 +119,27 @@ namespace StardewModdingAPI.Framework.Content
if (prefix is null)
return false;
+ string rawTrimmed = prefix.Trim();
+
// asset keys can't have a leading slash, but NormalizeAssetName will trim them
- {
- string trimmed = prefix.TrimStart();
- if (trimmed.StartsWith('/') || trimmed.StartsWith('\\'))
- return false;
- }
+ if (rawTrimmed.StartsWith('/') || rawTrimmed.StartsWith('\\'))
+ return false;
// normalize prefix
{
string normalized = PathUtilities.NormalizeAssetName(prefix);
- string trimmed = prefix.TrimEnd();
- if (trimmed.EndsWith('/') || trimmed.EndsWith('\\'))
+ // keep trailing slash
+ if (rawTrimmed.EndsWith('/') || rawTrimmed.EndsWith('\\'))
normalized += PathUtilities.PreferredAssetSeparator;
prefix = normalized;
}
// compare
+ if (prefix.Length == 0)
+ return true;
+
return
this.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)
&& (
diff --git a/src/SMAPI/Framework/ContentCoordinator.cs b/src/SMAPI/Framework/ContentCoordinator.cs
index 92452224..aade7b36 100644
--- a/src/SMAPI/Framework/ContentCoordinator.cs
+++ b/src/SMAPI/Framework/ContentCoordinator.cs
@@ -15,7 +15,7 @@ using StardewModdingAPI.Framework.Utilities;
using StardewModdingAPI.Internal;
using StardewModdingAPI.Metadata;
using StardewModdingAPI.Toolkit.Serialization;
-using StardewModdingAPI.Utilities;
+using StardewModdingAPI.Toolkit.Utilities;
using StardewValley;
using StardewValley.GameData;
using xTile;
@@ -80,9 +80,6 @@ namespace StardewModdingAPI.Framework
/// <summary>The cached asset load/edit operations to apply, indexed by asset name.</summary>
private readonly TickCacheDictionary<IAssetName, AssetOperationGroup[]> AssetOperationsByKey = new();
- /// <summary>The previously created case-insensitive path caches by root path.</summary>
- private readonly Dictionary<string, CaseInsensitivePathCache> CaseInsensitivePathCaches = new(StringComparer.OrdinalIgnoreCase);
-
/*********
** Accessors
@@ -211,7 +208,7 @@ namespace StardewModdingAPI.Framework
jsonHelper: this.JsonHelper,
onDisposing: this.OnDisposing,
aggressiveMemoryOptimizations: this.AggressiveMemoryOptimizations,
- relativePathCache: this.GetCaseInsensitivePathCache(rootDirectory)
+ relativePathCache: CaseInsensitivePathLookup.GetCachedFor(rootDirectory)
);
this.ContentManagers.Add(manager);
return manager;
@@ -486,18 +483,6 @@ namespace StardewModdingAPI.Framework
});
}
- /// <summary>Get a dictionary of relative paths within a root path, for case-insensitive file lookups.</summary>
- /// <param name="rootPath">The root path to scan.</param>
- public CaseInsensitivePathCache GetCaseInsensitivePathCache(string rootPath)
- {
- rootPath = PathUtilities.NormalizePath(rootPath);
-
- if (!this.CaseInsensitivePathCaches.TryGetValue(rootPath, out CaseInsensitivePathCache? cache))
- this.CaseInsensitivePathCaches[rootPath] = cache = new CaseInsensitivePathCache(rootPath);
-
- return cache;
- }
-
/// <summary>Get the tilesheet ID order used by the unmodified version of a map asset.</summary>
/// <param name="assetName">The asset path relative to the loader root directory, not including the <c>.xnb</c> extension.</param>
public TilesheetReference[] GetVanillaTilesheetIds(string assetName)
diff --git a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs
index f0f4bce9..8f64c5a8 100644
--- a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs
+++ b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs
@@ -9,7 +9,7 @@ using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI.Framework.Exceptions;
using StardewModdingAPI.Framework.Reflection;
using StardewModdingAPI.Toolkit.Serialization;
-using StardewModdingAPI.Utilities;
+using StardewModdingAPI.Toolkit.Utilities;
using StardewValley;
using xTile;
using xTile.Format;
@@ -33,7 +33,7 @@ namespace StardewModdingAPI.Framework.ContentManagers
private readonly IContentManager GameContentManager;
/// <summary>A case-insensitive lookup of relative paths within the <see cref="ContentManager.RootDirectory"/>.</summary>
- private readonly CaseInsensitivePathCache RelativePathCache;
+ private readonly CaseInsensitivePathLookup RelativePathCache;
/// <summary>If a map tilesheet's image source has no file extensions, the file extensions to check for in the local mod folder.</summary>
private readonly string[] LocalTilesheetExtensions = { ".png", ".xnb" };
@@ -56,7 +56,7 @@ namespace StardewModdingAPI.Framework.ContentManagers
/// <param name="onDisposing">A callback to invoke when the content manager is being disposed.</param>
/// <param name="aggressiveMemoryOptimizations">Whether to enable more aggressive memory optimizations.</param>
/// <param name="relativePathCache">A case-insensitive lookup of relative paths within the <paramref name="rootDirectory"/>.</param>
- public ModContentManager(string name, IContentManager gameContentManager, IServiceProvider serviceProvider, string modName, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action<BaseContentManager> onDisposing, bool aggressiveMemoryOptimizations, CaseInsensitivePathCache relativePathCache)
+ public ModContentManager(string name, IContentManager gameContentManager, IServiceProvider serviceProvider, string modName, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action<BaseContentManager> onDisposing, bool aggressiveMemoryOptimizations, CaseInsensitivePathLookup relativePathCache)
: base(name, serviceProvider, rootDirectory, currentCulture, coordinator, monitor, reflection, onDisposing, isNamespaced: true, aggressiveMemoryOptimizations: aggressiveMemoryOptimizations)
{
this.GameContentManager = gameContentManager;
diff --git a/src/SMAPI/Framework/ContentPack.cs b/src/SMAPI/Framework/ContentPack.cs
index 2cfd5cce..dde33c95 100644
--- a/src/SMAPI/Framework/ContentPack.cs
+++ b/src/SMAPI/Framework/ContentPack.cs
@@ -2,7 +2,7 @@ using System;
using System.IO;
using StardewModdingAPI.Framework.ModHelpers;
using StardewModdingAPI.Toolkit.Serialization;
-using StardewModdingAPI.Utilities;
+using StardewModdingAPI.Toolkit.Utilities;
namespace StardewModdingAPI.Framework
{
@@ -16,7 +16,7 @@ namespace StardewModdingAPI.Framework
private readonly JsonHelper JsonHelper;
/// <summary>A case-insensitive lookup of relative paths within the <see cref="DirectoryPath"/>.</summary>
- private readonly CaseInsensitivePathCache RelativePathCache;
+ private readonly CaseInsensitivePathLookup RelativePathCache;
/*********
@@ -48,7 +48,7 @@ namespace StardewModdingAPI.Framework
/// <param name="translation">Provides translations stored in the content pack's <c>i18n</c> folder.</param>
/// <param name="jsonHelper">Encapsulates SMAPI's JSON file parsing.</param>
/// <param name="relativePathCache">A case-insensitive lookup of relative paths within the <paramref name="directoryPath"/>.</param>
- public ContentPack(string directoryPath, IManifest manifest, IModContentHelper content, TranslationHelper translation, JsonHelper jsonHelper, CaseInsensitivePathCache relativePathCache)
+ public ContentPack(string directoryPath, IManifest manifest, IModContentHelper content, TranslationHelper translation, JsonHelper jsonHelper, CaseInsensitivePathLookup relativePathCache)
{
this.DirectoryPath = directoryPath;
this.Manifest = manifest;
diff --git a/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs b/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs
index 4a058a48..def0b728 100644
--- a/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs
+++ b/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs
@@ -4,7 +4,7 @@ using StardewModdingAPI.Framework.Content;
using StardewModdingAPI.Framework.ContentManagers;
using StardewModdingAPI.Framework.Exceptions;
using StardewModdingAPI.Framework.Reflection;
-using StardewModdingAPI.Utilities;
+using StardewModdingAPI.Toolkit.Utilities;
namespace StardewModdingAPI.Framework.ModHelpers
{
@@ -24,7 +24,7 @@ namespace StardewModdingAPI.Framework.ModHelpers
private readonly string ModName;
/// <summary>A case-insensitive lookup of relative paths within the <see cref="ContentManager.RootDirectory"/>.</summary>
- private readonly CaseInsensitivePathCache RelativePathCache;
+ private readonly CaseInsensitivePathLookup RelativePathCache;
/// <summary>Simplifies access to private code.</summary>
private readonly Reflector Reflection;
@@ -41,7 +41,7 @@ namespace StardewModdingAPI.Framework.ModHelpers
/// <param name="gameContentManager">The game content manager used for map tilesheets not provided by the mod.</param>
/// <param name="relativePathCache">A case-insensitive lookup of relative paths within the <paramref name="relativePathCache"/>.</param>
/// <param name="reflection">Simplifies access to private code.</param>
- public ModContentHelper(ContentCoordinator contentCore, string modFolderPath, IModMetadata mod, string modName, IContentManager gameContentManager, CaseInsensitivePathCache relativePathCache, Reflector reflection)
+ public ModContentHelper(ContentCoordinator contentCore, string modFolderPath, IModMetadata mod, string modName, IContentManager gameContentManager, CaseInsensitivePathLookup relativePathCache, Reflector reflection)
: base(mod)
{
string managedAssetPrefix = contentCore.GetManagedAssetPrefix(mod.Manifest.UniqueID);
diff --git a/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs b/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs
index 39cef758..348ba225 100644
--- a/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs
+++ b/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs
@@ -19,7 +19,7 @@ namespace StardewModdingAPI.Framework.ModHelpers
private readonly HashSet<string> AccessedModApis = new();
/// <summary>Generates proxy classes to access mod APIs through an arbitrary interface.</summary>
- private readonly InterfaceProxyFactory ProxyFactory;
+ private readonly IInterfaceProxyFactory ProxyFactory;
/*********
@@ -30,7 +30,7 @@ namespace StardewModdingAPI.Framework.ModHelpers
/// <param name="registry">The underlying mod registry.</param>
/// <param name="proxyFactory">Generates proxy classes to access mod APIs through an arbitrary interface.</param>
/// <param name="monitor">Encapsulates monitoring and logging for the mod.</param>
- public ModRegistryHelper(IModMetadata mod, ModRegistry registry, InterfaceProxyFactory proxyFactory, IMonitor monitor)
+ public ModRegistryHelper(IModMetadata mod, ModRegistry registry, IInterfaceProxyFactory proxyFactory, IMonitor monitor)
: base(mod)
{
this.Registry = registry;
diff --git a/src/SMAPI/Framework/ModLoading/ModResolver.cs b/src/SMAPI/Framework/ModLoading/ModResolver.cs
index afb388d0..74e7cb32 100644
--- a/src/SMAPI/Framework/ModLoading/ModResolver.cs
+++ b/src/SMAPI/Framework/ModLoading/ModResolver.cs
@@ -56,9 +56,10 @@ namespace StardewModdingAPI.Framework.ModLoading
/// <param name="mods">The mod manifests to validate.</param>
/// <param name="apiVersion">The current SMAPI version.</param>
/// <param name="getUpdateUrl">Get an update URL for an update key (if valid).</param>
+ /// <param name="validateFilesExist">Whether to validate that files referenced in the manifest (like <see cref="IManifest.EntryDll"/>) exist on disk. This can be disabled to only validate the manifest itself.</param>
[SuppressMessage("ReSharper", "ConstantConditionalAccessQualifier", Justification = "Manifest values may be null before they're validated.")]
[SuppressMessage("ReSharper", "ConditionIsAlwaysTrueOrFalse", Justification = "Manifest values may be null before they're validated.")]
- public void ValidateManifests(IEnumerable<IModMetadata> mods, ISemanticVersion apiVersion, Func<string, string?> getUpdateUrl)
+ public void ValidateManifests(IEnumerable<IModMetadata> mods, ISemanticVersion apiVersion, Func<string, string?> getUpdateUrl, bool validateFilesExist = true)
{
mods = mods.ToArray();
@@ -140,19 +141,15 @@ namespace StardewModdingAPI.Framework.ModLoading
continue;
}
- // invalid path
- if (!File.Exists(Path.Combine(mod.DirectoryPath, mod.Manifest.EntryDll!)))
+ // file doesn't exist
+ if (validateFilesExist)
{
- mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.InvalidManifest, $"its DLL '{mod.Manifest.EntryDll}' doesn't exist.");
- continue;
- }
-
- // invalid capitalization
- string? actualFilename = new DirectoryInfo(mod.DirectoryPath).GetFiles(mod.Manifest.EntryDll!).FirstOrDefault()?.Name;
- if (actualFilename != mod.Manifest.EntryDll)
- {
- mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.InvalidManifest, $"its {nameof(IManifest.EntryDll)} value '{mod.Manifest.EntryDll}' doesn't match the actual file capitalization '{actualFilename}'. The capitalization must match for crossplatform compatibility.");
- continue;
+ string fileName = CaseInsensitivePathLookup.GetCachedFor(mod.DirectoryPath).GetFilePath(mod.Manifest.EntryDll!);
+ if (!File.Exists(Path.Combine(mod.DirectoryPath, fileName)))
+ {
+ mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.InvalidManifest, $"its DLL '{mod.Manifest.EntryDll}' doesn't exist.");
+ continue;
+ }
}
}
diff --git a/src/SMAPI/Framework/Models/SConfig.cs b/src/SMAPI/Framework/Models/SConfig.cs
index d626ab4d..af2e1035 100644
--- a/src/SMAPI/Framework/Models/SConfig.cs
+++ b/src/SMAPI/Framework/Models/SConfig.cs
@@ -22,7 +22,8 @@ namespace StardewModdingAPI.Framework.Models
[nameof(VerboseLogging)] = false,
[nameof(LogNetworkTraffic)] = false,
[nameof(RewriteMods)] = true,
- [nameof(AggressiveMemoryOptimizations)] = false
+ [nameof(AggressiveMemoryOptimizations)] = false,
+ [nameof(UsePintail)] = false
};
/// <summary>The default values for <see cref="SuppressUpdateChecks"/>, to log changes if different.</summary>
@@ -64,6 +65,9 @@ namespace StardewModdingAPI.Framework.Models
/// <summary>Whether to enable more aggressive memory optimizations.</summary>
public bool AggressiveMemoryOptimizations { get; }
+ /// <summary>Whether to use the experimental Pintail API proxying library, instead of the original proxying built into SMAPI itself.</summary>
+ public bool UsePintail { get; }
+
/// <summary>Whether SMAPI should log network traffic. Best combined with <see cref="VerboseLogging"/>, which includes network metadata.</summary>
public bool LogNetworkTraffic { get; }
@@ -87,10 +91,11 @@ namespace StardewModdingAPI.Framework.Models
/// <param name="verboseLogging">Whether SMAPI should log more information about the game context.</param>
/// <param name="rewriteMods">Whether SMAPI should rewrite mods for compatibility.</param>
/// <param name="aggressiveMemoryOptimizations">Whether to enable more aggressive memory optimizations.</param>
+ /// <param name="usePintail">Whether to use the experimental Pintail API proxying library, instead of the original proxying built into SMAPI itself.</param>
/// <param name="logNetworkTraffic">Whether SMAPI should log network traffic.</param>
/// <param name="consoleColors">The colors to use for text written to the SMAPI console.</param>
/// <param name="suppressUpdateChecks">The mod IDs SMAPI should ignore when performing update checks or validating update keys.</param>
- public SConfig(bool developerMode, bool checkForUpdates, bool? paranoidWarnings, bool? useBetaChannel, string gitHubProjectName, string webApiBaseUrl, bool verboseLogging, bool? rewriteMods, bool? aggressiveMemoryOptimizations, bool logNetworkTraffic, ColorSchemeConfig consoleColors, string[]? suppressUpdateChecks)
+ public SConfig(bool developerMode, bool checkForUpdates, bool? paranoidWarnings, bool? useBetaChannel, string gitHubProjectName, string webApiBaseUrl, bool verboseLogging, bool? rewriteMods, bool? aggressiveMemoryOptimizations, bool usePintail, bool logNetworkTraffic, ColorSchemeConfig consoleColors, string[]? suppressUpdateChecks)
{
this.DeveloperMode = developerMode;
this.CheckForUpdates = checkForUpdates;
@@ -101,6 +106,7 @@ namespace StardewModdingAPI.Framework.Models
this.VerboseLogging = verboseLogging;
this.RewriteMods = rewriteMods ?? (bool)SConfig.DefaultValues[nameof(SConfig.RewriteMods)];
this.AggressiveMemoryOptimizations = aggressiveMemoryOptimizations ?? (bool)SConfig.DefaultValues[nameof(SConfig.AggressiveMemoryOptimizations)];
+ this.UsePintail = usePintail;
this.LogNetworkTraffic = logNetworkTraffic;
this.ConsoleColors = consoleColors;
this.SuppressUpdateChecks = suppressUpdateChecks ?? Array.Empty<string>();
diff --git a/src/SMAPI/Framework/Reflection/IInterfaceProxyFactory.cs b/src/SMAPI/Framework/Reflection/IInterfaceProxyFactory.cs
new file mode 100644
index 00000000..6429db58
--- /dev/null
+++ b/src/SMAPI/Framework/Reflection/IInterfaceProxyFactory.cs
@@ -0,0 +1,17 @@
+namespace StardewModdingAPI.Framework.Reflection
+{
+ /// <summary>Generates proxy classes to access mod APIs through an arbitrary interface.</summary>
+ internal interface IInterfaceProxyFactory
+ {
+ /*********
+ ** Methods
+ *********/
+ /// <summary>Create an API proxy.</summary>
+ /// <typeparam name="TInterface">The interface through which to access the API.</typeparam>
+ /// <param name="instance">The API instance to access.</param>
+ /// <param name="sourceModID">The unique ID of the mod consuming the API.</param>
+ /// <param name="targetModID">The unique ID of the mod providing the API.</param>
+ TInterface CreateProxy<TInterface>(object instance, string sourceModID, string targetModID)
+ where TInterface : class;
+ }
+}
diff --git a/src/SMAPI/Framework/Reflection/InterfaceProxyFactory.cs b/src/SMAPI/Framework/Reflection/InterfaceProxyFactory.cs
index 40adde8e..694c563d 100644
--- a/src/SMAPI/Framework/Reflection/InterfaceProxyFactory.cs
+++ b/src/SMAPI/Framework/Reflection/InterfaceProxyFactory.cs
@@ -4,8 +4,8 @@ using Nanoray.Pintail;
namespace StardewModdingAPI.Framework.Reflection
{
- /// <summary>Generates proxy classes to access mod APIs through an arbitrary interface.</summary>
- internal class InterfaceProxyFactory
+ /// <inheritdoc />
+ internal class InterfaceProxyFactory : IInterfaceProxyFactory
{
/*********
** Fields
@@ -28,11 +28,7 @@ namespace StardewModdingAPI.Framework.Reflection
));
}
- /// <summary>Create an API proxy.</summary>
- /// <typeparam name="TInterface">The interface through which to access the API.</typeparam>
- /// <param name="instance">The API instance to access.</param>
- /// <param name="sourceModID">The unique ID of the mod consuming the API.</param>
- /// <param name="targetModID">The unique ID of the mod providing the API.</param>
+ /// <inheritdoc />
public TInterface CreateProxy<TInterface>(object instance, string sourceModID, string targetModID)
where TInterface : class
{
diff --git a/src/SMAPI/Framework/Reflection/OriginalInterfaceProxyBuilder.cs b/src/SMAPI/Framework/Reflection/OriginalInterfaceProxyBuilder.cs
new file mode 100644
index 00000000..9576f768
--- /dev/null
+++ b/src/SMAPI/Framework/Reflection/OriginalInterfaceProxyBuilder.cs
@@ -0,0 +1,118 @@
+using System;
+using System.Linq;
+using System.Reflection;
+using System.Reflection.Emit;
+
+namespace StardewModdingAPI.Framework.Reflection
+{
+ /// <summary>Generates a proxy class to access a mod API through an arbitrary interface.</summary>
+ internal class OriginalInterfaceProxyBuilder
+ {
+ /*********
+ ** Fields
+ *********/
+ /// <summary>The target class type.</summary>
+ private readonly Type TargetType;
+
+ /// <summary>The generated proxy type.</summary>
+ private readonly Type ProxyType;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="name">The type name to generate.</param>
+ /// <param name="moduleBuilder">The CLR module in which to create proxy classes.</param>
+ /// <param name="interfaceType">The interface type to implement.</param>
+ /// <param name="targetType">The target type.</param>
+ public OriginalInterfaceProxyBuilder(string name, ModuleBuilder moduleBuilder, Type interfaceType, Type targetType)
+ {
+ // validate
+ if (name == null)
+ throw new ArgumentNullException(nameof(name));
+ if (targetType == null)
+ throw new ArgumentNullException(nameof(targetType));
+
+ // define proxy type
+ TypeBuilder proxyBuilder = moduleBuilder.DefineType(name, TypeAttributes.Public | TypeAttributes.Class);
+ proxyBuilder.AddInterfaceImplementation(interfaceType);
+
+ // create field to store target instance
+ FieldBuilder targetField = proxyBuilder.DefineField("__Target", targetType, FieldAttributes.Private);
+
+ // create constructor which accepts target instance and sets field
+ {
+ ConstructorBuilder constructor = proxyBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard | CallingConventions.HasThis, new[] { targetType });
+ ILGenerator il = constructor.GetILGenerator();
+
+ il.Emit(OpCodes.Ldarg_0); // this
+ // ReSharper disable once AssignNullToNotNullAttribute -- never null
+ il.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes)!); // call base constructor
+ il.Emit(OpCodes.Ldarg_0); // this
+ il.Emit(OpCodes.Ldarg_1); // load argument
+ il.Emit(OpCodes.Stfld, targetField); // set field to loaded argument
+ il.Emit(OpCodes.Ret);
+ }
+
+ // proxy methods
+ foreach (MethodInfo proxyMethod in interfaceType.GetMethods())
+ {
+ var targetMethod = targetType.GetMethod(proxyMethod.Name, proxyMethod.GetParameters().Select(a => a.ParameterType).ToArray());
+ if (targetMethod == null)
+ throw new InvalidOperationException($"The {interfaceType.FullName} interface defines method {proxyMethod.Name} which doesn't exist in the API.");
+
+ this.ProxyMethod(proxyBuilder, targetMethod, targetField);
+ }
+
+ // save info
+ this.TargetType = targetType;
+ this.ProxyType = proxyBuilder.CreateType()!;
+ }
+
+ /// <summary>Create an instance of the proxy for a target instance.</summary>
+ /// <param name="targetInstance">The target instance.</param>
+ public object CreateInstance(object targetInstance)
+ {
+ ConstructorInfo? constructor = this.ProxyType.GetConstructor(new[] { this.TargetType });
+ if (constructor == null)
+ throw new InvalidOperationException($"Couldn't find the constructor for generated proxy type '{this.ProxyType.Name}'."); // should never happen
+ return constructor.Invoke(new[] { targetInstance });
+ }
+
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Define a method which proxies access to a method on the target.</summary>
+ /// <param name="proxyBuilder">The proxy type being generated.</param>
+ /// <param name="target">The target method.</param>
+ /// <param name="instanceField">The proxy field containing the API instance.</param>
+ private void ProxyMethod(TypeBuilder proxyBuilder, MethodInfo target, FieldBuilder instanceField)
+ {
+ Type[] argTypes = target.GetParameters().Select(a => a.ParameterType).ToArray();
+
+ // create method
+ MethodBuilder methodBuilder = proxyBuilder.DefineMethod(target.Name, MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual);
+ methodBuilder.SetParameters(argTypes);
+ methodBuilder.SetReturnType(target.ReturnType);
+
+ // create method body
+ {
+ ILGenerator il = methodBuilder.GetILGenerator();
+
+ // load target instance
+ il.Emit(OpCodes.Ldarg_0);
+ il.Emit(OpCodes.Ldfld, instanceField);
+
+ // invoke target method on instance
+ for (int i = 0; i < argTypes.Length; i++)
+ il.Emit(OpCodes.Ldarg, i + 1);
+ il.Emit(OpCodes.Call, target);
+
+ // return result
+ il.Emit(OpCodes.Ret);
+ }
+ }
+ }
+}
diff --git a/src/SMAPI/Framework/Reflection/OriginalInterfaceProxyFactory.cs b/src/SMAPI/Framework/Reflection/OriginalInterfaceProxyFactory.cs
new file mode 100644
index 00000000..d6966978
--- /dev/null
+++ b/src/SMAPI/Framework/Reflection/OriginalInterfaceProxyFactory.cs
@@ -0,0 +1,57 @@
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Reflection.Emit;
+
+namespace StardewModdingAPI.Framework.Reflection
+{
+ /// <inheritdoc />
+ internal class OriginalInterfaceProxyFactory : IInterfaceProxyFactory
+ {
+ /*********
+ ** Fields
+ *********/
+ /// <summary>The CLR module in which to create proxy classes.</summary>
+ private readonly ModuleBuilder ModuleBuilder;
+
+ /// <summary>The generated proxy types.</summary>
+ private readonly IDictionary<string, OriginalInterfaceProxyBuilder> Builders = new Dictionary<string, OriginalInterfaceProxyBuilder>();
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public OriginalInterfaceProxyFactory()
+ {
+ AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName($"StardewModdingAPI.Proxies, Version={this.GetType().Assembly.GetName().Version}, Culture=neutral"), AssemblyBuilderAccess.Run);
+ this.ModuleBuilder = assemblyBuilder.DefineDynamicModule("StardewModdingAPI.Proxies");
+ }
+
+ /// <inheritdoc />
+ public TInterface CreateProxy<TInterface>(object instance, string sourceModID, string targetModID)
+ where TInterface : class
+ {
+ lock (this.Builders)
+ {
+ // validate
+ if (instance == null)
+ throw new InvalidOperationException("Can't proxy access to a null API.");
+ if (!typeof(TInterface).IsInterface)
+ throw new InvalidOperationException("The proxy type must be an interface, not a class.");
+
+ // get proxy type
+ Type targetType = instance.GetType();
+ string proxyTypeName = $"StardewModdingAPI.Proxies.From<{sourceModID}_{typeof(TInterface).FullName}>_To<{targetModID}_{targetType.FullName}>";
+ if (!this.Builders.TryGetValue(proxyTypeName, out OriginalInterfaceProxyBuilder? builder))
+ {
+ builder = new OriginalInterfaceProxyBuilder(proxyTypeName, this.ModuleBuilder, typeof(TInterface), targetType);
+ this.Builders[proxyTypeName] = builder;
+ }
+
+ // create instance
+ return (TInterface)builder.CreateInstance(instance);
+ }
+ }
+ }
+}
diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs
index 990fe5ea..44853627 100644
--- a/src/SMAPI/Framework/SCore.cs
+++ b/src/SMAPI/Framework/SCore.cs
@@ -1560,7 +1560,9 @@ namespace StardewModdingAPI.Framework
{
// init
HashSet<string> suppressUpdateChecks = new HashSet<string>(this.Settings.SuppressUpdateChecks, StringComparer.OrdinalIgnoreCase);
- InterfaceProxyFactory proxyFactory = new();
+ IInterfaceProxyFactory proxyFactory = this.Settings.UsePintail
+ ? new InterfaceProxyFactory()
+ : new OriginalInterfaceProxyFactory();
// load mods
foreach (IModMetadata mod in mods)
@@ -1699,7 +1701,7 @@ namespace StardewModdingAPI.Framework
/// <param name="errorReasonPhrase">The user-facing reason phrase explaining why the mod couldn't be loaded (if applicable).</param>
/// <param name="errorDetails">More detailed details about the error intended for developers (if any).</param>
/// <returns>Returns whether the mod was successfully loaded.</returns>
- private bool TryLoadMod(IModMetadata mod, IModMetadata[] mods, AssemblyLoader assemblyLoader, InterfaceProxyFactory proxyFactory, JsonHelper jsonHelper, ContentCoordinator contentCore, ModDatabase modDatabase, HashSet<string> suppressUpdateChecks, [NotNullWhen(false)] out ModFailReason? failReason, out string? errorReasonPhrase, out string? errorDetails)
+ private bool TryLoadMod(IModMetadata mod, IModMetadata[] mods, AssemblyLoader assemblyLoader, IInterfaceProxyFactory proxyFactory, JsonHelper jsonHelper, ContentCoordinator contentCore, ModDatabase modDatabase, HashSet<string> suppressUpdateChecks, [NotNullWhen(false)] out ModFailReason? failReason, out string? errorReasonPhrase, out string? errorDetails)
{
errorDetails = null;
@@ -1748,7 +1750,7 @@ namespace StardewModdingAPI.Framework
if (mod.IsContentPack)
{
IMonitor monitor = this.LogManager.GetMonitor(mod.DisplayName);
- CaseInsensitivePathCache relativePathCache = this.ContentCore.GetCaseInsensitivePathCache(mod.DirectoryPath);
+ CaseInsensitivePathLookup relativePathCache = CaseInsensitivePathLookup.GetCachedFor(mod.DirectoryPath);
GameContentHelper gameContentHelper = new(this.ContentCore, mod, mod.DisplayName, monitor, this.Reflection);
IModContentHelper modContentHelper = new ModContentHelper(this.ContentCore, mod.DirectoryPath, mod, mod.DisplayName, gameContentHelper.GetUnderlyingContentManager(), relativePathCache, this.Reflection);
TranslationHelper translationHelper = new(mod, contentCore.GetLocale(), contentCore.Language);
@@ -1765,7 +1767,10 @@ namespace StardewModdingAPI.Framework
else
{
// get mod info
- string assemblyPath = Path.Combine(mod.DirectoryPath, manifest.EntryDll!);
+ string assemblyPath = Path.Combine(
+ mod.DirectoryPath,
+ CaseInsensitivePathLookup.GetCachedFor(mod.DirectoryPath).GetFilePath(manifest.EntryDll!)
+ );
// load mod
Assembly modAssembly;
@@ -1830,7 +1835,7 @@ namespace StardewModdingAPI.Framework
{
IMonitor packMonitor = this.LogManager.GetMonitor(packManifest.Name);
- CaseInsensitivePathCache relativePathCache = this.ContentCore.GetCaseInsensitivePathCache(packDirPath);
+ CaseInsensitivePathLookup relativePathCache = CaseInsensitivePathLookup.GetCachedFor(packDirPath);
GameContentHelper gameContentHelper = new(contentCore, mod, packManifest.Name, packMonitor, this.Reflection);
IModContentHelper packContentHelper = new ModContentHelper(contentCore, packDirPath, mod, packManifest.Name, gameContentHelper.GetUnderlyingContentManager(), relativePathCache, this.Reflection);
@@ -1844,7 +1849,7 @@ namespace StardewModdingAPI.Framework
IModEvents events = new ModEvents(mod, this.EventManager);
ICommandHelper commandHelper = new CommandHelper(mod, this.CommandManager);
- CaseInsensitivePathCache relativePathCache = this.ContentCore.GetCaseInsensitivePathCache(mod.DirectoryPath);
+ CaseInsensitivePathLookup relativePathCache = CaseInsensitivePathLookup.GetCachedFor(mod.DirectoryPath);
#pragma warning disable CS0612 // deprecated code
ContentHelper contentHelper = new(contentCore, mod.DirectoryPath, mod, monitor, this.Reflection);
#pragma warning restore CS0612
diff --git a/src/SMAPI/Framework/Translator.cs b/src/SMAPI/Framework/Translator.cs
index b230a727..3beee250 100644
--- a/src/SMAPI/Framework/Translator.cs
+++ b/src/SMAPI/Framework/Translator.cs
@@ -51,7 +51,8 @@ namespace StardewModdingAPI.Framework
foreach (string key in this.GetAllKeysRaw())
{
string? text = this.GetRaw(key, locale, withFallback: true);
- this.ForLocale.Add(key, new Translation(this.Locale, key, text));
+ if (text != null)
+ this.ForLocale.Add(key, new Translation(this.Locale, key, text));
}
}
diff --git a/src/SMAPI/SMAPI.config.json b/src/SMAPI/SMAPI.config.json
index 49056e83..a317e6b8 100644
--- a/src/SMAPI/SMAPI.config.json
+++ b/src/SMAPI/SMAPI.config.json
@@ -47,6 +47,12 @@ copy all the settings, or you may cause bugs due to overridden changes in future
"AggressiveMemoryOptimizations": false,
/**
+ * Whether to use the experimental Pintail API proxying library, instead of the original
+ * proxying built into SMAPI itself.
+ */
+ "UsePintail": false,
+
+ /**
* Whether to add a section to the 'mod issues' list for mods which directly use potentially
* sensitive .NET APIs like file or shell access. Note that many mods do this legitimately as
* part of their normal functionality, so these warnings are meaningless without further
diff --git a/src/SMAPI/Utilities/CaseInsensitivePathCache.cs b/src/SMAPI/Utilities/CaseInsensitivePathCache.cs
deleted file mode 100644
index 2ac1b9f9..00000000
--- a/src/SMAPI/Utilities/CaseInsensitivePathCache.cs
+++ /dev/null
@@ -1,124 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-
-namespace StardewModdingAPI.Utilities
-{
- /// <summary>Provides an API for case-insensitive relative path lookups within a root directory.</summary>
- internal class CaseInsensitivePathCache
- {
- /*********
- ** Fields
- *********/
- /// <summary>The root directory path for relative paths.</summary>
- private readonly string RootPath;
-
- /// <summary>A case-insensitive lookup of file paths within the <see cref="RootPath"/>. Each path is listed in both file path and asset name format, so it's usable in both contexts without needing to re-parse paths.</summary>
- private readonly Lazy<Dictionary<string, string>> RelativePathCache;
-
-
- /*********
- ** Public methods
- *********/
- /// <summary>Construct an instance.</summary>
- /// <param name="rootPath">The root directory path for relative paths.</param>
- public CaseInsensitivePathCache(string rootPath)
- {
- this.RootPath = rootPath;
- this.RelativePathCache = new(this.GetRelativePathCache);
- }
-
- /// <summary>Get the exact capitalization for a given relative file path.</summary>
- /// <param name="relativePath">The relative path.</param>
- /// <remarks>Returns the resolved path in file path format, else the normalized <paramref name="relativePath"/>.</remarks>
- public string GetFilePath(string relativePath)
- {
- return this.GetImpl(PathUtilities.NormalizePath(relativePath));
- }
-
- /// <summary>Get the exact capitalization for a given asset name.</summary>
- /// <param name="relativePath">The relative path.</param>
- /// <remarks>Returns the resolved path in asset name format, else the normalized <paramref name="relativePath"/>.</remarks>
- public string GetAssetName(string relativePath)
- {
- return this.GetImpl(PathUtilities.NormalizeAssetName(relativePath));
- }
-
- /// <summary>Add a relative path that was just created by a SMAPI API.</summary>
- /// <param name="relativePath">The relative path. This must already be normalized in asset name or file path format.</param>
- public void Add(string relativePath)
- {
- // skip if cache isn't created yet (no need to add files manually in that case)
- if (!this.RelativePathCache.IsValueCreated)
- return;
-
- // skip if already cached
- if (this.RelativePathCache.Value.ContainsKey(relativePath))
- return;
-
- // make sure path exists
- relativePath = PathUtilities.NormalizePath(relativePath);
- if (!File.Exists(Path.Combine(this.RootPath, relativePath)))
- throw new InvalidOperationException($"Can't add relative path '{relativePath}' to the case-insensitive cache for '{this.RootPath}' because that file doesn't exist.");
-
- // cache path
- this.CacheRawPath(this.RelativePathCache.Value, relativePath);
- }
-
-
- /*********
- ** Private methods
- *********/
- /// <summary>Get the exact capitalization for a given relative path.</summary>
- /// <param name="relativePath">The relative path. This must already be normalized into asset name or file path format (i.e. using <see cref="PathUtilities.NormalizeAssetName"/> or <see cref="PathUtilities.NormalizePath"/> respectively).</param>
- /// <remarks>Returns the resolved path in the same format if found, else returns the path as-is.</remarks>
- private string GetImpl(string relativePath)
- {
- // invalid path
- if (string.IsNullOrWhiteSpace(relativePath))
- return relativePath;
-
- // already cached
- if (this.RelativePathCache.Value.TryGetValue(relativePath, out string? resolved))
- return resolved;
-
- // file exists but isn't cached for some reason
- // cache it now so any later references to it are case-insensitive
- if (File.Exists(Path.Combine(this.RootPath, relativePath)))
- {
- this.CacheRawPath(this.RelativePathCache.Value, relativePath);
- return relativePath;
- }
-
- // no such file, keep capitalization as-is
- return relativePath;
- }
-
- /// <summary>Get a case-insensitive lookup of file paths (see <see cref="RelativePathCache"/>).</summary>
- private Dictionary<string, string> GetRelativePathCache()
- {
- Dictionary<string, string> cache = new(StringComparer.OrdinalIgnoreCase);
-
- foreach (string path in Directory.EnumerateFiles(this.RootPath, "*", SearchOption.AllDirectories))
- {
- string relativePath = path.Substring(this.RootPath.Length + 1);
-
- this.CacheRawPath(cache, relativePath);
- }
-
- return cache;
- }
-
- /// <summary>Add a raw relative path to the cache.</summary>
- /// <param name="cache">The cache to update.</param>
- /// <param name="relativePath">The relative path to cache, with its exact filesystem capitalization.</param>
- private void CacheRawPath(IDictionary<string, string> cache, string relativePath)
- {
- string filePath = PathUtilities.NormalizePath(relativePath);
- string assetName = PathUtilities.NormalizeAssetName(relativePath);
-
- cache[filePath] = filePath;
- cache[assetName] = assetName;
- }
- }
-}