From f973b4c51839aa2364879ec2ba66da703f20ae06 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 7 May 2022 21:18:09 -0400 Subject: [PATCH 01/13] move CreateFakeContentPack into its own method --- src/SMAPI/Framework/SCore.cs | 43 ++++++++++++++++++++++-------------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index a9296d9b7..ad6de9971 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -1835,22 +1835,6 @@ IContentPack[] GetContentPacks() 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)); - return contentPack; - } - IModEvents events = new ModEvents(mod, this.EventManager); ICommandHelper commandHelper = new CommandHelper(mod, this.CommandManager); IFilePathLookup relativePathLookup = this.GetFilePathLookup(mod.DirectoryPath); @@ -1859,7 +1843,11 @@ IContentPack CreateFakeContentPack(string packDirPath, IManifest packManifest) #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(GetContentPacks), CreateFakeContentPack); + IContentPackHelper contentPackHelper = new ContentPackHelper( + mod: mod, + contentPacks: new Lazy(GetContentPacks), + createContentPack: (dirPath, manifest) => this.CreateFakeContentPack(dirPath, manifest, 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 +1876,27 @@ IContentPack CreateFakeContentPack(string packDirPath, IManifest packManifest) } } + /// Create a fake content pack instance for a parent mod. + /// The absolute path to the fake content pack's directory. + /// The fake content pack's manifest. + /// The content manager to use for mod content. + /// The mod for which the content pack is being created. + private IContentPack CreateFakeContentPack(string packDirPath, IManifest packManifest, ContentCoordinator contentCore, IModMetadata mod) + { + 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)); + return contentPack; + } + /// Load a mod's entry class. /// The mod assembly. /// The loaded instance. From 709638f197093ed9aaa9a3a764c85d40f4c19eac Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 7 May 2022 21:21:02 -0400 Subject: [PATCH 02/13] fix assets loaded through fake content pack using parent mod's path info --- docs/release-notes.md | 4 ++++ src/SMAPI/Framework/SCore.cs | 24 ++++++++++++++++-------- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/docs/release-notes.md b/docs/release-notes.md index 82cf51db8..9cd45f611 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -1,6 +1,10 @@ ← [README](README.md) # Release notes +## Upcoming release +* For mod authors: + * 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/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index ad6de9971..c8dcf747d 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -1880,20 +1880,28 @@ IContentPack[] GetContentPacks() /// The absolute path to the fake content pack's directory. /// The fake content pack's manifest. /// The content manager to use for mod content. - /// The mod for which the content pack is being created. - private IContentPack CreateFakeContentPack(string packDirPath, IManifest packManifest, ContentCoordinator contentCore, IModMetadata mod) + /// The mod for which the content pack is being created. + private IContentPack CreateFakeContentPack(string packDirPath, IManifest packManifest, ContentCoordinator contentCore, IModMetadata parentMod) { - IMonitor packMonitor = this.LogManager.GetMonitor(packManifest.Name); + IModMetadata fakeMod = new ModMetadata( + displayName: $"{parentMod.DisplayName} (fake content pack: {Path.GetRelativePath(Constants.ModsPath, packDirPath)})", + directoryPath: packDirPath, + rootPath: Constants.ModsPath, + manifest: packManifest, + dataRecord: null, + isIgnored: false + ); + 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); + GameContentHelper gameContentHelper = new(contentCore, fakeMod, packManifest.Name, packMonitor, this.Reflection); + IModContentHelper packContentHelper = new ModContentHelper(contentCore, packDirPath, fakeMod, packManifest.Name, gameContentHelper.GetUnderlyingContentManager(), relativePathCache, this.Reflection); + TranslationHelper packTranslationHelper = new(fakeMod, 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)); + this.ReloadTranslationsForTemporaryContentPack(parentMod, contentPack); + parentMod.FakeContentPacks.Add(new WeakReference(contentPack)); return contentPack; } From d4ff9f3f5c108493452879938aa224adb556b7c3 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 7 May 2022 21:53:18 -0400 Subject: [PATCH 03/13] log fake content packs created by mods --- docs/release-notes.md | 1 + .../Framework/ModHelpers/ContentPackHelper.cs | 10 +++++++++- src/SMAPI/Framework/SCore.cs | 14 +++++++++++--- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/docs/release-notes.md b/docs/release-notes.md index 9cd45f611..e558a1bbc 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -3,6 +3,7 @@ # Release notes ## Upcoming release * 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 diff --git a/src/SMAPI/Framework/ModHelpers/ContentPackHelper.cs b/src/SMAPI/Framework/ModHelpers/ContentPackHelper.cs index 9f4a7ceb2..6bc091fa7 100644 --- a/src/SMAPI/Framework/ModHelpers/ContentPackHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ContentPackHelper.cs @@ -42,7 +42,15 @@ public IEnumerable GetOwned() 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) + ); } /// diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index c8dcf747d..0465b6f15 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -1846,7 +1846,7 @@ IContentPack[] GetContentPacks() IContentPackHelper contentPackHelper = new ContentPackHelper( mod: mod, contentPacks: new Lazy(GetContentPacks), - createContentPack: (dirPath, manifest) => this.CreateFakeContentPack(dirPath, manifest, contentCore, mod) + 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); @@ -1883,8 +1883,10 @@ IContentPack[] GetContentPacks() /// The mod for which the content pack is being created. 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: $"{parentMod.DisplayName} (fake content pack: {Path.GetRelativePath(Constants.ModsPath, packDirPath)})", + displayName: packManifest.Name, directoryPath: packDirPath, rootPath: Constants.ModsPath, manifest: packManifest, @@ -1892,16 +1894,22 @@ private IContentPack CreateFakeContentPack(string packDirPath, IManifest packMan isIgnored: false ); + // create mod helpers IMonitor packMonitor = this.LogManager.GetMonitor(packManifest.Name); IFilePathLookup relativePathCache = this.GetFilePathLookup(packDirPath); - GameContentHelper gameContentHelper = new(contentCore, fakeMod, packManifest.Name, packMonitor, this.Reflection); IModContentHelper packContentHelper = new ModContentHelper(contentCore, packDirPath, fakeMod, packManifest.Name, gameContentHelper.GetUnderlyingContentManager(), relativePathCache, this.Reflection); TranslationHelper packTranslationHelper = new(fakeMod, contentCore.GetLocale(), contentCore.Language); + // add content pack ContentPack contentPack = new(packDirPath, packManifest, packContentHelper, packTranslationHelper, this.Toolkit.JsonHelper, relativePathCache); this.ReloadTranslationsForTemporaryContentPack(parentMod, contentPack); parentMod.FakeContentPacks.Add(new WeakReference(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; } From 3db035312641b629aaa5517569d0d30cf71bac29 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 7 May 2022 23:12:33 -0400 Subject: [PATCH 04/13] simplify and rewrite case-insensitive file path feature --- docs/release-notes.md | 2 + src/SMAPI.Tests/Core/ModResolverTests.cs | 21 +++-- .../Framework/ModScanning/ModScanner.cs | 22 +++--- .../PathLookups/CaseInsensitivePathLookup.cs | 78 ++++++------------- .../Utilities/PathLookups/IFilePathLookup.cs | 18 ++--- .../PathLookups/MinimalPathLookup.cs | 39 +++++++--- src/SMAPI/Framework/ContentCoordinator.cs | 12 +-- .../ContentManagers/ModContentManager.cs | 39 +++++----- src/SMAPI/Framework/ContentPack.cs | 33 ++++---- .../Framework/ModHelpers/ModContentHelper.cs | 16 +--- .../Framework/ModLoading/AssemblyLoader.cs | 14 ++-- src/SMAPI/Framework/ModLoading/ModResolver.cs | 10 +-- src/SMAPI/Framework/SCore.cs | 36 ++++----- 13 files changed, 158 insertions(+), 182 deletions(-) diff --git a/docs/release-notes.md b/docs/release-notes.md index e558a1bbc..d9761a6d2 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -2,6 +2,8 @@ # Release notes ## Upcoming release +* For players: + * Improved performance of case-insensitive file paths. * 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. diff --git a/src/SMAPI.Tests/Core/ModResolverTests.cs b/src/SMAPI.Tests/Core/ModResolverTests.cs index 3dfc9461a..70c782ab6 100644 --- a/src/SMAPI.Tests/Core/ModResolverTests.cs +++ b/src/SMAPI.Tests/Core/ModResolverTests.cs @@ -133,7 +133,7 @@ public void ReadBasicManifest_CanReadFile() [Test(Description = "Assert that validation doesn't fail if there are no mods installed.")] public void ValidateManifests_NoMods_DoesNothing() { - new ModResolver().ValidateManifests(Array.Empty(), apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFilePathLookup: _ => MinimalPathLookup.Instance, validateFilesExist: false); + new ModResolver().ValidateManifests(Array.Empty(), 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 @@ public void ValidateManifests_Skips_Failed() 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 @@ public void ValidateManifests_ModStatus_AssumeBroken_Fails() }); // 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(), It.IsAny(), It.IsAny()), Times.Once, "The validation did not fail the metadata."); @@ -175,7 +175,7 @@ public void ValidateManifests_MinimumApiVersion_Fails() 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(), It.IsAny(), It.IsAny()), Times.Once, "The validation did not fail the metadata."); @@ -190,7 +190,7 @@ public void ValidateManifests_MissingEntryDLL_Fails() 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(), It.IsAny(), It.IsAny()), Times.Once, "The validation did not fail the metadata."); @@ -207,7 +207,7 @@ public void ValidateManifests_DuplicateUniqueID_Fails() Mock 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(), It.IsAny()), Times.AtLeastOnce, "The validation did not fail the first mod with a unique ID."); @@ -233,7 +233,7 @@ public void ValidateManifests_Valid_Passes() 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 @@ private string GetTempFolderPath() return Path.Combine(Path.GetTempPath(), "smapi-unit-tests", Guid.NewGuid().ToString("N")); } + /// Get a file lookup for a given directory. + /// The full path to the directory. + private IFileLookup GetFileLookup(string rootDirectory) + { + return MinimalFileLookup.GetCachedFor(rootDirectory); + } + /// Get a randomized basic manifest. /// The value, or null for a generated value. /// The value, or null for a generated value. diff --git a/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs b/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs index aa4c33380..a85ef1093 100644 --- a/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs +++ b/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs @@ -114,10 +114,11 @@ public IEnumerable GetModFolders(string rootPath, string modPath, boo /// Extract information from a mod folder. /// The root folder containing mods. /// The folder to search for a mod. - public ModFolder ReadFolder(DirectoryInfo root, DirectoryInfo searchFolder) + /// Whether to match file paths case-insensitively, even on Linux. + 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 @@ private IEnumerable GetModFolders(DirectoryInfo root, DirectoryInfo f // treat as mod folder else - yield return this.ReadFolder(root, folder); + yield return this.ReadFolder(root, folder, useCaseInsensitiveFilePaths); } /// Consolidate adjacent folders into one mod folder, if possible. @@ -250,7 +251,8 @@ private IEnumerable TryConsolidate(DirectoryInfo root, DirectoryInfo /// Find the manifest for a mod folder. /// The folder to search. - private FileInfo? FindManifest(DirectoryInfo folder) + /// Whether to match file paths case-insensitively, even on Linux. + private FileInfo? FindManifest(DirectoryInfo folder, bool useCaseInsensitiveFilePaths) { // check for conventional manifest in current folder const string defaultName = "manifest.json"; @@ -259,14 +261,14 @@ private IEnumerable TryConsolidate(DirectoryInfo root, DirectoryInfo 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/CaseInsensitivePathLookup.cs index 9cc007373..496d54c38 100644 --- a/src/SMAPI.Toolkit/Utilities/PathLookups/CaseInsensitivePathLookup.cs +++ b/src/SMAPI.Toolkit/Utilities/PathLookups/CaseInsensitivePathLookup.cs @@ -4,8 +4,8 @@ namespace StardewModdingAPI.Toolkit.Utilities.PathLookups { - /// An API for case-insensitive relative path lookups within a root directory. - internal class CaseInsensitivePathLookup : IFilePathLookup + /// An API for case-insensitive file lookups within a root directory. + internal class CaseInsensitiveFileLookup : IFileLookup { /********* ** Fields @@ -16,8 +16,8 @@ internal class CaseInsensitivePathLookup : IFilePathLookup /// A case-insensitive lookup of file paths within the . 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. private readonly Lazy> RelativePathCache; - /// The case-insensitive path caches by root path. - private static readonly Dictionary CachedRoots = new(StringComparer.OrdinalIgnoreCase); + /// The case-insensitive file lookups by root path. + private static readonly Dictionary CachedRoots = new(StringComparer.OrdinalIgnoreCase); /********* @@ -26,22 +26,28 @@ internal class CaseInsensitivePathLookup : IFilePathLookup /// Construct an instance. /// The root directory path for relative paths. /// Which directories to scan from the root. - 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)); } /// - 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."); - /// - 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; } /// @@ -61,17 +67,17 @@ public void Add(string 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); + this.RelativePathCache.Value[relativePath] = relativePath; } /// Get a cached dictionary of relative paths within a root path, for case-insensitive file lookups. /// The root path to scan. - 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 @@ public static CaseInsensitivePathLookup GetCachedFor(string rootPath) /********* ** Private methods *********/ - /// Get the exact capitalization for a given relative path. - /// The relative path. This must already be normalized into asset name or file path format (i.e. using or respectively). - /// Returns the resolved path in the same format if found, else returns the path as-is. - 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; - } - /// Get a case-insensitive lookup of file paths (see ). /// Which directories to scan from the root. private Dictionary GetRelativePathCache(SearchOption searchOption) @@ -112,23 +95,10 @@ private Dictionary GetRelativePathCache(SearchOption searchOptio 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; } - - /// Add a raw relative path to the cache. - /// The cache to update. - /// The relative path to cache, with its exact filesystem capitalization. - private void CacheRawPath(IDictionary 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/IFilePathLookup.cs b/src/SMAPI.Toolkit/Utilities/PathLookups/IFilePathLookup.cs index 678e1383d..d43b5141b 100644 --- a/src/SMAPI.Toolkit/Utilities/PathLookups/IFilePathLookup.cs +++ b/src/SMAPI.Toolkit/Utilities/PathLookups/IFilePathLookup.cs @@ -1,20 +1,16 @@ +using System.IO; + namespace StardewModdingAPI.Toolkit.Utilities.PathLookups { - /// An API for relative path lookups within a root directory. - internal interface IFilePathLookup + /// An API for file lookups within a root directory. + internal interface IFileLookup { - /// Get the actual path for a given relative file path. - /// The relative path. - /// Returns the resolved path in file path format, else the normalized . - string GetFilePath(string relativePath); - - /// Get the actual path for a given asset name. + /// Get the file for a given relative file path, if it exists. /// The relative path. - /// Returns the resolved path in asset name format, else the normalized . - string GetAssetName(string relativePath); + FileInfo GetFile(string relativePath); /// Add a relative path that was just created by a SMAPI API. - /// The relative path. This must already be normalized in asset name or file path format. + /// The relative path. void Add(string relativePath); } } diff --git a/src/SMAPI.Toolkit/Utilities/PathLookups/MinimalPathLookup.cs b/src/SMAPI.Toolkit/Utilities/PathLookups/MinimalPathLookup.cs index 2cf14704d..414b569be 100644 --- a/src/SMAPI.Toolkit/Utilities/PathLookups/MinimalPathLookup.cs +++ b/src/SMAPI.Toolkit/Utilities/PathLookups/MinimalPathLookup.cs @@ -1,31 +1,52 @@ +using System.Collections.Generic; +using System.IO; + namespace StardewModdingAPI.Toolkit.Utilities.PathLookups { - /// An API for relative path lookups within a root directory with minimal preprocessing. - internal class MinimalPathLookup : IFilePathLookup + /// An API for file lookups within a root directory with minimal preprocessing. + internal class MinimalFileLookup : IFileLookup { /********* ** Accessors *********/ - /// A singleton instance for reuse. - public static readonly MinimalPathLookup Instance = new(); + /// The file lookups by root path. + private static readonly Dictionary CachedRoots = new(); + + /// The root directory path for relative paths. + private readonly string RootPath; /********* ** Public methods *********/ - /// - public string GetFilePath(string relativePath) + /// Construct an instance. + /// The root directory path for relative paths. + public MinimalFileLookup(string rootPath) { - return PathUtilities.NormalizePath(relativePath); + this.RootPath = rootPath; } /// - public string GetAssetName(string relativePath) + public FileInfo GetFile(string relativePath) { - return PathUtilities.NormalizeAssetName(relativePath); + return new( + Path.Combine(this.RootPath, PathUtilities.NormalizePath(relativePath)) + ); } /// public void Add(string relativePath) { } + + /// Get a cached dictionary of relative paths within a root path, for case-insensitive file lookups. + /// The root path to scan. + 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/Framework/ContentCoordinator.cs b/src/SMAPI/Framework/ContentCoordinator.cs index 4f52d57e2..02b753ba3 100644 --- a/src/SMAPI/Framework/ContentCoordinator.cs +++ b/src/SMAPI/Framework/ContentCoordinator.cs @@ -32,8 +32,8 @@ internal class ContentCoordinator : IDisposable /// An asset key prefix for assets from SMAPI mod folders. private readonly string ManagedPrefix = "SMAPI"; - /// Get a file path lookup for the given directory. - private readonly Func GetFilePathLookup; + /// Get a file lookup for the given directory. + private readonly Func GetFileLookup; /// Encapsulates monitoring and logging. private readonly IMonitor Monitor; @@ -123,12 +123,12 @@ internal class ContentCoordinator : IDisposable /// Encapsulates SMAPI's JSON file parsing. /// A callback to invoke the first time *any* game content manager loads an asset. /// A callback to invoke when an asset is fully loaded. - /// Get a file path lookup for the given directory. + /// Get a file lookup for the given directory. /// A callback to invoke when any asset names have been invalidated from the cache. /// Get the load/edit operations to apply to an asset by querying registered event handlers. - public ContentCoordinator(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action onLoadingFirstAsset, Action onAssetLoaded, Func getFilePathLookup, Action> onAssetsInvalidated, Func> requestAssetOperations) + public ContentCoordinator(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action onLoadingFirstAsset, Action onAssetLoaded, Func getFileLookup, Action> onAssetsInvalidated, Func> 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 @@ public ModContentManager CreateModContentManager(string name, string modName, st reflection: this.Reflection, jsonHelper: this.JsonHelper, onDisposing: this.OnDisposing, - relativePathLookup: this.GetFilePathLookup(rootDirectory) + fileLookup: this.GetFileLookup(rootDirectory) ); this.ContentManagers.Add(manager); return manager; diff --git a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs index 65dffd8b1..7cac8f360 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 @@ internal class ModContentManager : BaseContentManager /// The game content manager used for map tilesheets not provided by the mod. private readonly IContentManager GameContentManager; - /// A lookup for relative paths within the . - private readonly IFilePathLookup RelativePathLookup; + /// A lookup for files within the . + private readonly IFileLookup FileLookup; /// If a map tilesheet's image source has no file extensions, the file extensions to check for in the local mod folder. - private readonly string[] LocalTilesheetExtensions = { ".png", ".xnb" }; + private static readonly HashSet LocalTilesheetExtensions = new(StringComparer.OrdinalIgnoreCase) { ".png", ".xnb" }; /********* @@ -55,12 +56,12 @@ internal class ModContentManager : BaseContentManager /// Simplifies access to private code. /// Encapsulates SMAPI's JSON file parsing. /// A callback to invoke when the content manager is being disposed. - /// A lookup for relative paths within the . - public ModContentManager(string name, IContentManager gameContentManager, IServiceProvider serviceProvider, string modName, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action onDisposing, IFilePathLookup relativePathLookup) + /// A lookup for files within the . + public ModContentManager(string name, IContentManager gameContentManager, IServiceProvider serviceProvider, string modName, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action 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 @@ public override bool DoesAssetExist(IAssetName assetName) if (base.DoesAssetExist(assetName)) return true; - FileInfo file = this.GetModFile(assetName.Name); + FileInfo file = this.GetModFile(assetName.Name); return file.Exists; } @@ -103,7 +104,7 @@ public override T LoadExact(IAssetName assetName, bool useCache) try { // get file - FileInfo file = this.GetModFile(assetName.Name); + FileInfo file = this.GetModFile(assetName.Name); if (!file.Exists) throw this.GetLoadError(assetName, "the specified path doesn't exist."); @@ -139,9 +140,7 @@ public override LocalizedContentManager CreateTemporary() /// The is empty or contains invalid characters. 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 @@ private SContentLoadException GetLoadError(IAssetName assetName, string reasonPh } /// Get a file from the mod folder. + /// The expected asset type. /// The asset path relative to the content folder. - private FileInfo GetModFile(string path) + private FileInfo GetModFile(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 @@ private bool TryGetTilesheetAssetName(string modRelativeMapFolder, string relati // get relative to map file { string localKey = Path.Combine(modRelativeMapFolder, relativePath); - if (this.GetModFile(localKey).Exists) + if (this.GetModFile(localKey).Exists) { assetName = this.GetInternalAssetKey(localKey); return true; diff --git a/src/SMAPI/Framework/ContentPack.cs b/src/SMAPI/Framework/ContentPack.cs index 9503a0e66..5975fff6b 100644 --- a/src/SMAPI/Framework/ContentPack.cs +++ b/src/SMAPI/Framework/ContentPack.cs @@ -16,8 +16,8 @@ internal class ContentPack : IContentPack /// Encapsulates SMAPI's JSON file parsing. private readonly JsonHelper JsonHelper; - /// A lookup for relative paths within the . - private readonly IFilePathLookup RelativePathCache; + /// A lookup for files within the . + private readonly IFileLookup FileLookup; /********* @@ -48,15 +48,15 @@ internal class ContentPack : IContentPack /// Provides an API for loading content assets from the content pack's folder. /// Provides translations stored in the content pack's i18n folder. /// Encapsulates SMAPI's JSON file parsing. - /// A lookup for relative paths within the . - public ContentPack(string directoryPath, IManifest manifest, IModContentHelper content, TranslationHelper translation, JsonHelper jsonHelper, IFilePathLookup relativePathCache) + /// A lookup for files within the . + 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; } /// @@ -83,10 +83,17 @@ public void WriteJsonFile(string path, TModel data) where TModel : class { 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) + ); + } } /// @@ -111,21 +118,11 @@ public string GetActualAssetKey(string key) /// Get the underlying file info. /// The normalized file path relative to the content pack directory. private FileInfo GetFile(string relativePath) - { - return this.GetFile(relativePath, out _); - } - - /// Get the underlying file info. - /// The normalized file path relative to the content pack directory. - /// The relative path after case-insensitive matching. - 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/ModContentHelper.cs b/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs index 74ea73de6..6429f9bff 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 @@ internal class ModContentHelper : BaseHelper, IModContentHelper /// The friendly mod name for use in errors. private readonly string ModName; - /// A lookup for relative paths within the . - private readonly IFilePathLookup RelativePathLookup; - /// Simplifies access to private code. private readonly Reflector Reflection; @@ -39,9 +34,8 @@ internal class ModContentHelper : BaseHelper, IModContentHelper /// The mod using this instance. /// The friendly mod name for use in errors. /// The game content manager used for map tilesheets not provided by the mod. - /// A lookup for relative paths within the . /// Simplifies access to private code. - 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 @@ public ModContentHelper(ContentCoordinator contentCore, string modFolderPath, IM this.ContentCore = contentCore; this.ModContentManager = contentCore.CreateModContentManager(managedAssetPrefix, modName, modFolderPath, gameContentManager); this.ModName = modName; - this.RelativePathLookup = relativePathLookup; this.Reflection = reflection; } @@ -57,8 +50,6 @@ public ModContentHelper(ContentCoordinator contentCore, string modFolderPath, IM public T Load(string relativePath) where T : notnull { - relativePath = this.RelativePathLookup.GetAssetName(relativePath); - IAssetName assetName = this.ContentCore.ParseAssetName(relativePath, allowLocales: false); try @@ -74,7 +65,6 @@ public T Load(string relativePath) /// public IAssetName GetInternalAssetName(string relativePath) { - relativePath = this.RelativePathLookup.GetAssetName(relativePath); return this.ModContentManager.GetInternalAssetKey(relativePath); } @@ -85,9 +75,7 @@ public IAssetData GetPatchHelper(T data, string? relativePath = null) 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/ModLoading/AssemblyLoader.cs b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs index 72b547b19..a6756e0e7 100644 --- a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs +++ b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs @@ -85,11 +85,11 @@ public AssemblyLoader(Platform targetPlatform, IMonitor monitor, bool paranoidMo /// Preprocess and load an assembly. /// The mod for which the assembly is being loaded. - /// The assembly file path. + /// The assembly file. /// Assume the mod is compatible, even if incompatible code is detected. /// Returns the rewrite metadata for the preprocessed assembly. /// An incompatible CIL instruction was found while rewriting the assembly. - 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 @@ from assembly in AppDomain.CurrentDomain.GetAssemblies() 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 1b1fa04e8..3e7144f9f 100644 --- a/src/SMAPI/Framework/ModLoading/ModResolver.cs +++ b/src/SMAPI/Framework/ModLoading/ModResolver.cs @@ -58,11 +58,11 @@ public IEnumerable ReadManifests(ModToolkit toolkit, string rootPa /// The mod manifests to validate. /// The current SMAPI version. /// Get an update URL for an update key (if valid). - /// Get a file path lookup for the given directory. + /// Get a file lookup for the given directory. /// Whether to validate that files referenced in the manifest (like ) exist on disk. This can be disabled to only validate the manifest itself. [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 mods, ISemanticVersion apiVersion, Func getUpdateUrl, Func getFilePathLookup, bool validateFilesExist = true) + public void ValidateManifests(IEnumerable mods, ISemanticVersion apiVersion, Func getUpdateUrl, Func getFileLookup, bool validateFilesExist = true) { mods = mods.ToArray(); @@ -147,9 +147,9 @@ public void ValidateManifests(IEnumerable mods, ISemanticVersion a // 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/SCore.cs b/src/SMAPI/Framework/SCore.cs index 0465b6f15..3c6e1b6cd 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -405,7 +405,7 @@ private void InitializeBeforeFirstAssetLoaded() 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); @@ -1253,7 +1253,7 @@ private LocalizedContentManager CreateContentManager(IServiceProvider servicePro 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 @@ private bool TryLoadMod(IModMetadata mod, IModMetadata[] mods, AssemblyLoader as 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 @@ private bool TryLoadMod(IModMetadata mod, IModMetadata[] mods, AssemblyLoader as 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 @@ private bool TryLoadMod(IModMetadata mod, IModMetadata[] mods, AssemblyLoader as 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()}"; @@ -1837,12 +1834,11 @@ IContentPack[] GetContentPacks() { 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); + IModContentHelper modContentHelper = new ModContentHelper(contentCore, mod.DirectoryPath, mod, mod.DisplayName, gameContentHelper.GetUnderlyingContentManager(), this.Reflection); IContentPackHelper contentPackHelper = new ContentPackHelper( mod: mod, contentPacks: new Lazy(GetContentPacks), @@ -1896,13 +1892,13 @@ private IContentPack CreateFakeContentPack(string packDirPath, IManifest packMan // create mod helpers IMonitor packMonitor = this.LogManager.GetMonitor(packManifest.Name); - IFilePathLookup relativePathCache = this.GetFilePathLookup(packDirPath); GameContentHelper gameContentHelper = new(contentCore, fakeMod, packManifest.Name, packMonitor, this.Reflection); - IModContentHelper packContentHelper = new ModContentHelper(contentCore, packDirPath, fakeMod, packManifest.Name, gameContentHelper.GetUnderlyingContentManager(), relativePathCache, 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 - ContentPack contentPack = new(packDirPath, packManifest, packContentHelper, packTranslationHelper, this.Toolkit.JsonHelper, relativePathCache); + 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)); @@ -2061,13 +2057,13 @@ private IDictionary> ReadTranslationFiles(st return translations; } - /// Get a file path lookup for the given directory. + /// Get a file lookup for the given directory. /// The root path to scan. - 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); } /// Get the map display device which applies SMAPI features like tile rotation to loaded maps. From ecdda9b07798df516d8fd91d9c388b4be5f27230 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 7 May 2022 23:13:59 -0400 Subject: [PATCH 05/13] update filenames for case-insensitive path rewrite --- ...{CaseInsensitivePathLookup.cs => CaseInsensitiveFileLookup.cs} | 0 .../Utilities/PathLookups/{IFilePathLookup.cs => IFileLookup.cs} | 0 .../PathLookups/{MinimalPathLookup.cs => MinimalFileLookup.cs} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename src/SMAPI.Toolkit/Utilities/PathLookups/{CaseInsensitivePathLookup.cs => CaseInsensitiveFileLookup.cs} (100%) rename src/SMAPI.Toolkit/Utilities/PathLookups/{IFilePathLookup.cs => IFileLookup.cs} (100%) rename src/SMAPI.Toolkit/Utilities/PathLookups/{MinimalPathLookup.cs => MinimalFileLookup.cs} (100%) diff --git a/src/SMAPI.Toolkit/Utilities/PathLookups/CaseInsensitivePathLookup.cs b/src/SMAPI.Toolkit/Utilities/PathLookups/CaseInsensitiveFileLookup.cs similarity index 100% rename from src/SMAPI.Toolkit/Utilities/PathLookups/CaseInsensitivePathLookup.cs rename to src/SMAPI.Toolkit/Utilities/PathLookups/CaseInsensitiveFileLookup.cs diff --git a/src/SMAPI.Toolkit/Utilities/PathLookups/IFilePathLookup.cs b/src/SMAPI.Toolkit/Utilities/PathLookups/IFileLookup.cs similarity index 100% rename from src/SMAPI.Toolkit/Utilities/PathLookups/IFilePathLookup.cs rename to src/SMAPI.Toolkit/Utilities/PathLookups/IFileLookup.cs diff --git a/src/SMAPI.Toolkit/Utilities/PathLookups/MinimalPathLookup.cs b/src/SMAPI.Toolkit/Utilities/PathLookups/MinimalFileLookup.cs similarity index 100% rename from src/SMAPI.Toolkit/Utilities/PathLookups/MinimalPathLookup.cs rename to src/SMAPI.Toolkit/Utilities/PathLookups/MinimalFileLookup.cs From e286e5591b315712909024f79f46c46563b65a56 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 7 May 2022 23:26:34 -0400 Subject: [PATCH 06/13] enable case-insensitive file paths by default for Android/Linux players --- docs/release-notes.md | 2 ++ src/SMAPI/Framework/Models/SConfig.cs | 3 ++- src/SMAPI/SMAPI.config.json | 5 +++-- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/release-notes.md b/docs/release-notes.md index d9761a6d2..25dd295e1 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -3,6 +3,8 @@ # Release notes ## Upcoming release * For players: + * Enabled case-insensitive file paths by default for Android and Linux players. + _This was temporarily disabled in SMAPI 3.14.1. This is no longer enabled by default for macOS and Windows players._ * Improved performance of case-insensitive file paths. * For mod authors: * Dynamic content packs created via `helper.ContentPacks.CreateTemporary` or `CreateFake` are now listed in the log file. diff --git a/src/SMAPI/Framework/Models/SConfig.cs b/src/SMAPI/Framework/Models/SConfig.cs index 80d0d9baf..56ab623c0 100644 --- a/src/SMAPI/Framework/Models/SConfig.cs +++ b/src/SMAPI/Framework/Models/SConfig.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using StardewModdingAPI.Internal.ConsoleWriting; +using StardewModdingAPI.Toolkit.Utilities; namespace StardewModdingAPI.Framework.Models { @@ -22,7 +23,7 @@ internal class SConfig [nameof(VerboseLogging)] = false, [nameof(LogNetworkTraffic)] = false, [nameof(RewriteMods)] = true, - [nameof(UsePintail)] = true, + [nameof(UsePintail)] = Constants.Platform is Platform.Android or Platform.Linux, [nameof(UseCaseInsensitivePaths)] = false }; diff --git a/src/SMAPI/SMAPI.config.json b/src/SMAPI/SMAPI.config.json index bdd6374ab..315134382 100644 --- a/src/SMAPI/SMAPI.config.json +++ b/src/SMAPI/SMAPI.config.json @@ -41,9 +41,10 @@ copy all the settings, or you may cause bugs due to overridden changes in future /** * Whether to make SMAPI file APIs case-insensitive, even on Linux. - * This is experimental, and the initial implementation may impact load times. + * + * When this is commented out, it'll be true on Android or Linux, and false otherwise. */ - "UseCaseInsensitivePaths": false, + "UseCaseInsensitivePaths": null, /** * Whether to use the experimental Pintail API proxying library, instead of the original From 37617e9c26cad93dac462bc1893d167a4692d9df Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 7 May 2022 23:34:30 -0400 Subject: [PATCH 07/13] tweak default settings logic --- src/SMAPI/Framework/Models/SConfig.cs | 18 +++++++++--------- src/SMAPI/SMAPI.config.json | 13 ++++++------- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/src/SMAPI/Framework/Models/SConfig.cs b/src/SMAPI/Framework/Models/SConfig.cs index 56ab623c0..d27c6311a 100644 --- a/src/SMAPI/Framework/Models/SConfig.cs +++ b/src/SMAPI/Framework/Models/SConfig.cs @@ -96,19 +96,19 @@ internal class SConfig /// Whether SMAPI should log network traffic. /// The colors to use for text written to the SMAPI console. /// The mod IDs SMAPI should ignore when performing update checks or validating update keys. - 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(); } diff --git a/src/SMAPI/SMAPI.config.json b/src/SMAPI/SMAPI.config.json index 315134382..8324f45bd 100644 --- a/src/SMAPI/SMAPI.config.json +++ b/src/SMAPI/SMAPI.config.json @@ -40,9 +40,9 @@ 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. + * Whether to make SMAPI file APIs case-insensitive (even if the filesystem is case-sensitive). * - * When this is commented out, it'll be true on Android or Linux, and false otherwise. + * If null, it's only enabled on Android and Linux. */ "UseCaseInsensitivePaths": null, @@ -58,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. From b924fbae4ba6c490b84d06453d7f46fecf480bf4 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 8 May 2022 12:24:52 -0400 Subject: [PATCH 08/13] fix default settings --- src/SMAPI/Framework/Models/SConfig.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/SMAPI/Framework/Models/SConfig.cs b/src/SMAPI/Framework/Models/SConfig.cs index d27c6311a..1c7cd3ed5 100644 --- a/src/SMAPI/Framework/Models/SConfig.cs +++ b/src/SMAPI/Framework/Models/SConfig.cs @@ -23,8 +23,8 @@ internal class SConfig [nameof(VerboseLogging)] = false, [nameof(LogNetworkTraffic)] = false, [nameof(RewriteMods)] = true, - [nameof(UsePintail)] = Constants.Platform is Platform.Android or Platform.Linux, - [nameof(UseCaseInsensitivePaths)] = false + [nameof(UsePintail)] = true, + [nameof(UseCaseInsensitivePaths)] = Constants.Platform is Platform.Android or Platform.Linux }; /// The default values for , to log changes if different. From 26f95bca63e199cda3b3de1fa71eacab3110d17b Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 8 May 2022 18:22:35 -0400 Subject: [PATCH 09/13] optimize case where there's no legacy IAssetLoader/IAssetEditor instances --- docs/release-notes.md | 1 + src/SMAPI/Framework/ContentCoordinator.cs | 23 +++++++++++++---------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/docs/release-notes.md b/docs/release-notes.md index 25dd295e1..ee75bb837 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -6,6 +6,7 @@ * Enabled case-insensitive file paths by default for Android and Linux players. _This was temporarily disabled in SMAPI 3.14.1. This is no longer enabled by default for macOS and Windows players._ * Improved performance of case-insensitive file paths. + * Internal optimizations. * 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. diff --git a/src/SMAPI/Framework/ContentCoordinator.cs b/src/SMAPI/Framework/ContentCoordinator.cs index 02b753ba3..f7cab23d3 100644 --- a/src/SMAPI/Framework/ContentCoordinator.cs +++ b/src/SMAPI/Framework/ContentCoordinator.cs @@ -79,14 +79,14 @@ internal class ContentCoordinator : IDisposable private Lazy> LocaleCodes; /// The cached asset load/edit operations to apply, indexed by asset name. - private readonly TickCacheDictionary AssetOperationsByKey = new(); + private readonly TickCacheDictionary> AssetOperationsByKey = new(); /// A cache of asset operation groups created for legacy implementations. - [Obsolete] + [Obsolete("This only exists to support legacy code and will be removed in SMAPI 4.0.0.")] private readonly Dictionary> LegacyLoaderCache = new(ReferenceEqualityComparer.Instance); /// A cache of asset operation groups created for legacy implementations. - [Obsolete] + [Obsolete("This only exists to support legacy code and will be removed in SMAPI 4.0.0.")] private readonly Dictionary> LegacyEditorCache = new(ReferenceEqualityComparer.Instance); @@ -100,11 +100,11 @@ internal class ContentCoordinator : IDisposable public LocalizedContentManager.LanguageCode Language => this.MainContentManager.Language; /// Interceptors which provide the initial versions of matching assets. - [Obsolete] + [Obsolete("This only exists to support legacy code and will be removed in SMAPI 4.0.0.")] public IList> Loaders { get; } = new List>(); /// Interceptors which edit matching assets after they're loaded. - [Obsolete] + [Obsolete("This only exists to support legacy code and will be removed in SMAPI 4.0.0.")] public IList> Editors { get; } = new List>(); /// The absolute path to the . @@ -449,12 +449,16 @@ out bool updatedNpcWarps /// Get the asset load and edit operations to apply to a given asset if it's (re)loaded now. /// The asset type. /// The asset info to load or edit. - public IEnumerable GetAssetOperations(IAssetInfo info) + public IList GetAssetOperations(IAssetInfo info) where T : notnull { return this.AssetOperationsByKey.GetOrSet( info.Name, - () => this.GetAssetOperationsWithoutCache(info).ToArray() +#pragma warning disable CS0612, CS0618 // deprecated code + () => this.Editors.Count > 0 || this.Loaders.Count > 0 + ? this.GetAssetOperationsIncludingLegacyWithoutCache(info).ToArray() +#pragma warning restore CS0612, CS0618 + : this.RequestAssetOperations(info) ); } @@ -580,7 +584,8 @@ private bool TryLoadVanillaAsset(string assetName, [NotNullWhen(true)] out T? /// Get the asset load and edit operations to apply to a given asset if it's (re)loaded now, ignoring the cache. /// The asset type. /// The asset info to load or edit. - private IEnumerable GetAssetOperationsWithoutCache(IAssetInfo info) + [Obsolete("This only exists to support legacy code and will be removed in SMAPI 4.0.0.")] + private IEnumerable GetAssetOperationsIncludingLegacyWithoutCache(IAssetInfo info) where T : notnull { IAssetInfo legacyInfo = this.GetLegacyAssetInfo(info); @@ -590,7 +595,6 @@ private IEnumerable GetAssetOperationsWithoutCache(IAsse yield return group; // legacy load operations -#pragma warning disable CS0612, CS0618 // deprecated code foreach (ModLinked loader in this.Loaders) { // check if loader applies @@ -686,7 +690,6 @@ private IEnumerable GetAssetOperationsWithoutCache(IAsse ) ); } -#pragma warning restore CS0612, CS0618 } /// Get a cached asset operation group for a legacy or instance, creating it if needed. From e2a3fc4f9974e4ea0c575c82be9b431904d6706d Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 8 May 2022 18:28:02 -0400 Subject: [PATCH 10/13] avoid [Obsolete] without message for clarity --- src/SMAPI/Framework/ContentPack.cs | 4 ++-- src/SMAPI/Framework/ModHelpers/CommandHelper.cs | 2 +- src/SMAPI/Framework/ModHelpers/ContentHelper.cs | 2 +- src/SMAPI/Framework/ModHelpers/ModHelper.cs | 6 +++--- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/SMAPI/Framework/ContentPack.cs b/src/SMAPI/Framework/ContentPack.cs index 5975fff6b..70fe51f85 100644 --- a/src/SMAPI/Framework/ContentPack.cs +++ b/src/SMAPI/Framework/ContentPack.cs @@ -97,7 +97,7 @@ public void WriteJsonFile(string path, TModel data) where TModel : class } /// - [Obsolete] + [Obsolete($"Use {nameof(IContentPack.ModContent)}.{nameof(IModContentHelper.Load)} instead. This method will be removed in SMAPI 4.0.0.")] public T LoadAsset(string key) where T : notnull { @@ -105,7 +105,7 @@ public T LoadAsset(string key) } /// - [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; diff --git a/src/SMAPI/Framework/ModHelpers/CommandHelper.cs b/src/SMAPI/Framework/ModHelpers/CommandHelper.cs index 226a8d695..f39ed42e7 100644 --- a/src/SMAPI/Framework/ModHelpers/CommandHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/CommandHelper.cs @@ -33,7 +33,7 @@ public ICommandHelper Add(string name, string documentation, Action - [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 3c2441e89..6a92da24d 100644 --- a/src/SMAPI/Framework/ModHelpers/ContentHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ContentHelper.cs @@ -15,7 +15,7 @@ namespace StardewModdingAPI.Framework.ModHelpers { /// Provides an API for loading content assets. - [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/ModHelper.cs b/src/SMAPI/Framework/ModHelpers/ModHelper.cs index a23a9beb3..008195d96 100644 --- a/src/SMAPI/Framework/ModHelpers/ModHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ModHelper.cs @@ -13,7 +13,7 @@ internal class ModHelper : BaseHelper, IModHelper, IDisposable ** Fields *********/ /// The backing field for . - [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 @@ internal class ModHelper : BaseHelper, IModHelper, IDisposable public IModEvents Events { get; } /// - [Obsolete] + [Obsolete($"Use {nameof(IGameContentHelper)} or {nameof(IModContentHelper)} instead.")] public IContentHelper Content { get @@ -128,7 +128,7 @@ public ModHelper( } /// Get the underlying instance for . - [Obsolete] + [Obsolete("This only exists to support legacy code and will be removed in SMAPI 4.0.0.")] public ContentHelper GetLegacyContentHelper() { return this.ContentImpl; From 5f2e83969a0994d798b869b1b53e9fc82d556093 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 8 May 2022 18:37:23 -0400 Subject: [PATCH 11/13] only build AssetWithoutLocale when it's used --- src/SMAPI/Events/AssetRequestedEventArgs.cs | 19 +++++++++---------- src/SMAPI/Framework/Content/AssetInfo.cs | 6 ++++-- src/SMAPI/Framework/SCore.cs | 2 +- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/SMAPI/Events/AssetRequestedEventArgs.cs b/src/SMAPI/Events/AssetRequestedEventArgs.cs index 3bcf83b93..6b00b1d9c 100644 --- a/src/SMAPI/Events/AssetRequestedEventArgs.cs +++ b/src/SMAPI/Events/AssetRequestedEventArgs.cs @@ -19,19 +19,22 @@ public class AssetRequestedEventArgs : EventArgs /// Get the mod metadata for a content pack, if it's a valid content pack for the mod. private readonly Func GetOnBehalfOf; + /// The asset info being requested. + private readonly IAssetInfo AssetInfo; + /********* ** Accessors *********/ /// The name of the asset being requested. - public IAssetName Name { get; } + public IAssetName Name => this.AssetInfo.Name; /// The with any locale codes stripped. /// For example, if contains a locale like Data/Bundles.fr-FR, this will be the name without locale like Data/Bundles. If the name has no locale, this field is equivalent. - public IAssetName NameWithoutLocale { get; } + public IAssetName NameWithoutLocale => this.AssetInfo.NameWithoutLocale; /// The requested data type. - public Type DataType { get; } + public Type DataType => this.AssetInfo.DataType; /// The load operations requested by the event handler. internal IList LoadOperations { get; } = new List(); @@ -45,16 +48,12 @@ public class AssetRequestedEventArgs : EventArgs *********/ /// Construct an instance. /// The mod handling the event. - /// The name of the asset being requested. - /// The requested data type. - /// The with any locale codes stripped. + /// The asset info being requested. /// Get the mod metadata for a content pack, if it's a valid content pack for the mod. - internal AssetRequestedEventArgs(IModMetadata mod, IAssetName name, IAssetName nameWithoutLocale, Type dataType, Func getOnBehalfOf) + internal AssetRequestedEventArgs(IModMetadata mod, IAssetInfo assetInfo, Func getOnBehalfOf) { this.Mod = mod; - this.Name = name; - this.NameWithoutLocale = nameWithoutLocale; - this.DataType = dataType; + this.AssetInfo = assetInfo; this.GetOnBehalfOf = getOnBehalfOf; } diff --git a/src/SMAPI/Framework/Content/AssetInfo.cs b/src/SMAPI/Framework/Content/AssetInfo.cs index 363fffb35..a4f0a4080 100644 --- a/src/SMAPI/Framework/Content/AssetInfo.cs +++ b/src/SMAPI/Framework/Content/AssetInfo.cs @@ -13,6 +13,9 @@ internal class AssetInfo : IAssetInfo /// Normalizes an asset key to match the cache key. protected readonly Func GetNormalizedPath; + /// The backing field for . + private IAssetName? NameWithoutLocaleImpl; + /********* ** Accessors @@ -24,7 +27,7 @@ internal class AssetInfo : IAssetInfo public IAssetName Name { get; } /// - public IAssetName NameWithoutLocale { get; } + public IAssetName NameWithoutLocale => this.NameWithoutLocaleImpl ??= this.Name.GetBaseAssetName(); /// [Obsolete($"Use {nameof(AssetInfo.Name)} or {nameof(AssetInfo.NameWithoutLocale)} instead. This property will be removed in SMAPI 4.0.0.")] @@ -64,7 +67,6 @@ public AssetInfo(string? locale, IAssetName assetName, Type type, Func RequestAssetOperations(IAssetInfo asset) 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); From f8f8b237996a1c883d43e539a379bf713a5fd7be Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 8 May 2022 18:50:07 -0400 Subject: [PATCH 12/13] use records for asset edit operations --- src/SMAPI/Events/AssetRequestedEventArgs.cs | 24 ++++++------ .../Framework/Content/AssetEditOperation.cs | 39 +++---------------- .../Framework/Content/AssetLoadOperation.cs | 39 +++---------------- .../Framework/Content/AssetOperationGroup.cs | 33 ++-------------- src/SMAPI/Framework/ContentCoordinator.cs | 28 ++++++------- 5 files changed, 40 insertions(+), 123 deletions(-) diff --git a/src/SMAPI/Events/AssetRequestedEventArgs.cs b/src/SMAPI/Events/AssetRequestedEventArgs.cs index 6b00b1d9c..d0aef1db5 100644 --- a/src/SMAPI/Events/AssetRequestedEventArgs.cs +++ b/src/SMAPI/Events/AssetRequestedEventArgs.cs @@ -72,10 +72,10 @@ public void LoadFrom(Func load, AssetLoadPriority priority, string? onBe { 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() ) ); } @@ -96,10 +96,10 @@ public void LoadFromModFile(string relativePath, AssetLoadPriority prior { this.LoadOperations.Add( new AssetLoadOperation( - mod: this.Mod, - priority: priority, - onBehalfOf: null, - _ => this.Mod.Mod!.Helper.ModContent.Load(relativePath) + Mod: this.Mod, + OnBehalfOf: null, + Priority: priority, + GetData: _ => this.Mod.Mod!.Helper.ModContent.Load(relativePath) ) ); } @@ -119,10 +119,10 @@ public void Edit(Action apply, AssetEditPriority priority = AssetEdi { 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 464948b0c..11b8811bf 100644 --- a/src/SMAPI/Framework/Content/AssetEditOperation.cs +++ b/src/SMAPI/Framework/Content/AssetEditOperation.cs @@ -4,38 +4,9 @@ namespace StardewModdingAPI.Framework.Content { /// An edit to apply to an asset when it's requested from the content pipeline. - internal class AssetEditOperation - { - /********* - ** Accessors - *********/ - /// The mod applying the edit. - public IModMetadata Mod { get; } - - /// If there are multiple edits that apply to the same asset, the priority with which this one should be applied. - public AssetEditPriority Priority { get; } - - /// The content pack on whose behalf the edit is being applied, if any. - public IModMetadata? OnBehalfOf { get; } - - /// Apply the edit to an asset. - public Action ApplyEdit { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The mod applying the edit. - /// If there are multiple edits that apply to the same asset, the priority with which this one should be applied. - /// The content pack on whose behalf the edit is being applied, if any. - /// Apply the edit to an asset. - public AssetEditOperation(IModMetadata mod, AssetEditPriority priority, IModMetadata? onBehalfOf, Action applyEdit) - { - this.Mod = mod; - this.Priority = priority; - this.OnBehalfOf = onBehalfOf; - this.ApplyEdit = applyEdit; - } - } + /// The mod applying the edit. + /// If there are multiple edits that apply to the same asset, the priority with which this one should be applied. + /// The content pack on whose behalf the edit is being applied, if any. + /// Apply the edit to an asset. + internal record AssetEditOperation(IModMetadata Mod, AssetEditPriority Priority, IModMetadata? OnBehalfOf, Action ApplyEdit); } diff --git a/src/SMAPI/Framework/Content/AssetLoadOperation.cs b/src/SMAPI/Framework/Content/AssetLoadOperation.cs index b6cdec27c..7af07dfd0 100644 --- a/src/SMAPI/Framework/Content/AssetLoadOperation.cs +++ b/src/SMAPI/Framework/Content/AssetLoadOperation.cs @@ -4,38 +4,9 @@ namespace StardewModdingAPI.Framework.Content { /// An operation which provides the initial instance of an asset when it's requested from the content pipeline. - internal class AssetLoadOperation - { - /********* - ** Accessors - *********/ - /// The mod loading the asset. - public IModMetadata Mod { get; } - - /// The content pack on whose behalf the asset is being loaded, if any. - public IModMetadata? OnBehalfOf { get; } - - /// If there are multiple loads that apply to the same asset, the priority with which this one should be applied. - public AssetLoadPriority Priority { get; } - - /// Load the initial value for an asset. - public Func GetData { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The mod applying the edit. - /// If there are multiple loads that apply to the same asset, the priority with which this one should be applied. - /// The content pack on whose behalf the asset is being loaded, if any. - /// Load the initial value for an asset. - public AssetLoadOperation(IModMetadata mod, AssetLoadPriority priority, IModMetadata? onBehalfOf, Func getData) - { - this.Mod = mod; - this.Priority = priority; - this.OnBehalfOf = onBehalfOf; - this.GetData = getData; - } - } + /// The mod applying the edit. + /// If there are multiple loads that apply to the same asset, the priority with which this one should be applied. + /// The content pack on whose behalf the asset is being loaded, if any. + /// Load the initial value for an asset. + internal record AssetLoadOperation(IModMetadata Mod, IModMetadata? OnBehalfOf, AssetLoadPriority Priority, Func GetData); } diff --git a/src/SMAPI/Framework/Content/AssetOperationGroup.cs b/src/SMAPI/Framework/Content/AssetOperationGroup.cs index a2fcb7220..1566a8f0c 100644 --- a/src/SMAPI/Framework/Content/AssetOperationGroup.cs +++ b/src/SMAPI/Framework/Content/AssetOperationGroup.cs @@ -1,33 +1,8 @@ namespace StardewModdingAPI.Framework.Content { /// A set of operations to apply to an asset for a given or implementation. - internal class AssetOperationGroup - { - /********* - ** Accessors - *********/ - /// The mod applying the changes. - public IModMetadata Mod { get; } - - /// The load operations to apply. - public AssetLoadOperation[] LoadOperations { get; } - - /// The edit operations to apply. - public AssetEditOperation[] EditOperations { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The mod applying the changes. - /// The load operations to apply. - /// The edit operations to apply. - public AssetOperationGroup(IModMetadata mod, AssetLoadOperation[] loadOperations, AssetEditOperation[] editOperations) - { - this.Mod = mod; - this.LoadOperations = loadOperations; - this.EditOperations = editOperations; - } - } + /// The mod applying the changes. + /// The load operations to apply. + /// The edit operations to apply. + internal record AssetOperationGroup(IModMetadata Mod, AssetLoadOperation[] LoadOperations, AssetEditOperation[] EditOperations); } diff --git a/src/SMAPI/Framework/ContentCoordinator.cs b/src/SMAPI/Framework/ContentCoordinator.cs index f7cab23d3..6702f5e6c 100644 --- a/src/SMAPI/Framework/ContentCoordinator.cs +++ b/src/SMAPI/Framework/ContentCoordinator.cs @@ -615,19 +615,19 @@ private IEnumerable GetAssetOperationsIncludingLegacyWithou 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( + Mod: loader.Mod, + OnBehalfOf: null, + Priority: AssetLoadPriority.Exclusive, + GetData: assetInfo => loader.Data.Load( this.GetLegacyAssetInfo(assetInfo) ) ) }, - editOperations: Array.Empty() + EditOperations: Array.Empty() ) ); } @@ -674,15 +674,15 @@ private IEnumerable GetAssetOperationsIncludingLegacyWithou editor: editor.Data, dataType: info.DataType, createGroup: () => new AssetOperationGroup( - mod: editor.Mod, - loadOperations: Array.Empty(), - editOperations: new[] + Mod: editor.Mod, + LoadOperations: Array.Empty(), + EditOperations: new[] { new AssetEditOperation( - mod: editor.Mod, - priority: priority, - onBehalfOf: null, - applyEdit: assetData => editor.Data.Edit( + Mod: editor.Mod, + OnBehalfOf: null, + Priority: priority, + ApplyEdit: assetData => editor.Data.Edit( this.GetLegacyAssetData(assetData) ) ) From cbe8b597cb55285dea2bb2c34ab26f148a76bc17 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 8 May 2022 20:11:02 -0400 Subject: [PATCH 13/13] prepare for release --- build/common.targets | 2 +- docs/release-notes.md | 9 +++++---- src/SMAPI.Mods.ConsoleCommands/manifest.json | 4 ++-- src/SMAPI.Mods.ErrorHandler/manifest.json | 4 ++-- src/SMAPI.Mods.SaveBackup/manifest.json | 4 ++-- src/SMAPI/Constants.cs | 2 +- 6 files changed, 13 insertions(+), 12 deletions(-) diff --git a/build/common.targets b/build/common.targets index 44ee0caf9..0436ed5b1 100644 --- a/build/common.targets +++ b/build/common.targets @@ -1,7 +1,7 @@ - 3.14.1 + 3.14.2 SMAPI latest $(AssemblySearchPaths);{GAC} diff --git a/docs/release-notes.md b/docs/release-notes.md index ee75bb837..98747613f 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -1,12 +1,13 @@ ← [README](README.md) # Release notes -## Upcoming release +## 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. This is no longer enabled by default for macOS and Windows players._ - * Improved performance of case-insensitive file paths. - * Internal optimizations. + _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. diff --git a/src/SMAPI.Mods.ConsoleCommands/manifest.json b/src/SMAPI.Mods.ConsoleCommands/manifest.json index edbdd081c..c263456aa 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 af67453dd..6e6a271fa 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 14b68cb46..5ba91568e 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/Constants.cs b/src/SMAPI/Constants.cs index b1a9cc820..a289ce4bc 100644 --- a/src/SMAPI/Constants.cs +++ b/src/SMAPI/Constants.cs @@ -50,7 +50,7 @@ internal static class EarlyConstants internal static int? LogScreenId { get; set; } /// SMAPI's current raw semantic version. - internal static string RawApiVersion = "3.14.1"; + internal static string RawApiVersion = "3.14.2"; } /// Contains SMAPI's constants and assumptions.