diff options
31 files changed, 347 insertions, 407 deletions
diff --git a/build/common.targets b/build/common.targets index 44ee0caf..0436ed5b 100644 --- a/build/common.targets +++ b/build/common.targets @@ -1,7 +1,7 @@ <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <!--set general build properties --> - <Version>3.14.1</Version> + <Version>3.14.2</Version> <Product>SMAPI</Product> <LangVersion>latest</LangVersion> <AssemblySearchPaths>$(AssemblySearchPaths);{GAC}</AssemblySearchPaths> diff --git a/docs/release-notes.md b/docs/release-notes.md index 82cf51db..98747613 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -1,6 +1,17 @@ ← [README](README.md) # Release notes +## 3.14.2 +Released 08 May 2022 for Stardew Valley 1.5.6 or later. + +* For players: + * Enabled case-insensitive file paths by default for Android and Linux players. + _This was temporarily disabled in SMAPI 3.14.1, and will remain disabled by default on macOS and Windows since their filesystems are already case-insensitive._ + * Various performance improvements. +* For mod authors: + * Dynamic content packs created via `helper.ContentPacks.CreateTemporary` or `CreateFake` are now listed in the log file. + * Fixed assets loaded through a fake content pack not working correctly since 3.14.0. + ## 3.14.1 Released 06 May 2022 for Stardew Valley 1.5.6 or later. diff --git a/src/SMAPI.Mods.ConsoleCommands/manifest.json b/src/SMAPI.Mods.ConsoleCommands/manifest.json index edbdd081..c263456a 100644 --- a/src/SMAPI.Mods.ConsoleCommands/manifest.json +++ b/src/SMAPI.Mods.ConsoleCommands/manifest.json @@ -1,9 +1,9 @@ { "Name": "Console Commands", "Author": "SMAPI", - "Version": "3.14.1", + "Version": "3.14.2", "Description": "Adds SMAPI console commands that let you manipulate the game.", "UniqueID": "SMAPI.ConsoleCommands", "EntryDll": "ConsoleCommands.dll", - "MinimumApiVersion": "3.14.1" + "MinimumApiVersion": "3.14.2" } diff --git a/src/SMAPI.Mods.ErrorHandler/manifest.json b/src/SMAPI.Mods.ErrorHandler/manifest.json index af67453d..6e6a271f 100644 --- a/src/SMAPI.Mods.ErrorHandler/manifest.json +++ b/src/SMAPI.Mods.ErrorHandler/manifest.json @@ -1,9 +1,9 @@ { "Name": "Error Handler", "Author": "SMAPI", - "Version": "3.14.1", + "Version": "3.14.2", "Description": "Handles some common vanilla errors to log more useful info or avoid breaking the game.", "UniqueID": "SMAPI.ErrorHandler", "EntryDll": "ErrorHandler.dll", - "MinimumApiVersion": "3.14.1" + "MinimumApiVersion": "3.14.2" } diff --git a/src/SMAPI.Mods.SaveBackup/manifest.json b/src/SMAPI.Mods.SaveBackup/manifest.json index 14b68cb4..5ba91568 100644 --- a/src/SMAPI.Mods.SaveBackup/manifest.json +++ b/src/SMAPI.Mods.SaveBackup/manifest.json @@ -1,9 +1,9 @@ { "Name": "Save Backup", "Author": "SMAPI", - "Version": "3.14.1", + "Version": "3.14.2", "Description": "Automatically backs up all your saves once per day into its folder.", "UniqueID": "SMAPI.SaveBackup", "EntryDll": "SaveBackup.dll", - "MinimumApiVersion": "3.14.1" + "MinimumApiVersion": "3.14.2" } diff --git a/src/SMAPI.Tests/Core/ModResolverTests.cs b/src/SMAPI.Tests/Core/ModResolverTests.cs index 3dfc9461..70c782ab 100644 --- a/src/SMAPI.Tests/Core/ModResolverTests.cs +++ b/src/SMAPI.Tests/Core/ModResolverTests.cs @@ -133,7 +133,7 @@ namespace SMAPI.Tests.Core [Test(Description = "Assert that validation doesn't fail if there are no mods installed.")] public void ValidateManifests_NoMods_DoesNothing() { - new ModResolver().ValidateManifests(Array.Empty<ModMetadata>(), apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFilePathLookup: _ => MinimalPathLookup.Instance, validateFilesExist: false); + new ModResolver().ValidateManifests(Array.Empty<ModMetadata>(), apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFileLookup: this.GetFileLookup, validateFilesExist: false); } [Test(Description = "Assert that validation skips manifests that have already failed without calling any other properties.")] @@ -144,7 +144,7 @@ namespace SMAPI.Tests.Core mock.Setup(p => p.Status).Returns(ModMetadataStatus.Failed); // act - new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFilePathLookup: _ => MinimalPathLookup.Instance, validateFilesExist: false); + new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFileLookup: this.GetFileLookup, validateFilesExist: false); // assert mock.VerifyGet(p => p.Status, Times.Once, "The validation did not check the manifest status."); @@ -161,7 +161,7 @@ namespace SMAPI.Tests.Core }); // act - new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFilePathLookup: _ => MinimalPathLookup.Instance, validateFilesExist: false); + new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFileLookup: this.GetFileLookup, validateFilesExist: false); // assert mock.Verify(p => p.SetStatus(ModMetadataStatus.Failed, It.IsAny<ModFailReason>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once, "The validation did not fail the metadata."); @@ -175,7 +175,7 @@ namespace SMAPI.Tests.Core mock.Setup(p => p.Manifest).Returns(this.GetManifest(minimumApiVersion: "1.1")); // act - new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFilePathLookup: _ => MinimalPathLookup.Instance, validateFilesExist: false); + new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFileLookup: this.GetFileLookup, validateFilesExist: false); // assert mock.Verify(p => p.SetStatus(ModMetadataStatus.Failed, It.IsAny<ModFailReason>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once, "The validation did not fail the metadata."); @@ -190,7 +190,7 @@ namespace SMAPI.Tests.Core Directory.CreateDirectory(directoryPath); // act - new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFilePathLookup: _ => MinimalPathLookup.Instance); + new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFileLookup: this.GetFileLookup); // assert mock.Verify(p => p.SetStatus(ModMetadataStatus.Failed, It.IsAny<ModFailReason>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once, "The validation did not fail the metadata."); @@ -207,7 +207,7 @@ namespace SMAPI.Tests.Core Mock<IModMetadata> modB = this.GetMetadata(this.GetManifest(id: "Mod A", name: "Mod B", version: "1.0"), allowStatusChange: true); // act - new ModResolver().ValidateManifests(new[] { modA.Object, modB.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFilePathLookup: _ => MinimalPathLookup.Instance, validateFilesExist: false); + new ModResolver().ValidateManifests(new[] { modA.Object, modB.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFileLookup: this.GetFileLookup, validateFilesExist: false); // assert modA.Verify(p => p.SetStatus(ModMetadataStatus.Failed, ModFailReason.Duplicate, It.IsAny<string>(), It.IsAny<string>()), Times.AtLeastOnce, "The validation did not fail the first mod with a unique ID."); @@ -233,7 +233,7 @@ namespace SMAPI.Tests.Core mock.Setup(p => p.DirectoryPath).Returns(modFolder); // act - new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFilePathLookup: _ => MinimalPathLookup.Instance); + new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFileLookup: this.GetFileLookup); // assert // if Moq doesn't throw a method-not-setup exception, the validation didn't override the status. @@ -483,6 +483,13 @@ namespace SMAPI.Tests.Core return Path.Combine(Path.GetTempPath(), "smapi-unit-tests", Guid.NewGuid().ToString("N")); } + /// <summary>Get a file lookup for a given directory.</summary> + /// <param name="rootDirectory">The full path to the directory.</param> + private IFileLookup GetFileLookup(string rootDirectory) + { + return MinimalFileLookup.GetCachedFor(rootDirectory); + } + /// <summary>Get a randomized basic manifest.</summary> /// <param name="id">The <see cref="IManifest.UniqueID"/> value, or <c>null</c> for a generated value.</param> /// <param name="name">The <see cref="IManifest.Name"/> value, or <c>null</c> for a generated value.</param> diff --git a/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs b/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs index aa4c3338..a85ef109 100644 --- a/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs +++ b/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs @@ -114,10 +114,11 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning /// <summary>Extract information from a mod folder.</summary> /// <param name="root">The root folder containing mods.</param> /// <param name="searchFolder">The folder to search for a mod.</param> - public ModFolder ReadFolder(DirectoryInfo root, DirectoryInfo searchFolder) + /// <param name="useCaseInsensitiveFilePaths">Whether to match file paths case-insensitively, even on Linux.</param> + public ModFolder ReadFolder(DirectoryInfo root, DirectoryInfo searchFolder, bool useCaseInsensitiveFilePaths) { // find manifest.json - FileInfo? manifestFile = this.FindManifest(searchFolder); + FileInfo? manifestFile = this.FindManifest(searchFolder, useCaseInsensitiveFilePaths); // set appropriate invalid-mod error if (manifestFile == null) @@ -225,7 +226,7 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning // treat as mod folder else - yield return this.ReadFolder(root, folder); + yield return this.ReadFolder(root, folder, useCaseInsensitiveFilePaths); } /// <summary>Consolidate adjacent folders into one mod folder, if possible.</summary> @@ -250,7 +251,8 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning /// <summary>Find the manifest for a mod folder.</summary> /// <param name="folder">The folder to search.</param> - private FileInfo? FindManifest(DirectoryInfo folder) + /// <param name="useCaseInsensitiveFilePaths">Whether to match file paths case-insensitively, even on Linux.</param> + private FileInfo? FindManifest(DirectoryInfo folder, bool useCaseInsensitiveFilePaths) { // check for conventional manifest in current folder const string defaultName = "manifest.json"; @@ -259,14 +261,14 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning return file; // check for manifest with incorrect capitalization + if (useCaseInsensitiveFilePaths) { - CaseInsensitivePathLookup pathLookup = new(folder.FullName, SearchOption.TopDirectoryOnly); // don't use GetCachedFor, since we only need it temporarily - string realName = pathLookup.GetFilePath(defaultName); - if (realName != defaultName) - file = new(Path.Combine(folder.FullName, realName)); + CaseInsensitiveFileLookup fileLookup = new(folder.FullName, SearchOption.TopDirectoryOnly); // don't use GetCachedFor, since we only need it temporarily + file = fileLookup.GetFile(defaultName); + return file.Exists + ? file + : null; } - if (file.Exists) - return file; // not found return null; diff --git a/src/SMAPI.Toolkit/Utilities/PathLookups/CaseInsensitivePathLookup.cs b/src/SMAPI.Toolkit/Utilities/PathLookups/CaseInsensitiveFileLookup.cs index 9cc00737..496d54c3 100644 --- a/src/SMAPI.Toolkit/Utilities/PathLookups/CaseInsensitivePathLookup.cs +++ b/src/SMAPI.Toolkit/Utilities/PathLookups/CaseInsensitiveFileLookup.cs @@ -4,8 +4,8 @@ using System.IO; namespace StardewModdingAPI.Toolkit.Utilities.PathLookups { - /// <summary>An API for case-insensitive relative path lookups within a root directory.</summary> - internal class CaseInsensitivePathLookup : IFilePathLookup + /// <summary>An API for case-insensitive file lookups within a root directory.</summary> + internal class CaseInsensitiveFileLookup : IFileLookup { /********* ** Fields @@ -16,8 +16,8 @@ namespace StardewModdingAPI.Toolkit.Utilities.PathLookups /// <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; - /// <summary>The case-insensitive path caches by root path.</summary> - private static readonly Dictionary<string, CaseInsensitivePathLookup> CachedRoots = new(StringComparer.OrdinalIgnoreCase); + /// <summary>The case-insensitive file lookups by root path.</summary> + private static readonly Dictionary<string, CaseInsensitiveFileLookup> CachedRoots = new(StringComparer.OrdinalIgnoreCase); /********* @@ -26,22 +26,28 @@ namespace StardewModdingAPI.Toolkit.Utilities.PathLookups /// <summary>Construct an instance.</summary> /// <param name="rootPath">The root directory path for relative paths.</param> /// <param name="searchOption">Which directories to scan from the root.</param> - public CaseInsensitivePathLookup(string rootPath, SearchOption searchOption = SearchOption.AllDirectories) + public CaseInsensitiveFileLookup(string rootPath, SearchOption searchOption = SearchOption.AllDirectories) { - this.RootPath = rootPath; + this.RootPath = PathUtilities.NormalizePath(rootPath); this.RelativePathCache = new(() => this.GetRelativePathCache(searchOption)); } /// <inheritdoc /> - public string GetFilePath(string relativePath) + public FileInfo GetFile(string relativePath) { - return this.GetImpl(PathUtilities.NormalizePath(relativePath)); - } + // invalid path + if (string.IsNullOrWhiteSpace(relativePath)) + throw new InvalidOperationException("Can't get a file from an empty relative path."); - /// <inheritdoc /> - public string GetAssetName(string relativePath) - { - return this.GetImpl(PathUtilities.NormalizeAssetName(relativePath)); + // already cached + if (this.RelativePathCache.Value.TryGetValue(relativePath, out string? resolved)) + return new(Path.Combine(this.RootPath, resolved)); + + // keep capitalization as-is + FileInfo file = new(Path.Combine(this.RootPath, relativePath)); + if (file.Exists) + this.RelativePathCache.Value[relativePath] = relativePath; + return file; } /// <inheritdoc /> @@ -61,17 +67,17 @@ namespace StardewModdingAPI.Toolkit.Utilities.PathLookups 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); + this.RelativePathCache.Value[relativePath] = relativePath; } /// <summary>Get a cached dictionary of relative paths within a root path, for case-insensitive file lookups.</summary> /// <param name="rootPath">The root path to scan.</param> - public static CaseInsensitivePathLookup GetCachedFor(string rootPath) + public static CaseInsensitiveFileLookup GetCachedFor(string rootPath) { rootPath = PathUtilities.NormalizePath(rootPath); - if (!CaseInsensitivePathLookup.CachedRoots.TryGetValue(rootPath, out CaseInsensitivePathLookup? cache)) - CaseInsensitivePathLookup.CachedRoots[rootPath] = cache = new CaseInsensitivePathLookup(rootPath); + if (!CaseInsensitiveFileLookup.CachedRoots.TryGetValue(rootPath, out CaseInsensitiveFileLookup? cache)) + CaseInsensitiveFileLookup.CachedRoots[rootPath] = cache = new CaseInsensitiveFileLookup(rootPath); return cache; } @@ -80,29 +86,6 @@ namespace StardewModdingAPI.Toolkit.Utilities.PathLookups /********* ** 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; - - // keep capitalization as-is - if (File.Exists(Path.Combine(this.RootPath, relativePath))) - { - // file exists but isn't cached for some reason - // cache it now so any later references to it are case-insensitive - this.CacheRawPath(this.RelativePathCache.Value, relativePath); - } - return relativePath; - } - /// <summary>Get a case-insensitive lookup of file paths (see <see cref="RelativePathCache"/>).</summary> /// <param name="searchOption">Which directories to scan from the root.</param> private Dictionary<string, string> GetRelativePathCache(SearchOption searchOption) @@ -112,23 +95,10 @@ namespace StardewModdingAPI.Toolkit.Utilities.PathLookups foreach (string path in Directory.EnumerateFiles(this.RootPath, "*", searchOption)) { string relativePath = path.Substring(this.RootPath.Length + 1); - - this.CacheRawPath(cache, relativePath); + cache[relativePath] = 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; - } } } diff --git a/src/SMAPI.Toolkit/Utilities/PathLookups/IFileLookup.cs b/src/SMAPI.Toolkit/Utilities/PathLookups/IFileLookup.cs new file mode 100644 index 00000000..d43b5141 --- /dev/null +++ b/src/SMAPI.Toolkit/Utilities/PathLookups/IFileLookup.cs @@ -0,0 +1,16 @@ +using System.IO; + +namespace StardewModdingAPI.Toolkit.Utilities.PathLookups +{ + /// <summary>An API for file lookups within a root directory.</summary> + internal interface IFileLookup + { + /// <summary>Get the file for a given relative file path, if it exists.</summary> + /// <param name="relativePath">The relative path.</param> + FileInfo GetFile(string relativePath); + + /// <summary>Add a relative path that was just created by a SMAPI API.</summary> + /// <param name="relativePath">The relative path.</param> + void Add(string relativePath); + } +} diff --git a/src/SMAPI.Toolkit/Utilities/PathLookups/IFilePathLookup.cs b/src/SMAPI.Toolkit/Utilities/PathLookups/IFilePathLookup.cs deleted file mode 100644 index 678e1383..00000000 --- a/src/SMAPI.Toolkit/Utilities/PathLookups/IFilePathLookup.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace StardewModdingAPI.Toolkit.Utilities.PathLookups -{ - /// <summary>An API for relative path lookups within a root directory.</summary> - internal interface IFilePathLookup - { - /// <summary>Get the actual path 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> - string GetFilePath(string relativePath); - - /// <summary>Get the actual path 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> - string GetAssetName(string 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> - void Add(string relativePath); - } -} diff --git a/src/SMAPI.Toolkit/Utilities/PathLookups/MinimalFileLookup.cs b/src/SMAPI.Toolkit/Utilities/PathLookups/MinimalFileLookup.cs new file mode 100644 index 00000000..414b569b --- /dev/null +++ b/src/SMAPI.Toolkit/Utilities/PathLookups/MinimalFileLookup.cs @@ -0,0 +1,52 @@ +using System.Collections.Generic; +using System.IO; + +namespace StardewModdingAPI.Toolkit.Utilities.PathLookups +{ + /// <summary>An API for file lookups within a root directory with minimal preprocessing.</summary> + internal class MinimalFileLookup : IFileLookup + { + /********* + ** Accessors + *********/ + /// <summary>The file lookups by root path.</summary> + private static readonly Dictionary<string, MinimalFileLookup> CachedRoots = new(); + + /// <summary>The root directory path for relative paths.</summary> + private readonly string RootPath; + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="rootPath">The root directory path for relative paths.</param> + public MinimalFileLookup(string rootPath) + { + this.RootPath = rootPath; + } + + /// <inheritdoc /> + public FileInfo GetFile(string relativePath) + { + return new( + Path.Combine(this.RootPath, PathUtilities.NormalizePath(relativePath)) + ); + } + + /// <inheritdoc /> + public void Add(string relativePath) { } + + /// <summary>Get a cached dictionary of relative paths within a root path, for case-insensitive file lookups.</summary> + /// <param name="rootPath">The root path to scan.</param> + public static MinimalFileLookup GetCachedFor(string rootPath) + { + rootPath = PathUtilities.NormalizePath(rootPath); + + if (!MinimalFileLookup.CachedRoots.TryGetValue(rootPath, out MinimalFileLookup? lookup)) + MinimalFileLookup.CachedRoots[rootPath] = lookup = new MinimalFileLookup(rootPath); + + return lookup; + } + } +} diff --git a/src/SMAPI.Toolkit/Utilities/PathLookups/MinimalPathLookup.cs b/src/SMAPI.Toolkit/Utilities/PathLookups/MinimalPathLookup.cs deleted file mode 100644 index 2cf14704..00000000 --- a/src/SMAPI.Toolkit/Utilities/PathLookups/MinimalPathLookup.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace StardewModdingAPI.Toolkit.Utilities.PathLookups -{ - /// <summary>An API for relative path lookups within a root directory with minimal preprocessing.</summary> - internal class MinimalPathLookup : IFilePathLookup - { - /********* - ** Accessors - *********/ - /// <summary>A singleton instance for reuse.</summary> - public static readonly MinimalPathLookup Instance = new(); - - - /********* - ** Public methods - *********/ - /// <inheritdoc /> - public string GetFilePath(string relativePath) - { - return PathUtilities.NormalizePath(relativePath); - } - - /// <inheritdoc /> - public string GetAssetName(string relativePath) - { - return PathUtilities.NormalizeAssetName(relativePath); - } - - /// <inheritdoc /> - public void Add(string relativePath) { } - } -} diff --git a/src/SMAPI/Constants.cs b/src/SMAPI/Constants.cs index b1a9cc82..a289ce4b 100644 --- a/src/SMAPI/Constants.cs +++ b/src/SMAPI/Constants.cs @@ -50,7 +50,7 @@ namespace StardewModdingAPI internal static int? LogScreenId { get; set; } /// <summary>SMAPI's current raw semantic version.</summary> - internal static string RawApiVersion = "3.14.1"; + internal static string RawApiVersion = "3.14.2"; } /// <summary>Contains SMAPI's constants and assumptions.</summary> diff --git a/src/SMAPI/Events/AssetRequestedEventArgs.cs b/src/SMAPI/Events/AssetRequestedEventArgs.cs index 3bcf83b9..d0aef1db 100644 --- a/src/SMAPI/Events/AssetRequestedEventArgs.cs +++ b/src/SMAPI/Events/AssetRequestedEventArgs.cs @@ -19,19 +19,22 @@ namespace StardewModdingAPI.Events /// <summary>Get the mod metadata for a content pack, if it's a valid content pack for the mod.</summary> private readonly Func<IModMetadata, string?, string, IModMetadata?> GetOnBehalfOf; + /// <summary>The asset info being requested.</summary> + private readonly IAssetInfo AssetInfo; + /********* ** Accessors *********/ /// <summary>The name of the asset being requested.</summary> - public IAssetName Name { get; } + public IAssetName Name => this.AssetInfo.Name; /// <summary>The <see cref="Name"/> with any locale codes stripped.</summary> /// <remarks>For example, if <see cref="Name"/> contains a locale like <c>Data/Bundles.fr-FR</c>, this will be the name without locale like <c>Data/Bundles</c>. If the name has no locale, this field is equivalent.</remarks> - public IAssetName NameWithoutLocale { get; } + public IAssetName NameWithoutLocale => this.AssetInfo.NameWithoutLocale; /// <summary>The requested data type.</summary> - public Type DataType { get; } + public Type DataType => this.AssetInfo.DataType; /// <summary>The load operations requested by the event handler.</summary> internal IList<AssetLoadOperation> LoadOperations { get; } = new List<AssetLoadOperation>(); @@ -45,16 +48,12 @@ namespace StardewModdingAPI.Events *********/ /// <summary>Construct an instance.</summary> /// <param name="mod">The mod handling the event.</param> - /// <param name="name">The name of the asset being requested.</param> - /// <param name="dataType">The requested data type.</param> - /// <param name="nameWithoutLocale">The <paramref name="name"/> with any locale codes stripped.</param> + /// <param name="assetInfo">The asset info being requested.</param> /// <param name="getOnBehalfOf">Get the mod metadata for a content pack, if it's a valid content pack for the mod.</param> - internal AssetRequestedEventArgs(IModMetadata mod, IAssetName name, IAssetName nameWithoutLocale, Type dataType, Func<IModMetadata, string?, string, IModMetadata?> getOnBehalfOf) + internal AssetRequestedEventArgs(IModMetadata mod, IAssetInfo assetInfo, Func<IModMetadata, string?, string, IModMetadata?> getOnBehalfOf) { this.Mod = mod; - this.Name = name; - this.NameWithoutLocale = nameWithoutLocale; - this.DataType = dataType; + this.AssetInfo = assetInfo; this.GetOnBehalfOf = getOnBehalfOf; } @@ -73,10 +72,10 @@ namespace StardewModdingAPI.Events { this.LoadOperations.Add( new AssetLoadOperation( - mod: this.Mod, - priority: priority, - onBehalfOf: this.GetOnBehalfOf(this.Mod, onBehalfOf, "load assets"), - getData: _ => load() + Mod: this.Mod, + OnBehalfOf: this.GetOnBehalfOf(this.Mod, onBehalfOf, "load assets"), + Priority: priority, + GetData: _ => load() ) ); } @@ -97,10 +96,10 @@ namespace StardewModdingAPI.Events { this.LoadOperations.Add( new AssetLoadOperation( - mod: this.Mod, - priority: priority, - onBehalfOf: null, - _ => this.Mod.Mod!.Helper.ModContent.Load<TAsset>(relativePath) + Mod: this.Mod, + OnBehalfOf: null, + Priority: priority, + GetData: _ => this.Mod.Mod!.Helper.ModContent.Load<TAsset>(relativePath) ) ); } @@ -120,10 +119,10 @@ namespace StardewModdingAPI.Events { this.EditOperations.Add( new AssetEditOperation( - mod: this.Mod, - priority: priority, - onBehalfOf: this.GetOnBehalfOf(this.Mod, onBehalfOf, "edit assets"), - apply + Mod: this.Mod, + Priority: priority, + OnBehalfOf: this.GetOnBehalfOf(this.Mod, onBehalfOf, "edit assets"), + ApplyEdit: apply ) ); } diff --git a/src/SMAPI/Framework/Content/AssetEditOperation.cs b/src/SMAPI/Framework/Content/AssetEditOperation.cs index 464948b0..11b8811b 100644 --- a/src/SMAPI/Framework/Content/AssetEditOperation.cs +++ b/src/SMAPI/Framework/Content/AssetEditOperation.cs @@ -4,38 +4,9 @@ using StardewModdingAPI.Events; namespace StardewModdingAPI.Framework.Content { /// <summary>An edit to apply to an asset when it's requested from the content pipeline.</summary> - internal class AssetEditOperation - { - /********* - ** Accessors - *********/ - /// <summary>The mod applying the edit.</summary> - public IModMetadata Mod { get; } - - /// <summary>If there are multiple edits that apply to the same asset, the priority with which this one should be applied.</summary> - public AssetEditPriority Priority { get; } - - /// <summary>The content pack on whose behalf the edit is being applied, if any.</summary> - public IModMetadata? OnBehalfOf { get; } - - /// <summary>Apply the edit to an asset.</summary> - public Action<IAssetData> ApplyEdit { get; } - - - /********* - ** Public methods - *********/ - /// <summary>Construct an instance.</summary> - /// <param name="mod">The mod applying the edit.</param> - /// <param name="priority">If there are multiple edits that apply to the same asset, the priority with which this one should be applied.</param> - /// <param name="onBehalfOf">The content pack on whose behalf the edit is being applied, if any.</param> - /// <param name="applyEdit">Apply the edit to an asset.</param> - public AssetEditOperation(IModMetadata mod, AssetEditPriority priority, IModMetadata? onBehalfOf, Action<IAssetData> applyEdit) - { - this.Mod = mod; - this.Priority = priority; - this.OnBehalfOf = onBehalfOf; - this.ApplyEdit = applyEdit; - } - } + /// <param name="Mod">The mod applying the edit.</param> + /// <param name="Priority">If there are multiple edits that apply to the same asset, the priority with which this one should be applied.</param> + /// <param name="OnBehalfOf">The content pack on whose behalf the edit is being applied, if any.</param> + /// <param name="ApplyEdit">Apply the edit to an asset.</param> + internal record AssetEditOperation(IModMetadata Mod, AssetEditPriority Priority, IModMetadata? OnBehalfOf, Action<IAssetData> ApplyEdit); } diff --git a/src/SMAPI/Framework/Content/AssetInfo.cs b/src/SMAPI/Framework/Content/AssetInfo.cs index 363fffb3..a4f0a408 100644 --- a/src/SMAPI/Framework/Content/AssetInfo.cs +++ b/src/SMAPI/Framework/Content/AssetInfo.cs @@ -13,6 +13,9 @@ namespace StardewModdingAPI.Framework.Content /// <summary>Normalizes an asset key to match the cache key.</summary> protected readonly Func<string, string> GetNormalizedPath; + /// <summary>The backing field for <see cref="NameWithoutLocale"/>.</summary> + private IAssetName? NameWithoutLocaleImpl; + /********* ** Accessors @@ -24,7 +27,7 @@ namespace StardewModdingAPI.Framework.Content public IAssetName Name { get; } /// <inheritdoc /> - public IAssetName NameWithoutLocale { get; } + public IAssetName NameWithoutLocale => this.NameWithoutLocaleImpl ??= this.Name.GetBaseAssetName(); /// <inheritdoc /> [Obsolete($"Use {nameof(AssetInfo.Name)} or {nameof(AssetInfo.NameWithoutLocale)} instead. This property will be removed in SMAPI 4.0.0.")] @@ -64,7 +67,6 @@ namespace StardewModdingAPI.Framework.Content { this.Locale = locale; this.Name = assetName; - this.NameWithoutLocale = assetName.GetBaseAssetName(); this.DataType = type; this.GetNormalizedPath = getNormalizedPath; } diff --git a/src/SMAPI/Framework/Content/AssetLoadOperation.cs b/src/SMAPI/Framework/Content/AssetLoadOperation.cs index b6cdec27..7af07dfd 100644 --- a/src/SMAPI/Framework/Content/AssetLoadOperation.cs +++ b/src/SMAPI/Framework/Content/AssetLoadOperation.cs @@ -4,38 +4,9 @@ using StardewModdingAPI.Events; namespace StardewModdingAPI.Framework.Content { /// <summary>An operation which provides the initial instance of an asset when it's requested from the content pipeline.</summary> - internal class AssetLoadOperation - { - /********* - ** Accessors - *********/ - /// <summary>The mod loading the asset.</summary> - public IModMetadata Mod { get; } - - /// <summary>The content pack on whose behalf the asset is being loaded, if any.</summary> - public IModMetadata? OnBehalfOf { get; } - - /// <summary>If there are multiple loads that apply to the same asset, the priority with which this one should be applied.</summary> - public AssetLoadPriority Priority { get; } - - /// <summary>Load the initial value for an asset.</summary> - public Func<IAssetInfo, object> GetData { get; } - - - /********* - ** Public methods - *********/ - /// <summary>Construct an instance.</summary> - /// <param name="mod">The mod applying the edit.</param> - /// <param name="priority">If there are multiple loads that apply to the same asset, the priority with which this one should be applied.</param> - /// <param name="onBehalfOf">The content pack on whose behalf the asset is being loaded, if any.</param> - /// <param name="getData">Load the initial value for an asset.</param> - public AssetLoadOperation(IModMetadata mod, AssetLoadPriority priority, IModMetadata? onBehalfOf, Func<IAssetInfo, object> getData) - { - this.Mod = mod; - this.Priority = priority; - this.OnBehalfOf = onBehalfOf; - this.GetData = getData; - } - } + /// <param name="Mod">The mod applying the edit.</param> + /// <param name="Priority">If there are multiple loads that apply to the same asset, the priority with which this one should be applied.</param> + /// <param name="OnBehalfOf">The content pack on whose behalf the asset is being loaded, if any.</param> + /// <param name="GetData">Load the initial value for an asset.</param> + internal record AssetLoadOperation(IModMetadata Mod, IModMetadata? OnBehalfOf, AssetLoadPriority Priority, Func<IAssetInfo, object> GetData); } diff --git a/src/SMAPI/Framework/Content/AssetOperationGroup.cs b/src/SMAPI/Framework/Content/AssetOperationGroup.cs index a2fcb722..1566a8f0 100644 --- a/src/SMAPI/Framework/Content/AssetOperationGroup.cs +++ b/src/SMAPI/Framework/Content/AssetOperationGroup.cs @@ -1,33 +1,8 @@ namespace StardewModdingAPI.Framework.Content { /// <summary>A set of operations to apply to an asset for a given <see cref="IAssetEditor"/> or <see cref="IAssetLoader"/> implementation.</summary> - internal class AssetOperationGroup - { - /********* - ** Accessors - *********/ - /// <summary>The mod applying the changes.</summary> - public IModMetadata Mod { get; } - - /// <summary>The load operations to apply.</summary> - public AssetLoadOperation[] LoadOperations { get; } - - /// <summary>The edit operations to apply.</summary> - public AssetEditOperation[] EditOperations { get; } - - - /********* - ** Public methods - *********/ - /// <summary>Construct an instance.</summary> - /// <param name="mod">The mod applying the changes.</param> - /// <param name="loadOperations">The load operations to apply.</param> - /// <param name="editOperations">The edit operations to apply.</param> - public AssetOperationGroup(IModMetadata mod, AssetLoadOperation[] loadOperations, AssetEditOperation[] editOperations) - { - this.Mod = mod; - this.LoadOperations = loadOperations; - this.EditOperations = editOperations; - } - } + /// <param name="Mod">The mod applying the changes.</param> + /// <param name="LoadOperations">The load operations to apply.</param> + /// <param name="EditOperations">The edit operations to apply.</param> + internal record AssetOperationGroup(IModMetadata Mod, AssetLoadOperation[] LoadOperations, AssetEditOperation[] EditOperations); } diff --git a/src/SMAPI/Framework/ContentCoordinator.cs b/src/SMAPI/Framework/ContentCoordinator.cs index 4f52d57e..6702f5e6 100644 --- a/src/SMAPI/Framework/ContentCoordinator.cs +++ b/src/SMAPI/Framework/ContentCoordinator.cs @@ -32,8 +32,8 @@ namespace StardewModdingAPI.Framework /// <summary>An asset key prefix for assets from SMAPI mod folders.</summary> private readonly string ManagedPrefix = "SMAPI"; - /// <summary>Get a file path lookup for the given directory.</summary> - private readonly Func<string, IFilePathLookup> GetFilePathLookup; + /// <summary>Get a file lookup for the given directory.</summary> + private readonly Func<string, IFileLookup> GetFileLookup; /// <summary>Encapsulates monitoring and logging.</summary> private readonly IMonitor Monitor; @@ -79,14 +79,14 @@ namespace StardewModdingAPI.Framework private Lazy<Dictionary<string, LocalizedContentManager.LanguageCode>> LocaleCodes; /// <summary>The cached asset load/edit operations to apply, indexed by asset name.</summary> - private readonly TickCacheDictionary<IAssetName, AssetOperationGroup[]> AssetOperationsByKey = new(); + private readonly TickCacheDictionary<IAssetName, IList<AssetOperationGroup>> AssetOperationsByKey = new(); /// <summary>A cache of asset operation groups created for legacy <see cref="IAssetLoader"/> implementations.</summary> - [Obsolete] + [Obsolete("This only exists to support legacy code and will be removed in SMAPI 4.0.0.")] private readonly Dictionary<IAssetLoader, Dictionary<Type, AssetOperationGroup>> LegacyLoaderCache = new(ReferenceEqualityComparer.Instance); /// <summary>A cache of asset operation groups created for legacy <see cref="IAssetEditor"/> implementations.</summary> - [Obsolete] + [Obsolete("This only exists to support legacy code and will be removed in SMAPI 4.0.0.")] private readonly Dictionary<IAssetEditor, Dictionary<Type, AssetOperationGroup>> LegacyEditorCache = new(ReferenceEqualityComparer.Instance); @@ -100,11 +100,11 @@ namespace StardewModdingAPI.Framework public LocalizedContentManager.LanguageCode Language => this.MainContentManager.Language; /// <summary>Interceptors which provide the initial versions of matching assets.</summary> - [Obsolete] + [Obsolete("This only exists to support legacy code and will be removed in SMAPI 4.0.0.")] public IList<ModLinked<IAssetLoader>> Loaders { get; } = new List<ModLinked<IAssetLoader>>(); /// <summary>Interceptors which edit matching assets after they're loaded.</summary> - [Obsolete] + [Obsolete("This only exists to support legacy code and will be removed in SMAPI 4.0.0.")] public IList<ModLinked<IAssetEditor>> Editors { get; } = new List<ModLinked<IAssetEditor>>(); /// <summary>The absolute path to the <see cref="ContentManager.RootDirectory"/>.</summary> @@ -123,12 +123,12 @@ namespace StardewModdingAPI.Framework /// <param name="jsonHelper">Encapsulates SMAPI's JSON file parsing.</param> /// <param name="onLoadingFirstAsset">A callback to invoke the first time *any* game content manager loads an asset.</param> /// <param name="onAssetLoaded">A callback to invoke when an asset is fully loaded.</param> - /// <param name="getFilePathLookup">Get a file path lookup for the given directory.</param> + /// <param name="getFileLookup">Get a file lookup for the given directory.</param> /// <param name="onAssetsInvalidated">A callback to invoke when any asset names have been invalidated from the cache.</param> /// <param name="requestAssetOperations">Get the load/edit operations to apply to an asset by querying registered <see cref="IContentEvents.AssetRequested"/> event handlers.</param> - public ContentCoordinator(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action onLoadingFirstAsset, Action<BaseContentManager, IAssetName> onAssetLoaded, Func<string, IFilePathLookup> getFilePathLookup, Action<IList<IAssetName>> onAssetsInvalidated, Func<IAssetInfo, IList<AssetOperationGroup>> requestAssetOperations) + public ContentCoordinator(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action onLoadingFirstAsset, Action<BaseContentManager, IAssetName> onAssetLoaded, Func<string, IFileLookup> getFileLookup, Action<IList<IAssetName>> onAssetsInvalidated, Func<IAssetInfo, IList<AssetOperationGroup>> requestAssetOperations) { - this.GetFilePathLookup = getFilePathLookup; + this.GetFileLookup = getFileLookup; this.Monitor = monitor ?? throw new ArgumentNullException(nameof(monitor)); this.Reflection = reflection; this.JsonHelper = jsonHelper; @@ -200,7 +200,7 @@ namespace StardewModdingAPI.Framework reflection: this.Reflection, jsonHelper: this.JsonHelper, onDisposing: this.OnDisposing, - relativePathLookup: this.GetFilePathLookup(rootDirectory) + fileLookup: this.GetFileLookup(rootDirectory) ); this.ContentManagers.Add(manager); return manager; @@ -449,12 +449,16 @@ namespace StardewModdingAPI.Framework /// <summary>Get the asset load and edit operations to apply to a given asset if it's (re)loaded now.</summary> /// <typeparam name="T">The asset type.</typeparam> /// <param name="info">The asset info to load or edit.</param> - public IEnumerable<AssetOperationGroup> GetAssetOperations<T>(IAssetInfo info) + public IList<AssetOperationGroup> GetAssetOperations<T>(IAssetInfo info) where T : notnull { return this.AssetOperationsByKey.GetOrSet( info.Name, - () => this.GetAssetOperationsWithoutCache<T>(info).ToArray() +#pragma warning disable CS0612, CS0618 // deprecated code + () => this.Editors.Count > 0 || this.Loaders.Count > 0 + ? this.GetAssetOperationsIncludingLegacyWithoutCache<T>(info).ToArray() +#pragma warning restore CS0612, CS0618 + : this.RequestAssetOperations(info) ); } @@ -580,7 +584,8 @@ namespace StardewModdingAPI.Framework /// <summary>Get the asset load and edit operations to apply to a given asset if it's (re)loaded now, ignoring the <see cref="AssetOperationsByKey"/> cache.</summary> /// <typeparam name="T">The asset type.</typeparam> /// <param name="info">The asset info to load or edit.</param> - private IEnumerable<AssetOperationGroup> GetAssetOperationsWithoutCache<T>(IAssetInfo info) + [Obsolete("This only exists to support legacy code and will be removed in SMAPI 4.0.0.")] + private IEnumerable<AssetOperationGroup> GetAssetOperationsIncludingLegacyWithoutCache<T>(IAssetInfo info) where T : notnull { IAssetInfo legacyInfo = this.GetLegacyAssetInfo(info); @@ -590,7 +595,6 @@ namespace StardewModdingAPI.Framework yield return group; // legacy load operations -#pragma warning disable CS0612, CS0618 // deprecated code foreach (ModLinked<IAssetLoader> loader in this.Loaders) { // check if loader applies @@ -611,19 +615,19 @@ namespace StardewModdingAPI.Framework editor: loader.Data, dataType: info.DataType, createGroup: () => new AssetOperationGroup( - mod: loader.Mod, - loadOperations: new[] + Mod: loader.Mod, + LoadOperations: new[] { new AssetLoadOperation( - mod: loader.Mod, - priority: AssetLoadPriority.Exclusive, - onBehalfOf: null, - getData: assetInfo => loader.Data.Load<T>( + Mod: loader.Mod, + OnBehalfOf: null, + Priority: AssetLoadPriority.Exclusive, + GetData: assetInfo => loader.Data.Load<T>( this.GetLegacyAssetInfo(assetInfo) ) ) }, - editOperations: Array.Empty<AssetEditOperation>() + EditOperations: Array.Empty<AssetEditOperation>() ) ); } @@ -670,15 +674,15 @@ namespace StardewModdingAPI.Framework editor: editor.Data, dataType: info.DataType, createGroup: () => new AssetOperationGroup( - mod: editor.Mod, - loadOperations: Array.Empty<AssetLoadOperation>(), - editOperations: new[] + Mod: editor.Mod, + LoadOperations: Array.Empty<AssetLoadOperation>(), + EditOperations: new[] { new AssetEditOperation( - mod: editor.Mod, - priority: priority, - onBehalfOf: null, - applyEdit: assetData => editor.Data.Edit<T>( + Mod: editor.Mod, + OnBehalfOf: null, + Priority: priority, + ApplyEdit: assetData => editor.Data.Edit<T>( this.GetLegacyAssetData(assetData) ) ) @@ -686,7 +690,6 @@ namespace StardewModdingAPI.Framework ) ); } -#pragma warning restore CS0612, CS0618 } /// <summary>Get a cached asset operation group for a legacy <see cref="IAssetLoader"/> or <see cref="IAssetEditor"/> instance, creating it if needed.</summary> diff --git a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs index 65dffd8b..7cac8f36 100644 --- a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; @@ -33,11 +34,11 @@ namespace StardewModdingAPI.Framework.ContentManagers /// <summary>The game content manager used for map tilesheets not provided by the mod.</summary> private readonly IContentManager GameContentManager; - /// <summary>A lookup for relative paths within the <see cref="ContentManager.RootDirectory"/>.</summary> - private readonly IFilePathLookup RelativePathLookup; + /// <summary>A lookup for files within the <see cref="ContentManager.RootDirectory"/>.</summary> + private readonly IFileLookup FileLookup; /// <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" }; + private static readonly HashSet<string> LocalTilesheetExtensions = new(StringComparer.OrdinalIgnoreCase) { ".png", ".xnb" }; /********* @@ -55,12 +56,12 @@ namespace StardewModdingAPI.Framework.ContentManagers /// <param name="reflection">Simplifies access to private code.</param> /// <param name="jsonHelper">Encapsulates SMAPI's JSON file parsing.</param> /// <param name="onDisposing">A callback to invoke when the content manager is being disposed.</param> - /// <param name="relativePathLookup">A lookup for 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, IFilePathLookup relativePathLookup) + /// <param name="fileLookup">A lookup for files 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, IFileLookup fileLookup) : base(name, serviceProvider, rootDirectory, currentCulture, coordinator, monitor, reflection, onDisposing, isNamespaced: true) { this.GameContentManager = gameContentManager; - this.RelativePathLookup = relativePathLookup; + this.FileLookup = fileLookup; this.JsonHelper = jsonHelper; this.ModName = modName; @@ -73,7 +74,7 @@ namespace StardewModdingAPI.Framework.ContentManagers if (base.DoesAssetExist<T>(assetName)) return true; - FileInfo file = this.GetModFile(assetName.Name); + FileInfo file = this.GetModFile<T>(assetName.Name); return file.Exists; } @@ -103,7 +104,7 @@ namespace StardewModdingAPI.Framework.ContentManagers try { // get file - FileInfo file = this.GetModFile(assetName.Name); + FileInfo file = this.GetModFile<T>(assetName.Name); if (!file.Exists) throw this.GetLoadError(assetName, "the specified path doesn't exist."); @@ -139,9 +140,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// <exception cref="ArgumentException">The <paramref name="key"/> is empty or contains invalid characters.</exception> public IAssetName GetInternalAssetKey(string key) { - FileInfo file = this.GetModFile(key); - string relativePath = Path.GetRelativePath(this.RootDirectory, file.FullName); - string internalKey = Path.Combine(this.Name, relativePath); + string internalKey = Path.Combine(this.Name, PathUtilities.NormalizeAssetName(key)); return this.Coordinator.ParseAssetName(internalKey, allowLocales: false); } @@ -253,19 +252,17 @@ namespace StardewModdingAPI.Framework.ContentManagers } /// <summary>Get a file from the mod folder.</summary> + /// <typeparam name="T">The expected asset type.</typeparam> /// <param name="path">The asset path relative to the content folder.</param> - private FileInfo GetModFile(string path) + private FileInfo GetModFile<T>(string path) { - // map to case-insensitive path if needed - path = this.RelativePathLookup.GetFilePath(path); + // get exact file + FileInfo file = this.FileLookup.GetFile(path); - // try exact match - FileInfo file = new(Path.Combine(this.FullRootDirectory, path)); - - // try with default extension - if (!file.Exists) + // try with default image extensions + if (!file.Exists && typeof(Texture2D).IsAssignableFrom(typeof(T)) && !ModContentManager.LocalTilesheetExtensions.Contains(file.Extension)) { - foreach (string extension in this.LocalTilesheetExtensions) + foreach (string extension in ModContentManager.LocalTilesheetExtensions) { FileInfo result = new(file.FullName + extension); if (result.Exists) @@ -385,7 +382,7 @@ namespace StardewModdingAPI.Framework.ContentManagers // get relative to map file { string localKey = Path.Combine(modRelativeMapFolder, relativePath); - if (this.GetModFile(localKey).Exists) + if (this.GetModFile<Texture2D>(localKey).Exists) { assetName = this.GetInternalAssetKey(localKey); return true; diff --git a/src/SMAPI/Framework/ContentPack.cs b/src/SMAPI/Framework/ContentPack.cs index 9503a0e6..70fe51f8 100644 --- a/src/SMAPI/Framework/ContentPack.cs +++ b/src/SMAPI/Framework/ContentPack.cs @@ -16,8 +16,8 @@ namespace StardewModdingAPI.Framework /// <summary>Encapsulates SMAPI's JSON file parsing.</summary> private readonly JsonHelper JsonHelper; - /// <summary>A lookup for relative paths within the <see cref="DirectoryPath"/>.</summary> - private readonly IFilePathLookup RelativePathCache; + /// <summary>A lookup for files within the <see cref="DirectoryPath"/>.</summary> + private readonly IFileLookup FileLookup; /********* @@ -48,15 +48,15 @@ namespace StardewModdingAPI.Framework /// <param name="content">Provides an API for loading content assets from the content pack's folder.</param> /// <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 lookup for relative paths within the <paramref name="directoryPath"/>.</param> - public ContentPack(string directoryPath, IManifest manifest, IModContentHelper content, TranslationHelper translation, JsonHelper jsonHelper, IFilePathLookup relativePathCache) + /// <param name="fileLookup">A lookup for files within the <paramref name="directoryPath"/>.</param> + public ContentPack(string directoryPath, IManifest manifest, IModContentHelper content, TranslationHelper translation, JsonHelper jsonHelper, IFileLookup fileLookup) { this.DirectoryPath = directoryPath; this.Manifest = manifest; this.ModContent = content; this.TranslationImpl = translation; this.JsonHelper = jsonHelper; - this.RelativePathCache = relativePathCache; + this.FileLookup = fileLookup; } /// <inheritdoc /> @@ -83,14 +83,21 @@ namespace StardewModdingAPI.Framework { path = PathUtilities.NormalizePath(path); - FileInfo file = this.GetFile(path, out path); + FileInfo file = this.GetFile(path); + bool didExist = file.Exists; + this.JsonHelper.WriteJsonFile(file.FullName, data); - this.RelativePathCache.Add(path); + if (!didExist) + { + this.FileLookup.Add( + Path.GetRelativePath(this.DirectoryPath, file.FullName) + ); + } } /// <inheritdoc /> - [Obsolete] + [Obsolete($"Use {nameof(IContentPack.ModContent)}.{nameof(IModContentHelper.Load)} instead. This method will be removed in SMAPI 4.0.0.")] public T LoadAsset<T>(string key) where T : notnull { @@ -98,7 +105,7 @@ namespace StardewModdingAPI.Framework } /// <inheritdoc /> - [Obsolete] + [Obsolete($"Use {nameof(IContentPack.ModContent)}.{nameof(IModContentHelper.GetInternalAssetName)} instead. This method will be removed in SMAPI 4.0.0.")] public string GetActualAssetKey(string key) { return this.ModContent.GetInternalAssetName(key).Name; @@ -112,20 +119,10 @@ namespace StardewModdingAPI.Framework /// <param name="relativePath">The normalized file path relative to the content pack directory.</param> private FileInfo GetFile(string relativePath) { - return this.GetFile(relativePath, out _); - } - - /// <summary>Get the underlying file info.</summary> - /// <param name="relativePath">The normalized file path relative to the content pack directory.</param> - /// <param name="actualRelativePath">The relative path after case-insensitive matching.</param> - private FileInfo GetFile(string relativePath, out string actualRelativePath) - { if (!PathUtilities.IsSafeRelativePath(relativePath)) throw new InvalidOperationException($"You must call {nameof(IContentPack)} methods with a relative path."); - actualRelativePath = this.RelativePathCache.GetFilePath(relativePath); - - return new FileInfo(Path.Combine(this.DirectoryPath, actualRelativePath)); + return this.FileLookup.GetFile(relativePath); } } } diff --git a/src/SMAPI/Framework/ModHelpers/CommandHelper.cs b/src/SMAPI/Framework/ModHelpers/CommandHelper.cs index 226a8d69..f39ed42e 100644 --- a/src/SMAPI/Framework/ModHelpers/CommandHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/CommandHelper.cs @@ -33,7 +33,7 @@ namespace StardewModdingAPI.Framework.ModHelpers } /// <inheritdoc /> - [Obsolete] + [Obsolete("Use mod-provided APIs to integrate with mods instead. This method will be removed in SMAPI 4.0.0.")] public bool Trigger(string name, string[] arguments) { SCore.DeprecationManager.Warn( diff --git a/src/SMAPI/Framework/ModHelpers/ContentHelper.cs b/src/SMAPI/Framework/ModHelpers/ContentHelper.cs index 3c2441e8..6a92da24 100644 --- a/src/SMAPI/Framework/ModHelpers/ContentHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ContentHelper.cs @@ -15,7 +15,7 @@ using StardewValley; namespace StardewModdingAPI.Framework.ModHelpers { /// <summary>Provides an API for loading content assets.</summary> - [Obsolete] + [Obsolete($"Use {nameof(IMod.Helper)}.{nameof(IModHelper.GameContent)} or {nameof(IMod.Helper)}.{nameof(IModHelper.ModContent)} instead. This interface will be removed in SMAPI 4.0.0.")] internal class ContentHelper : BaseHelper, IContentHelper { /********* diff --git a/src/SMAPI/Framework/ModHelpers/ContentPackHelper.cs b/src/SMAPI/Framework/ModHelpers/ContentPackHelper.cs index 9f4a7ceb..6bc091fa 100644 --- a/src/SMAPI/Framework/ModHelpers/ContentPackHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ContentPackHelper.cs @@ -42,7 +42,15 @@ namespace StardewModdingAPI.Framework.ModHelpers public IContentPack CreateFake(string directoryPath) { string id = Guid.NewGuid().ToString("N"); - return this.CreateTemporary(directoryPath, id, id, id, id, new SemanticVersion(1, 0, 0)); + string relativePath = Path.GetRelativePath(Constants.ModsPath, directoryPath); + return this.CreateTemporary( + directoryPath: directoryPath, + id: id, + name: $"{this.Mod.DisplayName} (fake content pack: {relativePath})", + description: $"A temporary content pack created by the {this.Mod.DisplayName} mod.", + author: "???", + new SemanticVersion(1, 0, 0) + ); } /// <inheritdoc /> diff --git a/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs b/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs index 74ea73de..6429f9bf 100644 --- a/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs @@ -1,10 +1,8 @@ using System; -using Microsoft.Xna.Framework.Content; using StardewModdingAPI.Framework.Content; using StardewModdingAPI.Framework.ContentManagers; using StardewModdingAPI.Framework.Exceptions; using StardewModdingAPI.Framework.Reflection; -using StardewModdingAPI.Toolkit.Utilities.PathLookups; namespace StardewModdingAPI.Framework.ModHelpers { @@ -23,9 +21,6 @@ namespace StardewModdingAPI.Framework.ModHelpers /// <summary>The friendly mod name for use in errors.</summary> private readonly string ModName; - /// <summary>A lookup for relative paths within the <see cref="ContentManager.RootDirectory"/>.</summary> - private readonly IFilePathLookup RelativePathLookup; - /// <summary>Simplifies access to private code.</summary> private readonly Reflector Reflection; @@ -39,9 +34,8 @@ namespace StardewModdingAPI.Framework.ModHelpers /// <param name="mod">The mod using this instance.</param> /// <param name="modName">The friendly mod name for use in errors.</param> /// <param name="gameContentManager">The game content manager used for map tilesheets not provided by the mod.</param> - /// <param name="relativePathLookup">A lookup for relative paths within the <paramref name="relativePathLookup"/>.</param> /// <param name="reflection">Simplifies access to private code.</param> - public ModContentHelper(ContentCoordinator contentCore, string modFolderPath, IModMetadata mod, string modName, IContentManager gameContentManager, IFilePathLookup relativePathLookup, Reflector reflection) + public ModContentHelper(ContentCoordinator contentCore, string modFolderPath, IModMetadata mod, string modName, IContentManager gameContentManager, Reflector reflection) : base(mod) { string managedAssetPrefix = contentCore.GetManagedAssetPrefix(mod.Manifest.UniqueID); @@ -49,7 +43,6 @@ namespace StardewModdingAPI.Framework.ModHelpers this.ContentCore = contentCore; this.ModContentManager = contentCore.CreateModContentManager(managedAssetPrefix, modName, modFolderPath, gameContentManager); this.ModName = modName; - this.RelativePathLookup = relativePathLookup; this.Reflection = reflection; } @@ -57,8 +50,6 @@ namespace StardewModdingAPI.Framework.ModHelpers public T Load<T>(string relativePath) where T : notnull { - relativePath = this.RelativePathLookup.GetAssetName(relativePath); - IAssetName assetName = this.ContentCore.ParseAssetName(relativePath, allowLocales: false); try @@ -74,7 +65,6 @@ namespace StardewModdingAPI.Framework.ModHelpers /// <inheritdoc /> public IAssetName GetInternalAssetName(string relativePath) { - relativePath = this.RelativePathLookup.GetAssetName(relativePath); return this.ModContentManager.GetInternalAssetKey(relativePath); } @@ -85,9 +75,7 @@ namespace StardewModdingAPI.Framework.ModHelpers if (data == null) throw new ArgumentNullException(nameof(data), "Can't get a patch helper for a null value."); - relativePath = relativePath != null - ? this.RelativePathLookup.GetAssetName(relativePath) - : $"temp/{Guid.NewGuid():N}"; + relativePath ??= $"temp/{Guid.NewGuid():N}"; return new AssetDataForObject( locale: this.ContentCore.GetLocale(), diff --git a/src/SMAPI/Framework/ModHelpers/ModHelper.cs b/src/SMAPI/Framework/ModHelpers/ModHelper.cs index a23a9beb..008195d9 100644 --- a/src/SMAPI/Framework/ModHelpers/ModHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ModHelper.cs @@ -13,7 +13,7 @@ namespace StardewModdingAPI.Framework.ModHelpers ** Fields *********/ /// <summary>The backing field for <see cref="Content"/>.</summary> - [Obsolete] + [Obsolete("This only exists to support legacy code and will be removed in SMAPI 4.0.0.")] private readonly ContentHelper ContentImpl; @@ -27,7 +27,7 @@ namespace StardewModdingAPI.Framework.ModHelpers public IModEvents Events { get; } /// <inheritdoc /> - [Obsolete] + [Obsolete($"Use {nameof(IGameContentHelper)} or {nameof(IModContentHelper)} instead.")] public IContentHelper Content { get @@ -128,7 +128,7 @@ namespace StardewModdingAPI.Framework.ModHelpers } /// <summary>Get the underlying instance for <see cref="IContentHelper"/>.</summary> - [Obsolete] + [Obsolete("This only exists to support legacy code and will be removed in SMAPI 4.0.0.")] public ContentHelper GetLegacyContentHelper() { return this.ContentImpl; diff --git a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs index 72b547b1..a6756e0e 100644 --- a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs +++ b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs @@ -85,11 +85,11 @@ namespace StardewModdingAPI.Framework.ModLoading /// <summary>Preprocess and load an assembly.</summary> /// <param name="mod">The mod for which the assembly is being loaded.</param> - /// <param name="assemblyPath">The assembly file path.</param> + /// <param name="assemblyFile">The assembly file.</param> /// <param name="assumeCompatible">Assume the mod is compatible, even if incompatible code is detected.</param> /// <returns>Returns the rewrite metadata for the preprocessed assembly.</returns> /// <exception cref="IncompatibleInstructionException">An incompatible CIL instruction was found while rewriting the assembly.</exception> - public Assembly Load(IModMetadata mod, string assemblyPath, bool assumeCompatible) + public Assembly Load(IModMetadata mod, FileInfo assemblyFile, bool assumeCompatible) { // get referenced local assemblies AssemblyParseResult[] assemblies; @@ -100,19 +100,19 @@ namespace StardewModdingAPI.Framework.ModLoading where name != null select name ); - assemblies = this.GetReferencedLocalAssemblies(new FileInfo(assemblyPath), visitedAssemblyNames, this.AssemblyDefinitionResolver).ToArray(); + assemblies = this.GetReferencedLocalAssemblies(assemblyFile, visitedAssemblyNames, this.AssemblyDefinitionResolver).ToArray(); } // validate load if (!assemblies.Any() || assemblies[0].Status == AssemblyLoadStatus.Failed) { - throw new SAssemblyLoadFailedException(!File.Exists(assemblyPath) - ? $"Could not load '{assemblyPath}' because it doesn't exist." - : $"Could not load '{assemblyPath}'." + throw new SAssemblyLoadFailedException(!assemblyFile.Exists + ? $"Could not load '{assemblyFile.FullName}' because it doesn't exist." + : $"Could not load '{assemblyFile.FullName}'." ); } if (assemblies.Last().Status == AssemblyLoadStatus.AlreadyLoaded) // mod assembly is last in dependency order - throw new SAssemblyLoadFailedException($"Could not load '{assemblyPath}' because it was already loaded. Do you have two copies of this mod?"); + throw new SAssemblyLoadFailedException($"Could not load '{assemblyFile.FullName}' because it was already loaded. Do you have two copies of this mod?"); // rewrite & load assemblies in leaf-to-root order bool oneAssembly = assemblies.Length == 1; diff --git a/src/SMAPI/Framework/ModLoading/ModResolver.cs b/src/SMAPI/Framework/ModLoading/ModResolver.cs index 1b1fa04e..3e7144f9 100644 --- a/src/SMAPI/Framework/ModLoading/ModResolver.cs +++ b/src/SMAPI/Framework/ModLoading/ModResolver.cs @@ -58,11 +58,11 @@ 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="getFilePathLookup">Get a file path lookup for the given directory.</param> + /// <param name="getFileLookup">Get a file lookup for the given directory.</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, Func<string, IFilePathLookup> getFilePathLookup, bool validateFilesExist = true) + public void ValidateManifests(IEnumerable<IModMetadata> mods, ISemanticVersion apiVersion, Func<string, string?> getUpdateUrl, Func<string, IFileLookup> getFileLookup, bool validateFilesExist = true) { mods = mods.ToArray(); @@ -147,9 +147,9 @@ namespace StardewModdingAPI.Framework.ModLoading // file doesn't exist if (validateFilesExist) { - IFilePathLookup pathLookup = getFilePathLookup(mod.DirectoryPath); - string fileName = pathLookup.GetFilePath(mod.Manifest.EntryDll!); - if (!File.Exists(Path.Combine(mod.DirectoryPath, fileName))) + IFileLookup pathLookup = getFileLookup(mod.DirectoryPath); + FileInfo file = pathLookup.GetFile(mod.Manifest.EntryDll!); + if (!file.Exists) { 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 80d0d9ba..1c7cd3ed 100644 --- a/src/SMAPI/Framework/Models/SConfig.cs +++ b/src/SMAPI/Framework/Models/SConfig.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Linq; using StardewModdingAPI.Internal.ConsoleWriting; +using StardewModdingAPI.Toolkit.Utilities; namespace StardewModdingAPI.Framework.Models { @@ -23,7 +24,7 @@ namespace StardewModdingAPI.Framework.Models [nameof(LogNetworkTraffic)] = false, [nameof(RewriteMods)] = true, [nameof(UsePintail)] = true, - [nameof(UseCaseInsensitivePaths)] = false + [nameof(UseCaseInsensitivePaths)] = Constants.Platform is Platform.Android or Platform.Linux }; /// <summary>The default values for <see cref="SuppressUpdateChecks"/>, to log changes if different.</summary> @@ -95,19 +96,19 @@ namespace StardewModdingAPI.Framework.Models /// <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? usePintail, bool? useCaseInsensitivePaths, 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? usePintail, bool? useCaseInsensitivePaths, bool? logNetworkTraffic, ColorSchemeConfig consoleColors, string[]? suppressUpdateChecks) { this.DeveloperMode = developerMode; - this.CheckForUpdates = checkForUpdates; - this.ParanoidWarnings = paranoidWarnings ?? (bool)SConfig.DefaultValues[nameof(SConfig.ParanoidWarnings)]; - this.UseBetaChannel = useBetaChannel ?? (bool)SConfig.DefaultValues[nameof(SConfig.UseBetaChannel)]; + this.CheckForUpdates = checkForUpdates ?? (bool)SConfig.DefaultValues[nameof(this.CheckForUpdates)]; + this.ParanoidWarnings = paranoidWarnings ?? (bool)SConfig.DefaultValues[nameof(this.ParanoidWarnings)]; + this.UseBetaChannel = useBetaChannel ?? (bool)SConfig.DefaultValues[nameof(this.UseBetaChannel)]; this.GitHubProjectName = gitHubProjectName; this.WebApiBaseUrl = webApiBaseUrl; - this.VerboseLogging = verboseLogging; - this.RewriteMods = rewriteMods ?? (bool)SConfig.DefaultValues[nameof(SConfig.RewriteMods)]; - this.UsePintail = usePintail ?? (bool)SConfig.DefaultValues[nameof(SConfig.UsePintail)]; - this.UseCaseInsensitivePaths = useCaseInsensitivePaths ?? (bool)SConfig.DefaultValues[nameof(SConfig.UseCaseInsensitivePaths)]; - this.LogNetworkTraffic = logNetworkTraffic; + this.VerboseLogging = verboseLogging ?? (bool)SConfig.DefaultValues[nameof(this.VerboseLogging)]; + this.RewriteMods = rewriteMods ?? (bool)SConfig.DefaultValues[nameof(this.RewriteMods)]; + this.UsePintail = usePintail ?? (bool)SConfig.DefaultValues[nameof(this.UsePintail)]; + this.UseCaseInsensitivePaths = useCaseInsensitivePaths ?? (bool)SConfig.DefaultValues[nameof(this.UseCaseInsensitivePaths)]; + this.LogNetworkTraffic = logNetworkTraffic ?? (bool)SConfig.DefaultValues[nameof(this.LogNetworkTraffic)]; this.ConsoleColors = consoleColors; this.SuppressUpdateChecks = suppressUpdateChecks ?? Array.Empty<string>(); } diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index a9296d9b..f882682e 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -405,7 +405,7 @@ namespace StardewModdingAPI.Framework mods = mods.Where(p => !p.IsIgnored).ToArray(); // load mods - resolver.ValidateManifests(mods, Constants.ApiVersion, toolkit.GetUpdateUrl, getFilePathLookup: this.GetFilePathLookup); + resolver.ValidateManifests(mods, Constants.ApiVersion, toolkit.GetUpdateUrl, getFileLookup: this.GetFileLookup); mods = resolver.ProcessDependencies(mods, modDatabase).ToArray(); this.LoadMods(mods, this.Toolkit.JsonHelper, this.ContentCore, modDatabase); @@ -1160,7 +1160,7 @@ namespace StardewModdingAPI.Framework this.EventManager.AssetRequested.Raise( invoke: (mod, invoke) => { - AssetRequestedEventArgs args = new(mod, asset.Name, asset.NameWithoutLocale, asset.DataType, this.GetOnBehalfOfContentPack); + AssetRequestedEventArgs args = new(mod, asset, this.GetOnBehalfOfContentPack); invoke(args); @@ -1253,7 +1253,7 @@ namespace StardewModdingAPI.Framework onLoadingFirstAsset: this.InitializeBeforeFirstAssetLoaded, onAssetLoaded: this.OnAssetLoaded, onAssetsInvalidated: this.OnAssetsInvalidated, - getFilePathLookup: this.GetFilePathLookup, + getFileLookup: this.GetFileLookup, requestAssetOperations: this.RequestAssetOperations ); if (this.ContentCore.Language != this.Translator.LocaleEnum) @@ -1754,11 +1754,11 @@ namespace StardewModdingAPI.Framework if (mod.IsContentPack) { IMonitor monitor = this.LogManager.GetMonitor(mod.DisplayName); - IFilePathLookup relativePathCache = this.GetFilePathLookup(mod.DirectoryPath); + IFileLookup fileLookup = this.GetFileLookup(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); + IModContentHelper modContentHelper = new ModContentHelper(this.ContentCore, mod.DirectoryPath, mod, mod.DisplayName, gameContentHelper.GetUnderlyingContentManager(), this.Reflection); TranslationHelper translationHelper = new(mod, contentCore.GetLocale(), contentCore.Language); - IContentPack contentPack = new ContentPack(mod.DirectoryPath, manifest, modContentHelper, translationHelper, jsonHelper, relativePathCache); + IContentPack contentPack = new ContentPack(mod.DirectoryPath, manifest, modContentHelper, translationHelper, jsonHelper, fileLookup); mod.SetMod(contentPack, monitor, translationHelper); this.ModRegistry.Add(mod); @@ -1771,16 +1771,13 @@ namespace StardewModdingAPI.Framework else { // get mod info - string assemblyPath = Path.Combine( - mod.DirectoryPath, - this.GetFilePathLookup(mod.DirectoryPath).GetFilePath(manifest.EntryDll!) - ); + FileInfo assemblyFile = this.GetFileLookup(mod.DirectoryPath).GetFile(manifest.EntryDll!); // load mod Assembly modAssembly; try { - modAssembly = assemblyLoader.Load(mod, assemblyPath, assumeCompatible: mod.DataRecord?.Status == ModStatus.AssumeCompatible); + modAssembly = assemblyLoader.Load(mod, assemblyFile, assumeCompatible: mod.DataRecord?.Status == ModStatus.AssumeCompatible); this.ModRegistry.TrackAssemblies(mod, modAssembly); } catch (IncompatibleInstructionException) // details already in trace logs @@ -1799,7 +1796,7 @@ namespace StardewModdingAPI.Framework catch (Exception ex) { errorReasonPhrase = "its DLL couldn't be loaded."; - if (ex is BadImageFormatException && !EnvironmentUtility.Is64BitAssembly(assemblyPath)) + if (ex is BadImageFormatException && !EnvironmentUtility.Is64BitAssembly(assemblyFile.FullName)) errorReasonPhrase = "it needs to be updated for 64-bit mode."; errorDetails = $"Error: {ex.GetLogSummary()}"; @@ -1835,31 +1832,18 @@ namespace StardewModdingAPI.Framework TranslationHelper translationHelper = new(mod, contentCore.GetLocale(), contentCore.Language); IModHelper modHelper; { - IContentPack CreateFakeContentPack(string packDirPath, IManifest packManifest) - { - IMonitor packMonitor = this.LogManager.GetMonitor(packManifest.Name); - - IFilePathLookup relativePathCache = this.GetFilePathLookup(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); - TranslationHelper packTranslationHelper = new(mod, contentCore.GetLocale(), contentCore.Language); - - ContentPack contentPack = new(packDirPath, packManifest, packContentHelper, packTranslationHelper, this.Toolkit.JsonHelper, relativePathCache); - this.ReloadTranslationsForTemporaryContentPack(mod, contentPack); - mod.FakeContentPacks.Add(new WeakReference<ContentPack>(contentPack)); - return contentPack; - } - IModEvents events = new ModEvents(mod, this.EventManager); ICommandHelper commandHelper = new CommandHelper(mod, this.CommandManager); - IFilePathLookup relativePathLookup = this.GetFilePathLookup(mod.DirectoryPath); #pragma warning disable CS0612 // deprecated code ContentHelper contentHelper = new(contentCore, mod.DirectoryPath, mod, monitor, this.Reflection); #pragma warning restore CS0612 GameContentHelper gameContentHelper = new(contentCore, mod, mod.DisplayName, monitor, this.Reflection); - IModContentHelper modContentHelper = new ModContentHelper(contentCore, mod.DirectoryPath, mod, mod.DisplayName, gameContentHelper.GetUnderlyingContentManager(), relativePathLookup, this.Reflection); - IContentPackHelper contentPackHelper = new ContentPackHelper(mod, new Lazy<IContentPack[]>(GetContentPacks), CreateFakeContentPack); + IModContentHelper modContentHelper = new ModContentHelper(contentCore, mod.DirectoryPath, mod, mod.DisplayName, gameContentHelper.GetUnderlyingContentManager(), this.Reflection); + IContentPackHelper contentPackHelper = new ContentPackHelper( + mod: mod, + contentPacks: new Lazy<IContentPack[]>(GetContentPacks), + createContentPack: (dirPath, fakeManifest) => this.CreateFakeContentPack(dirPath, fakeManifest, contentCore, mod) + ); IDataHelper dataHelper = new DataHelper(mod, mod.DirectoryPath, jsonHelper); IReflectionHelper reflectionHelper = new ReflectionHelper(mod, mod.DisplayName, this.Reflection); IModRegistry modRegistryHelper = new ModRegistryHelper(mod, this.ModRegistry, proxyFactory, monitor); @@ -1888,6 +1872,43 @@ namespace StardewModdingAPI.Framework } } + /// <summary>Create a fake content pack instance for a parent mod.</summary> + /// <param name="packDirPath">The absolute path to the fake content pack's directory.</param> + /// <param name="packManifest">The fake content pack's manifest.</param> + /// <param name="contentCore">The content manager to use for mod content.</param> + /// <param name="parentMod">The mod for which the content pack is being created.</param> + private IContentPack CreateFakeContentPack(string packDirPath, IManifest packManifest, ContentCoordinator contentCore, IModMetadata parentMod) + { + // create fake mod info + string relativePath = Path.GetRelativePath(Constants.ModsPath, packDirPath); + IModMetadata fakeMod = new ModMetadata( + displayName: packManifest.Name, + directoryPath: packDirPath, + rootPath: Constants.ModsPath, + manifest: packManifest, + dataRecord: null, + isIgnored: false + ); + + // create mod helpers + IMonitor packMonitor = this.LogManager.GetMonitor(packManifest.Name); + GameContentHelper gameContentHelper = new(contentCore, fakeMod, packManifest.Name, packMonitor, this.Reflection); + IModContentHelper packContentHelper = new ModContentHelper(contentCore, packDirPath, fakeMod, packManifest.Name, gameContentHelper.GetUnderlyingContentManager(), this.Reflection); + TranslationHelper packTranslationHelper = new(fakeMod, contentCore.GetLocale(), contentCore.Language); + + // add content pack + IFileLookup fileLookup = this.GetFileLookup(packDirPath); + ContentPack contentPack = new(packDirPath, packManifest, packContentHelper, packTranslationHelper, this.Toolkit.JsonHelper, fileLookup); + this.ReloadTranslationsForTemporaryContentPack(parentMod, contentPack); + parentMod.FakeContentPacks.Add(new WeakReference<ContentPack>(contentPack)); + + // log change + string pathLabel = packDirPath.Contains("..") ? packDirPath : relativePath; + this.Monitor.Log($"{parentMod.DisplayName} created dynamic content pack '{packManifest.Name}' (unique ID: {packManifest.UniqueID}{(packManifest.Name.Contains(pathLabel) ? "" : $", path: {pathLabel}")})."); + + return contentPack; + } + /// <summary>Load a mod's entry class.</summary> /// <param name="modAssembly">The mod assembly.</param> /// <param name="mod">The loaded instance.</param> @@ -2036,13 +2057,13 @@ namespace StardewModdingAPI.Framework return translations; } - /// <summary>Get a file path lookup for the given directory.</summary> + /// <summary>Get a file lookup for the given directory.</summary> /// <param name="rootDirectory">The root path to scan.</param> - private IFilePathLookup GetFilePathLookup(string rootDirectory) + private IFileLookup GetFileLookup(string rootDirectory) { return this.Settings.UseCaseInsensitivePaths - ? CaseInsensitivePathLookup.GetCachedFor(rootDirectory) - : MinimalPathLookup.Instance; + ? CaseInsensitiveFileLookup.GetCachedFor(rootDirectory) + : MinimalFileLookup.GetCachedFor(rootDirectory); } /// <summary>Get the map display device which applies SMAPI features like tile rotation to loaded maps.</summary> diff --git a/src/SMAPI/SMAPI.config.json b/src/SMAPI/SMAPI.config.json index bdd6374a..8324f45b 100644 --- a/src/SMAPI/SMAPI.config.json +++ b/src/SMAPI/SMAPI.config.json @@ -40,10 +40,11 @@ copy all the settings, or you may cause bugs due to overridden changes in future "RewriteMods": true, /** - * Whether to make SMAPI file APIs case-insensitive, even on Linux. - * This is experimental, and the initial implementation may impact load times. + * Whether to make SMAPI file APIs case-insensitive (even if the filesystem is case-sensitive). + * + * If null, it's only enabled on Android and Linux. */ - "UseCaseInsensitivePaths": false, + "UseCaseInsensitivePaths": null, /** * Whether to use the experimental Pintail API proxying library, instead of the original @@ -57,17 +58,16 @@ copy all the settings, or you may cause bugs due to overridden changes in future * part of their normal functionality, so these warnings are meaningless without further * investigation. * - * When this is commented out, it'll be true for local debug builds and false otherwise. + * If null, it's only enabled for local debug builds. */ - //"ParanoidWarnings": true, + "ParanoidWarnings": null, /** * Whether SMAPI should show newer beta versions as an available update. * - * When this is commented out, it'll be true if the current SMAPI version is beta, and false - * otherwise. + * If null, it's only enabled if the current SMAPI version is beta. */ - //"UseBetaChannel": true, + "UseBetaChannel": null, /** * SMAPI's GitHub project name, used to perform update checks. |