From e55295385b592f422d43f0b525cf3bea7be19b52 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 31 Dec 2018 13:54:06 -0500 Subject: add HasFile content pack method --- docs/release-notes.md | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 5a7d5ef2..aae5cf3a 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -1,4 +1,10 @@ # Release notes +## 3.0 (upcoming release) +These changes have not been released yet. + +* For modders: + * Added `IContentPack.HasFile` method. + ## 2.11.3 Released 13 September 2019 for Stardew Valley 1.3.36. -- cgit From 31a49b83c2fda9f3990e953aeaefc2b415333f31 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 4 Jan 2019 18:32:12 -0500 Subject: update NuGet packages --- docs/release-notes.md | 1 + .../SMAPI.ModBuildConfig.Analyzer.Tests.csproj | 2 +- src/SMAPI.Tests/StardewModdingAPI.Tests.csproj | 4 ++-- src/SMAPI.Toolkit/StardewModdingAPI.Toolkit.csproj | 4 ++-- src/SMAPI.Web/StardewModdingAPI.Web.csproj | 4 ++-- src/SMAPI/StardewModdingAPI.csproj | 2 +- 6 files changed, 9 insertions(+), 8 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index aae5cf3a..efbd7ddb 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -4,6 +4,7 @@ These changes have not been released yet. * For modders: * Added `IContentPack.HasFile` method. + * Updated to Json.NET 12.0.1. ## 2.11.3 Released 13 September 2019 for Stardew Valley 1.3.36. diff --git a/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj b/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj index 45953eec..747a1d69 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj +++ b/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj @@ -9,7 +9,7 @@ - + diff --git a/src/SMAPI.Tests/StardewModdingAPI.Tests.csproj b/src/SMAPI.Tests/StardewModdingAPI.Tests.csproj index 1cb2d1e6..68cf7b34 100644 --- a/src/SMAPI.Tests/StardewModdingAPI.Tests.csproj +++ b/src/SMAPI.Tests/StardewModdingAPI.Tests.csproj @@ -17,8 +17,8 @@ - - + + diff --git a/src/SMAPI.Toolkit/StardewModdingAPI.Toolkit.csproj b/src/SMAPI.Toolkit/StardewModdingAPI.Toolkit.csproj index 46d38f17..a386fc5e 100644 --- a/src/SMAPI.Toolkit/StardewModdingAPI.Toolkit.csproj +++ b/src/SMAPI.Toolkit/StardewModdingAPI.Toolkit.csproj @@ -14,8 +14,8 @@ - - + + diff --git a/src/SMAPI.Web/StardewModdingAPI.Web.csproj b/src/SMAPI.Web/StardewModdingAPI.Web.csproj index d47361bd..88a13f7b 100644 --- a/src/SMAPI.Web/StardewModdingAPI.Web.csproj +++ b/src/SMAPI.Web/StardewModdingAPI.Web.csproj @@ -15,8 +15,8 @@ - - + + diff --git a/src/SMAPI/StardewModdingAPI.csproj b/src/SMAPI/StardewModdingAPI.csproj index eda53025..718366a7 100644 --- a/src/SMAPI/StardewModdingAPI.csproj +++ b/src/SMAPI/StardewModdingAPI.csproj @@ -19,7 +19,7 @@ - + -- cgit From 6b347b83a7c588638224a02840b1d90b4557ea2a Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 9 Feb 2019 15:16:14 -0500 Subject: fix Save Backup not pruning old backups if they're uncompressed --- docs/release-notes.md | 3 +++ src/SMAPI.Mods.SaveBackup/ModEntry.cs | 13 ++++++++----- 2 files changed, 11 insertions(+), 5 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index efbd7ddb..7724904b 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -2,6 +2,9 @@ ## 3.0 (upcoming release) These changes have not been released yet. +* For players: + * Fixed Save Backup not pruning old backups if they're uncompressed. + * For modders: * Added `IContentPack.HasFile` method. * Updated to Json.NET 12.0.1. diff --git a/src/SMAPI.Mods.SaveBackup/ModEntry.cs b/src/SMAPI.Mods.SaveBackup/ModEntry.cs index 30dbfbe6..33adf76d 100644 --- a/src/SMAPI.Mods.SaveBackup/ModEntry.cs +++ b/src/SMAPI.Mods.SaveBackup/ModEntry.cs @@ -124,20 +124,23 @@ namespace StardewModdingAPI.Mods.SaveBackup try { var oldBackups = backupFolder - .GetFiles() + .GetFileSystemInfos() .OrderByDescending(p => p.CreationTimeUtc) .Skip(backupsToKeep); - foreach (FileInfo file in oldBackups) + foreach (FileSystemInfo entry in oldBackups) { try { - this.Monitor.Log($"Deleting {file.Name}...", LogLevel.Trace); - file.Delete(); + this.Monitor.Log($"Deleting {entry.Name}...", LogLevel.Trace); + if (entry is DirectoryInfo folder) + folder.Delete(recursive: true); + else + entry.Delete(); } catch (Exception ex) { - this.Monitor.Log($"Error deleting old save backup '{file.Name}': {ex}", LogLevel.Error); + this.Monitor.Log($"Error deleting old save backup '{entry.Name}': {ex}", LogLevel.Error); } } } -- cgit From 4a297e29eb0c97be799ee3939e9747dc1c631427 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 18 Feb 2019 01:33:10 -0500 Subject: better handle player reconnecting before disconnection is registered --- docs/release-notes.md | 1 + src/SMAPI/Framework/SMultiplayer.cs | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 7724904b..3041dbd3 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -4,6 +4,7 @@ These changes have not been released yet. * For players: * Fixed Save Backup not pruning old backups if they're uncompressed. + * Fixed issues when a farmhand reconnects before the game notices they're disconnected. * For modders: * Added `IContentPack.HasFile` method. diff --git a/src/SMAPI/Framework/SMultiplayer.cs b/src/SMAPI/Framework/SMultiplayer.cs index 0241ef02..dde71092 100644 --- a/src/SMAPI/Framework/SMultiplayer.cs +++ b/src/SMAPI/Framework/SMultiplayer.cs @@ -201,7 +201,8 @@ namespace StardewModdingAPI.Framework MultiplayerPeer newPeer = new MultiplayerPeer(message.FarmerID, model, sendMessage, isHost: false); if (this.Peers.ContainsKey(message.FarmerID)) { - this.Monitor.Log($"Rejected mod context from farmhand {message.FarmerID}: already received context for that player.", LogLevel.Error); + this.Monitor.Log($"Received mod context from farmhand {message.FarmerID}, but the game didn't see them disconnect. This may indicate issues with the network connection.", LogLevel.Info); + this.Peers.Remove(message.FarmerID); return; } this.AddPeer(newPeer, canBeHost: false, raiseEvent: false); -- cgit From bad2ac2a29b8775be97133e4c4cfb67a4a7406ee Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 24 Feb 2019 19:56:08 -0500 Subject: remove deprecated APIs (#606) --- docs/release-notes.md | 1 + docs/technical-docs.md | 1 - .../ISemanticVersion.cs | 6 - src/SMAPI.Toolkit/SemanticVersion.cs | 19 +- .../Converters/SemanticVersionConverter.cs | 14 +- src/SMAPI/Constants.cs | 26 +-- src/SMAPI/Events/ContentEvents.cs | 45 ---- src/SMAPI/Events/ControlEvents.cs | 123 ---------- src/SMAPI/Events/EventArgsClickableMenuChanged.cs | 33 --- src/SMAPI/Events/EventArgsClickableMenuClosed.cs | 28 --- .../Events/EventArgsControllerButtonPressed.cs | 34 --- .../Events/EventArgsControllerButtonReleased.cs | 34 --- .../Events/EventArgsControllerTriggerPressed.cs | 39 ---- .../Events/EventArgsControllerTriggerReleased.cs | 39 ---- src/SMAPI/Events/EventArgsInput.cs | 64 ----- src/SMAPI/Events/EventArgsIntChanged.cs | 32 --- src/SMAPI/Events/EventArgsInventoryChanged.cs | 43 ---- src/SMAPI/Events/EventArgsKeyPressed.cs | 28 --- src/SMAPI/Events/EventArgsKeyboardStateChanged.cs | 33 --- src/SMAPI/Events/EventArgsLevelUp.cs | 55 ----- .../Events/EventArgsLocationBuildingsChanged.cs | 41 ---- .../Events/EventArgsLocationObjectsChanged.cs | 42 ---- src/SMAPI/Events/EventArgsLocationsChanged.cs | 35 --- src/SMAPI/Events/EventArgsMineLevelChanged.cs | 32 --- src/SMAPI/Events/EventArgsMouseStateChanged.cs | 44 ---- src/SMAPI/Events/EventArgsPlayerWarped.cs | 34 --- src/SMAPI/Events/EventArgsValueChanged.cs | 33 --- src/SMAPI/Events/GameEvents.cs | 122 ---------- src/SMAPI/Events/GraphicsEvents.cs | 120 ---------- src/SMAPI/Events/InputEvents.cs | 56 ----- src/SMAPI/Events/LocationEvents.cs | 67 ------ src/SMAPI/Events/MenuEvents.cs | 56 ----- src/SMAPI/Events/MineEvents.cs | 45 ---- src/SMAPI/Events/MultiplayerEvents.cs | 78 ------- src/SMAPI/Events/PlayerEvents.cs | 68 ------ src/SMAPI/Events/SaveEvents.cs | 100 -------- src/SMAPI/Events/SpecialisedEvents.cs | 45 ---- src/SMAPI/Events/TimeEvents.cs | 56 ----- .../Framework/Content/AssetDataForDictionary.cs | 33 --- src/SMAPI/Framework/DeprecationManager.cs | 29 --- src/SMAPI/Framework/Events/EventManager.cs | 260 --------------------- src/SMAPI/Framework/Events/ManagedEvent.cs | 105 +++++---- src/SMAPI/Framework/Events/ManagedEventBase.cs | 93 -------- src/SMAPI/Framework/ModHelpers/ModHelper.cs | 71 +----- src/SMAPI/Framework/ModLoading/ModResolver.cs | 4 - src/SMAPI/Framework/SCore.cs | 40 +--- src/SMAPI/Framework/SGame.cs | 207 +--------------- src/SMAPI/Framework/SMultiplayer.cs | 18 -- src/SMAPI/IAssetDataForDictionary.cs | 27 +-- src/SMAPI/IModHelper.cs | 38 --- src/SMAPI/Metadata/InstructionMetadata.cs | 3 - src/SMAPI/SemanticVersion.cs | 14 -- 52 files changed, 65 insertions(+), 2648 deletions(-) delete mode 100644 src/SMAPI/Events/ContentEvents.cs delete mode 100644 src/SMAPI/Events/ControlEvents.cs delete mode 100644 src/SMAPI/Events/EventArgsClickableMenuChanged.cs delete mode 100644 src/SMAPI/Events/EventArgsClickableMenuClosed.cs delete mode 100644 src/SMAPI/Events/EventArgsControllerButtonPressed.cs delete mode 100644 src/SMAPI/Events/EventArgsControllerButtonReleased.cs delete mode 100644 src/SMAPI/Events/EventArgsControllerTriggerPressed.cs delete mode 100644 src/SMAPI/Events/EventArgsControllerTriggerReleased.cs delete mode 100644 src/SMAPI/Events/EventArgsInput.cs delete mode 100644 src/SMAPI/Events/EventArgsIntChanged.cs delete mode 100644 src/SMAPI/Events/EventArgsInventoryChanged.cs delete mode 100644 src/SMAPI/Events/EventArgsKeyPressed.cs delete mode 100644 src/SMAPI/Events/EventArgsKeyboardStateChanged.cs delete mode 100644 src/SMAPI/Events/EventArgsLevelUp.cs delete mode 100644 src/SMAPI/Events/EventArgsLocationBuildingsChanged.cs delete mode 100644 src/SMAPI/Events/EventArgsLocationObjectsChanged.cs delete mode 100644 src/SMAPI/Events/EventArgsLocationsChanged.cs delete mode 100644 src/SMAPI/Events/EventArgsMineLevelChanged.cs delete mode 100644 src/SMAPI/Events/EventArgsMouseStateChanged.cs delete mode 100644 src/SMAPI/Events/EventArgsPlayerWarped.cs delete mode 100644 src/SMAPI/Events/EventArgsValueChanged.cs delete mode 100644 src/SMAPI/Events/GameEvents.cs delete mode 100644 src/SMAPI/Events/GraphicsEvents.cs delete mode 100644 src/SMAPI/Events/InputEvents.cs delete mode 100644 src/SMAPI/Events/LocationEvents.cs delete mode 100644 src/SMAPI/Events/MenuEvents.cs delete mode 100644 src/SMAPI/Events/MineEvents.cs delete mode 100644 src/SMAPI/Events/MultiplayerEvents.cs delete mode 100644 src/SMAPI/Events/PlayerEvents.cs delete mode 100644 src/SMAPI/Events/SaveEvents.cs delete mode 100644 src/SMAPI/Events/SpecialisedEvents.cs delete mode 100644 src/SMAPI/Events/TimeEvents.cs delete mode 100644 src/SMAPI/Framework/Events/ManagedEventBase.cs (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 3041dbd3..2f01ee93 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -8,6 +8,7 @@ These changes have not been released yet. * For modders: * Added `IContentPack.HasFile` method. + * Dropped support for all deprecated APIs. * Updated to Json.NET 12.0.1. ## 2.11.3 diff --git a/docs/technical-docs.md b/docs/technical-docs.md index 98dd3540..545f4aa3 100644 --- a/docs/technical-docs.md +++ b/docs/technical-docs.md @@ -106,7 +106,6 @@ SMAPI uses a small number of conditional compilation constants, which you can se flag | purpose ---- | ------- `SMAPI_FOR_WINDOWS` | Whether SMAPI is being compiled on Windows for players on Windows. Set automatically in `crossplatform.targets`. -`SMAPI_3_0_STRICT` | Whether to exclude all deprecated APIs from compilation. This is useful for testing mods for SMAPI 3.0 compatibility. # SMAPI web services ## Overview diff --git a/src/SMAPI.Toolkit.CoreInterfaces/ISemanticVersion.cs b/src/SMAPI.Toolkit.CoreInterfaces/ISemanticVersion.cs index 0a6e5758..4a61f9ae 100644 --- a/src/SMAPI.Toolkit.CoreInterfaces/ISemanticVersion.cs +++ b/src/SMAPI.Toolkit.CoreInterfaces/ISemanticVersion.cs @@ -17,12 +17,6 @@ namespace StardewModdingAPI /// The patch version for backwards-compatible bug fixes. int PatchVersion { get; } -#if !SMAPI_3_0_STRICT - /// An optional build tag. - [Obsolete("Use " + nameof(ISemanticVersion.PrereleaseTag) + " instead")] - string Build { get; } -#endif - /// An optional prerelease tag. string PrereleaseTag { get; } diff --git a/src/SMAPI.Toolkit/SemanticVersion.cs b/src/SMAPI.Toolkit/SemanticVersion.cs index ba9ca6c6..78b4c007 100644 --- a/src/SMAPI.Toolkit/SemanticVersion.cs +++ b/src/SMAPI.Toolkit/SemanticVersion.cs @@ -42,15 +42,6 @@ namespace StardewModdingAPI.Toolkit /// An optional prerelease tag. public string PrereleaseTag { get; } -#if !SMAPI_3_0_STRICT - /// An optional prerelease tag. - [Obsolete("Use " + nameof(ISemanticVersion.PrereleaseTag) + " instead")] - public string Build => this.PrereleaseTag; - - /// Whether the version was parsed from the legacy object format. - public bool IsLegacyFormat { get; } -#endif - /********* ** Public methods @@ -60,20 +51,12 @@ namespace StardewModdingAPI.Toolkit /// The minor version incremented for backwards-compatible changes. /// The patch version for backwards-compatible fixes. /// An optional prerelease tag. - /// Whether the version was parsed from the legacy object format. - public SemanticVersion(int major, int minor, int patch, string prereleaseTag = null -#if !SMAPI_3_0_STRICT - , bool isLegacyFormat = false -#endif - ) + public SemanticVersion(int major, int minor, int patch, string prereleaseTag = null) { this.MajorVersion = major; this.MinorVersion = minor; this.PatchVersion = patch; this.PrereleaseTag = this.GetNormalisedTag(prereleaseTag); -#if !SMAPI_3_0_STRICT - this.IsLegacyFormat = isLegacyFormat; -#endif this.AssertValid(); } diff --git a/src/SMAPI.Toolkit/Serialisation/Converters/SemanticVersionConverter.cs b/src/SMAPI.Toolkit/Serialisation/Converters/SemanticVersionConverter.cs index aca06849..c50de4db 100644 --- a/src/SMAPI.Toolkit/Serialisation/Converters/SemanticVersionConverter.cs +++ b/src/SMAPI.Toolkit/Serialisation/Converters/SemanticVersionConverter.cs @@ -67,20 +67,8 @@ namespace StardewModdingAPI.Toolkit.Serialisation.Converters int minor = obj.ValueIgnoreCase(nameof(ISemanticVersion.MinorVersion)); int patch = obj.ValueIgnoreCase(nameof(ISemanticVersion.PatchVersion)); string prereleaseTag = obj.ValueIgnoreCase(nameof(ISemanticVersion.PrereleaseTag)); -#if !SMAPI_3_0_STRICT - if (string.IsNullOrWhiteSpace(prereleaseTag)) - { - prereleaseTag = obj.ValueIgnoreCase("Build"); - if (prereleaseTag == "0") - prereleaseTag = null; // '0' from incorrect examples in old SMAPI documentation - } -#endif - return new SemanticVersion(major, minor, patch, prereleaseTag -#if !SMAPI_3_0_STRICT - , isLegacyFormat: true -#endif - ); + return new SemanticVersion(major, minor, patch, prereleaseTag); } /// Read a JSON string. diff --git a/src/SMAPI/Constants.cs b/src/SMAPI/Constants.cs index 9d686e2f..736a10ea 100644 --- a/src/SMAPI/Constants.cs +++ b/src/SMAPI/Constants.cs @@ -44,32 +44,10 @@ namespace StardewModdingAPI public static string SavesPath { get; } = Path.Combine(Constants.DataPath, "Saves"); /// The name of the current save folder (if save info is available, regardless of whether the save file exists yet). - public static string SaveFolderName - { - get - { - return Constants.GetSaveFolderName() -#if SMAPI_3_0_STRICT - ; -#else - ?? ""; -#endif - } - } + public static string SaveFolderName => Constants.GetSaveFolderName(); /// The absolute path to the current save folder (if save info is available and the save file exists). - public static string CurrentSavePath - { - get - { - return Constants.GetSaveFolderPathIfExists() -#if SMAPI_3_0_STRICT - ; -#else - ?? ""; -#endif - } - } + public static string CurrentSavePath => Constants.GetSaveFolderPathIfExists(); /**** ** Internal diff --git a/src/SMAPI/Events/ContentEvents.cs b/src/SMAPI/Events/ContentEvents.cs deleted file mode 100644 index aca76ef7..00000000 --- a/src/SMAPI/Events/ContentEvents.cs +++ /dev/null @@ -1,45 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewModdingAPI.Framework; -using StardewModdingAPI.Framework.Events; - -namespace StardewModdingAPI.Events -{ - /// Events raised when the game loads content. - [Obsolete("Use " + nameof(Mod.Helper) + "." + nameof(IModHelper.Events) + " instead. See https://smapi.io/3.0 for more info.")] - public static class ContentEvents - { - /********* - ** Fields - *********/ - /// The core event manager. - private static EventManager EventManager; - - - /********* - ** Events - *********/ - /// Raised after the content language changes. - public static event EventHandler> AfterLocaleChanged - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - ContentEvents.EventManager.Legacy_LocaleChanged.Add(value); - } - remove => ContentEvents.EventManager.Legacy_LocaleChanged.Remove(value); - } - - - /********* - ** Public methods - *********/ - /// Initialise the events. - /// The core event manager. - internal static void Init(EventManager eventManager) - { - ContentEvents.EventManager = eventManager; - } - } -} -#endif diff --git a/src/SMAPI/Events/ControlEvents.cs b/src/SMAPI/Events/ControlEvents.cs deleted file mode 100644 index 45aedc9b..00000000 --- a/src/SMAPI/Events/ControlEvents.cs +++ /dev/null @@ -1,123 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using Microsoft.Xna.Framework.Input; -using StardewModdingAPI.Framework; -using StardewModdingAPI.Framework.Events; - -namespace StardewModdingAPI.Events -{ - /// Events raised when the player uses a controller, keyboard, or mouse. - [Obsolete("Use " + nameof(Mod.Helper) + "." + nameof(IModHelper.Events) + " instead. See https://smapi.io/3.0 for more info.")] - public static class ControlEvents - { - /********* - ** Fields - *********/ - /// The core event manager. - private static EventManager EventManager; - - - /********* - ** Events - *********/ - /// Raised when the changes. That happens when the player presses or releases a key. - public static event EventHandler KeyboardChanged - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - ControlEvents.EventManager.Legacy_KeyboardChanged.Add(value); - } - remove => ControlEvents.EventManager.Legacy_KeyboardChanged.Remove(value); - } - - /// Raised after the player presses a keyboard key. - public static event EventHandler KeyPressed - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - ControlEvents.EventManager.Legacy_KeyPressed.Add(value); - } - remove => ControlEvents.EventManager.Legacy_KeyPressed.Remove(value); - } - - /// Raised after the player releases a keyboard key. - public static event EventHandler KeyReleased - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - ControlEvents.EventManager.Legacy_KeyReleased.Add(value); - } - remove => ControlEvents.EventManager.Legacy_KeyReleased.Remove(value); - } - - /// Raised when the changes. That happens when the player moves the mouse, scrolls the mouse wheel, or presses/releases a button. - public static event EventHandler MouseChanged - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - ControlEvents.EventManager.Legacy_MouseChanged.Add(value); - } - remove => ControlEvents.EventManager.Legacy_MouseChanged.Remove(value); - } - - /// The player pressed a controller button. This event isn't raised for trigger buttons. - public static event EventHandler ControllerButtonPressed - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - ControlEvents.EventManager.Legacy_ControllerButtonPressed.Add(value); - } - remove => ControlEvents.EventManager.Legacy_ControllerButtonPressed.Remove(value); - } - - /// The player released a controller button. This event isn't raised for trigger buttons. - public static event EventHandler ControllerButtonReleased - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - ControlEvents.EventManager.Legacy_ControllerButtonReleased.Add(value); - } - remove => ControlEvents.EventManager.Legacy_ControllerButtonReleased.Remove(value); - } - - /// The player pressed a controller trigger button. - public static event EventHandler ControllerTriggerPressed - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - ControlEvents.EventManager.Legacy_ControllerTriggerPressed.Add(value); - } - remove => ControlEvents.EventManager.Legacy_ControllerTriggerPressed.Remove(value); - } - - /// The player released a controller trigger button. - public static event EventHandler ControllerTriggerReleased - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - ControlEvents.EventManager.Legacy_ControllerTriggerReleased.Add(value); - } - remove => ControlEvents.EventManager.Legacy_ControllerTriggerReleased.Remove(value); - } - - - /********* - ** Public methods - *********/ - /// Initialise the events. - /// The core event manager. - internal static void Init(EventManager eventManager) - { - ControlEvents.EventManager = eventManager; - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsClickableMenuChanged.cs b/src/SMAPI/Events/EventArgsClickableMenuChanged.cs deleted file mode 100644 index a0b903b7..00000000 --- a/src/SMAPI/Events/EventArgsClickableMenuChanged.cs +++ /dev/null @@ -1,33 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewValley.Menus; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsClickableMenuChanged : EventArgs - { - /********* - ** Accessors - *********/ - /// The previous menu. - public IClickableMenu NewMenu { get; } - - /// The current menu. - public IClickableMenu PriorMenu { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The previous menu. - /// The current menu. - public EventArgsClickableMenuChanged(IClickableMenu priorMenu, IClickableMenu newMenu) - { - this.NewMenu = newMenu; - this.PriorMenu = priorMenu; - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsClickableMenuClosed.cs b/src/SMAPI/Events/EventArgsClickableMenuClosed.cs deleted file mode 100644 index 77db69ea..00000000 --- a/src/SMAPI/Events/EventArgsClickableMenuClosed.cs +++ /dev/null @@ -1,28 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewValley.Menus; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsClickableMenuClosed : EventArgs - { - /********* - ** Accessors - *********/ - /// The menu that was closed. - public IClickableMenu PriorMenu { get; } - - - /********* - ** Accessors - *********/ - /// Construct an instance. - /// The menu that was closed. - public EventArgsClickableMenuClosed(IClickableMenu priorMenu) - { - this.PriorMenu = priorMenu; - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsControllerButtonPressed.cs b/src/SMAPI/Events/EventArgsControllerButtonPressed.cs deleted file mode 100644 index 949446e1..00000000 --- a/src/SMAPI/Events/EventArgsControllerButtonPressed.cs +++ /dev/null @@ -1,34 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Input; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsControllerButtonPressed : EventArgs - { - /********* - ** Accessors - *********/ - /// The player who pressed the button. - public PlayerIndex PlayerIndex { get; } - - /// The controller button that was pressed. - public Buttons ButtonPressed { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The player who pressed the button. - /// The controller button that was pressed. - public EventArgsControllerButtonPressed(PlayerIndex playerIndex, Buttons button) - { - this.PlayerIndex = playerIndex; - this.ButtonPressed = button; - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsControllerButtonReleased.cs b/src/SMAPI/Events/EventArgsControllerButtonReleased.cs deleted file mode 100644 index d6d6d840..00000000 --- a/src/SMAPI/Events/EventArgsControllerButtonReleased.cs +++ /dev/null @@ -1,34 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Input; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsControllerButtonReleased : EventArgs - { - /********* - ** Accessors - *********/ - /// The player who pressed the button. - public PlayerIndex PlayerIndex { get; } - - /// The controller button that was pressed. - public Buttons ButtonReleased { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The player who pressed the button. - /// The controller button that was released. - public EventArgsControllerButtonReleased(PlayerIndex playerIndex, Buttons button) - { - this.PlayerIndex = playerIndex; - this.ButtonReleased = button; - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsControllerTriggerPressed.cs b/src/SMAPI/Events/EventArgsControllerTriggerPressed.cs deleted file mode 100644 index 33be2fa3..00000000 --- a/src/SMAPI/Events/EventArgsControllerTriggerPressed.cs +++ /dev/null @@ -1,39 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Input; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsControllerTriggerPressed : EventArgs - { - /********* - ** Accessors - *********/ - /// The player who pressed the button. - public PlayerIndex PlayerIndex { get; } - - /// The controller button that was pressed. - public Buttons ButtonPressed { get; } - - /// The current trigger value. - public float Value { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The player who pressed the trigger button. - /// The trigger button that was pressed. - /// The current trigger value. - public EventArgsControllerTriggerPressed(PlayerIndex playerIndex, Buttons button, float value) - { - this.PlayerIndex = playerIndex; - this.ButtonPressed = button; - this.Value = value; - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsControllerTriggerReleased.cs b/src/SMAPI/Events/EventArgsControllerTriggerReleased.cs deleted file mode 100644 index e90ff712..00000000 --- a/src/SMAPI/Events/EventArgsControllerTriggerReleased.cs +++ /dev/null @@ -1,39 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Input; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsControllerTriggerReleased : EventArgs - { - /********* - ** Accessors - *********/ - /// The player who pressed the button. - public PlayerIndex PlayerIndex { get; } - - /// The controller button that was released. - public Buttons ButtonReleased { get; } - - /// The current trigger value. - public float Value { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The player who pressed the trigger button. - /// The trigger button that was released. - /// The current trigger value. - public EventArgsControllerTriggerReleased(PlayerIndex playerIndex, Buttons button, float value) - { - this.PlayerIndex = playerIndex; - this.ButtonReleased = button; - this.Value = value; - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsInput.cs b/src/SMAPI/Events/EventArgsInput.cs deleted file mode 100644 index 5cff3408..00000000 --- a/src/SMAPI/Events/EventArgsInput.cs +++ /dev/null @@ -1,64 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using System.Collections.Generic; - -namespace StardewModdingAPI.Events -{ - /// Event arguments when a button is pressed or released. - public class EventArgsInput : EventArgs - { - /********* - ** Fields - *********/ - /// The buttons to suppress. - private readonly HashSet SuppressButtons; - - - /********* - ** Accessors - *********/ - /// The button on the controller, keyboard, or mouse. - public SButton Button { get; } - - /// The current cursor position. - public ICursorPosition Cursor { get; } - - /// Whether the input should trigger actions on the affected tile. - public bool IsActionButton => this.Button.IsActionButton(); - - /// Whether the input should use tools on the affected tile. - public bool IsUseToolButton => this.Button.IsUseToolButton(); - - /// Whether a mod has indicated the key was already handled. - public bool IsSuppressed => this.SuppressButtons.Contains(this.Button); - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The button on the controller, keyboard, or mouse. - /// The cursor position. - /// The buttons to suppress. - public EventArgsInput(SButton button, ICursorPosition cursor, HashSet suppressButtons) - { - this.Button = button; - this.Cursor = cursor; - this.SuppressButtons = suppressButtons; - } - - /// Prevent the game from handling the current button press. This doesn't prevent other mods from receiving the event. - public void SuppressButton() - { - this.SuppressButton(this.Button); - } - - /// Prevent the game from handling a button press. This doesn't prevent other mods from receiving the event. - /// The button to suppress. - public void SuppressButton(SButton button) - { - this.SuppressButtons.Add(button); - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsIntChanged.cs b/src/SMAPI/Events/EventArgsIntChanged.cs deleted file mode 100644 index 76ec6d08..00000000 --- a/src/SMAPI/Events/EventArgsIntChanged.cs +++ /dev/null @@ -1,32 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for an integer field that changed value. - public class EventArgsIntChanged : EventArgs - { - /********* - ** Accessors - *********/ - /// The previous value. - public int PriorInt { get; } - - /// The current value. - public int NewInt { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The previous value. - /// The current value. - public EventArgsIntChanged(int priorInt, int newInt) - { - this.PriorInt = priorInt; - this.NewInt = newInt; - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsInventoryChanged.cs b/src/SMAPI/Events/EventArgsInventoryChanged.cs deleted file mode 100644 index 488dd23f..00000000 --- a/src/SMAPI/Events/EventArgsInventoryChanged.cs +++ /dev/null @@ -1,43 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using System.Collections.Generic; -using System.Linq; -using StardewValley; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsInventoryChanged : EventArgs - { - /********* - ** Accessors - *********/ - /// The player's inventory. - public IList Inventory { get; } - - /// The added items. - public List Added { get; } - - /// The removed items. - public List Removed { get; } - - /// The items whose stack sizes changed. - public List QuantityChanged { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The player's inventory. - /// The inventory changes. - public EventArgsInventoryChanged(IList inventory, ItemStackChange[] changedItems) - { - this.Inventory = inventory; - this.Added = changedItems.Where(n => n.ChangeType == ChangeType.Added).ToList(); - this.Removed = changedItems.Where(n => n.ChangeType == ChangeType.Removed).ToList(); - this.QuantityChanged = changedItems.Where(n => n.ChangeType == ChangeType.StackChange).ToList(); - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsKeyPressed.cs b/src/SMAPI/Events/EventArgsKeyPressed.cs deleted file mode 100644 index 6204d821..00000000 --- a/src/SMAPI/Events/EventArgsKeyPressed.cs +++ /dev/null @@ -1,28 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using Microsoft.Xna.Framework.Input; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsKeyPressed : EventArgs - { - /********* - ** Accessors - *********/ - /// The keyboard button that was pressed. - public Keys KeyPressed { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The keyboard button that was pressed. - public EventArgsKeyPressed(Keys key) - { - this.KeyPressed = key; - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsKeyboardStateChanged.cs b/src/SMAPI/Events/EventArgsKeyboardStateChanged.cs deleted file mode 100644 index 2c3203b1..00000000 --- a/src/SMAPI/Events/EventArgsKeyboardStateChanged.cs +++ /dev/null @@ -1,33 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using Microsoft.Xna.Framework.Input; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsKeyboardStateChanged : EventArgs - { - /********* - ** Accessors - *********/ - /// The previous keyboard state. - public KeyboardState NewState { get; } - - /// The current keyboard state. - public KeyboardState PriorState { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The previous keyboard state. - /// The current keyboard state. - public EventArgsKeyboardStateChanged(KeyboardState priorState, KeyboardState newState) - { - this.PriorState = priorState; - this.NewState = newState; - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsLevelUp.cs b/src/SMAPI/Events/EventArgsLevelUp.cs deleted file mode 100644 index 06c70088..00000000 --- a/src/SMAPI/Events/EventArgsLevelUp.cs +++ /dev/null @@ -1,55 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewModdingAPI.Enums; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsLevelUp : EventArgs - { - /********* - ** Accessors - *********/ - /// The player skill that leveled up. - public LevelType Type { get; } - - /// The new skill level. - public int NewLevel { get; } - - /// The player skill types. - public enum LevelType - { - /// The combat skill. - Combat = SkillType.Combat, - - /// The farming skill. - Farming = SkillType.Farming, - - /// The fishing skill. - Fishing = SkillType.Fishing, - - /// The foraging skill. - Foraging = SkillType.Foraging, - - /// The mining skill. - Mining = SkillType.Mining, - - /// The luck skill. - Luck = SkillType.Luck - } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The player skill that leveled up. - /// The new skill level. - public EventArgsLevelUp(LevelType type, int newLevel) - { - this.Type = type; - this.NewLevel = newLevel; - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsLocationBuildingsChanged.cs b/src/SMAPI/Events/EventArgsLocationBuildingsChanged.cs deleted file mode 100644 index 25e84722..00000000 --- a/src/SMAPI/Events/EventArgsLocationBuildingsChanged.cs +++ /dev/null @@ -1,41 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using System.Collections.Generic; -using System.Linq; -using StardewValley; -using StardewValley.Buildings; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsLocationBuildingsChanged : EventArgs - { - /********* - ** Accessors - *********/ - /// The location which changed. - public GameLocation Location { get; } - - /// The buildings added to the location. - public IEnumerable Added { get; } - - /// The buildings removed from the location. - public IEnumerable Removed { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The location which changed. - /// The buildings added to the location. - /// The buildings removed from the location. - public EventArgsLocationBuildingsChanged(GameLocation location, IEnumerable added, IEnumerable removed) - { - this.Location = location; - this.Added = added.ToArray(); - this.Removed = removed.ToArray(); - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsLocationObjectsChanged.cs b/src/SMAPI/Events/EventArgsLocationObjectsChanged.cs deleted file mode 100644 index 9ca2e3e2..00000000 --- a/src/SMAPI/Events/EventArgsLocationObjectsChanged.cs +++ /dev/null @@ -1,42 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.Xna.Framework; -using StardewValley; -using SObject = StardewValley.Object; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsLocationObjectsChanged : EventArgs - { - /********* - ** Accessors - *********/ - /// The location which changed. - public GameLocation Location { get; } - - /// The objects added to the location. - public IEnumerable> Added { get; } - - /// The objects removed from the location. - public IEnumerable> Removed { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The location which changed. - /// The objects added to the location. - /// The objects removed from the location. - public EventArgsLocationObjectsChanged(GameLocation location, IEnumerable> added, IEnumerable> removed) - { - this.Location = location; - this.Added = added.ToArray(); - this.Removed = removed.ToArray(); - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsLocationsChanged.cs b/src/SMAPI/Events/EventArgsLocationsChanged.cs deleted file mode 100644 index 1a59e612..00000000 --- a/src/SMAPI/Events/EventArgsLocationsChanged.cs +++ /dev/null @@ -1,35 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using System.Collections.Generic; -using System.Linq; -using StardewValley; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsLocationsChanged : EventArgs - { - /********* - ** Accessors - *********/ - /// The added locations. - public IEnumerable Added { get; } - - /// The removed locations. - public IEnumerable Removed { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The added locations. - /// The removed locations. - public EventArgsLocationsChanged(IEnumerable added, IEnumerable removed) - { - this.Added = added.ToArray(); - this.Removed = removed.ToArray(); - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsMineLevelChanged.cs b/src/SMAPI/Events/EventArgsMineLevelChanged.cs deleted file mode 100644 index c63b04e9..00000000 --- a/src/SMAPI/Events/EventArgsMineLevelChanged.cs +++ /dev/null @@ -1,32 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsMineLevelChanged : EventArgs - { - /********* - ** Accessors - *********/ - /// The previous mine level. - public int PreviousMineLevel { get; } - - /// The current mine level. - public int CurrentMineLevel { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The previous mine level. - /// The current mine level. - public EventArgsMineLevelChanged(int previousMineLevel, int currentMineLevel) - { - this.PreviousMineLevel = previousMineLevel; - this.CurrentMineLevel = currentMineLevel; - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsMouseStateChanged.cs b/src/SMAPI/Events/EventArgsMouseStateChanged.cs deleted file mode 100644 index 09f3f759..00000000 --- a/src/SMAPI/Events/EventArgsMouseStateChanged.cs +++ /dev/null @@ -1,44 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Input; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsMouseStateChanged : EventArgs - { - /********* - ** Accessors - *********/ - /// The previous mouse state. - public MouseState PriorState { get; } - - /// The current mouse state. - public MouseState NewState { get; } - - /// The previous mouse position on the screen adjusted for the zoom level. - public Point PriorPosition { get; } - - /// The current mouse position on the screen adjusted for the zoom level. - public Point NewPosition { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The previous mouse state. - /// The current mouse state. - /// The previous mouse position on the screen adjusted for the zoom level. - /// The current mouse position on the screen adjusted for the zoom level. - public EventArgsMouseStateChanged(MouseState priorState, MouseState newState, Point priorPosition, Point newPosition) - { - this.PriorState = priorState; - this.NewState = newState; - this.PriorPosition = priorPosition; - this.NewPosition = newPosition; - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsPlayerWarped.cs b/src/SMAPI/Events/EventArgsPlayerWarped.cs deleted file mode 100644 index d1aa1588..00000000 --- a/src/SMAPI/Events/EventArgsPlayerWarped.cs +++ /dev/null @@ -1,34 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewValley; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a event. - public class EventArgsPlayerWarped : EventArgs - { - /********* - ** Accessors - *********/ - /// The player's previous location. - public GameLocation PriorLocation { get; } - - /// The player's current location. - public GameLocation NewLocation { get; } - - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The player's previous location. - /// The player's current location. - public EventArgsPlayerWarped(GameLocation priorLocation, GameLocation newLocation) - { - this.NewLocation = newLocation; - this.PriorLocation = priorLocation; - } - } -} -#endif diff --git a/src/SMAPI/Events/EventArgsValueChanged.cs b/src/SMAPI/Events/EventArgsValueChanged.cs deleted file mode 100644 index 7bfac7a2..00000000 --- a/src/SMAPI/Events/EventArgsValueChanged.cs +++ /dev/null @@ -1,33 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; - -namespace StardewModdingAPI.Events -{ - /// Event arguments for a field that changed value. - /// The value type. - public class EventArgsValueChanged : EventArgs - { - /********* - ** Accessors - *********/ - /// The previous value. - public T PriorValue { get; } - - /// The current value. - public T NewValue { get; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The previous value. - /// The current value. - public EventArgsValueChanged(T priorValue, T newValue) - { - this.PriorValue = priorValue; - this.NewValue = newValue; - } - } -} -#endif diff --git a/src/SMAPI/Events/GameEvents.cs b/src/SMAPI/Events/GameEvents.cs deleted file mode 100644 index 9d945277..00000000 --- a/src/SMAPI/Events/GameEvents.cs +++ /dev/null @@ -1,122 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewModdingAPI.Framework; -using StardewModdingAPI.Framework.Events; - -namespace StardewModdingAPI.Events -{ - /// Events raised when the game changes state. - [Obsolete("Use " + nameof(Mod.Helper) + "." + nameof(IModHelper.Events) + " instead. See https://smapi.io/3.0 for more info.")] - public static class GameEvents - { - /********* - ** Fields - *********/ - /// The core event manager. - private static EventManager EventManager; - - - /********* - ** Events - *********/ - /// Raised when the game updates its state (≈60 times per second). - public static event EventHandler UpdateTick - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - GameEvents.EventManager.Legacy_UpdateTick.Add(value); - } - remove => GameEvents.EventManager.Legacy_UpdateTick.Remove(value); - } - - /// Raised every other tick (≈30 times per second). - public static event EventHandler SecondUpdateTick - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - GameEvents.EventManager.Legacy_SecondUpdateTick.Add(value); - } - remove => GameEvents.EventManager.Legacy_SecondUpdateTick.Remove(value); - } - - /// Raised every fourth tick (≈15 times per second). - public static event EventHandler FourthUpdateTick - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - GameEvents.EventManager.Legacy_FourthUpdateTick.Add(value); - } - remove => GameEvents.EventManager.Legacy_FourthUpdateTick.Remove(value); - } - - /// Raised every eighth tick (≈8 times per second). - public static event EventHandler EighthUpdateTick - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - GameEvents.EventManager.Legacy_EighthUpdateTick.Add(value); - } - remove => GameEvents.EventManager.Legacy_EighthUpdateTick.Remove(value); - } - - /// Raised every 15th tick (≈4 times per second). - public static event EventHandler QuarterSecondTick - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - GameEvents.EventManager.Legacy_QuarterSecondTick.Add(value); - } - remove => GameEvents.EventManager.Legacy_QuarterSecondTick.Remove(value); - } - - /// Raised every 30th tick (≈twice per second). - public static event EventHandler HalfSecondTick - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - GameEvents.EventManager.Legacy_HalfSecondTick.Add(value); - } - remove => GameEvents.EventManager.Legacy_HalfSecondTick.Remove(value); - } - - /// Raised every 60th tick (≈once per second). - public static event EventHandler OneSecondTick - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - GameEvents.EventManager.Legacy_OneSecondTick.Add(value); - } - remove => GameEvents.EventManager.Legacy_OneSecondTick.Remove(value); - } - - /// Raised once after the game initialises and all methods have been called. - public static event EventHandler FirstUpdateTick - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - GameEvents.EventManager.Legacy_FirstUpdateTick.Add(value); - } - remove => GameEvents.EventManager.Legacy_FirstUpdateTick.Remove(value); - } - - - /********* - ** Public methods - *********/ - /// Initialise the events. - /// The core event manager. - internal static void Init(EventManager eventManager) - { - GameEvents.EventManager = eventManager; - } - } -} -#endif diff --git a/src/SMAPI/Events/GraphicsEvents.cs b/src/SMAPI/Events/GraphicsEvents.cs deleted file mode 100644 index 24a16a29..00000000 --- a/src/SMAPI/Events/GraphicsEvents.cs +++ /dev/null @@ -1,120 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewModdingAPI.Framework; -using StardewModdingAPI.Framework.Events; - -namespace StardewModdingAPI.Events -{ - /// Events raised during the game's draw loop, when the game is rendering content to the window. - [Obsolete("Use " + nameof(Mod.Helper) + "." + nameof(IModHelper.Events) + " instead. See https://smapi.io/3.0 for more info.")] - public static class GraphicsEvents - { - /********* - ** Fields - *********/ - /// The core event manager. - private static EventManager EventManager; - - - /********* - ** Events - *********/ - /// Raised after the game window is resized. - public static event EventHandler Resize - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - GraphicsEvents.EventManager.Legacy_Resize.Add(value); - } - remove => GraphicsEvents.EventManager.Legacy_Resize.Remove(value); - } - - /**** - ** Main render events - ****/ - /// Raised before drawing the world to the screen. - public static event EventHandler OnPreRenderEvent - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - GraphicsEvents.EventManager.Legacy_OnPreRenderEvent.Add(value); - } - remove => GraphicsEvents.EventManager.Legacy_OnPreRenderEvent.Remove(value); - } - - /// Raised after drawing the world to the screen. - public static event EventHandler OnPostRenderEvent - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - GraphicsEvents.EventManager.Legacy_OnPostRenderEvent.Add(value); - } - remove => GraphicsEvents.EventManager.Legacy_OnPostRenderEvent.Remove(value); - } - - /**** - ** HUD events - ****/ - /// Raised before drawing the HUD (item toolbar, clock, etc) to the screen. The HUD is available at this point, but not necessarily visible. (For example, the event is raised even if a menu is open.) - public static event EventHandler OnPreRenderHudEvent - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - GraphicsEvents.EventManager.Legacy_OnPreRenderHudEvent.Add(value); - } - remove => GraphicsEvents.EventManager.Legacy_OnPreRenderHudEvent.Remove(value); - } - - /// Raised after drawing the HUD (item toolbar, clock, etc) to the screen. The HUD is available at this point, but not necessarily visible. (For example, the event is raised even if a menu is open.) - public static event EventHandler OnPostRenderHudEvent - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - GraphicsEvents.EventManager.Legacy_OnPostRenderHudEvent.Add(value); - } - remove => GraphicsEvents.EventManager.Legacy_OnPostRenderHudEvent.Remove(value); - } - - /**** - ** GUI events - ****/ - /// Raised before drawing a menu to the screen during a draw loop. This includes the game's internal menus like the title screen. - public static event EventHandler OnPreRenderGuiEvent - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - GraphicsEvents.EventManager.Legacy_OnPreRenderGuiEvent.Add(value); - } - remove => GraphicsEvents.EventManager.Legacy_OnPreRenderGuiEvent.Remove(value); - } - - /// Raised after drawing a menu to the screen during a draw loop. This includes the game's internal menus like the title screen. - public static event EventHandler OnPostRenderGuiEvent - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - GraphicsEvents.EventManager.Legacy_OnPostRenderGuiEvent.Add(value); - } - remove => GraphicsEvents.EventManager.Legacy_OnPostRenderGuiEvent.Remove(value); - } - - - /********* - ** Public methods - *********/ - /// Initialise the events. - /// The core event manager. - internal static void Init(EventManager eventManager) - { - GraphicsEvents.EventManager = eventManager; - } - } -} -#endif diff --git a/src/SMAPI/Events/InputEvents.cs b/src/SMAPI/Events/InputEvents.cs deleted file mode 100644 index c5ab8c83..00000000 --- a/src/SMAPI/Events/InputEvents.cs +++ /dev/null @@ -1,56 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewModdingAPI.Framework; -using StardewModdingAPI.Framework.Events; - -namespace StardewModdingAPI.Events -{ - /// Events raised when the player uses a controller, keyboard, or mouse button. - [Obsolete("Use " + nameof(Mod.Helper) + "." + nameof(IModHelper.Events) + " instead. See https://smapi.io/3.0 for more info.")] - public static class InputEvents - { - /********* - ** Fields - *********/ - /// The core event manager. - private static EventManager EventManager; - - - /********* - ** Events - *********/ - /// Raised when the player presses a button on the keyboard, controller, or mouse. - public static event EventHandler ButtonPressed - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - InputEvents.EventManager.Legacy_ButtonPressed.Add(value); - } - remove => InputEvents.EventManager.Legacy_ButtonPressed.Remove(value); - } - - /// Raised when the player releases a keyboard key on the keyboard, controller, or mouse. - public static event EventHandler ButtonReleased - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - InputEvents.EventManager.Legacy_ButtonReleased.Add(value); - } - remove => InputEvents.EventManager.Legacy_ButtonReleased.Remove(value); - } - - - /********* - ** Public methods - *********/ - /// Initialise the events. - /// The core event manager. - internal static void Init(EventManager eventManager) - { - InputEvents.EventManager = eventManager; - } - } -} -#endif diff --git a/src/SMAPI/Events/LocationEvents.cs b/src/SMAPI/Events/LocationEvents.cs deleted file mode 100644 index 0761bdd8..00000000 --- a/src/SMAPI/Events/LocationEvents.cs +++ /dev/null @@ -1,67 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewModdingAPI.Framework; -using StardewModdingAPI.Framework.Events; - -namespace StardewModdingAPI.Events -{ - /// Events raised when the player transitions between game locations, a location is added or removed, or the objects in the current location change. - [Obsolete("Use " + nameof(Mod.Helper) + "." + nameof(IModHelper.Events) + " instead. See https://smapi.io/3.0 for more info.")] - public static class LocationEvents - { - /********* - ** Fields - *********/ - /// The core event manager. - private static EventManager EventManager; - - - /********* - ** Events - *********/ - /// Raised after a game location is added or removed. - public static event EventHandler LocationsChanged - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - LocationEvents.EventManager.Legacy_LocationsChanged.Add(value); - } - remove => LocationEvents.EventManager.Legacy_LocationsChanged.Remove(value); - } - - /// Raised after buildings are added or removed in a location. - public static event EventHandler BuildingsChanged - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - LocationEvents.EventManager.Legacy_BuildingsChanged.Add(value); - } - remove => LocationEvents.EventManager.Legacy_BuildingsChanged.Remove(value); - } - - /// Raised after objects are added or removed in a location. - public static event EventHandler ObjectsChanged - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - LocationEvents.EventManager.Legacy_ObjectsChanged.Add(value); - } - remove => LocationEvents.EventManager.Legacy_ObjectsChanged.Remove(value); - } - - - /********* - ** Public methods - *********/ - /// Initialise the events. - /// The core event manager. - internal static void Init(EventManager eventManager) - { - LocationEvents.EventManager = eventManager; - } - } -} -#endif diff --git a/src/SMAPI/Events/MenuEvents.cs b/src/SMAPI/Events/MenuEvents.cs deleted file mode 100644 index 8647c268..00000000 --- a/src/SMAPI/Events/MenuEvents.cs +++ /dev/null @@ -1,56 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewModdingAPI.Framework; -using StardewModdingAPI.Framework.Events; - -namespace StardewModdingAPI.Events -{ - /// Events raised when a game menu is opened or closed (including internal menus like the title screen). - [Obsolete("Use " + nameof(Mod.Helper) + "." + nameof(IModHelper.Events) + " instead. See https://smapi.io/3.0 for more info.")] - public static class MenuEvents - { - /********* - ** Fields - *********/ - /// The core event manager. - private static EventManager EventManager; - - - /********* - ** Events - *********/ - /// Raised after a game menu is opened or replaced with another menu. This event is not invoked when a menu is closed. - public static event EventHandler MenuChanged - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - MenuEvents.EventManager.Legacy_MenuChanged.Add(value); - } - remove => MenuEvents.EventManager.Legacy_MenuChanged.Remove(value); - } - - /// Raised after a game menu is closed. - public static event EventHandler MenuClosed - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - MenuEvents.EventManager.Legacy_MenuClosed.Add(value); - } - remove => MenuEvents.EventManager.Legacy_MenuClosed.Remove(value); - } - - - /********* - ** Public methods - *********/ - /// Initialise the events. - /// The core event manager. - internal static void Init(EventManager eventManager) - { - MenuEvents.EventManager = eventManager; - } - } -} -#endif diff --git a/src/SMAPI/Events/MineEvents.cs b/src/SMAPI/Events/MineEvents.cs deleted file mode 100644 index 929da35b..00000000 --- a/src/SMAPI/Events/MineEvents.cs +++ /dev/null @@ -1,45 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewModdingAPI.Framework; -using StardewModdingAPI.Framework.Events; - -namespace StardewModdingAPI.Events -{ - /// Events raised when something happens in the mines. - [Obsolete("Use " + nameof(Mod.Helper) + "." + nameof(IModHelper.Events) + " instead. See https://smapi.io/3.0 for more info.")] - public static class MineEvents - { - /********* - ** Fields - *********/ - /// The core event manager. - private static EventManager EventManager; - - - /********* - ** Events - *********/ - /// Raised after the player warps to a new level of the mine. - public static event EventHandler MineLevelChanged - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - MineEvents.EventManager.Legacy_MineLevelChanged.Add(value); - } - remove => MineEvents.EventManager.Legacy_MineLevelChanged.Remove(value); - } - - - /********* - ** Public methods - *********/ - /// Initialise the events. - /// The core event manager. - internal static void Init(EventManager eventManager) - { - MineEvents.EventManager = eventManager; - } - } -} -#endif diff --git a/src/SMAPI/Events/MultiplayerEvents.cs b/src/SMAPI/Events/MultiplayerEvents.cs deleted file mode 100644 index 0650a8e2..00000000 --- a/src/SMAPI/Events/MultiplayerEvents.cs +++ /dev/null @@ -1,78 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewModdingAPI.Framework; -using StardewModdingAPI.Framework.Events; - -namespace StardewModdingAPI.Events -{ - /// Events raised during the multiplayer sync process. - [Obsolete("Use " + nameof(Mod.Helper) + "." + nameof(IModHelper.Events) + " instead. See https://smapi.io/3.0 for more info.")] - public static class MultiplayerEvents - { - /********* - ** Fields - *********/ - /// The core event manager. - private static EventManager EventManager; - - - /********* - ** Events - *********/ - /// Raised before the game syncs changes from other players. - public static event EventHandler BeforeMainSync - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - MultiplayerEvents.EventManager.Legacy_BeforeMainSync.Add(value); - } - remove => MultiplayerEvents.EventManager.Legacy_BeforeMainSync.Remove(value); - } - - /// Raised after the game syncs changes from other players. - public static event EventHandler AfterMainSync - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - MultiplayerEvents.EventManager.Legacy_AfterMainSync.Add(value); - } - remove => MultiplayerEvents.EventManager.Legacy_AfterMainSync.Remove(value); - } - - /// Raised before the game broadcasts changes to other players. - public static event EventHandler BeforeMainBroadcast - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - MultiplayerEvents.EventManager.Legacy_BeforeMainBroadcast.Add(value); - } - remove => MultiplayerEvents.EventManager.Legacy_BeforeMainBroadcast.Remove(value); - } - - /// Raised after the game broadcasts changes to other players. - public static event EventHandler AfterMainBroadcast - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - MultiplayerEvents.EventManager.Legacy_AfterMainBroadcast.Add(value); - } - remove => MultiplayerEvents.EventManager.Legacy_AfterMainBroadcast.Remove(value); - } - - - /********* - ** Public methods - *********/ - /// Initialise the events. - /// The core event manager. - internal static void Init(EventManager eventManager) - { - MultiplayerEvents.EventManager = eventManager; - } - } -} -#endif diff --git a/src/SMAPI/Events/PlayerEvents.cs b/src/SMAPI/Events/PlayerEvents.cs deleted file mode 100644 index 11ba1e54..00000000 --- a/src/SMAPI/Events/PlayerEvents.cs +++ /dev/null @@ -1,68 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewModdingAPI.Framework; -using StardewModdingAPI.Framework.Events; - -namespace StardewModdingAPI.Events -{ - /// Events raised when the player data changes. - [Obsolete("Use " + nameof(Mod.Helper) + "." + nameof(IModHelper.Events) + " instead. See https://smapi.io/3.0 for more info.")] - public static class PlayerEvents - { - /********* - ** Fields - *********/ - /// The core event manager. - private static EventManager EventManager; - - - /********* - ** Events - *********/ - /// Raised after the player's inventory changes in any way (added or removed item, sorted, etc). - public static event EventHandler InventoryChanged - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - PlayerEvents.EventManager.Legacy_InventoryChanged.Add(value); - } - remove => PlayerEvents.EventManager.Legacy_InventoryChanged.Remove(value); - } - - /// Raised after the player levels up a skill. This happens as soon as they level up, not when the game notifies the player after their character goes to bed. - public static event EventHandler LeveledUp - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - PlayerEvents.EventManager.Legacy_LeveledUp.Add(value); - } - remove => PlayerEvents.EventManager.Legacy_LeveledUp.Remove(value); - } - - /// Raised after the player warps to a new location. - public static event EventHandler Warped - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - PlayerEvents.EventManager.Legacy_PlayerWarped.Add(value); - } - remove => PlayerEvents.EventManager.Legacy_PlayerWarped.Remove(value); - } - - - - /********* - ** Public methods - *********/ - /// Initialise the events. - /// The core event manager. - internal static void Init(EventManager eventManager) - { - PlayerEvents.EventManager = eventManager; - } - } -} -#endif diff --git a/src/SMAPI/Events/SaveEvents.cs b/src/SMAPI/Events/SaveEvents.cs deleted file mode 100644 index da276d22..00000000 --- a/src/SMAPI/Events/SaveEvents.cs +++ /dev/null @@ -1,100 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewModdingAPI.Framework; -using StardewModdingAPI.Framework.Events; - -namespace StardewModdingAPI.Events -{ - /// Events raised before and after the player saves/loads the game. - [Obsolete("Use " + nameof(Mod.Helper) + "." + nameof(IModHelper.Events) + " instead. See https://smapi.io/3.0 for more info.")] - public static class SaveEvents - { - /********* - ** Fields - *********/ - /// The core event manager. - private static EventManager EventManager; - - - /********* - ** Events - *********/ - /// Raised before the game creates the save file. - public static event EventHandler BeforeCreate - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - SaveEvents.EventManager.Legacy_BeforeCreateSave.Add(value); - } - remove => SaveEvents.EventManager.Legacy_BeforeCreateSave.Remove(value); - } - - /// Raised after the game finishes creating the save file. - public static event EventHandler AfterCreate - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - SaveEvents.EventManager.Legacy_AfterCreateSave.Add(value); - } - remove => SaveEvents.EventManager.Legacy_AfterCreateSave.Remove(value); - } - - /// Raised before the game begins writes data to the save file. - public static event EventHandler BeforeSave - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - SaveEvents.EventManager.Legacy_BeforeSave.Add(value); - } - remove => SaveEvents.EventManager.Legacy_BeforeSave.Remove(value); - } - - /// Raised after the game finishes writing data to the save file. - public static event EventHandler AfterSave - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - SaveEvents.EventManager.Legacy_AfterSave.Add(value); - } - remove => SaveEvents.EventManager.Legacy_AfterSave.Remove(value); - } - - /// Raised after the player loads a save slot. - public static event EventHandler AfterLoad - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - SaveEvents.EventManager.Legacy_AfterLoad.Add(value); - } - remove => SaveEvents.EventManager.Legacy_AfterLoad.Remove(value); - } - - /// Raised after the game returns to the title screen. - public static event EventHandler AfterReturnToTitle - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - SaveEvents.EventManager.Legacy_AfterReturnToTitle.Add(value); - } - remove => SaveEvents.EventManager.Legacy_AfterReturnToTitle.Remove(value); - } - - - /********* - ** Public methods - *********/ - /// Initialise the events. - /// The core event manager. - internal static void Init(EventManager eventManager) - { - SaveEvents.EventManager = eventManager; - } - } -} -#endif diff --git a/src/SMAPI/Events/SpecialisedEvents.cs b/src/SMAPI/Events/SpecialisedEvents.cs deleted file mode 100644 index 4f16e4da..00000000 --- a/src/SMAPI/Events/SpecialisedEvents.cs +++ /dev/null @@ -1,45 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewModdingAPI.Framework; -using StardewModdingAPI.Framework.Events; - -namespace StardewModdingAPI.Events -{ - /// Events serving specialised edge cases that shouldn't be used by most mods. - [Obsolete("Use " + nameof(Mod.Helper) + "." + nameof(IModHelper.Events) + " instead. See https://smapi.io/3.0 for more info.")] - public static class SpecialisedEvents - { - /********* - ** Fields - *********/ - /// The core event manager. - private static EventManager EventManager; - - - /********* - ** Events - *********/ - /// Raised when the game updates its state (≈60 times per second), regardless of normal SMAPI validation. This event is not thread-safe and may be invoked while game logic is running asynchronously. Changes to game state in this method may crash the game or corrupt an in-progress save. Do not use this event unless you're fully aware of the context in which your code will be run. Mods using this method will trigger a stability warning in the SMAPI console. - public static event EventHandler UnvalidatedUpdateTick - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - SpecialisedEvents.EventManager.Legacy_UnvalidatedUpdateTick.Add(value); - } - remove => SpecialisedEvents.EventManager.Legacy_UnvalidatedUpdateTick.Remove(value); - } - - - /********* - ** Public methods - *********/ - /// Initialise the events. - /// The core event manager. - internal static void Init(EventManager eventManager) - { - SpecialisedEvents.EventManager = eventManager; - } - } -} -#endif diff --git a/src/SMAPI/Events/TimeEvents.cs b/src/SMAPI/Events/TimeEvents.cs deleted file mode 100644 index 389532d9..00000000 --- a/src/SMAPI/Events/TimeEvents.cs +++ /dev/null @@ -1,56 +0,0 @@ -#if !SMAPI_3_0_STRICT -using System; -using StardewModdingAPI.Framework; -using StardewModdingAPI.Framework.Events; - -namespace StardewModdingAPI.Events -{ - /// Events raised when the in-game date or time changes. - [Obsolete("Use " + nameof(Mod.Helper) + "." + nameof(IModHelper.Events) + " instead. See https://smapi.io/3.0 for more info.")] - public static class TimeEvents - { - /********* - ** Fields - *********/ - /// The core event manager. - private static EventManager EventManager; - - - /********* - ** Events - *********/ - /// Raised after the game begins a new day, including when loading a save. - public static event EventHandler AfterDayStarted - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - TimeEvents.EventManager.Legacy_AfterDayStarted.Add(value); - } - remove => TimeEvents.EventManager.Legacy_AfterDayStarted.Remove(value); - } - - /// Raised after the in-game clock changes. - public static event EventHandler TimeOfDayChanged - { - add - { - SCore.DeprecationManager.WarnForOldEvents(); - TimeEvents.EventManager.Legacy_TimeOfDayChanged.Add(value); - } - remove => TimeEvents.EventManager.Legacy_TimeOfDayChanged.Remove(value); - } - - - /********* - ** Public methods - *********/ - /// Initialise the events. - /// The core event manager. - internal static void Init(EventManager eventManager) - { - TimeEvents.EventManager = eventManager; - } - } -} -#endif diff --git a/src/SMAPI/Framework/Content/AssetDataForDictionary.cs b/src/SMAPI/Framework/Content/AssetDataForDictionary.cs index 11a2564c..a331f38a 100644 --- a/src/SMAPI/Framework/Content/AssetDataForDictionary.cs +++ b/src/SMAPI/Framework/Content/AssetDataForDictionary.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; namespace StardewModdingAPI.Framework.Content { @@ -18,37 +17,5 @@ namespace StardewModdingAPI.Framework.Content /// A callback to invoke when the data is replaced (if any). public AssetDataForDictionary(string locale, string assetName, IDictionary data, Func getNormalisedPath, Action> onDataReplaced) : base(locale, assetName, data, getNormalisedPath, onDataReplaced) { } - -#if !SMAPI_3_0_STRICT - /// Add or replace an entry in the dictionary. - /// The entry key. - /// The entry value. - [Obsolete("Access " + nameof(AssetData>.Data) + "field directly.")] - public void Set(TKey key, TValue value) - { - SCore.DeprecationManager.Warn($"AssetDataForDictionary.{nameof(Set)}", "2.10", DeprecationLevel.PendingRemoval); - this.Data[key] = value; - } - - /// Add or replace an entry in the dictionary. - /// The entry key. - /// A callback which accepts the current value and returns the new value. - [Obsolete("Access " + nameof(AssetData>.Data) + "field directly.")] - public void Set(TKey key, Func value) - { - SCore.DeprecationManager.Warn($"AssetDataForDictionary.{nameof(Set)}", "2.10", DeprecationLevel.PendingRemoval); - this.Data[key] = value(this.Data[key]); - } - - /// Dynamically replace values in the dictionary. - /// A lambda which takes the current key and value for an entry, and returns the new value. - [Obsolete("Access " + nameof(AssetData>.Data) + "field directly.")] - public void Set(Func replacer) - { - SCore.DeprecationManager.Warn($"AssetDataForDictionary.{nameof(Set)}", "2.10", DeprecationLevel.PendingRemoval); - foreach (var pair in this.Data.ToArray()) - this.Data[pair.Key] = replacer(pair.Key, pair.Value); - } -#endif } } diff --git a/src/SMAPI/Framework/DeprecationManager.cs b/src/SMAPI/Framework/DeprecationManager.cs index 984bb487..636b1979 100644 --- a/src/SMAPI/Framework/DeprecationManager.cs +++ b/src/SMAPI/Framework/DeprecationManager.cs @@ -14,11 +14,7 @@ namespace StardewModdingAPI.Framework private readonly HashSet LoggedDeprecations = new HashSet(StringComparer.InvariantCultureIgnoreCase); /// Encapsulates monitoring and logging for a given module. -#if !SMAPI_3_0_STRICT - private readonly Monitor Monitor; -#else private readonly IMonitor Monitor; -#endif /// Tracks the installed mods. private readonly ModRegistry ModRegistry; @@ -26,11 +22,6 @@ namespace StardewModdingAPI.Framework /// The queued deprecation warnings to display. private readonly IList QueuedWarnings = new List(); -#if !SMAPI_3_0_STRICT - /// Whether the one-time deprecation message has been shown. - private bool DeprecationHeaderShown = false; -#endif - /********* ** Public methods @@ -38,11 +29,7 @@ namespace StardewModdingAPI.Framework /// Construct an instance. /// Encapsulates monitoring and logging for a given module. /// Tracks the installed mods. -#if !SMAPI_3_0_STRICT - public DeprecationManager(Monitor monitor, ModRegistry modRegistry) -#else public DeprecationManager(IMonitor monitor, ModRegistry modRegistry) -#endif { this.Monitor = monitor; this.ModRegistry = modRegistry; @@ -81,26 +68,10 @@ namespace StardewModdingAPI.Framework /// Print any queued messages. public void PrintQueued() { -#if !SMAPI_3_0_STRICT - if (!this.DeprecationHeaderShown && this.QueuedWarnings.Any()) - { - this.Monitor.Newline(); - this.Monitor.Log("Some of your mods will break in the upcoming SMAPI 3.0. Please update your mods now, or notify the author if no update is available. See https://mods.smapi.io for links to the latest versions.", LogLevel.Warn); - this.Monitor.Newline(); - this.DeprecationHeaderShown = true; - } -#endif - foreach (DeprecationWarning warning in this.QueuedWarnings.OrderBy(p => p.ModName).ThenBy(p => p.NounPhrase)) { // build message -#if SMAPI_3_0_STRICT string message = $"{warning.ModName} uses deprecated code ({warning.NounPhrase} is deprecated since SMAPI {warning.Version})."; -#else - string message = warning.NounPhrase == "legacy events" - ? $"{warning.ModName ?? "An unknown mod"} will break in the upcoming SMAPI 3.0 (legacy events are deprecated since SMAPI {warning.Version})." - : $"{warning.ModName ?? "An unknown mod"} will break in the upcoming SMAPI 3.0 ({warning.NounPhrase} is deprecated since SMAPI {warning.Version})."; -#endif // get log level LogLevel level; diff --git a/src/SMAPI/Framework/Events/EventManager.cs b/src/SMAPI/Framework/Events/EventManager.cs index 13244601..23879f1d 100644 --- a/src/SMAPI/Framework/Events/EventManager.cs +++ b/src/SMAPI/Framework/Events/EventManager.cs @@ -1,7 +1,4 @@ using System.Diagnostics.CodeAnalysis; -#if !SMAPI_3_0_STRICT -using Microsoft.Xna.Framework.Input; -#endif using StardewModdingAPI.Events; namespace StardewModdingAPI.Framework.Events @@ -167,196 +164,6 @@ namespace StardewModdingAPI.Framework.Events public readonly ManagedEvent UnvalidatedUpdateTicked; -#if !SMAPI_3_0_STRICT - /********* - ** Events (old) - *********/ - /**** - ** ContentEvents - ****/ - /// Raised after the content language changes. - public readonly ManagedEvent> Legacy_LocaleChanged; - - /**** - ** ControlEvents - ****/ - /// Raised when the changes. That happens when the player presses or releases a key. - public readonly ManagedEvent Legacy_KeyboardChanged; - - /// Raised after the player presses a keyboard key. - public readonly ManagedEvent Legacy_KeyPressed; - - /// Raised after the player releases a keyboard key. - public readonly ManagedEvent Legacy_KeyReleased; - - /// Raised when the changes. That happens when the player moves the mouse, scrolls the mouse wheel, or presses/releases a button. - public readonly ManagedEvent Legacy_MouseChanged; - - /// The player pressed a controller button. This event isn't raised for trigger buttons. - public readonly ManagedEvent Legacy_ControllerButtonPressed; - - /// The player released a controller button. This event isn't raised for trigger buttons. - public readonly ManagedEvent Legacy_ControllerButtonReleased; - - /// The player pressed a controller trigger button. - public readonly ManagedEvent Legacy_ControllerTriggerPressed; - - /// The player released a controller trigger button. - public readonly ManagedEvent Legacy_ControllerTriggerReleased; - - /**** - ** GameEvents - ****/ - /// Raised once after the game initialises and all methods have been called. - public readonly ManagedEvent Legacy_FirstUpdateTick; - - /// Raised when the game updates its state (≈60 times per second). - public readonly ManagedEvent Legacy_UpdateTick; - - /// Raised every other tick (≈30 times per second). - public readonly ManagedEvent Legacy_SecondUpdateTick; - - /// Raised every fourth tick (≈15 times per second). - public readonly ManagedEvent Legacy_FourthUpdateTick; - - /// Raised every eighth tick (≈8 times per second). - public readonly ManagedEvent Legacy_EighthUpdateTick; - - /// Raised every 15th tick (≈4 times per second). - public readonly ManagedEvent Legacy_QuarterSecondTick; - - /// Raised every 30th tick (≈twice per second). - public readonly ManagedEvent Legacy_HalfSecondTick; - - /// Raised every 60th tick (≈once per second). - public readonly ManagedEvent Legacy_OneSecondTick; - - /**** - ** GraphicsEvents - ****/ - /// Raised after the game window is resized. - public readonly ManagedEvent Legacy_Resize; - - /// Raised before drawing the world to the screen. - public readonly ManagedEvent Legacy_OnPreRenderEvent; - - /// Raised after drawing the world to the screen. - public readonly ManagedEvent Legacy_OnPostRenderEvent; - - /// Raised before drawing the HUD (item toolbar, clock, etc) to the screen. The HUD is available at this point, but not necessarily visible. (For example, the event is raised even if a menu is open.) - public readonly ManagedEvent Legacy_OnPreRenderHudEvent; - - /// Raised after drawing the HUD (item toolbar, clock, etc) to the screen. The HUD is available at this point, but not necessarily visible. (For example, the event is raised even if a menu is open.) - public readonly ManagedEvent Legacy_OnPostRenderHudEvent; - - /// Raised before drawing a menu to the screen during a draw loop. This includes the game's internal menus like the title screen. - public readonly ManagedEvent Legacy_OnPreRenderGuiEvent; - - /// Raised after drawing a menu to the screen during a draw loop. This includes the game's internal menus like the title screen. - public readonly ManagedEvent Legacy_OnPostRenderGuiEvent; - - /**** - ** InputEvents - ****/ - /// Raised after the player presses a button on the keyboard, controller, or mouse. - public readonly ManagedEvent Legacy_ButtonPressed; - - /// Raised after the player releases a keyboard key on the keyboard, controller, or mouse. - public readonly ManagedEvent Legacy_ButtonReleased; - - /**** - ** LocationEvents - ****/ - /// Raised after a game location is added or removed. - public readonly ManagedEvent Legacy_LocationsChanged; - - /// Raised after buildings are added or removed in a location. - public readonly ManagedEvent Legacy_BuildingsChanged; - - /// Raised after objects are added or removed in a location. - public readonly ManagedEvent Legacy_ObjectsChanged; - - /**** - ** MenuEvents - ****/ - /// Raised after a game menu is opened or replaced with another menu. This event is not invoked when a menu is closed. - public readonly ManagedEvent Legacy_MenuChanged; - - /// Raised after a game menu is closed. - public readonly ManagedEvent Legacy_MenuClosed; - - /**** - ** MultiplayerEvents - ****/ - /// Raised before the game syncs changes from other players. - public readonly ManagedEvent Legacy_BeforeMainSync; - - /// Raised after the game syncs changes from other players. - public readonly ManagedEvent Legacy_AfterMainSync; - - /// Raised before the game broadcasts changes to other players. - public readonly ManagedEvent Legacy_BeforeMainBroadcast; - - /// Raised after the game broadcasts changes to other players. - public readonly ManagedEvent Legacy_AfterMainBroadcast; - - /**** - ** MineEvents - ****/ - /// Raised after the player warps to a new level of the mine. - public readonly ManagedEvent Legacy_MineLevelChanged; - - /**** - ** PlayerEvents - ****/ - /// Raised after the player's inventory changes in any way (added or removed item, sorted, etc). - public readonly ManagedEvent Legacy_InventoryChanged; - - /// Raised after the player levels up a skill. This happens as soon as they level up, not when the game notifies the player after their character goes to bed. - public readonly ManagedEvent Legacy_LeveledUp; - - /// Raised after the player warps to a new location. - public readonly ManagedEvent Legacy_PlayerWarped; - - - /**** - ** SaveEvents - ****/ - /// Raised before the game creates the save file. - public readonly ManagedEvent Legacy_BeforeCreateSave; - - /// Raised after the game finishes creating the save file. - public readonly ManagedEvent Legacy_AfterCreateSave; - - /// Raised before the game begins writes data to the save file. - public readonly ManagedEvent Legacy_BeforeSave; - - /// Raised after the game finishes writing data to the save file. - public readonly ManagedEvent Legacy_AfterSave; - - /// Raised after the player loads a save slot. - public readonly ManagedEvent Legacy_AfterLoad; - - /// Raised after the game returns to the title screen. - public readonly ManagedEvent Legacy_AfterReturnToTitle; - - /**** - ** SpecialisedEvents - ****/ - /// Raised when the game updates its state (≈60 times per second), regardless of normal SMAPI validation. This event is not thread-safe and may be invoked while game logic is running asynchronously. Changes to game state in this method may crash the game or corrupt an in-progress save. Do not use this event unless you're fully aware of the context in which your code will be run. Mods using this method will trigger a stability warning in the SMAPI console. - public readonly ManagedEvent Legacy_UnvalidatedUpdateTick; - - /**** - ** TimeEvents - ****/ - /// Raised after the game begins a new day, including when loading a save. - public readonly ManagedEvent Legacy_AfterDayStarted; - - /// Raised after the in-game clock changes. - public readonly ManagedEvent Legacy_TimeOfDayChanged; -#endif - - /********* ** Public methods *********/ @@ -367,9 +174,6 @@ namespace StardewModdingAPI.Framework.Events { // create shortcut initialisers ManagedEvent ManageEventOf(string typeName, string eventName) => new ManagedEvent($"{typeName}.{eventName}", monitor, modRegistry); -#if !SMAPI_3_0_STRICT - ManagedEvent ManageEvent(string typeName, string eventName) => new ManagedEvent($"{typeName}.{eventName}", monitor, modRegistry); -#endif // init events (new) this.MenuChanged = ManageEventOf(nameof(IModEvents.Display), nameof(IDisplayEvents.MenuChanged)); @@ -422,70 +226,6 @@ namespace StardewModdingAPI.Framework.Events this.LoadStageChanged = ManageEventOf(nameof(IModEvents.Specialised), nameof(ISpecialisedEvents.LoadStageChanged)); this.UnvalidatedUpdateTicking = ManageEventOf(nameof(IModEvents.Specialised), nameof(ISpecialisedEvents.UnvalidatedUpdateTicking)); this.UnvalidatedUpdateTicked = ManageEventOf(nameof(IModEvents.Specialised), nameof(ISpecialisedEvents.UnvalidatedUpdateTicked)); - -#if !SMAPI_3_0_STRICT - // init events (old) - this.Legacy_LocaleChanged = ManageEventOf>(nameof(ContentEvents), nameof(ContentEvents.AfterLocaleChanged)); - - this.Legacy_ControllerButtonPressed = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.ControllerButtonPressed)); - this.Legacy_ControllerButtonReleased = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.ControllerButtonReleased)); - this.Legacy_ControllerTriggerPressed = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.ControllerTriggerPressed)); - this.Legacy_ControllerTriggerReleased = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.ControllerTriggerReleased)); - this.Legacy_KeyboardChanged = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.KeyboardChanged)); - this.Legacy_KeyPressed = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.KeyPressed)); - this.Legacy_KeyReleased = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.KeyReleased)); - this.Legacy_MouseChanged = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.MouseChanged)); - - this.Legacy_FirstUpdateTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.FirstUpdateTick)); - this.Legacy_UpdateTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.UpdateTick)); - this.Legacy_SecondUpdateTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.SecondUpdateTick)); - this.Legacy_FourthUpdateTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.FourthUpdateTick)); - this.Legacy_EighthUpdateTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.EighthUpdateTick)); - this.Legacy_QuarterSecondTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.QuarterSecondTick)); - this.Legacy_HalfSecondTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.HalfSecondTick)); - this.Legacy_OneSecondTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.OneSecondTick)); - - this.Legacy_Resize = ManageEvent(nameof(GraphicsEvents), nameof(GraphicsEvents.Resize)); - this.Legacy_OnPreRenderEvent = ManageEvent(nameof(GraphicsEvents), nameof(GraphicsEvents.OnPreRenderEvent)); - this.Legacy_OnPostRenderEvent = ManageEvent(nameof(GraphicsEvents), nameof(GraphicsEvents.OnPostRenderEvent)); - this.Legacy_OnPreRenderHudEvent = ManageEvent(nameof(GraphicsEvents), nameof(GraphicsEvents.OnPreRenderHudEvent)); - this.Legacy_OnPostRenderHudEvent = ManageEvent(nameof(GraphicsEvents), nameof(GraphicsEvents.OnPostRenderHudEvent)); - this.Legacy_OnPreRenderGuiEvent = ManageEvent(nameof(GraphicsEvents), nameof(GraphicsEvents.OnPreRenderGuiEvent)); - this.Legacy_OnPostRenderGuiEvent = ManageEvent(nameof(GraphicsEvents), nameof(GraphicsEvents.OnPostRenderGuiEvent)); - - this.Legacy_ButtonPressed = ManageEventOf(nameof(InputEvents), nameof(InputEvents.ButtonPressed)); - this.Legacy_ButtonReleased = ManageEventOf(nameof(InputEvents), nameof(InputEvents.ButtonReleased)); - - this.Legacy_LocationsChanged = ManageEventOf(nameof(LocationEvents), nameof(LocationEvents.LocationsChanged)); - this.Legacy_BuildingsChanged = ManageEventOf(nameof(LocationEvents), nameof(LocationEvents.BuildingsChanged)); - this.Legacy_ObjectsChanged = ManageEventOf(nameof(LocationEvents), nameof(LocationEvents.ObjectsChanged)); - - this.Legacy_MenuChanged = ManageEventOf(nameof(MenuEvents), nameof(MenuEvents.MenuChanged)); - this.Legacy_MenuClosed = ManageEventOf(nameof(MenuEvents), nameof(MenuEvents.MenuClosed)); - - this.Legacy_BeforeMainBroadcast = ManageEvent(nameof(MultiplayerEvents), nameof(MultiplayerEvents.BeforeMainBroadcast)); - this.Legacy_AfterMainBroadcast = ManageEvent(nameof(MultiplayerEvents), nameof(MultiplayerEvents.AfterMainBroadcast)); - this.Legacy_BeforeMainSync = ManageEvent(nameof(MultiplayerEvents), nameof(MultiplayerEvents.BeforeMainSync)); - this.Legacy_AfterMainSync = ManageEvent(nameof(MultiplayerEvents), nameof(MultiplayerEvents.AfterMainSync)); - - this.Legacy_MineLevelChanged = ManageEventOf(nameof(MineEvents), nameof(MineEvents.MineLevelChanged)); - - this.Legacy_InventoryChanged = ManageEventOf(nameof(PlayerEvents), nameof(PlayerEvents.InventoryChanged)); - this.Legacy_LeveledUp = ManageEventOf(nameof(PlayerEvents), nameof(PlayerEvents.LeveledUp)); - this.Legacy_PlayerWarped = ManageEventOf(nameof(PlayerEvents), nameof(PlayerEvents.Warped)); - - this.Legacy_BeforeCreateSave = ManageEvent(nameof(SaveEvents), nameof(SaveEvents.BeforeCreate)); - this.Legacy_AfterCreateSave = ManageEvent(nameof(SaveEvents), nameof(SaveEvents.AfterCreate)); - this.Legacy_BeforeSave = ManageEvent(nameof(SaveEvents), nameof(SaveEvents.BeforeSave)); - this.Legacy_AfterSave = ManageEvent(nameof(SaveEvents), nameof(SaveEvents.AfterSave)); - this.Legacy_AfterLoad = ManageEvent(nameof(SaveEvents), nameof(SaveEvents.AfterLoad)); - this.Legacy_AfterReturnToTitle = ManageEvent(nameof(SaveEvents), nameof(SaveEvents.AfterReturnToTitle)); - - this.Legacy_UnvalidatedUpdateTick = ManageEvent(nameof(SpecialisedEvents), nameof(SpecialisedEvents.UnvalidatedUpdateTick)); - - this.Legacy_AfterDayStarted = ManageEvent(nameof(TimeEvents), nameof(TimeEvents.AfterDayStarted)); - this.Legacy_TimeOfDayChanged = ManageEventOf(nameof(TimeEvents), nameof(TimeEvents.TimeOfDayChanged)); -#endif } } } diff --git a/src/SMAPI/Framework/Events/ManagedEvent.cs b/src/SMAPI/Framework/Events/ManagedEvent.cs index f9e7f6ec..2afe7a03 100644 --- a/src/SMAPI/Framework/Events/ManagedEvent.cs +++ b/src/SMAPI/Framework/Events/ManagedEvent.cs @@ -1,11 +1,12 @@ using System; +using System.Collections.Generic; using System.Linq; namespace StardewModdingAPI.Framework.Events { /// An event wrapper which intercepts and logs errors in handler code. /// The event arguments type. - internal class ManagedEvent : ManagedEventBase> + internal class ManagedEvent { /********* ** Fields @@ -13,6 +14,21 @@ namespace StardewModdingAPI.Framework.Events /// The underlying event. private event EventHandler Event; + /// A human-readable name for the event. + private readonly string EventName; + + /// Writes messages to the log. + private readonly IMonitor Monitor; + + /// The mod registry with which to identify mods. + protected readonly ModRegistry ModRegistry; + + /// The display names for the mods which added each delegate. + private readonly IDictionary, IModMetadata> SourceMods = new Dictionary, IModMetadata>(); + + /// The cached invocation list. + private EventHandler[] CachedInvocationList; + /********* ** Public methods @@ -22,7 +38,17 @@ namespace StardewModdingAPI.Framework.Events /// Writes messages to the log. /// The mod registry with which to identify mods. public ManagedEvent(string eventName, IMonitor monitor, ModRegistry modRegistry) - : base(eventName, monitor, modRegistry) { } + { + this.EventName = eventName; + this.Monitor = monitor; + this.ModRegistry = modRegistry; + } + + /// Get whether anything is listening to the event. + public bool HasListeners() + { + return this.CachedInvocationList?.Length > 0; + } /// Add an event handler. /// The event handler. @@ -91,71 +117,50 @@ namespace StardewModdingAPI.Framework.Events } } } - } - -#if !SMAPI_3_0_STRICT - /// An event wrapper which intercepts and logs errors in handler code. - internal class ManagedEvent : ManagedEventBase - { - /********* - ** Fields - *********/ - /// The underlying event. - private event EventHandler Event; /********* - ** Public methods + ** Private methods *********/ - /// Construct an instance. - /// A human-readable name for the event. - /// Writes messages to the log. - /// The mod registry with which to identify mods. - public ManagedEvent(string eventName, IMonitor monitor, ModRegistry modRegistry) - : base(eventName, monitor, modRegistry) { } - - /// Add an event handler. + /// Track an event handler. + /// The mod which added the handler. /// The event handler. - public void Add(EventHandler handler) + /// The updated event invocation list. + protected void AddTracking(IModMetadata mod, EventHandler handler, IEnumerable> invocationList) { - this.Add(handler, this.ModRegistry.GetFromStack()); + this.SourceMods[handler] = mod; + this.CachedInvocationList = invocationList?.ToArray() ?? new EventHandler[0]; } - /// Add an event handler. + /// Remove tracking for an event handler. /// The event handler. - /// The mod which added the event handler. - public void Add(EventHandler handler, IModMetadata mod) + /// The updated event invocation list. + protected void RemoveTracking(EventHandler handler, IEnumerable> invocationList) { - this.Event += handler; - this.AddTracking(mod, handler, this.Event?.GetInvocationList().Cast()); + this.CachedInvocationList = invocationList?.ToArray() ?? new EventHandler[0]; + if (!this.CachedInvocationList.Contains(handler)) // don't remove if there's still a reference to the removed handler (e.g. it was added twice and removed once) + this.SourceMods.Remove(handler); } - /// Remove an event handler. + /// Get the mod which registered the given event handler, if available. /// The event handler. - public void Remove(EventHandler handler) + protected IModMetadata GetSourceMod(EventHandler handler) { - this.Event -= handler; - this.RemoveTracking(handler, this.Event?.GetInvocationList().Cast()); + return this.SourceMods.TryGetValue(handler, out IModMetadata mod) + ? mod + : null; } - /// Raise the event and notify all handlers. - public void Raise() + /// Log an exception from an event handler. + /// The event handler instance. + /// The exception that was raised. + protected void LogError(EventHandler handler, Exception ex) { - if (this.Event == null) - return; - - foreach (EventHandler handler in this.CachedInvocationList) - { - try - { - handler.Invoke(null, EventArgs.Empty); - } - catch (Exception ex) - { - this.LogError(handler, ex); - } - } + IModMetadata mod = this.GetSourceMod(handler); + if (mod != null) + mod.LogAsMod($"This mod failed in the {this.EventName} event. Technical details: \n{ex.GetLogSummary()}", LogLevel.Error); + else + this.Monitor.Log($"A mod failed in the {this.EventName} event. Technical details: \n{ex.GetLogSummary()}", LogLevel.Error); } } -#endif } diff --git a/src/SMAPI/Framework/Events/ManagedEventBase.cs b/src/SMAPI/Framework/Events/ManagedEventBase.cs deleted file mode 100644 index c8c3516b..00000000 --- a/src/SMAPI/Framework/Events/ManagedEventBase.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace StardewModdingAPI.Framework.Events -{ - /// The base implementation for an event wrapper which intercepts and logs errors in handler code. - internal abstract class ManagedEventBase - { - /********* - ** Fields - *********/ - /// A human-readable name for the event. - private readonly string EventName; - - /// Writes messages to the log. - private readonly IMonitor Monitor; - - /// The mod registry with which to identify mods. - protected readonly ModRegistry ModRegistry; - - /// The display names for the mods which added each delegate. - private readonly IDictionary SourceMods = new Dictionary(); - - /// The cached invocation list. - protected TEventHandler[] CachedInvocationList { get; private set; } - - - /********* - ** Public methods - *********/ - /// Get whether anything is listening to the event. - public bool HasListeners() - { - return this.CachedInvocationList?.Length > 0; - } - - /********* - ** Protected methods - *********/ - /// Construct an instance. - /// A human-readable name for the event. - /// Writes messages to the log. - /// The mod registry with which to identify mods. - protected ManagedEventBase(string eventName, IMonitor monitor, ModRegistry modRegistry) - { - this.EventName = eventName; - this.Monitor = monitor; - this.ModRegistry = modRegistry; - } - - /// Track an event handler. - /// The mod which added the handler. - /// The event handler. - /// The updated event invocation list. - protected void AddTracking(IModMetadata mod, TEventHandler handler, IEnumerable invocationList) - { - this.SourceMods[handler] = mod; - this.CachedInvocationList = invocationList?.ToArray() ?? new TEventHandler[0]; - } - - /// Remove tracking for an event handler. - /// The event handler. - /// The updated event invocation list. - protected void RemoveTracking(TEventHandler handler, IEnumerable invocationList) - { - this.CachedInvocationList = invocationList?.ToArray() ?? new TEventHandler[0]; - if (!this.CachedInvocationList.Contains(handler)) // don't remove if there's still a reference to the removed handler (e.g. it was added twice and removed once) - this.SourceMods.Remove(handler); - } - - /// Get the mod which registered the given event handler, if available. - /// The event handler. - protected IModMetadata GetSourceMod(TEventHandler handler) - { - return this.SourceMods.TryGetValue(handler, out IModMetadata mod) - ? mod - : null; - } - - /// Log an exception from an event handler. - /// The event handler instance. - /// The exception that was raised. - protected void LogError(TEventHandler handler, Exception ex) - { - IModMetadata mod = this.GetSourceMod(handler); - if (mod != null) - mod.LogAsMod($"This mod failed in the {this.EventName} event. Technical details: \n{ex.GetLogSummary()}", LogLevel.Error); - else - this.Monitor.Log($"A mod failed in the {this.EventName} event. Technical details: \n{ex.GetLogSummary()}", LogLevel.Error); - } - } -} diff --git a/src/SMAPI/Framework/ModHelpers/ModHelper.cs b/src/SMAPI/Framework/ModHelpers/ModHelper.cs index 6c9838c9..86e8eb28 100644 --- a/src/SMAPI/Framework/ModHelpers/ModHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ModHelper.cs @@ -1,11 +1,8 @@ using System; -using System.Collections.Generic; using System.IO; using StardewModdingAPI.Events; using StardewModdingAPI.Framework.Input; using StardewModdingAPI.Toolkit.Serialisation; -using StardewModdingAPI.Toolkit.Serialisation.Models; -using StardewModdingAPI.Toolkit.Utilities; namespace StardewModdingAPI.Framework.ModHelpers { @@ -18,11 +15,6 @@ namespace StardewModdingAPI.Framework.ModHelpers /// The full path to the mod's folder. public string DirectoryPath { get; } -#if !SMAPI_3_0_STRICT - /// Encapsulates SMAPI's JSON file parsing. - private readonly JsonHelper JsonHelper; -#endif - /// Manages access to events raised by SMAPI, which let your mod react when something happens in the game. public IModEvents Events { get; } @@ -60,7 +52,6 @@ namespace StardewModdingAPI.Framework.ModHelpers /// Construct an instance. /// The mod's unique ID. /// The full path to the mod's folder. - /// Encapsulate SMAPI's JSON parsing. /// Manages the game's input state. /// Manages access to events raised by SMAPI. /// An API for loading content assets. @@ -73,7 +64,7 @@ namespace StardewModdingAPI.Framework.ModHelpers /// An API for reading translations stored in the mod's i18n folder. /// An argument is null or empty. /// The path does not exist on disk. - public ModHelper(string modID, string modDirectory, JsonHelper jsonHelper, SInputState inputState, IModEvents events, IContentHelper contentHelper, IContentPackHelper contentPackHelper, ICommandHelper commandHelper, IDataHelper dataHelper, IModRegistry modRegistry, IReflectionHelper reflectionHelper, IMultiplayerHelper multiplayer, ITranslationHelper translationHelper) + public ModHelper(string modID, string modDirectory, SInputState inputState, IModEvents events, IContentHelper contentHelper, IContentPackHelper contentPackHelper, ICommandHelper commandHelper, IDataHelper dataHelper, IModRegistry modRegistry, IReflectionHelper reflectionHelper, IMultiplayerHelper multiplayer, ITranslationHelper translationHelper) : base(modID) { // validate directory @@ -94,9 +85,6 @@ namespace StardewModdingAPI.Framework.ModHelpers this.Multiplayer = multiplayer ?? throw new ArgumentNullException(nameof(multiplayer)); this.Translation = translationHelper ?? throw new ArgumentNullException(nameof(translationHelper)); this.Events = events; -#if !SMAPI_3_0_STRICT - this.JsonHelper = jsonHelper ?? throw new ArgumentNullException(nameof(jsonHelper)); -#endif } /**** @@ -121,63 +109,6 @@ namespace StardewModdingAPI.Framework.ModHelpers this.Data.WriteJsonFile("config.json", config); } -#if !SMAPI_3_0_STRICT - /**** - ** Generic JSON files - ****/ - /// Read a JSON file. - /// The model type. - /// The file path relative to the mod directory. - /// Returns the deserialised model, or null if the file doesn't exist or is empty. - [Obsolete("Use " + nameof(ModHelper.Data) + "." + nameof(IDataHelper.ReadJsonFile) + " instead")] - public TModel ReadJsonFile(string path) - where TModel : class - { - path = Path.Combine(this.DirectoryPath, PathUtilities.NormalisePathSeparators(path)); - return this.JsonHelper.ReadJsonFileIfExists(path, out TModel data) - ? data - : null; - } - - /// Save to a JSON file. - /// The model type. - /// The file path relative to the mod directory. - /// The model to save. - [Obsolete("Use " + nameof(ModHelper.Data) + "." + nameof(IDataHelper.WriteJsonFile) + " instead")] - public void WriteJsonFile(string path, TModel model) - where TModel : class - { - path = Path.Combine(this.DirectoryPath, PathUtilities.NormalisePathSeparators(path)); - this.JsonHelper.WriteJsonFile(path, model); - } -#endif - - /**** - ** Content packs - ****/ -#if !SMAPI_3_0_STRICT - /// Manually create a transitional content pack to support pre-SMAPI content packs. This provides a way to access legacy content packs using the SMAPI content pack APIs, but the content pack will not be visible in the log or validated by SMAPI. - /// The absolute directory path containing the content pack files. - /// The content pack's unique ID. - /// The content pack name. - /// The content pack description. - /// The content pack author's name. - /// The content pack version. - [Obsolete("Use " + nameof(IModHelper) + "." + nameof(IModHelper.ContentPacks) + "." + nameof(IContentPackHelper.CreateTemporary) + " instead")] - public IContentPack CreateTransitionalContentPack(string directoryPath, string id, string name, string description, string author, ISemanticVersion version) - { - SCore.DeprecationManager.Warn($"{nameof(IModHelper)}.{nameof(IModHelper.CreateTransitionalContentPack)}", "2.5", DeprecationLevel.PendingRemoval); - return this.ContentPacks.CreateTemporary(directoryPath, id, name, description, author, version); - } - - /// Get all content packs loaded for this mod. - [Obsolete("Use " + nameof(IModHelper) + "." + nameof(IModHelper.ContentPacks) + "." + nameof(IContentPackHelper.GetOwned) + " instead")] - public IEnumerable GetContentPacks() - { - return this.ContentPacks.GetOwned(); - } -#endif - /**** ** Disposal ****/ diff --git a/src/SMAPI/Framework/ModLoading/ModResolver.cs b/src/SMAPI/Framework/ModLoading/ModResolver.cs index 75d3849d..f2002530 100644 --- a/src/SMAPI/Framework/ModLoading/ModResolver.cs +++ b/src/SMAPI/Framework/ModLoading/ModResolver.cs @@ -147,12 +147,8 @@ namespace StardewModdingAPI.Framework.ModLoading string actualFilename = new DirectoryInfo(mod.DirectoryPath).GetFiles(mod.Manifest.EntryDll).FirstOrDefault()?.Name; if (actualFilename != mod.Manifest.EntryDll) { -#if SMAPI_3_0_STRICT mod.SetStatus(ModMetadataStatus.Failed, $"its {nameof(IManifest.EntryDll)} value '{mod.Manifest.EntryDll}' doesn't match the actual file capitalisation '{actualFilename}'. The capitalisation must match for crossplatform compatibility."); continue; -#else - SCore.DeprecationManager.Warn(mod.DisplayName, $"{nameof(IManifest.EntryDll)} value with case-insensitive capitalisation", "2.11", DeprecationLevel.PendingRemoval); -#endif } } diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index 5dd52992..06a2e0af 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -190,24 +190,6 @@ namespace StardewModdingAPI.Framework // initialise SMAPI try { -#if !SMAPI_3_0_STRICT - // hook up events - ContentEvents.Init(this.EventManager); - ControlEvents.Init(this.EventManager); - GameEvents.Init(this.EventManager); - GraphicsEvents.Init(this.EventManager); - InputEvents.Init(this.EventManager); - LocationEvents.Init(this.EventManager); - MenuEvents.Init(this.EventManager); - MineEvents.Init(this.EventManager); - MultiplayerEvents.Init(this.EventManager); - PlayerEvents.Init(this.EventManager); - SaveEvents.Init(this.EventManager); - SpecialisedEvents.Init(this.EventManager); - TimeEvents.Init(this.EventManager); -#endif - - // init JSON parser JsonConverter[] converters = { new ColorConverter(), new PointConverter(), @@ -262,10 +244,6 @@ namespace StardewModdingAPI.Framework // set window titles this.GameInstance.Window.Title = $"Stardew Valley {Constants.GameVersion} - running SMAPI {Constants.ApiVersion}"; Console.Title = $"SMAPI {Constants.ApiVersion} - running Stardew Valley {Constants.GameVersion}"; -#if SMAPI_3_0_STRICT - this.GameInstance.Window.Title += " [SMAPI 3.0 strict mode]"; - Console.Title += " [SMAPI 3.0 strict mode]"; -#endif } catch (Exception ex) { @@ -375,9 +353,6 @@ namespace StardewModdingAPI.Framework private void InitialiseAfterGameStart() { // add headers -#if SMAPI_3_0_STRICT - this.Monitor.Log($"You're running SMAPI 3.0 strict mode, so most mods won't work correctly. If that wasn't intended, install the normal version of SMAPI from https://smapi.io instead.", LogLevel.Warn); -#endif if (this.Settings.DeveloperMode) this.Monitor.Log($"You have SMAPI for developers, so the console will be much more verbose. You can disable developer mode by installing the non-developer version of SMAPI, or by editing {Constants.ApiConfigPath}.", LogLevel.Info); if (!this.Settings.CheckForUpdates) @@ -439,11 +414,6 @@ namespace StardewModdingAPI.Framework int modsLoaded = this.ModRegistry.GetAll().Count(); this.GameInstance.Window.Title = $"Stardew Valley {Constants.GameVersion} - running SMAPI {Constants.ApiVersion} with {modsLoaded} mods"; Console.Title = $"SMAPI {Constants.ApiVersion} - running Stardew Valley {Constants.GameVersion} with {modsLoaded} mods"; -#if SMAPI_3_0_STRICT - this.GameInstance.Window.Title += " [SMAPI 3.0 strict mode]"; - Console.Title += " [SMAPI 3.0 strict mode]"; -#endif - // start SMAPI console new Thread(this.RunConsoleLoop).Start(); @@ -926,14 +896,6 @@ namespace StardewModdingAPI.Framework return false; } -#if !SMAPI_3_0_STRICT - // add deprecation warning for old version format - { - if (mod.Manifest?.Version is Toolkit.SemanticVersion version && version.IsLegacyFormat) - SCore.DeprecationManager.Warn(mod.DisplayName, "non-string manifest version", "2.8", DeprecationLevel.PendingRemoval); - } -#endif - // validate dependencies // Although dependences are validated before mods are loaded, a dependency may have failed to load. if (mod.Manifest.Dependencies?.Any() == true) @@ -1039,7 +1001,7 @@ namespace StardewModdingAPI.Framework return new ContentPack(packDirPath, packManifest, packContentHelper, this.Toolkit.JsonHelper); } - modHelper = new ModHelper(manifest.UniqueID, mod.DirectoryPath, this.Toolkit.JsonHelper, this.GameInstance.Input, events, contentHelper, contentPackHelper, commandHelper, dataHelper, modRegistryHelper, reflectionHelper, multiplayerHelper, translationHelper); + modHelper = new ModHelper(manifest.UniqueID, mod.DirectoryPath, this.GameInstance.Input, events, contentHelper, contentPackHelper, commandHelper, dataHelper, modRegistryHelper, reflectionHelper, multiplayerHelper, translationHelper); } // init mod diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index 704eb6bc..b35e1d71 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -9,9 +9,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -#if !SMAPI_3_0_STRICT -using Microsoft.Xna.Framework.Input; -#endif using Netcode; using StardewModdingAPI.Enums; using StardewModdingAPI.Events; @@ -228,12 +225,7 @@ namespace StardewModdingAPI.Framework // raise events this.Events.LoadStageChanged.Raise(new LoadStageChangedEventArgs(oldStage, newStage)); if (newStage == LoadStage.None) - { this.Events.ReturnedToTitle.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - this.Events.Legacy_AfterReturnToTitle.Raise(); -#endif - } } /// Constructor a content manager to read XNB files. @@ -344,9 +336,6 @@ namespace StardewModdingAPI.Framework SGame.TicksElapsed++; base.Update(gameTime); events.UnvalidatedUpdateTicked.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_UnvalidatedUpdateTick.Raise(); -#endif return; } @@ -393,9 +382,6 @@ namespace StardewModdingAPI.Framework // This should *always* run, even when suppressing mod events, since the game uses // this too. For example, doing this after mod event suppression would prevent the // user from doing anything on the overnight shipping screen. -#if !SMAPI_3_0_STRICT - SInputState previousInputState = this.Input.Clone(); -#endif SInputState inputState = this.Input; if (this.IsActive) inputState.TrueUpdate(); @@ -416,9 +402,6 @@ namespace StardewModdingAPI.Framework this.IsBetweenCreateEvents = true; this.Monitor.Log("Context: before save creation.", LogLevel.Trace); events.SaveCreating.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_BeforeCreateSave.Raise(); -#endif } // raise before-save @@ -427,9 +410,6 @@ namespace StardewModdingAPI.Framework this.IsBetweenSaveEvents = true; this.Monitor.Log("Context: before save.", LogLevel.Trace); events.Saving.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_BeforeSave.Raise(); -#endif } // suppress non-save events @@ -437,9 +417,6 @@ namespace StardewModdingAPI.Framework SGame.TicksElapsed++; base.Update(gameTime); events.UnvalidatedUpdateTicked.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_UnvalidatedUpdateTick.Raise(); -#endif return; } if (this.IsBetweenCreateEvents) @@ -449,9 +426,6 @@ namespace StardewModdingAPI.Framework this.Monitor.Log($"Context: after save creation, starting {Game1.currentSeason} {Game1.dayOfMonth} Y{Game1.year}.", LogLevel.Trace); this.OnLoadStageChanged(LoadStage.CreatedSaveFile); events.SaveCreated.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_AfterCreateSave.Raise(); -#endif } if (this.IsBetweenSaveEvents) { @@ -460,10 +434,6 @@ namespace StardewModdingAPI.Framework this.Monitor.Log($"Context: after save, starting {Game1.currentSeason} {Game1.dayOfMonth} Y{Game1.year}.", LogLevel.Trace); events.Saved.RaiseEmpty(); events.DayStarted.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_AfterSave.Raise(); - events.Legacy_AfterDayStarted.Raise(); -#endif } /********* @@ -492,15 +462,8 @@ namespace StardewModdingAPI.Framework *********/ if (this.Watchers.LocaleWatcher.IsChanged) { - var was = this.Watchers.LocaleWatcher.PreviousValue; - var now = this.Watchers.LocaleWatcher.CurrentValue; - - this.Monitor.Log($"Context: locale set to {now}.", LogLevel.Trace); - + this.Monitor.Log($"Context: locale set to {this.Watchers.LocaleWatcher.CurrentValue}.", LogLevel.Trace); this.OnLocaleChanged(); -#if !SMAPI_3_0_STRICT - events.Legacy_LocaleChanged.Raise(new EventArgsValueChanged(was.ToString(), now.ToString())); -#endif this.Watchers.LocaleWatcher.Reset(); } @@ -527,10 +490,6 @@ namespace StardewModdingAPI.Framework this.OnLoadStageChanged(LoadStage.Ready); events.SaveLoaded.RaiseEmpty(); events.DayStarted.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_AfterLoad.Raise(); - events.Legacy_AfterDayStarted.Raise(); -#endif } /********* @@ -549,9 +508,6 @@ namespace StardewModdingAPI.Framework Point newSize = this.Watchers.WindowSizeWatcher.CurrentValue; events.WindowResized.Raise(new WindowResizedEventArgs(oldSize, newSize)); -#if !SMAPI_3_0_STRICT - events.Legacy_Resize.Raise(); -#endif this.Watchers.WindowSizeWatcher.Reset(); } @@ -610,23 +566,6 @@ namespace StardewModdingAPI.Framework this.Monitor.Log($"Events: button {button} pressed.", LogLevel.Trace); events.ButtonPressed.Raise(new ButtonPressedEventArgs(button, cursor, inputState)); - -#if !SMAPI_3_0_STRICT - // legacy events - events.Legacy_ButtonPressed.Raise(new EventArgsInput(button, cursor, inputState.SuppressButtons)); - if (button.TryGetKeyboard(out Keys key)) - { - if (key != Keys.None) - events.Legacy_KeyPressed.Raise(new EventArgsKeyPressed(key)); - } - else if (button.TryGetController(out Buttons controllerButton)) - { - if (controllerButton == Buttons.LeftTrigger || controllerButton == Buttons.RightTrigger) - events.Legacy_ControllerTriggerPressed.Raise(new EventArgsControllerTriggerPressed(PlayerIndex.One, controllerButton, controllerButton == Buttons.LeftTrigger ? inputState.RealController.Triggers.Left : inputState.RealController.Triggers.Right)); - else - events.Legacy_ControllerButtonPressed.Raise(new EventArgsControllerButtonPressed(PlayerIndex.One, controllerButton)); - } -#endif } else if (status == InputStatus.Released) { @@ -634,33 +573,8 @@ namespace StardewModdingAPI.Framework this.Monitor.Log($"Events: button {button} released.", LogLevel.Trace); events.ButtonReleased.Raise(new ButtonReleasedEventArgs(button, cursor, inputState)); - -#if !SMAPI_3_0_STRICT - // legacy events - events.Legacy_ButtonReleased.Raise(new EventArgsInput(button, cursor, inputState.SuppressButtons)); - if (button.TryGetKeyboard(out Keys key)) - { - if (key != Keys.None) - events.Legacy_KeyReleased.Raise(new EventArgsKeyPressed(key)); - } - else if (button.TryGetController(out Buttons controllerButton)) - { - if (controllerButton == Buttons.LeftTrigger || controllerButton == Buttons.RightTrigger) - events.Legacy_ControllerTriggerReleased.Raise(new EventArgsControllerTriggerReleased(PlayerIndex.One, controllerButton, controllerButton == Buttons.LeftTrigger ? inputState.RealController.Triggers.Left : inputState.RealController.Triggers.Right)); - else - events.Legacy_ControllerButtonReleased.Raise(new EventArgsControllerButtonReleased(PlayerIndex.One, controllerButton)); - } -#endif } } - -#if !SMAPI_3_0_STRICT - // raise legacy state-changed events - if (inputState.RealKeyboard != previousInputState.RealKeyboard) - events.Legacy_KeyboardChanged.Raise(new EventArgsKeyboardStateChanged(previousInputState.RealKeyboard, inputState.RealKeyboard)); - if (inputState.RealMouse != previousInputState.RealMouse) - events.Legacy_MouseChanged.Raise(new EventArgsMouseStateChanged(previousInputState.RealMouse, inputState.RealMouse, new Point((int)previousInputState.CursorPosition.ScreenPixels.X, (int)previousInputState.CursorPosition.ScreenPixels.Y), new Point((int)inputState.CursorPosition.ScreenPixels.X, (int)inputState.CursorPosition.ScreenPixels.Y))); -#endif } } @@ -678,12 +592,6 @@ namespace StardewModdingAPI.Framework // raise menu events events.MenuChanged.Raise(new MenuChangedEventArgs(was, now)); -#if !SMAPI_3_0_STRICT - if (now != null) - events.Legacy_MenuChanged.Raise(new EventArgsClickableMenuChanged(was, now)); - else - events.Legacy_MenuClosed.Raise(new EventArgsClickableMenuClosed(was)); -#endif } /********* @@ -711,9 +619,6 @@ namespace StardewModdingAPI.Framework } events.LocationListChanged.Raise(new LocationListChangedEventArgs(added, removed)); -#if !SMAPI_3_0_STRICT - events.Legacy_LocationsChanged.Raise(new EventArgsLocationsChanged(added, removed)); -#endif } // raise location contents changed @@ -730,9 +635,6 @@ namespace StardewModdingAPI.Framework watcher.BuildingsWatcher.Reset(); events.BuildingListChanged.Raise(new BuildingListChangedEventArgs(location, added, removed)); -#if !SMAPI_3_0_STRICT - events.Legacy_BuildingsChanged.Raise(new EventArgsLocationBuildingsChanged(location, added, removed)); -#endif } // debris changed @@ -777,9 +679,6 @@ namespace StardewModdingAPI.Framework watcher.ObjectsWatcher.Reset(); events.ObjectListChanged.Raise(new ObjectListChangedEventArgs(location, added, removed)); -#if !SMAPI_3_0_STRICT - events.Legacy_ObjectsChanged.Raise(new EventArgsLocationObjectsChanged(location, added, removed)); -#endif } // terrain features changed @@ -809,9 +708,6 @@ namespace StardewModdingAPI.Framework this.Monitor.Log($"Events: time changed from {was} to {now}.", LogLevel.Trace); events.TimeChanged.Raise(new TimeChangedEventArgs(was, now)); -#if !SMAPI_3_0_STRICT - events.Legacy_TimeOfDayChanged.Raise(new EventArgsIntChanged(was, now)); -#endif } else this.Watchers.TimeWatcher.Reset(); @@ -829,9 +725,6 @@ namespace StardewModdingAPI.Framework GameLocation oldLocation = playerTracker.LocationWatcher.PreviousValue; events.Warped.Raise(new WarpedEventArgs(playerTracker.Player, oldLocation, newLocation)); -#if !SMAPI_3_0_STRICT - events.Legacy_PlayerWarped.Raise(new EventArgsPlayerWarped(oldLocation, newLocation)); -#endif } // raise player leveled up a skill @@ -841,9 +734,6 @@ namespace StardewModdingAPI.Framework this.Monitor.Log($"Events: player skill '{pair.Key}' changed from {pair.Value.PreviousValue} to {pair.Value.CurrentValue}.", LogLevel.Trace); events.LevelChanged.Raise(new LevelChangedEventArgs(playerTracker.Player, pair.Key, pair.Value.PreviousValue, pair.Value.CurrentValue)); -#if !SMAPI_3_0_STRICT - events.Legacy_LeveledUp.Raise(new EventArgsLevelUp((EventArgsLevelUp.LevelType)pair.Key, pair.Value.CurrentValue)); -#endif } // raise player inventory changed @@ -853,9 +743,6 @@ namespace StardewModdingAPI.Framework if (this.Monitor.IsVerbose) this.Monitor.Log("Events: player inventory changed.", LogLevel.Trace); events.InventoryChanged.Raise(new InventoryChangedEventArgs(playerTracker.Player, changedItems)); -#if !SMAPI_3_0_STRICT - events.Legacy_InventoryChanged.Raise(new EventArgsInventoryChanged(Game1.player.Items, changedItems)); -#endif } // raise mine level changed @@ -863,9 +750,6 @@ namespace StardewModdingAPI.Framework { if (this.Monitor.IsVerbose) this.Monitor.Log($"Context: mine level changed to {mineLevel}.", LogLevel.Trace); -#if !SMAPI_3_0_STRICT - events.Legacy_MineLevelChanged.Raise(new EventArgsMineLevelChanged(playerTracker.MineLevelWatcher.PreviousValue, mineLevel)); -#endif } } this.Watchers.CurrentPlayerTracker?.Reset(); @@ -910,25 +794,6 @@ namespace StardewModdingAPI.Framework /********* ** Update events *********/ -#if !SMAPI_3_0_STRICT - events.Legacy_UnvalidatedUpdateTick.Raise(); - if (isFirstTick) - events.Legacy_FirstUpdateTick.Raise(); - events.Legacy_UpdateTick.Raise(); - if (SGame.TicksElapsed % 2 == 0) - events.Legacy_SecondUpdateTick.Raise(); - if (SGame.TicksElapsed % 4 == 0) - events.Legacy_FourthUpdateTick.Raise(); - if (SGame.TicksElapsed % 8 == 0) - events.Legacy_EighthUpdateTick.Raise(); - if (SGame.TicksElapsed % 15 == 0) - events.Legacy_QuarterSecondTick.Raise(); - if (SGame.TicksElapsed % 30 == 0) - events.Legacy_HalfSecondTick.Raise(); - if (SGame.TicksElapsed % 60 == 0) - events.Legacy_OneSecondTick.Raise(); -#endif - this.UpdateCrashTimer.Reset(); } catch (Exception ex) @@ -1014,14 +879,8 @@ namespace StardewModdingAPI.Framework try { events.RenderingActiveMenu.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_OnPreRenderGuiEvent.Raise(); -#endif activeClickableMenu.draw(Game1.spriteBatch); events.RenderedActiveMenu.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_OnPostRenderGuiEvent.Raise(); -#endif } catch (Exception ex) { @@ -1029,10 +888,6 @@ namespace StardewModdingAPI.Framework activeClickableMenu.exitThisMenu(); } events.Rendered.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_OnPostRenderEvent.Raise(); -#endif - Game1.spriteBatch.End(); } if (Game1.overlayMenu != null) @@ -1055,14 +910,8 @@ namespace StardewModdingAPI.Framework { Game1.activeClickableMenu.drawBackground(Game1.spriteBatch); events.RenderingActiveMenu.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_OnPreRenderGuiEvent.Raise(); -#endif Game1.activeClickableMenu.draw(Game1.spriteBatch); events.RenderedActiveMenu.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_OnPostRenderGuiEvent.Raise(); -#endif } catch (Exception ex) { @@ -1070,9 +919,6 @@ namespace StardewModdingAPI.Framework Game1.activeClickableMenu.exitThisMenu(); } events.Rendered.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_OnPostRenderEvent.Raise(); -#endif Game1.spriteBatch.End(); this.drawOverlays(Game1.spriteBatch); if ((double)Game1.options.zoomLevel != 1.0) @@ -1097,9 +943,6 @@ namespace StardewModdingAPI.Framework Game1.spriteBatch.DrawString(Game1.dialogueFont, Game1.content.LoadString("Strings\\StringsFromCSFiles:Game1.cs.3686"), new Vector2(16f, 32f), new Color(0, (int)byte.MaxValue, 0)); Game1.spriteBatch.DrawString(Game1.dialogueFont, Game1.parseText(Game1.errorMessage, Game1.dialogueFont, Game1.graphics.GraphicsDevice.Viewport.Width), new Vector2(16f, 48f), Color.White); events.Rendered.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_OnPostRenderEvent.Raise(); -#endif Game1.spriteBatch.End(); } else if (Game1.currentMinigame != null) @@ -1112,9 +955,6 @@ namespace StardewModdingAPI.Framework Game1.spriteBatch.End(); } this.drawOverlays(Game1.spriteBatch); -#if !SMAPI_3_0_STRICT - this.RaisePostRender(needsNewBatch: true); -#endif if ((double)Game1.options.zoomLevel == 1.0) return; this.GraphicsDevice.SetRenderTarget((RenderTarget2D)null); @@ -1132,14 +972,8 @@ namespace StardewModdingAPI.Framework try { events.RenderingActiveMenu.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_OnPreRenderGuiEvent.Raise(); -#endif Game1.activeClickableMenu.draw(Game1.spriteBatch); events.RenderedActiveMenu.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_OnPostRenderGuiEvent.Raise(); -#endif } catch (Exception ex) { @@ -1229,9 +1063,6 @@ namespace StardewModdingAPI.Framework if (++batchOpens == 1) events.Rendering.RaiseEmpty(); events.RenderingWorld.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_OnPreRenderEvent.Raise(); -#endif if (Game1.background != null) Game1.background.draw(Game1.spriteBatch); Game1.mapDisplayDevice.BeginScene(Game1.spriteBatch); @@ -1389,7 +1220,7 @@ namespace StardewModdingAPI.Framework } Game1.drawPlayerHeldObject(Game1.player); } - label_129: + label_129: if ((Game1.player.UsingTool || Game1.pickingTool) && Game1.player.CurrentTool != null && ((!Game1.player.CurrentTool.Name.Equals("Seeds") || Game1.pickingTool) && (Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.getStandingX(), (int)Game1.player.Position.Y - 38), Game1.viewport.Size) != null && Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.getStandingX(), Game1.player.getStandingY()), Game1.viewport.Size) == null))) Game1.drawTool(Game1.player); if (Game1.currentLocation.Map.GetLayer("AlwaysFront") != null) @@ -1544,14 +1375,8 @@ namespace StardewModdingAPI.Framework if ((Game1.displayHUD || Game1.eventUp) && (Game1.currentBillboard == 0 && Game1.gameMode == (byte)3) && (!Game1.freezeControls && !Game1.panMode && !Game1.HostPaused)) { events.RenderingHud.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_OnPreRenderHudEvent.Raise(); -#endif this.drawHUD(); events.RenderedHud.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_OnPostRenderHudEvent.Raise(); -#endif } else if (Game1.activeClickableMenu == null && Game1.farmEvent == null) Game1.spriteBatch.Draw(Game1.mouseCursors, new Vector2((float)Game1.getOldMouseX(), (float)Game1.getOldMouseY()), new Microsoft.Xna.Framework.Rectangle?(Game1.getSourceRectForStandardTileSheet(Game1.mouseCursors, 0, 16, 16)), Color.White, 0.0f, Vector2.Zero, (float)(4.0 + (double)Game1.dialogueButtonScale / 150.0), SpriteEffects.None, 1f); @@ -1660,14 +1485,8 @@ namespace StardewModdingAPI.Framework try { events.RenderingActiveMenu.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_OnPreRenderGuiEvent.Raise(); -#endif Game1.activeClickableMenu.draw(Game1.spriteBatch); events.RenderedActiveMenu.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_OnPostRenderGuiEvent.Raise(); -#endif } catch (Exception ex) { @@ -1684,9 +1503,6 @@ namespace StardewModdingAPI.Framework } events.Rendered.RaiseEmpty(); -#if !SMAPI_3_0_STRICT - events.Legacy_OnPostRenderEvent.Raise(); -#endif Game1.spriteBatch.End(); this.drawOverlays(Game1.spriteBatch); this.renderScreenBuffer(); @@ -1694,24 +1510,5 @@ namespace StardewModdingAPI.Framework } } } - - /**** - ** Methods - ****/ -#if !SMAPI_3_0_STRICT - /// Raise the if there are any listeners. - /// Whether to create a new sprite batch. - private void RaisePostRender(bool needsNewBatch = false) - { - if (this.Events.Legacy_OnPostRenderEvent.HasListeners()) - { - if (needsNewBatch) - Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - this.Events.Legacy_OnPostRenderEvent.Raise(); - if (needsNewBatch) - Game1.spriteBatch.End(); - } - } -#endif } } diff --git a/src/SMAPI/Framework/SMultiplayer.cs b/src/SMAPI/Framework/SMultiplayer.cs index dde71092..ffe2320b 100644 --- a/src/SMAPI/Framework/SMultiplayer.cs +++ b/src/SMAPI/Framework/SMultiplayer.cs @@ -89,24 +89,6 @@ namespace StardewModdingAPI.Framework this.HostPeer = null; } -#if !SMAPI_3_0_STRICT - /// Handle sync messages from other players and perform other initial sync logic. - public override void UpdateEarly() - { - this.EventManager.Legacy_BeforeMainSync.Raise(); - base.UpdateEarly(); - this.EventManager.Legacy_AfterMainSync.Raise(); - } - - /// Broadcast sync messages to other players and perform other final sync logic. - public override void UpdateLate(bool forceSync = false) - { - this.EventManager.Legacy_BeforeMainBroadcast.Raise(); - base.UpdateLate(forceSync); - this.EventManager.Legacy_AfterMainBroadcast.Raise(); - } -#endif - /// Initialise a client before the game connects to a remote server. /// The client to initialise. public override Client InitClient(Client client) diff --git a/src/SMAPI/IAssetDataForDictionary.cs b/src/SMAPI/IAssetDataForDictionary.cs index 911599d9..1136316f 100644 --- a/src/SMAPI/IAssetDataForDictionary.cs +++ b/src/SMAPI/IAssetDataForDictionary.cs @@ -1,32 +1,7 @@ -using System; using System.Collections.Generic; -using StardewModdingAPI.Framework.Content; namespace StardewModdingAPI { /// Encapsulates access and changes to dictionary content being read from a data file. - public interface IAssetDataForDictionary : IAssetData> - { -#if !SMAPI_3_0_STRICT - /********* - ** Public methods - *********/ - /// Add or replace an entry in the dictionary. - /// The entry key. - /// The entry value. - [Obsolete("Access " + nameof(AssetData>.Data) + "field directly.")] - void Set(TKey key, TValue value); - - /// Add or replace an entry in the dictionary. - /// The entry key. - /// A callback which accepts the current value and returns the new value. - [Obsolete("Access " + nameof(AssetData>.Data) + "field directly.")] - void Set(TKey key, Func value); - - /// Dynamically replace values in the dictionary. - /// A lambda which takes the current key and value for an entry, and returns the new value. - [Obsolete("Access " + nameof(AssetData>.Data) + "field directly.")] - void Set(Func replacer); -#endif - } + public interface IAssetDataForDictionary : IAssetData> { } } diff --git a/src/SMAPI/IModHelper.cs b/src/SMAPI/IModHelper.cs index 0220b4f7..cd746e06 100644 --- a/src/SMAPI/IModHelper.cs +++ b/src/SMAPI/IModHelper.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using StardewModdingAPI.Events; namespace StardewModdingAPI @@ -58,41 +56,5 @@ namespace StardewModdingAPI /// The config class type. /// The config settings to save. void WriteConfig(TConfig config) where TConfig : class, new(); - -#if !SMAPI_3_0_STRICT - /**** - ** Generic JSON files - ****/ - /// Read a JSON file. - /// The model type. - /// The file path relative to the mod directory. - /// Returns the deserialised model, or null if the file doesn't exist or is empty. - [Obsolete("Use " + nameof(IModHelper.Data) + "." + nameof(IDataHelper.ReadJsonFile) + " instead")] - TModel ReadJsonFile(string path) where TModel : class; - - /// Save to a JSON file. - /// The model type. - /// The file path relative to the mod directory. - /// The model to save. - [Obsolete("Use " + nameof(IModHelper.Data) + "." + nameof(IDataHelper.WriteJsonFile) + " instead")] - void WriteJsonFile(string path, TModel model) where TModel : class; - - /**** - ** Content packs - ****/ - /// Manually create a transitional content pack to support pre-SMAPI content packs. This provides a way to access legacy content packs using the SMAPI content pack APIs, but the content pack will not be visible in the log or validated by SMAPI. - /// The absolute directory path containing the content pack files. - /// The content pack's unique ID. - /// The content pack name. - /// The content pack description. - /// The content pack author's name. - /// The content pack version. - [Obsolete("Use " + nameof(IModHelper) + "." + nameof(IModHelper.ContentPacks) + "." + nameof(IContentPackHelper.CreateTemporary) + " instead")] - IContentPack CreateTransitionalContentPack(string directoryPath, string id, string name, string description, string author, ISemanticVersion version); - - /// Get all content packs loaded for this mod. - [Obsolete("Use " + nameof(IModHelper) + "." + nameof(IModHelper.ContentPacks) + "." + nameof(IContentPackHelper.GetOwned) + " instead")] - IEnumerable GetContentPacks(); -#endif } } diff --git a/src/SMAPI/Metadata/InstructionMetadata.cs b/src/SMAPI/Metadata/InstructionMetadata.cs index 272ceb09..72410d41 100644 --- a/src/SMAPI/Metadata/InstructionMetadata.cs +++ b/src/SMAPI/Metadata/InstructionMetadata.cs @@ -53,9 +53,6 @@ namespace StardewModdingAPI.Metadata yield return new FieldFinder(typeof(SaveGame).FullName, nameof(SaveGame.locationSerializer), InstructionHandleResult.DetectedSaveSerialiser); yield return new EventFinder(typeof(ISpecialisedEvents).FullName, nameof(ISpecialisedEvents.UnvalidatedUpdateTicked), InstructionHandleResult.DetectedUnvalidatedUpdateTick); yield return new EventFinder(typeof(ISpecialisedEvents).FullName, nameof(ISpecialisedEvents.UnvalidatedUpdateTicking), InstructionHandleResult.DetectedUnvalidatedUpdateTick); -#if !SMAPI_3_0_STRICT - yield return new EventFinder(typeof(SpecialisedEvents).FullName, nameof(SpecialisedEvents.UnvalidatedUpdateTick), InstructionHandleResult.DetectedUnvalidatedUpdateTick); -#endif /**** ** detect paranoid issues diff --git a/src/SMAPI/SemanticVersion.cs b/src/SMAPI/SemanticVersion.cs index ec2d9e40..acdc92f8 100644 --- a/src/SMAPI/SemanticVersion.cs +++ b/src/SMAPI/SemanticVersion.cs @@ -1,6 +1,5 @@ using System; using Newtonsoft.Json; -using StardewModdingAPI.Framework; namespace StardewModdingAPI { @@ -26,19 +25,6 @@ namespace StardewModdingAPI /// The patch version for backwards-compatible bug fixes. public int PatchVersion => this.Version.PatchVersion; -#if !SMAPI_3_0_STRICT - /// An optional build tag. - [Obsolete("Use " + nameof(ISemanticVersion.PrereleaseTag) + " instead")] - public string Build - { - get - { - SCore.DeprecationManager?.Warn($"{nameof(ISemanticVersion)}.{nameof(ISemanticVersion.Build)}", "2.8", DeprecationLevel.PendingRemoval); - return this.Version.PrereleaseTag; - } - } -#endif - /// An optional prerelease tag. public string PrereleaseTag => this.Version.PrereleaseTag; -- cgit From dc0556ff5feead4ced16b82f407b6b271cbb3d30 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Thu, 7 Mar 2019 18:19:11 -0500 Subject: fix log level for multiplayer 'received message' logs --- docs/release-notes.md | 1 + src/SMAPI/Framework/SMultiplayer.cs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 2f01ee93..c10e663d 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -5,6 +5,7 @@ These changes have not been released yet. * For players: * Fixed Save Backup not pruning old backups if they're uncompressed. * Fixed issues when a farmhand reconnects before the game notices they're disconnected. + * Fixed 'received message' logs shown in non-developer mode. * For modders: * Added `IContentPack.HasFile` method. diff --git a/src/SMAPI/Framework/SMultiplayer.cs b/src/SMAPI/Framework/SMultiplayer.cs index ffe2320b..382910a0 100644 --- a/src/SMAPI/Framework/SMultiplayer.cs +++ b/src/SMAPI/Framework/SMultiplayer.cs @@ -433,7 +433,7 @@ namespace StardewModdingAPI.Framework ModMessageModel model = this.JsonHelper.Deserialise(json); HashSet playerIDs = new HashSet(model.ToPlayerIDs ?? this.GetKnownPlayerIDs()); if (this.Monitor.IsVerbose) - this.Monitor.Log($"Received message: {json}."); + this.Monitor.Log($"Received message: {json}.", LogLevel.Trace); // notify local mods if (playerIDs.Contains(Game1.player.UniqueMultiplayerID)) -- cgit From 332bcfa5a19509352aa417a04a677b5701c16986 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Thu, 21 Mar 2019 23:12:26 -0400 Subject: add content pack translations --- docs/release-notes.md | 1 + src/SMAPI/Framework/ContentPack.cs | 7 +++++- src/SMAPI/Framework/IModMetadata.cs | 10 ++++++-- src/SMAPI/Framework/ModLoading/ModMetadata.cs | 12 ++++++++-- src/SMAPI/Framework/SCore.cs | 33 +++++++++++++-------------- src/SMAPI/IContentPack.cs | 3 +++ 6 files changed, 44 insertions(+), 22 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index c10e663d..afcf0066 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -8,6 +8,7 @@ These changes have not been released yet. * Fixed 'received message' logs shown in non-developer mode. * For modders: + * Added support for content pack translations. * Added `IContentPack.HasFile` method. * Dropped support for all deprecated APIs. * Updated to Json.NET 12.0.1. diff --git a/src/SMAPI/Framework/ContentPack.cs b/src/SMAPI/Framework/ContentPack.cs index 5384d98f..829a7dc1 100644 --- a/src/SMAPI/Framework/ContentPack.cs +++ b/src/SMAPI/Framework/ContentPack.cs @@ -30,6 +30,9 @@ namespace StardewModdingAPI.Framework /// The content pack's manifest. public IManifest Manifest { get; } + /// Provides translations stored in the content pack's i18n folder. See for more info. + public ITranslationHelper Translation { get; } + /********* ** Public methods @@ -38,12 +41,14 @@ namespace StardewModdingAPI.Framework /// The full path to the content pack's folder. /// The content pack's manifest. /// Provides an API for loading content assets. + /// Provides translations stored in the content pack's i18n folder. /// Encapsulates SMAPI's JSON file parsing. - public ContentPack(string directoryPath, IManifest manifest, IContentHelper content, JsonHelper jsonHelper) + public ContentPack(string directoryPath, IManifest manifest, IContentHelper content, ITranslationHelper translation, JsonHelper jsonHelper) { this.DirectoryPath = directoryPath; this.Manifest = manifest; this.Content = content; + this.Translation = translation; this.JsonHelper = jsonHelper; } diff --git a/src/SMAPI/Framework/IModMetadata.cs b/src/SMAPI/Framework/IModMetadata.cs index 38514959..32870c2a 100644 --- a/src/SMAPI/Framework/IModMetadata.cs +++ b/src/SMAPI/Framework/IModMetadata.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using StardewModdingAPI.Framework.ModHelpers; using StardewModdingAPI.Framework.ModLoading; using StardewModdingAPI.Toolkit.Framework.Clients.WebApi; using StardewModdingAPI.Toolkit.Framework.ModData; @@ -42,6 +43,9 @@ namespace StardewModdingAPI.Framework /// The content pack instance (if loaded and is true). IContentPack ContentPack { get; } + /// The translations for this mod (if loaded). + TranslationHelper Translations { get; } + /// Writes messages to the console and log file as this mod. IMonitor Monitor { get; } @@ -67,12 +71,14 @@ namespace StardewModdingAPI.Framework /// Set the mod instance. /// The mod instance to set. - IModMetadata SetMod(IMod mod); + /// The translations for this mod (if loaded). + IModMetadata SetMod(IMod mod, TranslationHelper translations); /// Set the mod instance. /// The contentPack instance to set. /// Writes messages to the console and log file. - IModMetadata SetMod(IContentPack contentPack, IMonitor monitor); + /// The translations for this mod (if loaded). + IModMetadata SetMod(IContentPack contentPack, IMonitor monitor, TranslationHelper translations); /// Set the mod-provided API instance. /// The mod-provided API. diff --git a/src/SMAPI/Framework/ModLoading/ModMetadata.cs b/src/SMAPI/Framework/ModLoading/ModMetadata.cs index 4ff021b7..39f2f482 100644 --- a/src/SMAPI/Framework/ModLoading/ModMetadata.cs +++ b/src/SMAPI/Framework/ModLoading/ModMetadata.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using StardewModdingAPI.Framework.ModHelpers; using StardewModdingAPI.Toolkit.Framework.Clients.WebApi; using StardewModdingAPI.Toolkit.Framework.ModData; using StardewModdingAPI.Toolkit.Framework.UpdateData; @@ -46,6 +47,9 @@ namespace StardewModdingAPI.Framework.ModLoading /// The content pack instance (if loaded and is true). public IContentPack ContentPack { get; private set; } + /// The translations for this mod (if loaded). + public TranslationHelper Translations { get; private set; } + /// Writes messages to the console and log file as this mod. public IMonitor Monitor { get; private set; } @@ -100,26 +104,30 @@ namespace StardewModdingAPI.Framework.ModLoading /// Set the mod instance. /// The mod instance to set. - public IModMetadata SetMod(IMod mod) + /// The translations for this mod (if loaded). + public IModMetadata SetMod(IMod mod, TranslationHelper translations) { if (this.ContentPack != null) throw new InvalidOperationException("A mod can't be both an assembly mod and content pack."); this.Mod = mod; this.Monitor = mod.Monitor; + this.Translations = translations; return this; } /// Set the mod instance. /// The contentPack instance to set. /// Writes messages to the console and log file. - public IModMetadata SetMod(IContentPack contentPack, IMonitor monitor) + /// The translations for this mod (if loaded). + public IModMetadata SetMod(IContentPack contentPack, IMonitor monitor, TranslationHelper translations) { if (this.Mod != null) throw new InvalidOperationException("A mod can't be both an assembly mod and content pack."); this.ContentPack = contentPack; this.Monitor = monitor; + this.Translations = translations; return this; } diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index 06a2e0af..2f0e0f05 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -427,8 +427,8 @@ namespace StardewModdingAPI.Framework LocalizedContentManager.LanguageCode languageCode = this.ContentCore.Language; // update mod translation helpers - foreach (IModMetadata mod in this.ModRegistry.GetAll(contentPacks: false)) - (mod.Mod.Helper.Translation as TranslationHelper)?.SetLocale(locale, languageCode); + foreach (IModMetadata mod in this.ModRegistry.GetAll()) + mod.Translations.SetLocale(locale, languageCode); } /// Run a loop handling console input. @@ -725,8 +725,9 @@ namespace StardewModdingAPI.Framework LogSkip(contentPack, errorPhrase, errorDetails); } } - IModMetadata[] loadedContentPacks = this.ModRegistry.GetAll(assemblyMods: false).ToArray(); - IModMetadata[] loadedMods = this.ModRegistry.GetAll(contentPacks: false).ToArray(); + IModMetadata[] loaded = this.ModRegistry.GetAll().ToArray(); + IModMetadata[] loadedContentPacks = loaded.Where(p => p.IsContentPack).ToArray(); + IModMetadata[] loadedMods = loaded.Where(p => !p.IsContentPack).ToArray(); // unlock content packs this.ModRegistry.AreAllModsLoaded = true; @@ -766,10 +767,10 @@ namespace StardewModdingAPI.Framework } // log mod warnings - this.LogModWarnings(this.ModRegistry.GetAll().ToArray(), skippedMods); + this.LogModWarnings(loaded, skippedMods); // initialise translations - this.ReloadTranslations(loadedMods); + this.ReloadTranslations(loaded); // initialise loaded non-content-pack mods foreach (IModMetadata metadata in loadedMods) @@ -919,8 +920,9 @@ namespace StardewModdingAPI.Framework IManifest manifest = mod.Manifest; IMonitor monitor = this.GetSecondaryMonitor(mod.DisplayName); IContentHelper contentHelper = new ContentHelper(this.ContentCore, mod.DirectoryPath, manifest.UniqueID, mod.DisplayName, monitor); - IContentPack contentPack = new ContentPack(mod.DirectoryPath, manifest, contentHelper, jsonHelper); - mod.SetMod(contentPack, monitor); + TranslationHelper translationHelper = new TranslationHelper(manifest.UniqueID, manifest.Name, contentCore.GetLocale(), contentCore.Language); + IContentPack contentPack = new ContentPack(mod.DirectoryPath, manifest, contentHelper, translationHelper, jsonHelper); + mod.SetMod(contentPack, monitor, translationHelper); this.ModRegistry.Add(mod); errorReasonPhrase = null; @@ -982,6 +984,7 @@ namespace StardewModdingAPI.Framework // init mod helpers IMonitor monitor = this.GetSecondaryMonitor(mod.DisplayName); + TranslationHelper translationHelper = new TranslationHelper(manifest.UniqueID, manifest.Name, contentCore.GetLocale(), contentCore.Language); IModHelper modHelper; { IModEvents events = new ModEvents(mod, this.EventManager); @@ -992,13 +995,13 @@ namespace StardewModdingAPI.Framework IReflectionHelper reflectionHelper = new ReflectionHelper(manifest.UniqueID, mod.DisplayName, this.Reflection); IModRegistry modRegistryHelper = new ModRegistryHelper(manifest.UniqueID, this.ModRegistry, proxyFactory, monitor); IMultiplayerHelper multiplayerHelper = new MultiplayerHelper(manifest.UniqueID, this.GameInstance.Multiplayer); - ITranslationHelper translationHelper = new TranslationHelper(manifest.UniqueID, manifest.Name, contentCore.GetLocale(), contentCore.Language); IContentPack CreateFakeContentPack(string packDirPath, IManifest packManifest) { IMonitor packMonitor = this.GetSecondaryMonitor(packManifest.Name); IContentHelper packContentHelper = new ContentHelper(contentCore, packDirPath, packManifest.UniqueID, packManifest.Name, packMonitor); - return new ContentPack(packDirPath, packManifest, packContentHelper, this.Toolkit.JsonHelper); + ITranslationHelper packTranslationHelper = new TranslationHelper(packManifest.UniqueID, packManifest.Name, contentCore.GetLocale(), contentCore.Language); + return new ContentPack(packDirPath, packManifest, packContentHelper, packTranslationHelper, this.Toolkit.JsonHelper); } modHelper = new ModHelper(manifest.UniqueID, mod.DirectoryPath, this.GameInstance.Input, events, contentHelper, contentPackHelper, commandHelper, dataHelper, modRegistryHelper, reflectionHelper, multiplayerHelper, translationHelper); @@ -1010,7 +1013,7 @@ namespace StardewModdingAPI.Framework modEntry.Monitor = monitor; // track mod - mod.SetMod(modEntry); + mod.SetMod(modEntry, translationHelper); this.ModRegistry.Add(mod); return true; } @@ -1025,7 +1028,7 @@ namespace StardewModdingAPI.Framework /// Write a summary of mod warnings to the console and log. /// The loaded mods. /// The mods which were skipped, along with the friendly and developer reasons. - private void LogModWarnings(IModMetadata[] mods, IDictionary> skippedMods) + private void LogModWarnings(IEnumerable mods, IDictionary> skippedMods) { // get mods with warnings IModMetadata[] modsWithWarnings = mods.Where(p => p.Warnings != ModWarning.None).ToArray(); @@ -1165,9 +1168,6 @@ namespace StardewModdingAPI.Framework JsonHelper jsonHelper = this.Toolkit.JsonHelper; foreach (IModMetadata metadata in mods) { - if (metadata.IsContentPack) - throw new InvalidOperationException("Can't reload translations for a content pack."); - // read translation files IDictionary> translations = new Dictionary>(); DirectoryInfo translationsDir = new DirectoryInfo(Path.Combine(metadata.DirectoryPath, "i18n")); @@ -1217,8 +1217,7 @@ namespace StardewModdingAPI.Framework } // update translation - TranslationHelper translationHelper = (TranslationHelper)metadata.Mod.Helper.Translation; - translationHelper.SetTranslations(translations); + metadata.Translations.SetTranslations(translations); } } diff --git a/src/SMAPI/IContentPack.cs b/src/SMAPI/IContentPack.cs index 32cbc6fc..7085c538 100644 --- a/src/SMAPI/IContentPack.cs +++ b/src/SMAPI/IContentPack.cs @@ -17,6 +17,9 @@ namespace StardewModdingAPI /// The content pack's manifest. IManifest Manifest { get; } + /// Provides translations stored in the content pack's i18n folder. See for more info. + ITranslationHelper Translation { get; } + /********* ** Public methods -- cgit From f78502a3a4a133b93cf9bf01eb426867e7798045 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Thu, 21 Mar 2019 23:14:31 -0400 Subject: fix incorrect input check, update release notes --- docs/release-notes.md | 1 + src/SMAPI/Framework/Input/SInputState.cs | 3 +++ 2 files changed, 4 insertions(+) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index afcf0066..4fb7b6c3 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -3,6 +3,7 @@ These changes have not been released yet. * For players: + * Improved performance. * Fixed Save Backup not pruning old backups if they're uncompressed. * Fixed issues when a farmhand reconnects before the game notices they're disconnected. * Fixed 'received message' logs shown in non-developer mode. diff --git a/src/SMAPI/Framework/Input/SInputState.cs b/src/SMAPI/Framework/Input/SInputState.cs index 96a7003a..a15272d5 100644 --- a/src/SMAPI/Framework/Input/SInputState.cs +++ b/src/SMAPI/Framework/Input/SInputState.cs @@ -94,7 +94,10 @@ namespace StardewModdingAPI.Framework.Input this.RealKeyboard = realKeyboard; this.RealMouse = realMouse; if (cursorAbsolutePos != this.CursorPositionImpl?.AbsolutePixels || playerTilePos != this.LastPlayerTile) + { + this.LastPlayerTile = playerTilePos; this.CursorPositionImpl = this.GetCursorPosition(realMouse, cursorAbsolutePos); + } // update suppressed states this.SuppressButtons.RemoveWhere(p => !this.GetStatus(activeButtons, p).IsDown()); -- cgit From 4689eeb6a3af1aead00347fc2575bfebdee50113 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 30 Mar 2019 01:25:12 -0400 Subject: load mods much earlier so they can intercept all content assets --- docs/release-notes.md | 2 + src/SMAPI/Context.cs | 3 ++ src/SMAPI/Framework/ContentCoordinator.cs | 11 ++-- .../ContentManagers/GameContentManager.cs | 17 +++++- src/SMAPI/Framework/SCore.cs | 62 ++++++++++++++-------- src/SMAPI/Framework/SGame.cs | 9 +++- src/SMAPI/Framework/SGameConstructorHack.cs | 8 ++- 7 files changed, 85 insertions(+), 27 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 4fb7b6c3..649cd774 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -11,6 +11,8 @@ These changes have not been released yet. * For modders: * Added support for content pack translations. * Added `IContentPack.HasFile` method. + * Added `Context.IsGameLaunched` field. + * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialised when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialised). * Dropped support for all deprecated APIs. * Updated to Json.NET 12.0.1. diff --git a/src/SMAPI/Context.cs b/src/SMAPI/Context.cs index 1cdef7f1..a933752d 100644 --- a/src/SMAPI/Context.cs +++ b/src/SMAPI/Context.cs @@ -14,6 +14,9 @@ namespace StardewModdingAPI /**** ** Public ****/ + /// Whether the game has performed core initialisation. This becomes true right before the first update tick.. + public static bool IsGameLaunched { get; internal set; } + /// Whether the player has loaded a save and the world has finished initialising. public static bool IsWorldReady { get; internal set; } diff --git a/src/SMAPI/Framework/ContentCoordinator.cs b/src/SMAPI/Framework/ContentCoordinator.cs index ee654081..caeb7ee9 100644 --- a/src/SMAPI/Framework/ContentCoordinator.cs +++ b/src/SMAPI/Framework/ContentCoordinator.cs @@ -36,6 +36,9 @@ namespace StardewModdingAPI.Framework /// Encapsulates SMAPI's JSON file parsing. private readonly JsonHelper JsonHelper; + /// A callback to invoke the first time *any* game content manager loads an asset. + private readonly Action OnLoadingFirstAsset; + /// The loaded content managers (including the ). private readonly IList ContentManagers = new List(); @@ -72,14 +75,16 @@ namespace StardewModdingAPI.Framework /// Encapsulates monitoring and logging. /// Simplifies access to private code. /// Encapsulates SMAPI's JSON file parsing. - public ContentCoordinator(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper) + /// A callback to invoke the first time *any* game content manager loads an asset. + public ContentCoordinator(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action onLoadingFirstAsset) { this.Monitor = monitor ?? throw new ArgumentNullException(nameof(monitor)); this.Reflection = reflection; this.JsonHelper = jsonHelper; + this.OnLoadingFirstAsset = onLoadingFirstAsset; this.FullRootDirectory = Path.Combine(Constants.ExecutionPath, rootDirectory); this.ContentManagers.Add( - this.MainContentManager = new GameContentManager("Game1.content", serviceProvider, rootDirectory, currentCulture, this, monitor, reflection, this.OnDisposing) + this.MainContentManager = new GameContentManager("Game1.content", serviceProvider, rootDirectory, currentCulture, this, monitor, reflection, this.OnDisposing, onLoadingFirstAsset) ); this.CoreAssets = new CoreAssetPropagator(this.MainContentManager.AssertAndNormaliseAssetName, reflection, monitor); } @@ -88,7 +93,7 @@ namespace StardewModdingAPI.Framework /// A name for the mod manager. Not guaranteed to be unique. public GameContentManager CreateGameContentManager(string name) { - GameContentManager manager = new GameContentManager(name, this.MainContentManager.ServiceProvider, this.MainContentManager.RootDirectory, this.MainContentManager.CurrentCulture, this, this.Monitor, this.Reflection, this.OnDisposing); + GameContentManager manager = new GameContentManager(name, this.MainContentManager.ServiceProvider, this.MainContentManager.RootDirectory, this.MainContentManager.CurrentCulture, this, this.Monitor, this.Reflection, this.OnDisposing, this.OnLoadingFirstAsset); this.ContentManagers.Add(manager); return manager; } diff --git a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs index ee940cc7..f159f035 100644 --- a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs @@ -28,6 +28,12 @@ namespace StardewModdingAPI.Framework.ContentManagers /// A lookup which indicates whether the asset is localisable (i.e. the filename contains the locale), if previously loaded. private readonly IDictionary IsLocalisableLookup; + /// Whether the next load is the first for any game content manager. + private static bool IsFirstLoad = true; + + /// A callback to invoke the first time *any* game content manager loads an asset. + private readonly Action OnLoadingFirstAsset; + /********* ** Public methods @@ -41,10 +47,12 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Encapsulates monitoring and logging. /// Simplifies access to private code. /// A callback to invoke when the content manager is being disposed. - public GameContentManager(string name, IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, Action onDisposing) + /// A callback to invoke the first time *any* game content manager loads an asset. + public GameContentManager(string name, IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, Action onDisposing, Action onLoadingFirstAsset) : base(name, serviceProvider, rootDirectory, currentCulture, coordinator, monitor, reflection, onDisposing, isModFolder: false) { this.IsLocalisableLookup = reflection.GetField>(this, "_localizedAsset").GetValue(); + this.OnLoadingFirstAsset = onLoadingFirstAsset; } /// Load an asset that has been processed by the content pipeline. @@ -53,6 +61,13 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The language code for which to load content. public override T Load(string assetName, LanguageCode language) { + // raise first-load callback + if (GameContentManager.IsFirstLoad) + { + GameContentManager.IsFirstLoad = false; + this.OnLoadingFirstAsset(); + } + // normalise asset name assetName = this.AssertAndNormaliseAssetName(assetName); if (this.TryParseExplicitLanguageAssetKey(assetName, out string newAssetName, out LanguageCode newLanguage)) diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index 2f0e0f05..f64af82b 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -209,8 +209,19 @@ namespace StardewModdingAPI.Framework AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => AssemblyLoader.ResolveAssembly(e.Name); // override game - SGame.ConstructorHack = new SGameConstructorHack(this.Monitor, this.Reflection, this.Toolkit.JsonHelper); - this.GameInstance = new SGame(this.Monitor, this.MonitorForGame, this.Reflection, this.EventManager, this.Toolkit.JsonHelper, this.ModRegistry, SCore.DeprecationManager, this.OnLocaleChanged, this.InitialiseAfterGameStart, this.Dispose); + SGame.ConstructorHack = new SGameConstructorHack(this.Monitor, this.Reflection, this.Toolkit.JsonHelper, this.InitialiseBeforeFirstAssetLoaded); + this.GameInstance = new SGame( + monitor: this.Monitor, + monitorForGame: this.MonitorForGame, + reflection: this.Reflection, + eventManager: this.EventManager, + jsonHelper: this.Toolkit.JsonHelper, + modRegistry: this.ModRegistry, + deprecationManager: SCore.DeprecationManager, + onLocaleChanged: this.OnLocaleChanged, + onGameInitialised: this.InitialiseAfterGameStart, + onGameExiting: this.Dispose + ); StardewValley.Program.gamePtr = this.GameInstance; // apply game patches @@ -280,6 +291,19 @@ namespace StardewModdingAPI.Framework File.Delete(Constants.FatalCrashMarker); } + // add headers + if (this.Settings.DeveloperMode) + this.Monitor.Log($"You have SMAPI for developers, so the console will be much more verbose. You can disable developer mode by installing the non-developer version of SMAPI, or by editing {Constants.ApiConfigPath}.", LogLevel.Info); + if (!this.Settings.CheckForUpdates) + this.Monitor.Log($"You configured SMAPI to not check for updates. Running an old version of SMAPI is not recommended. You can enable update checks by reinstalling SMAPI or editing {Constants.ApiConfigPath}.", LogLevel.Warn); + if (!this.Monitor.WriteToConsole) + this.Monitor.Log("Writing to the terminal is disabled because the --no-terminal argument was received. This usually means launching the terminal failed.", LogLevel.Warn); + this.Monitor.VerboseLog("Verbose logging enabled."); + + // update window titles + this.GameInstance.Window.Title = $"Stardew Valley {Constants.GameVersion} - running SMAPI {Constants.ApiVersion}"; + Console.Title = $"SMAPI {Constants.ApiVersion} - running Stardew Valley {Constants.GameVersion}"; + // start game this.Monitor.Log("Starting game...", LogLevel.Debug); try @@ -349,21 +373,14 @@ namespace StardewModdingAPI.Framework /********* ** Private methods *********/ - /// Initialise SMAPI and mods after the game starts. - private void InitialiseAfterGameStart() + /// Initialise mods before the first game asset is loaded. At this point the core content managers are loaded (so mods can load their own assets), but the game is mostly uninitialised. + private void InitialiseBeforeFirstAssetLoaded() { - // add headers - if (this.Settings.DeveloperMode) - this.Monitor.Log($"You have SMAPI for developers, so the console will be much more verbose. You can disable developer mode by installing the non-developer version of SMAPI, or by editing {Constants.ApiConfigPath}.", LogLevel.Info); - if (!this.Settings.CheckForUpdates) - this.Monitor.Log($"You configured SMAPI to not check for updates. Running an old version of SMAPI is not recommended. You can enable update checks by reinstalling SMAPI or editing {Constants.ApiConfigPath}.", LogLevel.Warn); - if (!this.Monitor.WriteToConsole) - this.Monitor.Log("Writing to the terminal is disabled because the --no-terminal argument was received. This usually means launching the terminal failed.", LogLevel.Warn); - this.Monitor.VerboseLog("Verbose logging enabled."); - - // validate XNB integrity - if (!this.ValidateContentIntegrity()) - this.Monitor.Log("SMAPI found problems in your game's content files which are likely to cause errors or crashes. Consider uninstalling XNB mods or reinstalling the game.", LogLevel.Error); + if (this.Monitor.IsExiting) + { + this.Monitor.Log("SMAPI shutting down: aborting initialisation.", LogLevel.Warn); + return; + } // load mod data ModToolkit toolkit = new ModToolkit(); @@ -404,16 +421,19 @@ namespace StardewModdingAPI.Framework // check for updates this.CheckForUpdatesAsync(mods); } - if (this.Monitor.IsExiting) - { - this.Monitor.Log("SMAPI shutting down: aborting initialisation.", LogLevel.Warn); - return; - } // update window titles int modsLoaded = this.ModRegistry.GetAll().Count(); this.GameInstance.Window.Title = $"Stardew Valley {Constants.GameVersion} - running SMAPI {Constants.ApiVersion} with {modsLoaded} mods"; Console.Title = $"SMAPI {Constants.ApiVersion} - running Stardew Valley {Constants.GameVersion} with {modsLoaded} mods"; + } + + /// Initialise SMAPI and mods after the game starts. + private void InitialiseAfterGameStart() + { + // validate XNB integrity + if (!this.ValidateContentIntegrity()) + this.Monitor.Log("SMAPI found problems in your game's content files which are likely to cause errors or crashes. Consider uninstalling XNB mods or reinstalling the game.", LogLevel.Error); // start SMAPI console new Thread(this.RunConsoleLoop).Start(); diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index b35e1d71..002a5d1b 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -75,6 +75,9 @@ namespace StardewModdingAPI.Framework /// A callback to invoke after the content language changes. private readonly Action OnLocaleChanged; + /// A callback to invoke the first time *any* game content manager loads an asset. + private readonly Action OnLoadingFirstAsset; + /// A callback to invoke after the game finishes initialising. private readonly Action OnGameInitialised; @@ -139,6 +142,7 @@ namespace StardewModdingAPI.Framework /// A callback to invoke when the game exits. internal SGame(IMonitor monitor, IMonitor monitorForGame, Reflector reflection, EventManager eventManager, JsonHelper jsonHelper, ModRegistry modRegistry, DeprecationManager deprecationManager, Action onLocaleChanged, Action onGameInitialised, Action onGameExiting) { + this.OnLoadingFirstAsset = SGame.ConstructorHack.OnLoadingFirstAsset; SGame.ConstructorHack = null; // check expectations @@ -237,7 +241,7 @@ namespace StardewModdingAPI.Framework // NOTE: this method is called before the SGame constructor runs. Don't depend on anything being initialised at this point. if (this.ContentCore == null) { - this.ContentCore = new ContentCoordinator(serviceProvider, rootDirectory, Thread.CurrentThread.CurrentUICulture, SGame.ConstructorHack.Monitor, SGame.ConstructorHack.Reflection, SGame.ConstructorHack.JsonHelper); + this.ContentCore = new ContentCoordinator(serviceProvider, rootDirectory, Thread.CurrentThread.CurrentUICulture, SGame.ConstructorHack.Monitor, SGame.ConstructorHack.Reflection, SGame.ConstructorHack.JsonHelper, this.OnLoadingFirstAsset ?? SGame.ConstructorHack?.OnLoadingFirstAsset); this.NextContentManagerIsMain = true; return this.ContentCore.CreateGameContentManager("Game1._temporaryContent"); } @@ -764,7 +768,10 @@ namespace StardewModdingAPI.Framework // game launched bool isFirstTick = SGame.TicksElapsed == 0; if (isFirstTick) + { + Context.IsGameLaunched = true; events.GameLaunched.Raise(new GameLaunchedEventArgs()); + } // preloaded if (Context.IsSaveLoaded && Context.LoadStage != LoadStage.Loaded && Context.LoadStage != LoadStage.Ready) diff --git a/src/SMAPI/Framework/SGameConstructorHack.cs b/src/SMAPI/Framework/SGameConstructorHack.cs index 494bab99..c3d22197 100644 --- a/src/SMAPI/Framework/SGameConstructorHack.cs +++ b/src/SMAPI/Framework/SGameConstructorHack.cs @@ -1,3 +1,4 @@ +using System; using StardewModdingAPI.Framework.Reflection; using StardewModdingAPI.Toolkit.Serialisation; using StardewValley; @@ -19,6 +20,9 @@ namespace StardewModdingAPI.Framework /// Encapsulates SMAPI's JSON file parsing. public JsonHelper JsonHelper { get; } + /// A callback to invoke the first time *any* game content manager loads an asset. + public Action OnLoadingFirstAsset { get; } + /********* ** Public methods @@ -27,11 +31,13 @@ namespace StardewModdingAPI.Framework /// Encapsulates monitoring and logging. /// Simplifies access to private game code. /// Encapsulates SMAPI's JSON file parsing. - public SGameConstructorHack(IMonitor monitor, Reflector reflection, JsonHelper jsonHelper) + /// A callback to invoke the first time *any* game content manager loads an asset. + public SGameConstructorHack(IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action onLoadingFirstAsset) { this.Monitor = monitor; this.Reflection = reflection; this.JsonHelper = jsonHelper; + this.OnLoadingFirstAsset = onLoadingFirstAsset; } } } -- cgit From d10ded0fcc5e92f16d13a34e1d83925a1f99feb1 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Thu, 4 Apr 2019 00:10:03 -0400 Subject: update compatibility list --- docs/release-notes.md | 1 + .../wwwroot/StardewModdingAPI.metadata.json | 151 +++++++++++++++++++-- 2 files changed, 144 insertions(+), 8 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 649cd774..e9819860 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -4,6 +4,7 @@ These changes have not been released yet. * For players: * Improved performance. + * Updated mod compatibility list. * Fixed Save Backup not pruning old backups if they're uncompressed. * Fixed issues when a farmhand reconnects before the game notices they're disconnected. * Fixed 'received message' logs shown in non-developer mode. diff --git a/src/SMAPI.Web/wwwroot/StardewModdingAPI.metadata.json b/src/SMAPI.Web/wwwroot/StardewModdingAPI.metadata.json index d0c55552..a3336ed3 100644 --- a/src/SMAPI.Web/wwwroot/StardewModdingAPI.metadata.json +++ b/src/SMAPI.Web/wwwroot/StardewModdingAPI.metadata.json @@ -59,15 +59,15 @@ "Default | UpdateKey": "Nexus:2270" }, - "Content Patcher": { - "ID": "Pathoschild.ContentPatcher", - "Default | UpdateKey": "Nexus:1915" - }, + //"Content Patcher": { + // "ID": "Pathoschild.ContentPatcher", + // "Default | UpdateKey": "Nexus:1915" + //}, - "Custom Farming Redux": { - "ID": "Platonymous.CustomFarming", - "Default | UpdateKey": "Nexus:991" - }, + //"Custom Farming Redux": { + // "ID": "Platonymous.CustomFarming", + // "Default | UpdateKey": "Nexus:991" + //}, "Custom Shirts": { "ID": "Platonymous.CustomShirts", @@ -234,6 +234,141 @@ "~ | StatusReasonPhrase": "debug mode was removed in SMAPI 1.0." }, + /********* + ** Broke in SMAPI 3.0 (runtime errors due to lifecycle changes) + *********/ + "Advancing Sprinklers": { + "ID": "warix3.advancingsprinklers", + "~1.0.0 | Status": "AssumeBroken" + }, + + "Arcade 2048": { + "ID": "Platonymous.2048", + "~1.0.6 | Status": "AssumeBroken" // possibly due to PyTK + }, + + "Arcade Snake": { + "ID": "Platonymous.Snake", + "~1.1.0 | Status": "AssumeBroken" // possibly due to PyTK + }, + + "Better Sprinklers": { + "ID": "Speeder.BetterSprinklers", + "~2.3.1-unofficial.7-pathoschild | Status": "AssumeBroken" + }, + + "Companion NPCs": { + "ID": "Redwood.CompanionNPCs", + "~0.0.9 | Status": "AssumeBroken" + }, + + "Content Patcher": { + "ID": "Pathoschild.ContentPatcher", + "Default | UpdateKey": "Nexus:1915", + "~1.6.4 | Status": "AssumeBroken" + }, + + "Crop Transplant Mod": { + "ID": "DIGUS.CropTransplantMod", + "~1.1.3 | Status": "AssumeBroken" + }, + + "Custom Adventure Guild Challenges": { + "ID": "DefenTheNation.CustomGuildChallenges", + "~1.8 | Status": "AssumeBroken" + }, + + "Custom Farming Redux": { + "ID": "Platonymous.CustomFarming", + "Default | UpdateKey": "Nexus:991", + "~2.10.10 | Status": "AssumeBroken" // possibly due to PyTK + }, + + "Deep Woods": { + "ID": "maxvollmer.deepwoodsmod", + "~1.5-beta.1 | Status": "AssumeBroken" + }, + + "Everlasting Baits and Unbreaking Tackles": { + "ID": "DIGUS.EverlastingBaitsAndUnbreakableTacklesMod", + "~1.2.4 | Status": "AssumeBroken" + }, + + "Farmhouse Redone": { + "ID": "mabelsyrup.farmhouse", + "~0.2 | Status": "AssumeBroken" + }, + + "Geode Info Menu": { + "ID": "cat.geodeinfomenu", + "~1.5 | Status": "AssumeBroken" + }, + + "Harp of Yoba Redux": { + "ID": "Platonymous.HarpOfYobaRedux", + "~2.6.3 | Status": "AssumeBroken" // possibly due to PyTK + }, + + "Infested Levels": { + "ID": "Eireon.InfestedLevels", + "~1.0.5 | Status": "AssumeBroken" + }, + + "JoJaBan - Arcade Sokoban": { + "ID": "Platonymous.JoJaBan", + "~0.4.3 | Status": "AssumeBroken" // possibly due to PyTK + }, + + "Level Extender": { + "ID": "DevinLematty.LevelExtender", + "~3.1 | Status": "AssumeBroken" + }, + + "Mod Update Menu": { + "ID": "cat.modupdatemenu", + "~1.4 | Status": "AssumeBroken" + }, + + "Mushroom Levels": { + "ID": "Eireon.MushroomLevels", + "~1.0.4 | Status": "AssumeBroken" + }, + + "Notes": { + "ID": "Platonymous.Notes", + "~1.0.5 | Status": "AssumeBroken" // possibly due to PyTK + }, + + "Quick Start": { + "ID": "WuestMan.QuickStart", + "~1.5 | Status": "AssumeBroken" + }, + + "Seed Bag": { + "ID": "Platonymous.SeedBag", + "~1.2.7 | Status": "AssumeBroken" // possibly due to PyTK + }, + + "Separate Money": { + "ID": "funnysnek.SeparateMoney", + "~1.4.2 | Status": "AssumeBroken" + }, + + "Split Money": { + "ID": "Platonymous.SplitMoney", + "~1.2.4 | Status": "AssumeBroken" // possibly due to PyTK + }, + + "Stack to Nearby Chests": { + "ID": "Ilyaki.StackToNearbyChests", + "~1.4.4 | Status": "AssumeBroken" + }, + + "Tree Transplant": { + "ID": "TreeTransplant", + "~1.0.5 | Status": "AssumeBroken" + }, + /********* ** Broke in SDV 1.3.36 *********/ -- cgit From 09d1c5a601e77c051dfde8a31f422b2c898086c3 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 6 Apr 2019 00:35:53 -0400 Subject: list all detected issues in trace logs for incompatible mods --- docs/release-notes.md | 1 + src/SMAPI/Framework/ModLoading/AssemblyLoader.cs | 20 +++++++++---------- .../ReferenceToMemberWithUnexpectedTypeFinder.cs | 5 +---- .../ModLoading/IncompatibleInstructionException.cs | 23 ++++------------------ 4 files changed, 16 insertions(+), 33 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index e9819860..6aa3c024 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -14,6 +14,7 @@ These changes have not been released yet. * Added `IContentPack.HasFile` method. * Added `Context.IsGameLaunched` field. * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialised when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialised). + * When a mod is incompatible, the trace logs now list all detected issues instead of the first one. * Dropped support for all deprecated APIs. * Updated to Json.NET 12.0.1. diff --git a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs index 878b3148..ca171ae1 100644 --- a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs +++ b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs @@ -105,7 +105,7 @@ namespace StardewModdingAPI.Framework.ModLoading continue; // rewrite assembly - bool changed = this.RewriteAssembly(mod, assembly.Definition, assumeCompatible, loggedMessages, logPrefix: " "); + bool changed = this.RewriteAssembly(mod, assembly.Definition, loggedMessages, logPrefix: " "); // detect broken assembly reference foreach (AssemblyNameReference reference in assembly.Definition.MainModule.AssemblyReferences) @@ -114,7 +114,7 @@ namespace StardewModdingAPI.Framework.ModLoading { this.Monitor.LogOnce(loggedMessages, $" Broken code in {assembly.File.Name}: reference to missing assembly '{reference.FullName}'."); if (!assumeCompatible) - throw new IncompatibleInstructionException($"assembly reference to {reference.FullName}", $"Found a reference to missing assembly '{reference.FullName}' while loading assembly {assembly.File.Name}."); + throw new IncompatibleInstructionException($"Found a reference to missing assembly '{reference.FullName}' while loading assembly {assembly.File.Name}."); mod.SetWarning(ModWarning.BrokenCodeLoaded); break; } @@ -143,6 +143,10 @@ namespace StardewModdingAPI.Framework.ModLoading this.AssemblyDefinitionResolver.Add(assembly.Definition); } + // throw if incompatibilities detected + if (!assumeCompatible && mod.Warnings.HasFlag(ModWarning.BrokenCodeLoaded)) + throw new IncompatibleInstructionException(); + // last assembly loaded is the root return lastAssembly; } @@ -244,12 +248,11 @@ namespace StardewModdingAPI.Framework.ModLoading /// Rewrite the types referenced by an assembly. /// The mod for which the assembly is being loaded. /// The assembly to rewrite. - /// Assume the mod is compatible, even if incompatible code is detected. /// The messages that have already been logged for this mod. /// A string to prefix to log messages. /// Returns whether the assembly was modified. /// An incompatible CIL instruction was found while rewriting the assembly. - private bool RewriteAssembly(IModMetadata mod, AssemblyDefinition assembly, bool assumeCompatible, HashSet loggedMessages, string logPrefix) + private bool RewriteAssembly(IModMetadata mod, AssemblyDefinition assembly, HashSet loggedMessages, string logPrefix) { ModuleDefinition module = assembly.MainModule; string filename = $"{assembly.Name.Name}.dll"; @@ -288,7 +291,7 @@ namespace StardewModdingAPI.Framework.ModLoading foreach (IInstructionHandler handler in handlers) { InstructionHandleResult result = handler.Handle(module, method, this.AssemblyMap, platformChanged); - this.ProcessInstructionHandleResult(mod, handler, result, loggedMessages, logPrefix, assumeCompatible, filename); + this.ProcessInstructionHandleResult(mod, handler, result, loggedMessages, logPrefix, filename); if (result == InstructionHandleResult.Rewritten) anyRewritten = true; } @@ -303,7 +306,7 @@ namespace StardewModdingAPI.Framework.ModLoading { Instruction instruction = instructions[offset]; InstructionHandleResult result = handler.Handle(module, cil, instruction, this.AssemblyMap, platformChanged); - this.ProcessInstructionHandleResult(mod, handler, result, loggedMessages, logPrefix, assumeCompatible, filename); + this.ProcessInstructionHandleResult(mod, handler, result, loggedMessages, logPrefix, filename); if (result == InstructionHandleResult.Rewritten) anyRewritten = true; } @@ -318,10 +321,9 @@ namespace StardewModdingAPI.Framework.ModLoading /// The instruction handler. /// The result returned by the handler. /// The messages already logged for the current mod. - /// Assume the mod is compatible, even if incompatible code is detected. /// A string to prefix to log messages. /// The assembly filename for log messages. - private void ProcessInstructionHandleResult(IModMetadata mod, IInstructionHandler handler, InstructionHandleResult result, HashSet loggedMessages, string logPrefix, bool assumeCompatible, string filename) + private void ProcessInstructionHandleResult(IModMetadata mod, IInstructionHandler handler, InstructionHandleResult result, HashSet loggedMessages, string logPrefix, string filename) { switch (result) { @@ -331,8 +333,6 @@ namespace StardewModdingAPI.Framework.ModLoading case InstructionHandleResult.NotCompatible: this.Monitor.LogOnce(loggedMessages, $"{logPrefix}Broken code in {filename}: {handler.NounPhrase}."); - if (!assumeCompatible) - throw new IncompatibleInstructionException(handler.NounPhrase, $"Found an incompatible CIL instruction ({handler.NounPhrase}) while loading assembly {filename}."); mod.SetWarning(ModWarning.BrokenCodeLoaded); break; diff --git a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs index 82c4920a..459e3210 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs @@ -80,10 +80,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders // compare return types MethodDefinition methodDef = methodReference.Resolve(); if (methodDef == null) - { - this.NounPhrase = $"reference to {methodReference.DeclaringType.FullName}.{methodReference.Name} (no such method)"; - return InstructionHandleResult.NotCompatible; - } + return InstructionHandleResult.None; // validated by ReferenceToMissingMemberFinder if (candidateMethods.All(method => !RewriteHelper.LooksLikeSameType(method.ReturnType, methodDef.ReturnType))) { diff --git a/src/SMAPI/Framework/ModLoading/IncompatibleInstructionException.cs b/src/SMAPI/Framework/ModLoading/IncompatibleInstructionException.cs index 17ec24b1..1f9add30 100644 --- a/src/SMAPI/Framework/ModLoading/IncompatibleInstructionException.cs +++ b/src/SMAPI/Framework/ModLoading/IncompatibleInstructionException.cs @@ -5,31 +5,16 @@ namespace StardewModdingAPI.Framework.ModLoading /// An exception raised when an incompatible instruction is found while loading a mod assembly. internal class IncompatibleInstructionException : Exception { - /********* - ** Accessors - *********/ - /// A brief noun phrase which describes the incompatible instruction that was found. - public string NounPhrase { get; } - - /********* ** Public methods *********/ /// Construct an instance. - /// A brief noun phrase which describes the incompatible instruction that was found. - public IncompatibleInstructionException(string nounPhrase) - : base($"Found an incompatible CIL instruction ({nounPhrase}).") - { - this.NounPhrase = nounPhrase; - } + public IncompatibleInstructionException() + : base("Found incompatible CIL instructions.") { } /// Construct an instance. - /// A brief noun phrase which describes the incompatible instruction that was found. /// A message which describes the error. - public IncompatibleInstructionException(string nounPhrase, string message) - : base(message) - { - this.NounPhrase = nounPhrase; - } + public IncompatibleInstructionException(string message) + : base(message) { } } } -- cgit From 6c220453e16c6cb5ad150b61cf02685a97557b3c Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 15 Apr 2019 00:40:45 -0400 Subject: fix translatable assets not updated when switching language (#586) --- docs/release-notes.md | 1 + src/SMAPI/Framework/ContentCoordinator.cs | 7 +++++++ .../ContentManagers/BaseContentManager.cs | 3 +++ .../ContentManagers/GameContentManager.cs | 23 ++++++++++++++++++++++ .../Framework/ContentManagers/IContentManager.cs | 3 +++ src/SMAPI/Framework/SCore.cs | 6 +++++- src/SMAPI/Framework/SGame.cs | 8 +------- 7 files changed, 43 insertions(+), 8 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 6aa3c024..84738ff7 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -8,6 +8,7 @@ These changes have not been released yet. * Fixed Save Backup not pruning old backups if they're uncompressed. * Fixed issues when a farmhand reconnects before the game notices they're disconnected. * Fixed 'received message' logs shown in non-developer mode. + * Fixed some assets not updated when you switch language to English. * For modders: * Added support for content pack translations. diff --git a/src/SMAPI/Framework/ContentCoordinator.cs b/src/SMAPI/Framework/ContentCoordinator.cs index caeb7ee9..25eeb2ef 100644 --- a/src/SMAPI/Framework/ContentCoordinator.cs +++ b/src/SMAPI/Framework/ContentCoordinator.cs @@ -114,6 +114,13 @@ namespace StardewModdingAPI.Framework return this.MainContentManager.GetLocale(LocalizedContentManager.CurrentLanguageCode); } + /// Perform any cleanup needed when the locale changes. + public void OnLocaleChanged() + { + foreach (IContentManager contentManager in this.ContentManagers) + contentManager.OnLocaleChanged(); + } + /// Get whether this asset is mapped to a mod folder. /// The asset key. public bool IsManagedAssetKey(string key) diff --git a/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs b/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs index 7821e454..b2b3769b 100644 --- a/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs @@ -138,6 +138,9 @@ namespace StardewModdingAPI.Framework.ContentManagers } } + /// Perform any cleanup needed when the locale changes. + public virtual void OnLocaleChanged() { } + /// Normalise path separators in a file path. For asset keys, see instead. /// The file path to normalise. [Pure] diff --git a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs index f159f035..55cf15ec 100644 --- a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs @@ -112,6 +112,29 @@ namespace StardewModdingAPI.Framework.ContentManagers return data; } + /// Perform any cleanup needed when the locale changes. + public override void OnLocaleChanged() + { + base.OnLocaleChanged(); + + // find assets for which a translatable version was loaded + HashSet removeAssetNames = new HashSet(StringComparer.InvariantCultureIgnoreCase); + foreach (string key in this.IsLocalisableLookup.Where(p => p.Value).Select(p => p.Key)) + removeAssetNames.Add(this.TryParseExplicitLanguageAssetKey(key, out string assetName, out _) ? assetName : key); + + // invalidate translatable assets + string[] invalidated = this + .InvalidateCache((key, type) => + removeAssetNames.Contains(key) + || (this.TryParseExplicitLanguageAssetKey(key, out string assetName, out _) && removeAssetNames.Contains(assetName)) + ) + .Select(p => p.Item1) + .OrderBy(p => p, StringComparer.InvariantCultureIgnoreCase) + .ToArray(); + if (invalidated.Any()) + this.Monitor.Log($"Invalidated {invalidated.Length} asset names: {string.Join(", ", invalidated)} for locale change.", LogLevel.Trace); + } + /// Create a new content manager for temporary use. public override LocalizedContentManager CreateTemporary() { diff --git a/src/SMAPI/Framework/ContentManagers/IContentManager.cs b/src/SMAPI/Framework/ContentManagers/IContentManager.cs index 17618edd..66ef9181 100644 --- a/src/SMAPI/Framework/ContentManagers/IContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/IContentManager.cs @@ -52,6 +52,9 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The asset to clone. T CloneIfPossible(T asset); + /// Perform any cleanup needed when the locale changes. + void OnLocaleChanged(); + /// Normalise path separators in a file path. For asset keys, see instead. /// The file path to normalise. [Pure] diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index f64af82b..e8d5b672 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -208,6 +208,9 @@ namespace StardewModdingAPI.Framework // add more leniant assembly resolvers AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => AssemblyLoader.ResolveAssembly(e.Name); + // hook locale event + LocalizedContentManager.OnLanguageChange += locale => this.OnLocaleChanged(); + // override game SGame.ConstructorHack = new SGameConstructorHack(this.Monitor, this.Reflection, this.Toolkit.JsonHelper, this.InitialiseBeforeFirstAssetLoaded); this.GameInstance = new SGame( @@ -218,7 +221,6 @@ namespace StardewModdingAPI.Framework jsonHelper: this.Toolkit.JsonHelper, modRegistry: this.ModRegistry, deprecationManager: SCore.DeprecationManager, - onLocaleChanged: this.OnLocaleChanged, onGameInitialised: this.InitialiseAfterGameStart, onGameExiting: this.Dispose ); @@ -442,6 +444,8 @@ namespace StardewModdingAPI.Framework /// Handle the game changing locale. private void OnLocaleChanged() { + this.ContentCore.OnLocaleChanged(); + // get locale string locale = this.ContentCore.GetLocale(); LocalizedContentManager.LanguageCode languageCode = this.ContentCore.Language; diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index 002a5d1b..684ff3ba 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -72,9 +72,6 @@ namespace StardewModdingAPI.Framework /// Whether the game is creating the save file and SMAPI has already raised . private bool IsBetweenCreateEvents; - /// A callback to invoke after the content language changes. - private readonly Action OnLocaleChanged; - /// A callback to invoke the first time *any* game content manager loads an asset. private readonly Action OnLoadingFirstAsset; @@ -137,10 +134,9 @@ namespace StardewModdingAPI.Framework /// Encapsulates SMAPI's JSON file parsing. /// Tracks the installed mods. /// Manages deprecation warnings. - /// A callback to invoke after the content language changes. /// A callback to invoke after the game finishes initialising. /// A callback to invoke when the game exits. - internal SGame(IMonitor monitor, IMonitor monitorForGame, Reflector reflection, EventManager eventManager, JsonHelper jsonHelper, ModRegistry modRegistry, DeprecationManager deprecationManager, Action onLocaleChanged, Action onGameInitialised, Action onGameExiting) + internal SGame(IMonitor monitor, IMonitor monitorForGame, Reflector reflection, EventManager eventManager, JsonHelper jsonHelper, ModRegistry modRegistry, DeprecationManager deprecationManager, Action onGameInitialised, Action onGameExiting) { this.OnLoadingFirstAsset = SGame.ConstructorHack.OnLoadingFirstAsset; SGame.ConstructorHack = null; @@ -159,7 +155,6 @@ namespace StardewModdingAPI.Framework this.ModRegistry = modRegistry; this.Reflection = reflection; this.DeprecationManager = deprecationManager; - this.OnLocaleChanged = onLocaleChanged; this.OnGameInitialised = onGameInitialised; this.OnGameExiting = onGameExiting; Game1.input = new SInputState(); @@ -467,7 +462,6 @@ namespace StardewModdingAPI.Framework if (this.Watchers.LocaleWatcher.IsChanged) { this.Monitor.Log($"Context: locale set to {this.Watchers.LocaleWatcher.CurrentValue}.", LogLevel.Trace); - this.OnLocaleChanged(); this.Watchers.LocaleWatcher.Reset(); } -- cgit From 78f28357e4f87ed619144229ea65c1e1cb0f9dd3 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 15 Apr 2019 22:36:50 -0400 Subject: update code for SDV 1.4 (#638) --- docs/release-notes.md | 1 + .../Framework/Commands/Player/SetMoneyCommand.cs | 4 +- .../Framework/ItemData/ItemType.cs | 17 +-- .../Framework/ItemRepository.cs | 4 + src/SMAPI/Framework/SGame.cs | 120 ++++++++------------- src/SMAPI/Metadata/CoreAssetPropagator.cs | 4 +- 6 files changed, 64 insertions(+), 86 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 84738ff7..32f4db37 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -3,6 +3,7 @@ These changes have not been released yet. * For players: + * Updated for Stardew Valley 1.4. * Improved performance. * Updated mod compatibility list. * Fixed Save Backup not pruning old backups if they're uncompressed. diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/SetMoneyCommand.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/SetMoneyCommand.cs index ad11cc66..1706bbc1 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/SetMoneyCommand.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/SetMoneyCommand.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using StardewValley; namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.Player @@ -65,7 +65,7 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.Player public override void Update(IMonitor monitor) { if (this.InfiniteMoney) - Game1.player.money = 999999; + Game1.player.Money = 999999; } } } diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/ItemData/ItemType.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/ItemData/ItemType.cs index 7ee662d0..5d269c89 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/ItemData/ItemType.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/ItemData/ItemType.cs @@ -6,28 +6,31 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.ItemData /// A big craftable object in BigCraftable, - /// A item. + /// A item. Boots, - /// A flooring item. + /// A item. + Clothing, + + /// A flooring item. Flooring, - /// A item. + /// A item. Furniture, - /// A item. + /// A item. Hat, /// Any object in (except rings). Object, - /// A item. + /// A item. Ring, - /// A tool. + /// A tool. Tool, - /// A wall item. + /// A wall item. Wallpaper, /// A or item. diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs index fc631826..90cdb872 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs @@ -35,6 +35,10 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework yield return new SearchableItem(ItemType.Tool, this.CustomIDOffset + 2, new Pan()); yield return new SearchableItem(ItemType.Tool, this.CustomIDOffset + 3, new Wand()); + // clothing + foreach (int id in Game1.clothingInformation.Keys) + yield return new SearchableItem(ItemType.Clothing, id, new Clothing(id)); + // wallpapers for (int id = 0; id < 112; id++) yield return new SearchableItem(ItemType.Wallpaper, id, new Wallpaper(id) { Category = SObject.furnitureCategory }); diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index 684ff3ba..c06f62cf 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -22,6 +22,7 @@ using StardewModdingAPI.Toolkit.Serialisation; using StardewValley; using StardewValley.BellsAndWhistles; using StardewValley.Buildings; +using StardewValley.Events; using StardewValley.Locations; using StardewValley.Menus; using StardewValley.TerrainFeatures; @@ -864,14 +865,14 @@ namespace StardewModdingAPI.Framework var events = this.Events; if (Game1._newDayTask != null) - this.GraphicsDevice.Clear(this.bgColor); + this.GraphicsDevice.Clear(Game1.bgColor); else { if ((double)Game1.options.zoomLevel != 1.0) this.GraphicsDevice.SetRenderTarget(this.screen); if (this.IsSaving) { - this.GraphicsDevice.Clear(this.bgColor); + this.GraphicsDevice.Clear(Game1.bgColor); IClickableMenu activeClickableMenu = Game1.activeClickableMenu; if (activeClickableMenu != null) { @@ -901,7 +902,7 @@ namespace StardewModdingAPI.Framework } else { - this.GraphicsDevice.Clear(this.bgColor); + this.GraphicsDevice.Clear(Game1.bgColor); if (Game1.activeClickableMenu != null && Game1.options.showMenuBackground && Game1.activeClickableMenu.showWithoutTransparencyIfOptionIsSet()) { Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); @@ -925,7 +926,7 @@ namespace StardewModdingAPI.Framework if ((double)Game1.options.zoomLevel != 1.0) { this.GraphicsDevice.SetRenderTarget((RenderTarget2D)null); - this.GraphicsDevice.Clear(this.bgColor); + this.GraphicsDevice.Clear(Game1.bgColor); Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); Game1.spriteBatch.Draw((Texture2D)this.screen, Vector2.Zero, new Microsoft.Xna.Framework.Rectangle?(this.screen.Bounds), Color.White, 0.0f, Vector2.Zero, Game1.options.zoomLevel, SpriteEffects.None, 1f); Game1.spriteBatch.End(); @@ -959,7 +960,7 @@ namespace StardewModdingAPI.Framework if ((double)Game1.options.zoomLevel == 1.0) return; this.GraphicsDevice.SetRenderTarget((RenderTarget2D)null); - this.GraphicsDevice.Clear(this.bgColor); + this.GraphicsDevice.Clear(Game1.bgColor); Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); Game1.spriteBatch.Draw((Texture2D)this.screen, Vector2.Zero, new Microsoft.Xna.Framework.Rectangle?(this.screen.Bounds), Color.White, 0.0f, Vector2.Zero, Game1.options.zoomLevel, SpriteEffects.None, 1f); Game1.spriteBatch.End(); @@ -988,7 +989,7 @@ namespace StardewModdingAPI.Framework if ((double)Game1.options.zoomLevel == 1.0) return; this.GraphicsDevice.SetRenderTarget((RenderTarget2D)null); - this.GraphicsDevice.Clear(this.bgColor); + this.GraphicsDevice.Clear(Game1.bgColor); Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); Game1.spriteBatch.Draw((Texture2D)this.screen, Vector2.Zero, new Microsoft.Xna.Framework.Rectangle?(this.screen.Bounds), Color.White, 0.0f, Vector2.Zero, Game1.options.zoomLevel, SpriteEffects.None, 1f); Game1.spriteBatch.End(); @@ -1003,7 +1004,7 @@ namespace StardewModdingAPI.Framework string str2 = Game1.content.LoadString("Strings\\StringsFromCSFiles:Game1.cs.3688"); string s = str2 + str1; string str3 = str2 + "... "; - int widthOfString = SpriteText.getWidthOfString(str3); + int widthOfString = SpriteText.getWidthOfString(str3, 999999); int height = 64; int x = 64; int y = Game1.graphics.GraphicsDevice.Viewport.GetTitleSafeArea().Bottom - height; @@ -1014,7 +1015,7 @@ namespace StardewModdingAPI.Framework if ((double)Game1.options.zoomLevel != 1.0) { this.GraphicsDevice.SetRenderTarget((RenderTarget2D)null); - this.GraphicsDevice.Clear(this.bgColor); + this.GraphicsDevice.Clear(Game1.bgColor); Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); Game1.spriteBatch.Draw((Texture2D)this.screen, Vector2.Zero, new Microsoft.Xna.Framework.Rectangle?(this.screen.Bounds), Color.White, 0.0f, Vector2.Zero, Game1.options.zoomLevel, SpriteEffects.None, 1f); Game1.spriteBatch.End(); @@ -1031,7 +1032,6 @@ namespace StardewModdingAPI.Framework { byte batchOpens = 0; // used for rendering event - Microsoft.Xna.Framework.Rectangle rectangle; Viewport viewport; if (Game1.gameMode == (byte)0) { @@ -1052,14 +1052,27 @@ namespace StardewModdingAPI.Framework for (int index = 0; index < Game1.currentLightSources.Count; ++index) { if (Utility.isOnScreen((Vector2)((NetFieldBase)Game1.currentLightSources.ElementAt(index).position), (int)((double)(float)((NetFieldBase)Game1.currentLightSources.ElementAt(index).radius) * 64.0 * 4.0))) - Game1.spriteBatch.Draw(Game1.currentLightSources.ElementAt(index).lightTexture, Game1.GlobalToLocal(Game1.viewport, (Vector2)((NetFieldBase)Game1.currentLightSources.ElementAt(index).position)) / (float)(Game1.options.lightingQuality / 2), new Microsoft.Xna.Framework.Rectangle?(Game1.currentLightSources.ElementAt(index).lightTexture.Bounds), (Color)((NetFieldBase)Game1.currentLightSources.ElementAt(index).color), 0.0f, new Vector2((float)Game1.currentLightSources.ElementAt(index).lightTexture.Bounds.Center.X, (float)Game1.currentLightSources.ElementAt(index).lightTexture.Bounds.Center.Y), (float)((NetFieldBase)Game1.currentLightSources.ElementAt(index).radius) / (float)(Game1.options.lightingQuality / 2), SpriteEffects.None, 0.9f); + { + SpriteBatch spriteBatch = Game1.spriteBatch; + Texture2D lightTexture = Game1.currentLightSources.ElementAt(index).lightTexture; + Vector2 position = Game1.GlobalToLocal(Game1.viewport, (Vector2)((NetFieldBase)Game1.currentLightSources.ElementAt(index).position)) / (float)(Game1.options.lightingQuality / 2); + Microsoft.Xna.Framework.Rectangle? sourceRectangle = new Microsoft.Xna.Framework.Rectangle?(Game1.currentLightSources.ElementAt(index).lightTexture.Bounds); + Color color = (Color)((NetFieldBase)Game1.currentLightSources.ElementAt(index).color); + Microsoft.Xna.Framework.Rectangle bounds = Game1.currentLightSources.ElementAt(index).lightTexture.Bounds; + double x = (double)bounds.Center.X; + bounds = Game1.currentLightSources.ElementAt(index).lightTexture.Bounds; + double y = (double)bounds.Center.Y; + Vector2 origin = new Vector2((float)x, (float)y); + double num = (double)(float)((NetFieldBase)Game1.currentLightSources.ElementAt(index).radius) / (double)(Game1.options.lightingQuality / 2); + spriteBatch.Draw(lightTexture, position, sourceRectangle, color, 0.0f, origin, (float)num, SpriteEffects.None, 0.9f); + } } Game1.spriteBatch.End(); this.GraphicsDevice.SetRenderTarget((double)Game1.options.zoomLevel == 1.0 ? (RenderTarget2D)null : this.screen); } if (Game1.bloomDay && Game1.bloom != null) Game1.bloom.BeginDraw(); - this.GraphicsDevice.Clear(this.bgColor); + this.GraphicsDevice.Clear(Game1.bgColor); Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); if (++batchOpens == 1) events.Rendering.RaiseEmpty(); @@ -1113,16 +1126,13 @@ namespace StardewModdingAPI.Framework Vector2 local = Game1.GlobalToLocal(farmerShadow.Position + new Vector2(32f, 24f)); Microsoft.Xna.Framework.Rectangle? sourceRectangle = new Microsoft.Xna.Framework.Rectangle?(Game1.shadowTexture.Bounds); Color white = Color.White; - double num1 = 0.0; Microsoft.Xna.Framework.Rectangle bounds = Game1.shadowTexture.Bounds; double x = (double)bounds.Center.X; bounds = Game1.shadowTexture.Bounds; double y = (double)bounds.Center.Y; Vector2 origin = new Vector2((float)x, (float)y); - double num2 = 4.0 - (!farmerShadow.running && !farmerShadow.UsingTool || farmerShadow.FarmerSprite.currentAnimationIndex <= 1 ? 0.0 : (double)Math.Abs(FarmerRenderer.featureYOffsetPerFrame[farmerShadow.FarmerSprite.CurrentFrame]) * 0.5); - int num3 = 0; - double num4 = 0.0; - spriteBatch.Draw(shadowTexture, local, sourceRectangle, white, (float)num1, origin, (float)num2, (SpriteEffects)num3, (float)num4); + double num = 4.0 - (!farmerShadow.running && !farmerShadow.UsingTool || farmerShadow.FarmerSprite.currentAnimationIndex <= 1 ? 0.0 : (double)Math.Abs(FarmerRenderer.featureYOffsetPerFrame[farmerShadow.FarmerSprite.CurrentFrame]) * 0.5); + spriteBatch.Draw(shadowTexture, local, sourceRectangle, white, 0.0f, origin, (float)num, SpriteEffects.None, 0.0f); } } } @@ -1136,7 +1146,7 @@ namespace StardewModdingAPI.Framework { foreach (NPC character in Game1.currentLocation.characters) { - if (!(bool)((NetFieldBase)character.swimming) && !character.HideShadow && Game1.currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(character.getTileLocation())) + if (!(bool)((NetFieldBase)character.swimming) && !character.HideShadow && (!(bool)((NetFieldBase)character.isInvisible) && Game1.currentLocation.shouldShadowBeDrawnAboveBuildingsLayer(character.getTileLocation()))) Game1.spriteBatch.Draw(Game1.shadowTexture, Game1.GlobalToLocal(Game1.viewport, character.Position + new Vector2((float)(character.Sprite.SpriteWidth * 4) / 2f, (float)(character.GetBoundingBox().Height + (character.IsMonster ? 0 : 12)))), new Microsoft.Xna.Framework.Rectangle?(Game1.shadowTexture.Bounds), Color.White, 0.0f, new Vector2((float)Game1.shadowTexture.Bounds.Center.X, (float)Game1.shadowTexture.Bounds.Center.Y), (float)(4.0 + (double)character.yJumpOffset / 40.0) * (float)((NetFieldBase)character.scale), SpriteEffects.None, Math.Max(0.0f, (float)character.getStandingY() / 10000f) - 1E-06f); } } @@ -1157,16 +1167,13 @@ namespace StardewModdingAPI.Framework Vector2 local = Game1.GlobalToLocal(farmerShadow.Position + new Vector2(32f, 24f)); Microsoft.Xna.Framework.Rectangle? sourceRectangle = new Microsoft.Xna.Framework.Rectangle?(Game1.shadowTexture.Bounds); Color white = Color.White; - double num1 = 0.0; Microsoft.Xna.Framework.Rectangle bounds = Game1.shadowTexture.Bounds; double x = (double)bounds.Center.X; bounds = Game1.shadowTexture.Bounds; double y = (double)bounds.Center.Y; Vector2 origin = new Vector2((float)x, (float)y); - double num2 = 4.0 - (!farmerShadow.running && !farmerShadow.UsingTool || farmerShadow.FarmerSprite.currentAnimationIndex <= 1 ? 0.0 : (double)Math.Abs(FarmerRenderer.featureYOffsetPerFrame[farmerShadow.FarmerSprite.CurrentFrame]) * 0.5); - int num3 = 0; - double num4 = 0.0; - spriteBatch.Draw(shadowTexture, local, sourceRectangle, white, (float)num1, origin, (float)num2, (SpriteEffects)num3, (float)num4); + double num = 4.0 - (!farmerShadow.running && !farmerShadow.UsingTool || farmerShadow.FarmerSprite.currentAnimationIndex <= 1 ? 0.0 : (double)Math.Abs(FarmerRenderer.featureYOffsetPerFrame[farmerShadow.FarmerSprite.CurrentFrame]) * 0.5); + spriteBatch.Draw(shadowTexture, local, sourceRectangle, white, 0.0f, origin, (float)num, SpriteEffects.None, 0.0f); } } } @@ -1199,29 +1206,8 @@ namespace StardewModdingAPI.Framework Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); if (Game1.displayFarmer && Game1.player.ActiveObject != null && ((bool)((NetFieldBase)Game1.player.ActiveObject.bigCraftable) && this.checkBigCraftableBoundariesForFrontLayer()) && Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.getStandingX(), Game1.player.getStandingY()), Game1.viewport.Size) == null) Game1.drawPlayerHeldObject(Game1.player); - else if (Game1.displayFarmer && Game1.player.ActiveObject != null) - { - if (Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location((int)Game1.player.Position.X, (int)Game1.player.Position.Y - 38), Game1.viewport.Size) == null || Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location((int)Game1.player.Position.X, (int)Game1.player.Position.Y - 38), Game1.viewport.Size).TileIndexProperties.ContainsKey("FrontAlways")) - { - Layer layer1 = Game1.currentLocation.Map.GetLayer("Front"); - rectangle = Game1.player.GetBoundingBox(); - Location mapDisplayLocation1 = new Location(rectangle.Right, (int)Game1.player.Position.Y - 38); - Size size1 = Game1.viewport.Size; - if (layer1.PickTile(mapDisplayLocation1, size1) != null) - { - Layer layer2 = Game1.currentLocation.Map.GetLayer("Front"); - rectangle = Game1.player.GetBoundingBox(); - Location mapDisplayLocation2 = new Location(rectangle.Right, (int)Game1.player.Position.Y - 38); - Size size2 = Game1.viewport.Size; - if (layer2.PickTile(mapDisplayLocation2, size2).TileIndexProperties.ContainsKey("FrontAlways")) - goto label_129; - } - else - goto label_129; - } + else if (Game1.displayFarmer && Game1.player.ActiveObject != null && (Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location((int)Game1.player.Position.X, (int)Game1.player.Position.Y - 38), Game1.viewport.Size) != null && !Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location((int)Game1.player.Position.X, (int)Game1.player.Position.Y - 38), Game1.viewport.Size).TileIndexProperties.ContainsKey("FrontAlways") || Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.GetBoundingBox().Right, (int)Game1.player.Position.Y - 38), Game1.viewport.Size) != null && !Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.GetBoundingBox().Right, (int)Game1.player.Position.Y - 38), Game1.viewport.Size).TileIndexProperties.ContainsKey("FrontAlways"))) Game1.drawPlayerHeldObject(Game1.player); - } - label_129: if ((Game1.player.UsingTool || Game1.pickingTool) && Game1.player.CurrentTool != null && ((!Game1.player.CurrentTool.Name.Equals("Seeds") || Game1.pickingTool) && (Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.getStandingX(), (int)Game1.player.Position.Y - 38), Game1.viewport.Size) != null && Game1.currentLocation.Map.GetLayer("Front").PickTile(new Location(Game1.player.getStandingX(), Game1.player.getStandingY()), Game1.viewport.Size) == null))) Game1.drawTool(Game1.player); if (Game1.currentLocation.Map.GetLayer("AlwaysFront") != null) @@ -1329,17 +1315,16 @@ namespace StardewModdingAPI.Framework { int num4 = num3; viewport = Game1.graphics.GraphicsDevice.Viewport; - int width1 = viewport.Width; - if (num4 < width1) + int width = viewport.Width; + if (num4 < width) { SpriteBatch spriteBatch = Game1.spriteBatch; Texture2D staminaRect = Game1.staminaRect; int x = num3; int y = (int)num2; - int width2 = 1; viewport = Game1.graphics.GraphicsDevice.Viewport; int height = viewport.Height; - Microsoft.Xna.Framework.Rectangle destinationRectangle = new Microsoft.Xna.Framework.Rectangle(x, y, width2, height); + Microsoft.Xna.Framework.Rectangle destinationRectangle = new Microsoft.Xna.Framework.Rectangle(x, y, 1, height); Color color = Color.Red * 0.5f; spriteBatch.Draw(staminaRect, destinationRectangle, color); num3 += 64; @@ -1352,8 +1337,8 @@ namespace StardewModdingAPI.Framework { double num4 = (double)num5; viewport = Game1.graphics.GraphicsDevice.Viewport; - double height1 = (double)viewport.Height; - if (num4 < height1) + double height = (double)viewport.Height; + if (num4 < height) { SpriteBatch spriteBatch = Game1.spriteBatch; Texture2D staminaRect = Game1.staminaRect; @@ -1361,8 +1346,7 @@ namespace StardewModdingAPI.Framework int y = (int)num5; viewport = Game1.graphics.GraphicsDevice.Viewport; int width = viewport.Width; - int height2 = 1; - Microsoft.Xna.Framework.Rectangle destinationRectangle = new Microsoft.Xna.Framework.Rectangle(x, y, width, height2); + Microsoft.Xna.Framework.Rectangle destinationRectangle = new Microsoft.Xna.Framework.Rectangle(x, y, width, 1); Color color = Color.Red * 0.5f; spriteBatch.Draw(staminaRect, destinationRectangle, color); num5 += 64f; @@ -1379,9 +1363,11 @@ namespace StardewModdingAPI.Framework this.drawHUD(); events.RenderedHud.RaiseEmpty(); } - else if (Game1.activeClickableMenu == null && Game1.farmEvent == null) - Game1.spriteBatch.Draw(Game1.mouseCursors, new Vector2((float)Game1.getOldMouseX(), (float)Game1.getOldMouseY()), new Microsoft.Xna.Framework.Rectangle?(Game1.getSourceRectForStandardTileSheet(Game1.mouseCursors, 0, 16, 16)), Color.White, 0.0f, Vector2.Zero, (float)(4.0 + (double)Game1.dialogueButtonScale / 150.0), SpriteEffects.None, 1f); - if (Game1.hudMessages.Count > 0 && (!Game1.eventUp || Game1.isFestival())) + else if (Game1.activeClickableMenu == null) + { + FarmEvent farmEvent = Game1.farmEvent; + } + if (Game1.hudMessages.Count > 0) { for (int i = Game1.hudMessages.Count - 1; i >= 0; --i) Game1.hudMessages[i].draw(Game1.spriteBatch, i); @@ -1393,26 +1379,8 @@ namespace StardewModdingAPI.Framework this.drawDialogueBox(); if (Game1.progressBar) { - SpriteBatch spriteBatch1 = Game1.spriteBatch; - Texture2D fadeToBlackRect = Game1.fadeToBlackRect; - int x1 = (Game1.graphics.GraphicsDevice.Viewport.GetTitleSafeArea().Width - Game1.dialogueWidth) / 2; - rectangle = Game1.graphics.GraphicsDevice.Viewport.GetTitleSafeArea(); - int y1 = rectangle.Bottom - 128; - int dialogueWidth = Game1.dialogueWidth; - int height1 = 32; - Microsoft.Xna.Framework.Rectangle destinationRectangle1 = new Microsoft.Xna.Framework.Rectangle(x1, y1, dialogueWidth, height1); - Color lightGray = Color.LightGray; - spriteBatch1.Draw(fadeToBlackRect, destinationRectangle1, lightGray); - SpriteBatch spriteBatch2 = Game1.spriteBatch; - Texture2D staminaRect = Game1.staminaRect; - int x2 = (Game1.graphics.GraphicsDevice.Viewport.GetTitleSafeArea().Width - Game1.dialogueWidth) / 2; - rectangle = Game1.graphics.GraphicsDevice.Viewport.GetTitleSafeArea(); - int y2 = rectangle.Bottom - 128; - int width = (int)((double)Game1.pauseAccumulator / (double)Game1.pauseTime * (double)Game1.dialogueWidth); - int height2 = 32; - Microsoft.Xna.Framework.Rectangle destinationRectangle2 = new Microsoft.Xna.Framework.Rectangle(x2, y2, width, height2); - Color dimGray = Color.DimGray; - spriteBatch2.Draw(staminaRect, destinationRectangle2, dimGray); + Game1.spriteBatch.Draw(Game1.fadeToBlackRect, new Microsoft.Xna.Framework.Rectangle((Game1.graphics.GraphicsDevice.Viewport.GetTitleSafeArea().Width - Game1.dialogueWidth) / 2, Game1.graphics.GraphicsDevice.Viewport.GetTitleSafeArea().Bottom - 128, Game1.dialogueWidth, 32), Color.LightGray); + Game1.spriteBatch.Draw(Game1.staminaRect, new Microsoft.Xna.Framework.Rectangle((Game1.graphics.GraphicsDevice.Viewport.GetTitleSafeArea().Width - Game1.dialogueWidth) / 2, Game1.graphics.GraphicsDevice.Viewport.GetTitleSafeArea().Bottom - 128, (int)((double)Game1.pauseAccumulator / (double)Game1.pauseTime * (double)Game1.dialogueWidth), 32), Color.DimGray); } if (Game1.eventUp && Game1.currentLocation != null && Game1.currentLocation.currentEvent != null) Game1.currentLocation.currentEvent.drawAfterMap(Game1.spriteBatch); @@ -1497,6 +1465,8 @@ namespace StardewModdingAPI.Framework } else if (Game1.farmEvent != null) Game1.farmEvent.drawAboveEverything(Game1.spriteBatch); + if (Game1.emoteMenu != null) + Game1.emoteMenu.draw(Game1.spriteBatch); if (Game1.HostPaused) { string s = Game1.content.LoadString("Strings\\StringsFromCSFiles:DayTimeMoneyBox.cs.10378"); diff --git a/src/SMAPI/Metadata/CoreAssetPropagator.cs b/src/SMAPI/Metadata/CoreAssetPropagator.cs index a64dc89b..c4086712 100644 --- a/src/SMAPI/Metadata/CoreAssetPropagator.cs +++ b/src/SMAPI/Metadata/CoreAssetPropagator.cs @@ -152,12 +152,12 @@ namespace StardewModdingAPI.Metadata case "characters\\farmer\\farmer_base": // Farmer if (Game1.player == null || !Game1.player.IsMale) return false; - return Game1.player.FarmerRenderer = new FarmerRenderer(key); + return Game1.player.FarmerRenderer = new FarmerRenderer(key, Game1.player); case "characters\\farmer\\farmer_girl_base": // Farmer if (Game1.player == null || Game1.player.IsMale) return false; - return Game1.player.FarmerRenderer = new FarmerRenderer(key); + return Game1.player.FarmerRenderer = new FarmerRenderer(key, Game1.player); case "characters\\farmer\\hairstyles": // Game1.loadContent return FarmerRenderer.hairStylesTexture = content.Load(key); -- cgit From f8e32f4433647b7bd69590b937927808168649df Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 24 Apr 2019 01:26:15 -0400 Subject: update release notes, tweak launch script comments (#640) --- docs/release-notes.md | 1 + src/SMAPI.Installer/unix-launcher.sh | 12 +++++------- 2 files changed, 6 insertions(+), 7 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 32f4db37..12fd5a3d 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -6,6 +6,7 @@ These changes have not been released yet. * Updated for Stardew Valley 1.4. * Improved performance. * Updated mod compatibility list. + * Rewrote launch script on Linux to improve compatibility (thanks to kurumushi and toastal!). * Fixed Save Backup not pruning old backups if they're uncompressed. * Fixed issues when a farmhand reconnects before the game notices they're disconnected. * Fixed 'received message' logs shown in non-developer mode. diff --git a/src/SMAPI.Installer/unix-launcher.sh b/src/SMAPI.Installer/unix-launcher.sh index fc08577f..0ca5c852 100644 --- a/src/SMAPI.Installer/unix-launcher.sh +++ b/src/SMAPI.Installer/unix-launcher.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # MonoKickstart Shell Script # Written by Ethan "flibitijibibo" Lee -# Modified for StardewModdingAPI by Viz and Pathoschild +# Modified for SMAPI by various contributors # Move to script's directory cd "$(dirname "$0")" || exit $? @@ -61,9 +61,7 @@ else COMMAND="type" fi - # open SMAPI in terminal - # First let's try xterm (best compatiblity) or find a sensible default - # Setting TERMINAL should let you override this at the commandline for easier testing of other terminals. + # select terminal (prefer $TERMINAL for overrides and testing, then xterm for best compatibility, then known supported terminals) for terminal in "$TERMINAL" xterm x-terminal-emulator kitty terminator xfce4-terminal gnome-terminal konsole terminal termite; do if $COMMAND "$terminal" 2>/dev/null; then # Find the true shell behind x-terminal-emulator @@ -72,15 +70,15 @@ else break; else export LAUNCHTERM="$(basename "$(readlink -ef which x-terminal-emulator)")" - # Remember that we are using x-terminal-emulator just in case it points outside the $PATH + # Remember that we're using x-terminal-emulator just in case it points outside the $PATH export XTE=1 break; fi fi done + # if no terminal was found, run in current shell or with no output if [ -z "$LAUNCHTERM" ]; then - # We failed to detect a terminal, run in current shell, or with no output sh -c 'TERM=xterm $LAUNCHER' if [ $? -eq 127 ]; then $LAUNCHER --no-terminal @@ -88,7 +86,7 @@ else exit fi - # Now let's run the terminal and account for quirks, or if no terminal was found, run in the current process. + # run in selected terminal and account for quirks case $LAUNCHTERM in terminator) # Terminator converts -e to -x when used through x-terminal-emulator for some reason -- cgit From a450b0ebefbf7eb4ca5fa41947eef36fe18ca19a Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 1 May 2019 19:40:47 -0400 Subject: drop monitor.ExitGameImmediately method This is bad practice in most cases, and was only used by two mods which didn't legitimately need to exit immediately. --- docs/release-notes.md | 3 ++- src/SMAPI/Framework/Monitor.cs | 33 ++++++++------------------------- src/SMAPI/Framework/SCore.cs | 17 +++++++++-------- src/SMAPI/Framework/SGame.cs | 23 ++++++++++++++++++----- src/SMAPI/IMonitor.cs | 7 ------- 5 files changed, 37 insertions(+), 46 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 12fd5a3d..05fccd74 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -18,7 +18,8 @@ These changes have not been released yet. * Added `Context.IsGameLaunched` field. * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialised when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialised). * When a mod is incompatible, the trace logs now list all detected issues instead of the first one. - * Dropped support for all deprecated APIs. + * Removed all deprecated APIs. + * Removed the `Monitor.ExitGameImmediately` method. * Updated to Json.NET 12.0.1. ## 2.11.3 diff --git a/src/SMAPI/Framework/Monitor.cs b/src/SMAPI/Framework/Monitor.cs index 617bfd85..3771f114 100644 --- a/src/SMAPI/Framework/Monitor.cs +++ b/src/SMAPI/Framework/Monitor.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using System.Threading; using StardewModdingAPI.Framework.Logging; using StardewModdingAPI.Internal.ConsoleWriting; @@ -27,16 +26,10 @@ namespace StardewModdingAPI.Framework /// The maximum length of the values. private static readonly int MaxLevelLength = (from level in Enum.GetValues(typeof(LogLevel)).Cast() select level.ToString().Length).Max(); - /// Propagates notification that SMAPI should exit. - private readonly CancellationTokenSource ExitTokenSource; - /********* ** Accessors *********/ - /// Whether SMAPI is aborting. Mods don't need to worry about this unless they have background tasks. - public bool IsExiting => this.ExitTokenSource.IsCancellationRequested; - /// Whether verbose logging is enabled. This enables more detailed diagnostic messages than are normally needed. public bool IsVerbose { get; } @@ -57,10 +50,9 @@ namespace StardewModdingAPI.Framework /// The name of the module which logs messages using this instance. /// Intercepts access to the console output. /// The log file to which to write messages. - /// Propagates notification that SMAPI should exit. /// The console color scheme to use. /// Whether verbose logging is enabled. This enables more detailed diagnostic messages than are normally needed. - public Monitor(string source, ConsoleInterceptionManager consoleInterceptor, LogFileManager logFile, CancellationTokenSource exitTokenSource, MonitorColorScheme colorScheme, bool isVerbose) + public Monitor(string source, ConsoleInterceptionManager consoleInterceptor, LogFileManager logFile, MonitorColorScheme colorScheme, bool isVerbose) { // validate if (string.IsNullOrWhiteSpace(source)) @@ -71,7 +63,6 @@ namespace StardewModdingAPI.Framework this.LogFile = logFile ?? throw new ArgumentNullException(nameof(logFile), "The log file manager cannot be null."); this.ConsoleWriter = new ColorfulConsoleWriter(Constants.Platform, colorScheme); this.ConsoleInterceptor = consoleInterceptor; - this.ExitTokenSource = exitTokenSource; this.IsVerbose = isVerbose; } @@ -91,14 +82,6 @@ namespace StardewModdingAPI.Framework this.Log(message, LogLevel.Trace); } - /// Immediately exit the game without saving. This should only be invoked when an irrecoverable fatal error happens that risks save corruption or game-breaking bugs. - /// The reason for the shutdown. - public void ExitGameImmediately(string reason) - { - this.LogFatal($"{this.Source} requested an immediate game shutdown: {reason}"); - this.ExitTokenSource.Cancel(); - } - /// Write a newline to the console and log file. internal void Newline() { @@ -107,6 +90,13 @@ namespace StardewModdingAPI.Framework this.LogFile.WriteLine(""); } + /// Log a fatal error message. + /// The message to log. + internal void LogFatal(string message) + { + this.LogImpl(this.Source, message, ConsoleLogLevel.Critical); + } + /// Log console input from the user. /// The user input to log. internal void LogUserInput(string input) @@ -120,13 +110,6 @@ namespace StardewModdingAPI.Framework /********* ** Private methods *********/ - /// Log a fatal error message. - /// The message to log. - private void LogFatal(string message) - { - this.LogImpl(this.Source, message, ConsoleLogLevel.Critical); - } - /// Write a message line to the log. /// The name of the mod logging the message. /// The message to log. diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index e8d5b672..03a27fa9 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -57,7 +57,7 @@ namespace StardewModdingAPI.Framework private readonly Monitor MonitorForGame; /// Tracks whether the game should exit immediately and any pending initialisation should be cancelled. - private readonly CancellationTokenSource CancellationTokenSource = new CancellationTokenSource(); + private readonly CancellationTokenSource CancellationToken = new CancellationTokenSource(); /// Simplifies access to private game code. private readonly Reflector Reflection = new Reflector(); @@ -144,7 +144,7 @@ namespace StardewModdingAPI.Framework // init basics this.Settings = JsonConvert.DeserializeObject(File.ReadAllText(Constants.ApiConfigPath)); this.LogFile = new LogFileManager(logPath); - this.Monitor = new Monitor("SMAPI", this.ConsoleManager, this.LogFile, this.CancellationTokenSource, this.Settings.ColorScheme, this.Settings.VerboseLogging) + this.Monitor = new Monitor("SMAPI", this.ConsoleManager, this.LogFile, this.Settings.ColorScheme, this.Settings.VerboseLogging) { WriteToConsole = writeToConsole, ShowTraceInConsole = this.Settings.DeveloperMode, @@ -222,7 +222,8 @@ namespace StardewModdingAPI.Framework modRegistry: this.ModRegistry, deprecationManager: SCore.DeprecationManager, onGameInitialised: this.InitialiseAfterGameStart, - onGameExiting: this.Dispose + onGameExiting: this.Dispose, + cancellationToken: this.CancellationToken ); StardewValley.Program.gamePtr = this.GameInstance; @@ -237,7 +238,7 @@ namespace StardewModdingAPI.Framework // add exit handler new Thread(() => { - this.CancellationTokenSource.Token.WaitHandle.WaitOne(); + this.CancellationToken.Token.WaitHandle.WaitOne(); if (this.IsGameRunning) { try @@ -363,7 +364,7 @@ namespace StardewModdingAPI.Framework this.IsGameRunning = false; this.ConsoleManager?.Dispose(); this.ContentCore?.Dispose(); - this.CancellationTokenSource?.Dispose(); + this.CancellationToken?.Dispose(); this.GameInstance?.Dispose(); this.LogFile?.Dispose(); @@ -378,7 +379,7 @@ namespace StardewModdingAPI.Framework /// Initialise mods before the first game asset is loaded. At this point the core content managers are loaded (so mods can load their own assets), but the game is mostly uninitialised. private void InitialiseBeforeFirstAssetLoaded() { - if (this.Monitor.IsExiting) + if (this.CancellationToken.IsCancellationRequested) { this.Monitor.Log("SMAPI shutting down: aborting initialisation.", LogLevel.Warn); return; @@ -482,7 +483,7 @@ namespace StardewModdingAPI.Framework inputThread.Start(); // keep console thread alive while the game is running - while (this.IsGameRunning && !this.Monitor.IsExiting) + while (this.IsGameRunning && !this.CancellationToken.IsCancellationRequested) Thread.Sleep(1000 / 10); if (inputThread.ThreadState == ThreadState.Running) inputThread.Abort(); @@ -1336,7 +1337,7 @@ namespace StardewModdingAPI.Framework /// The name of the module which will log messages with this instance. private Monitor GetSecondaryMonitor(string name) { - return new Monitor(name, this.ConsoleManager, this.LogFile, this.CancellationTokenSource, this.Settings.ColorScheme, this.Settings.VerboseLogging) + return new Monitor(name, this.ConsoleManager, this.LogFile, this.Settings.ColorScheme, this.Settings.VerboseLogging) { WriteToConsole = this.Monitor.WriteToConsole, ShowTraceInConsole = this.Settings.DeveloperMode, diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index c06f62cf..2d43f8c4 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -43,7 +43,7 @@ namespace StardewModdingAPI.Framework ** SMAPI state ****/ /// Encapsulates monitoring and logging for SMAPI. - private readonly IMonitor Monitor; + private readonly Monitor Monitor; /// Encapsulates monitoring and logging on the game's behalf. private readonly IMonitor MonitorForGame; @@ -85,6 +85,9 @@ namespace StardewModdingAPI.Framework /// Simplifies access to private game code. private readonly Reflector Reflection; + /// Propagates notification that SMAPI should exit. + private readonly CancellationTokenSource CancellationToken; + /**** ** Game state ****/ @@ -137,7 +140,8 @@ namespace StardewModdingAPI.Framework /// Manages deprecation warnings. /// A callback to invoke after the game finishes initialising. /// A callback to invoke when the game exits. - internal SGame(IMonitor monitor, IMonitor monitorForGame, Reflector reflection, EventManager eventManager, JsonHelper jsonHelper, ModRegistry modRegistry, DeprecationManager deprecationManager, Action onGameInitialised, Action onGameExiting) + /// Propagates notification that SMAPI should exit. + internal SGame(Monitor monitor, IMonitor monitorForGame, Reflector reflection, EventManager eventManager, JsonHelper jsonHelper, ModRegistry modRegistry, DeprecationManager deprecationManager, Action onGameInitialised, Action onGameExiting, CancellationTokenSource cancellationToken) { this.OnLoadingFirstAsset = SGame.ConstructorHack.OnLoadingFirstAsset; SGame.ConstructorHack = null; @@ -161,6 +165,7 @@ namespace StardewModdingAPI.Framework Game1.input = new SInputState(); Game1.multiplayer = new SMultiplayer(monitor, eventManager, jsonHelper, modRegistry, reflection, this.OnModMessageReceived); Game1.hooks = new SModHooks(this.OnNewDayAfterFade); + this.CancellationToken = cancellationToken; // init observables Game1.locations = new ObservableCollection(); @@ -274,7 +279,7 @@ namespace StardewModdingAPI.Framework } // Abort if SMAPI is exiting. - if (this.Monitor.IsExiting) + if (this.CancellationToken.IsCancellationRequested) { this.Monitor.Log("SMAPI shutting down: aborting update.", LogLevel.Trace); return; @@ -805,7 +810,7 @@ namespace StardewModdingAPI.Framework // exit if irrecoverable if (!this.UpdateCrashTimer.Decrement()) - this.Monitor.ExitGameImmediately("the game crashed when updating, and SMAPI was unable to recover the game."); + this.ExitGameImmediately("The game crashed when updating, and SMAPI was unable to recover the game."); } } @@ -827,7 +832,7 @@ namespace StardewModdingAPI.Framework // exit if irrecoverable if (!this.DrawCrashTimer.Decrement()) { - this.Monitor.ExitGameImmediately("the game crashed when drawing, and SMAPI was unable to recover the game."); + this.ExitGameImmediately("The game crashed when drawing, and SMAPI was unable to recover the game."); return; } @@ -1481,5 +1486,13 @@ namespace StardewModdingAPI.Framework } } } + + /// Immediately exit the game without saving. This should only be invoked when an irrecoverable fatal error happens that risks save corruption or game-breaking bugs. + /// The fatal log message. + private void ExitGameImmediately(string message) + { + this.Monitor.LogFatal(message); + this.CancellationToken.Cancel(); + } } } diff --git a/src/SMAPI/IMonitor.cs b/src/SMAPI/IMonitor.cs index 943c1c59..f2d110b8 100644 --- a/src/SMAPI/IMonitor.cs +++ b/src/SMAPI/IMonitor.cs @@ -6,9 +6,6 @@ namespace StardewModdingAPI /********* ** Accessors *********/ - /// Whether SMAPI is aborting. Mods don't need to worry about this unless they have background tasks. - bool IsExiting { get; } - /// Whether verbose logging is enabled. This enables more detailed diagnostic messages than are normally needed. bool IsVerbose { get; } @@ -24,9 +21,5 @@ namespace StardewModdingAPI /// Log a message that only appears when is enabled. /// The message to log. void VerboseLog(string message); - - /// Immediately exit the game without saving. This should only be invoked when an irrecoverable fatal error happens that risks save corruption or game-breaking bugs. - /// The reason for the shutdown. - void ExitGameImmediately(string reason); } } -- cgit From 30cc7ac9161e4cea91c3b566a7edb5e438af98cb Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 1 May 2019 23:45:50 -0400 Subject: consolidate XNB mods when scanning mods --- docs/release-notes.md | 1 + .../Framework/ModScanning/ModScanner.cs | 27 ++++++++++++++++++---- src/SMAPI.Toolkit/ModToolkit.cs | 9 ++++++++ 3 files changed, 32 insertions(+), 5 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 05fccd74..68763598 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -7,6 +7,7 @@ These changes have not been released yet. * Improved performance. * Updated mod compatibility list. * Rewrote launch script on Linux to improve compatibility (thanks to kurumushi and toastal!). + * Improved handling for XNB mods unzipped into `Mods` (improved detection over generic invalid mods, and multi-folder XNB mods are now counted as one mod). * Fixed Save Backup not pruning old backups if they're uncompressed. * Fixed issues when a farmhand reconnects before the game notices they're disconnected. * Fixed 'received message' logs shown in non-developer mode. diff --git a/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs b/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs index 507e7be2..ae0f292f 100644 --- a/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs +++ b/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs @@ -52,6 +52,15 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning return this.GetModFolders(root, root); } + /// Extract information about all mods in the given folder. + /// The root folder containing mods. Only the will be searched, but this field allows it to be treated as a potential mod folder of its own. + /// The mod path to search. + // /// If the folder contains multiple XNB mods, treat them as subfolders of a single mod. This is useful when reading a single mod archive, as opposed to a mods folder. + public IEnumerable GetModFolders(string rootPath, string modPath) + { + return this.GetModFolders(root: new DirectoryInfo(rootPath), folder: new DirectoryInfo(modPath)); + } + /// Extract information from a mod folder. /// The root folder containing mods. /// The folder to search for a mod. @@ -120,17 +129,25 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning /// The folder to search for mods. public IEnumerable GetModFolders(DirectoryInfo root, DirectoryInfo folder) { + bool isRoot = folder.FullName == root.FullName; + // skip - if (folder.FullName != root.FullName && folder.Name.StartsWith(".")) + if (!isRoot && folder.Name.StartsWith(".")) yield return new ModFolder(root, folder, ModType.Invalid, null, "ignored folder because its name starts with a dot.", shouldBeLoaded: false); - // recurse into subfolders + // find mods in subfolders else if (this.IsModSearchFolder(root, folder)) { - foreach (DirectoryInfo subfolder in folder.EnumerateDirectories()) + ModFolder[] subfolders = folder.EnumerateDirectories().SelectMany(sub => this.GetModFolders(root, sub)).ToArray(); + if (!isRoot && subfolders.Length > 1 && subfolders.All(p => p.Type == ModType.Xnb)) + { + // if this isn't the root, and all subfolders are XNB mods, treat the whole folder as one XNB mod + yield return new ModFolder(folder, folder, ModType.Xnb, null, subfolders[0].ManifestParseError); + } + else { - foreach (ModFolder match in this.GetModFolders(root, subfolder)) - yield return match; + foreach (ModFolder subfolder in subfolders) + yield return subfolder; } } diff --git a/src/SMAPI.Toolkit/ModToolkit.cs b/src/SMAPI.Toolkit/ModToolkit.cs index 1b53e59e..f1da62a2 100644 --- a/src/SMAPI.Toolkit/ModToolkit.cs +++ b/src/SMAPI.Toolkit/ModToolkit.cs @@ -69,6 +69,15 @@ namespace StardewModdingAPI.Toolkit return new ModScanner(this.JsonHelper).GetModFolders(rootPath); } + /// Extract information about all mods in the given folder. + /// The root folder containing mods. Only the will be searched, but this field allows it to be treated as a potential mod folder of its own. + /// The mod path to search. + // /// If the folder contains multiple XNB mods, treat them as subfolders of a single mod. This is useful when reading a single mod archive, as opposed to a mods folder. + public IEnumerable GetModFolders(string rootPath, string modPath) + { + return new ModScanner(this.JsonHelper).GetModFolders(rootPath, modPath); + } + /// Get an update URL for an update key (if valid). /// The update key. public string GetUpdateUrl(string updateKey) -- cgit From 83ae036e09aab6830fcf83ae3065628d4ab91143 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 4 May 2019 13:53:34 -0400 Subject: improve XNB mod and ignore file matching --- docs/release-notes.md | 7 +- .../Framework/ModScanning/ModFolder.cs | 20 ++- .../Framework/ModScanning/ModParseError.cs | 24 ++++ .../Framework/ModScanning/ModScanner.cs | 141 ++++++++++++++++----- src/SMAPI.Toolkit/Framework/ModScanning/ModType.cs | 3 + src/SMAPI/Framework/ModLoading/ModResolver.cs | 7 +- 6 files changed, 156 insertions(+), 46 deletions(-) create mode 100644 src/SMAPI.Toolkit/Framework/ModScanning/ModParseError.cs (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 68763598..14d1a8fa 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -5,9 +5,12 @@ These changes have not been released yet. * For players: * Updated for Stardew Valley 1.4. * Improved performance. - * Updated mod compatibility list. * Rewrote launch script on Linux to improve compatibility (thanks to kurumushi and toastal!). - * Improved handling for XNB mods unzipped into `Mods` (improved detection over generic invalid mods, and multi-folder XNB mods are now counted as one mod). + * Improved mod scanning: + * Now ignores metadata files/folders like `__MACOSX` and `__folder_managed_by_vortex`. + * Now ignores content files like `.txt` or `.png`, which avoids missing-manifest errors in some common cases. + * Now detects XNB mods more accurately, and consolidates multi-folder XNB mods. + * Updated mod compatibility list. * Fixed Save Backup not pruning old backups if they're uncompressed. * Fixed issues when a farmhand reconnects before the game notices they're disconnected. * Fixed 'received message' logs shown in non-developer mode. diff --git a/src/SMAPI.Toolkit/Framework/ModScanning/ModFolder.cs b/src/SMAPI.Toolkit/Framework/ModScanning/ModFolder.cs index adfee527..4ce17c66 100644 --- a/src/SMAPI.Toolkit/Framework/ModScanning/ModFolder.cs +++ b/src/SMAPI.Toolkit/Framework/ModScanning/ModFolder.cs @@ -25,30 +25,38 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning public Manifest Manifest { get; } /// The error which occurred parsing the manifest, if any. - public string ManifestParseError { get; } + public ModParseError ManifestParseError { get; set; } - /// Whether the mod should be loaded by default. This is false if it was found within a folder whose name starts with a dot. - public bool ShouldBeLoaded { get; } + /// A human-readable message for the , if any. + public string ManifestParseErrorText { get; set; } /********* ** Public methods *********/ + /// Construct an instance. + /// The root folder containing mods. + /// The folder containing the mod's manifest.json. + /// The mod type. + /// The mod manifest. + public ModFolder(DirectoryInfo root, DirectoryInfo directory, ModType type, Manifest manifest) + : this(root, directory, type, manifest, ModParseError.None, null) { } + /// Construct an instance. /// The root folder containing mods. /// The folder containing the mod's manifest.json. /// The mod type. /// The mod manifest. /// The error which occurred parsing the manifest, if any. - /// Whether the mod should be loaded by default. This should be false if it was found within a folder whose name starts with a dot. - public ModFolder(DirectoryInfo root, DirectoryInfo directory, ModType type, Manifest manifest, string manifestParseError = null, bool shouldBeLoaded = true) + /// A human-readable message for the , if any. + public ModFolder(DirectoryInfo root, DirectoryInfo directory, ModType type, Manifest manifest, ModParseError manifestParseError, string manifestParseErrorText) { // save info this.Directory = directory; this.Type = type; this.Manifest = manifest; this.ManifestParseError = manifestParseError; - this.ShouldBeLoaded = shouldBeLoaded; + this.ManifestParseErrorText = manifestParseErrorText; // set display name this.DisplayName = manifest?.Name; diff --git a/src/SMAPI.Toolkit/Framework/ModScanning/ModParseError.cs b/src/SMAPI.Toolkit/Framework/ModScanning/ModParseError.cs new file mode 100644 index 00000000..b10510ff --- /dev/null +++ b/src/SMAPI.Toolkit/Framework/ModScanning/ModParseError.cs @@ -0,0 +1,24 @@ +namespace StardewModdingAPI.Toolkit.Framework.ModScanning +{ + /// Indicates why a mod could not be parsed. + public enum ModParseError + { + /// No parse error. + None, + + /// The folder is empty or contains only ignored files. + EmptyFolder, + + /// The folder is ignored by convention. + IgnoredFolder, + + /// The mod's manifest.json could not be parsed. + ManifestInvalid, + + /// The folder contains non-ignored and non-XNB files, but none of them are manifest.json. + ManifestMissing, + + /// The folder is an XNB mod, which can't be loaded through SMAPI. + XnbMod + } +} diff --git a/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs b/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs index ae0f292f..54cb2b8b 100644 --- a/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs +++ b/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text.RegularExpressions; using StardewModdingAPI.Toolkit.Serialisation; using StardewModdingAPI.Toolkit.Serialisation.Models; @@ -17,20 +18,32 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning private readonly JsonHelper JsonHelper; /// A list of filesystem entry names to ignore when checking whether a folder should be treated as a mod. - private readonly HashSet IgnoreFilesystemEntries = new HashSet(StringComparer.InvariantCultureIgnoreCase) + private readonly HashSet IgnoreFilesystemEntries = new HashSet { - ".DS_Store", - "mcs", - "Thumbs.db" + // OS metadata files + new Regex(@"^__folder_managed_by_vortex$", RegexOptions.Compiled | RegexOptions.IgnoreCase), // Vortex mod manager + new Regex(@"^(?:__MACOSX|\._\.DS_Store|\.DS_Store|mcs)$", RegexOptions.Compiled | RegexOptions.IgnoreCase), // MacOS + new Regex(@"^(?:desktop\.ini|Thumbs\.db)$", RegexOptions.Compiled | RegexOptions.IgnoreCase), // Windows + new Regex(@"\.(?:url|lnk)$", RegexOptions.Compiled | RegexOptions.IgnoreCase), // Windows shortcut files + + // other + new Regex(@"\.(?:bmp|gif|jpeg|jpg|png|psd|tif)$", RegexOptions.Compiled | RegexOptions.IgnoreCase), // image files + new Regex(@"\.(?:md|rtf|txt)$", RegexOptions.Compiled | RegexOptions.IgnoreCase), // text files + new Regex(@"\.(?:backup|bak|old)$", RegexOptions.Compiled | RegexOptions.IgnoreCase) // backup file }; - /// The extensions for files which an XNB mod may contain. If a mod contains *only* these file extensions, it should be considered an XNB mod. + /// The extensions for files which an XNB mod may contain. If a mod doesn't have a manifest.json and contains *only* these file extensions, it should be considered an XNB mod. private readonly HashSet PotentialXnbModExtensions = new HashSet(StringComparer.InvariantCultureIgnoreCase) { - ".md", - ".png", - ".txt", - ".xnb" + // XNB files + ".xgs", + ".xnb", + ".xsb", + ".xwb", + + // unpacking artifacts + ".json", + ".yaml" }; @@ -72,30 +85,36 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning // set appropriate invalid-mod error if (manifestFile == null) { - FileInfo[] files = searchFolder.GetFiles("*", SearchOption.AllDirectories).Where(this.IsRelevant).ToArray(); + FileInfo[] files = this.RecursivelyGetRelevantFiles(searchFolder).ToArray(); if (!files.Any()) - return new ModFolder(root, searchFolder, ModType.Invalid, null, "it's an empty folder."); - if (files.All(file => this.PotentialXnbModExtensions.Contains(file.Extension))) - return new ModFolder(root, searchFolder, ModType.Xnb, null, "it's not a SMAPI mod (see https://smapi.io/xnb for info)."); - return new ModFolder(root, searchFolder, ModType.Invalid, null, "it contains files, but none of them are manifest.json."); + return new ModFolder(root, searchFolder, ModType.Invalid, null, ModParseError.EmptyFolder, "it's an empty folder."); + if (files.All(this.IsPotentialXnbFile)) + return new ModFolder(root, searchFolder, ModType.Xnb, null, ModParseError.XnbMod, "it's not a SMAPI mod (see https://smapi.io/xnb for info)."); + return new ModFolder(root, searchFolder, ModType.Invalid, null, ModParseError.ManifestMissing, "it contains files, but none of them are manifest.json."); } // read mod info Manifest manifest = null; - string manifestError = null; + ModParseError error = ModParseError.None; + string errorText = null; { try { if (!this.JsonHelper.ReadJsonFileIfExists(manifestFile.FullName, out manifest) || manifest == null) - manifestError = "its manifest is invalid."; + { + error = ModParseError.ManifestInvalid; + errorText = "its manifest is invalid."; + } } catch (SParseException ex) { - manifestError = $"parsing its manifest failed: {ex.Message}"; + error = ModParseError.ManifestInvalid; + errorText = $"parsing its manifest failed: {ex.Message}"; } catch (Exception ex) { - manifestError = $"parsing its manifest failed:\n{ex}"; + error = ModParseError.ManifestInvalid; + errorText = $"parsing its manifest failed:\n{ex}"; } } @@ -117,7 +136,7 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning } // build result - return new ModFolder(root, manifestFile.Directory, type, manifest, manifestError); + return new ModFolder(root, manifestFile.Directory, type, manifest, error, errorText); } @@ -127,28 +146,30 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning /// Recursively extract information about all mods in the given folder. /// The root mod folder. /// The folder to search for mods. - public IEnumerable GetModFolders(DirectoryInfo root, DirectoryInfo folder) + private IEnumerable GetModFolders(DirectoryInfo root, DirectoryInfo folder) { bool isRoot = folder.FullName == root.FullName; // skip - if (!isRoot && folder.Name.StartsWith(".")) - yield return new ModFolder(root, folder, ModType.Invalid, null, "ignored folder because its name starts with a dot.", shouldBeLoaded: false); - - // find mods in subfolders - else if (this.IsModSearchFolder(root, folder)) + if (!isRoot) { - ModFolder[] subfolders = folder.EnumerateDirectories().SelectMany(sub => this.GetModFolders(root, sub)).ToArray(); - if (!isRoot && subfolders.Length > 1 && subfolders.All(p => p.Type == ModType.Xnb)) + if (folder.Name.StartsWith(".")) { - // if this isn't the root, and all subfolders are XNB mods, treat the whole folder as one XNB mod - yield return new ModFolder(folder, folder, ModType.Xnb, null, subfolders[0].ManifestParseError); - } - else - { - foreach (ModFolder subfolder in subfolders) - yield return subfolder; + yield return new ModFolder(root, folder, ModType.Ignored, null, ModParseError.IgnoredFolder, "ignored folder because its name starts with a dot."); + yield break; } + if (!this.IsRelevant(folder)) + yield break; + } + + // find mods in subfolders + if (this.IsModSearchFolder(root, folder)) + { + IEnumerable subfolders = folder.EnumerateDirectories().SelectMany(sub => this.GetModFolders(root, sub)); + if (!isRoot) + subfolders = this.TryConsolidate(root, folder, subfolders.ToArray()); + foreach (ModFolder subfolder in subfolders) + yield return subfolder; } // treat as mod folder @@ -156,6 +177,26 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning yield return this.ReadFolder(root, folder); } + /// Consolidate adjacent folders into one mod folder, if possible. + /// The folder containing both parent and subfolders. + /// The parent folder to consolidate, if possible. + /// The subfolders to consolidate, if possible. + private IEnumerable TryConsolidate(DirectoryInfo root, DirectoryInfo parentFolder, ModFolder[] subfolders) + { + if (subfolders.Length > 1) + { + // a collection of empty folders + if (subfolders.All(p => p.ManifestParseError == ModParseError.EmptyFolder)) + return new[] { new ModFolder(root, parentFolder, ModType.Invalid, null, ModParseError.EmptyFolder, subfolders[0].ManifestParseErrorText) }; + + // an XNB mod + if (subfolders.All(p => p.Type == ModType.Xnb || p.ManifestParseError == ModParseError.EmptyFolder)) + return new[] { new ModFolder(root, parentFolder, ModType.Xnb, null, ModParseError.XnbMod, subfolders[0].ManifestParseErrorText) }; + } + + return subfolders; + } + /// Find the manifest for a mod folder. /// The folder to search. private FileInfo FindManifest(DirectoryInfo folder) @@ -193,11 +234,41 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning return subfolders.Any() && !files.Any(); } + /// Recursively get all relevant files in a folder based on the result of . + /// The root folder to search. + private IEnumerable RecursivelyGetRelevantFiles(DirectoryInfo folder) + { + foreach (FileSystemInfo entry in folder.GetFileSystemInfos()) + { + if (!this.IsRelevant(entry)) + continue; + + if (entry is FileInfo file) + yield return file; + + if (entry is DirectoryInfo subfolder) + { + foreach (FileInfo subfolderFile in this.RecursivelyGetRelevantFiles(subfolder)) + yield return subfolderFile; + } + } + } + /// Get whether a file or folder is relevant when deciding how to process a mod folder. /// The file or folder. private bool IsRelevant(FileSystemInfo entry) { - return !this.IgnoreFilesystemEntries.Contains(entry.Name); + return !this.IgnoreFilesystemEntries.Any(p => p.IsMatch(entry.Name)); + } + + /// Get whether a file is potentially part of an XNB mod. + /// The file. + private bool IsPotentialXnbFile(FileInfo entry) + { + if (!this.IsRelevant(entry)) + return true; + + return this.PotentialXnbModExtensions.Contains(entry.Extension); // use EndsWith to handle cases like image..png } /// Strip newlines from a string. diff --git a/src/SMAPI.Toolkit/Framework/ModScanning/ModType.cs b/src/SMAPI.Toolkit/Framework/ModScanning/ModType.cs index 2ceb9e40..bc86edb6 100644 --- a/src/SMAPI.Toolkit/Framework/ModScanning/ModType.cs +++ b/src/SMAPI.Toolkit/Framework/ModScanning/ModType.cs @@ -6,6 +6,9 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning /// The mod is invalid and its type could not be determined. Invalid, + /// The folder is ignored by convention. + Ignored, + /// A mod which uses SMAPI directly. Smapi, diff --git a/src/SMAPI/Framework/ModLoading/ModResolver.cs b/src/SMAPI/Framework/ModLoading/ModResolver.cs index f2002530..b6bdb357 100644 --- a/src/SMAPI/Framework/ModLoading/ModResolver.cs +++ b/src/SMAPI/Framework/ModLoading/ModResolver.cs @@ -38,13 +38,14 @@ namespace StardewModdingAPI.Framework.ModLoading } // build metadata - ModMetadataStatus status = folder.ManifestParseError == null || !folder.ShouldBeLoaded + bool shouldIgnore = folder.Type == ModType.Ignored; + ModMetadataStatus status = folder.ManifestParseError == ModParseError.None || shouldIgnore ? ModMetadataStatus.Found : ModMetadataStatus.Failed; string relativePath = PathUtilities.GetRelativePath(rootPath, folder.Directory.FullName); - yield return new ModMetadata(folder.DisplayName, folder.Directory.FullName, relativePath, manifest, dataRecord, isIgnored: !folder.ShouldBeLoaded) - .SetStatus(status, !folder.ShouldBeLoaded ? "disabled by dot convention" : folder.ManifestParseError); + yield return new ModMetadata(folder.DisplayName, folder.Directory.FullName, relativePath, manifest, dataRecord, isIgnored: shouldIgnore) + .SetStatus(status, shouldIgnore ? "disabled by dot convention" : folder.ManifestParseErrorText); } } -- cgit From f2dd11fe3fbe8b31665ad25e6e58b0026c00098e Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 10 May 2019 23:49:08 -0400 Subject: fix inconsistent LoadStage behavior when creating a new save --- docs/release-notes.md | 1 + src/SMAPI/Framework/SGame.cs | 2 +- src/SMAPI/Patches/LoadContextPatch.cs | 55 +++++++++++------------------------ 3 files changed, 19 insertions(+), 39 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 14d1a8fa..e4024d07 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -25,6 +25,7 @@ These changes have not been released yet. * Removed all deprecated APIs. * Removed the `Monitor.ExitGameImmediately` method. * Updated to Json.NET 12.0.1. + * Fixed `LoadStageChanged` event not raising correct flags in some cases when creating a new save. ## 2.11.3 Released 13 September 2019 for Stardew Valley 1.3.36. diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index 2d43f8c4..1d4db834 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -774,7 +774,7 @@ namespace StardewModdingAPI.Framework } // preloaded - if (Context.IsSaveLoaded && Context.LoadStage != LoadStage.Loaded && Context.LoadStage != LoadStage.Ready) + if (Context.IsSaveLoaded && Context.LoadStage != LoadStage.Loaded && Context.LoadStage != LoadStage.Ready && Game1.dayOfMonth != 0) this.OnLoadStageChanged(LoadStage.Loaded); // update tick diff --git a/src/SMAPI/Patches/LoadContextPatch.cs b/src/SMAPI/Patches/LoadContextPatch.cs index 3f86c9a9..93a059aa 100644 --- a/src/SMAPI/Patches/LoadContextPatch.cs +++ b/src/SMAPI/Patches/LoadContextPatch.cs @@ -1,16 +1,15 @@ using System; -using System.Collections.ObjectModel; -using System.Collections.Specialized; using Harmony; using StardewModdingAPI.Enums; using StardewModdingAPI.Framework.Patching; using StardewModdingAPI.Framework.Reflection; using StardewValley; using StardewValley.Menus; +using StardewValley.Minigames; namespace StardewModdingAPI.Patches { - /// A Harmony patch for which notifies SMAPI for save creation load stages. + /// Harmony patches which notify SMAPI for save creation load stages. /// This patch hooks into , checks if TitleMenu.transitioningCharacterCreationMenu is true (which means the player is creating a new save file), then raises after the location list is cleared twice (the second clear happens right before locations are created), and when the method ends. internal class LoadContextPatch : IHarmonyPatch { @@ -23,12 +22,6 @@ namespace StardewModdingAPI.Patches /// A callback to invoke when the load stage changes. private static Action OnStageChanged; - /// Whether was called as part of save creation. - private static bool IsCreating; - - /// The number of times that has been cleared since started. - private static int TimesLocationsCleared; - /********* ** Accessors @@ -53,9 +46,15 @@ namespace StardewModdingAPI.Patches /// The Harmony instance. public void Apply(HarmonyInstance harmony) { + // detect CreatedBasicInfo + harmony.Patch( + original: AccessTools.Method(typeof(TitleMenu), nameof(TitleMenu.createdNewCharacter)), + prefix: new HarmonyMethod(this.GetType(), nameof(LoadContextPatch.Before_TitleMenu_CreatedNewCharacter)) + ); + + // detect CreatedLocations harmony.Patch( original: AccessTools.Method(typeof(Game1), nameof(Game1.loadForNewGame)), - prefix: new HarmonyMethod(this.GetType(), nameof(LoadContextPatch.Before_Game1_LoadForNewGame)), postfix: new HarmonyMethod(this.GetType(), nameof(LoadContextPatch.After_Game1_LoadForNewGame)) ); } @@ -64,45 +63,25 @@ namespace StardewModdingAPI.Patches /********* ** Private methods *********/ - /// The method to call instead of . + /// Called before . /// Returns whether to execute the original method. /// This method must be static for Harmony to work correctly. See the Harmony documentation before renaming arguments. - private static bool Before_Game1_LoadForNewGame() + private static bool Before_TitleMenu_CreatedNewCharacter() { - LoadContextPatch.IsCreating = Game1.activeClickableMenu is TitleMenu menu && LoadContextPatch.Reflection.GetField(menu, "transitioningCharacterCreationMenu").GetValue(); - LoadContextPatch.TimesLocationsCleared = 0; - if (LoadContextPatch.IsCreating) - { - // raise CreatedBasicInfo after locations are cleared twice - ObservableCollection locations = (ObservableCollection)Game1.locations; - locations.CollectionChanged += LoadContextPatch.OnLocationListChanged; - } - + LoadContextPatch.OnStageChanged(LoadStage.CreatedBasicInfo); return true; } - /// The method to call instead after . + /// Called after . /// This method must be static for Harmony to work correctly. See the Harmony documentation before renaming arguments. private static void After_Game1_LoadForNewGame() { - if (LoadContextPatch.IsCreating) - { - // clean up - ObservableCollection locations = (ObservableCollection)Game1.locations; - locations.CollectionChanged -= LoadContextPatch.OnLocationListChanged; + bool creating = + (Game1.currentMinigame is Intro) // creating save with intro + || (Game1.activeClickableMenu is TitleMenu menu && LoadContextPatch.Reflection.GetField(menu, "transitioningCharacterCreationMenu").GetValue()); // creating save, skipped intro - // raise stage changed + if (creating) LoadContextPatch.OnStageChanged(LoadStage.CreatedLocations); - } - } - - /// Raised when changes. - /// The event sender. - /// The event arguments. - private static void OnLocationListChanged(object sender, NotifyCollectionChangedEventArgs e) - { - if (++LoadContextPatch.TimesLocationsCleared == 2) - LoadContextPatch.OnStageChanged(LoadStage.CreatedBasicInfo); } } } -- cgit From 5cd5e2416dfe6eab1a36be1646890d57f3f4a191 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Thu, 16 May 2019 19:16:08 -0400 Subject: fix cache misses for non-English players --- docs/release-notes.md | 1 + .../ContentManagers/GameContentManager.cs | 32 ++++++++++++++++------ 2 files changed, 24 insertions(+), 9 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index e4024d07..3718ac38 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -15,6 +15,7 @@ These changes have not been released yet. * Fixed issues when a farmhand reconnects before the game notices they're disconnected. * Fixed 'received message' logs shown in non-developer mode. * Fixed some assets not updated when you switch language to English. + * Fixed lag in some cases due to incorrect asset caching when playing in non-English. * For modders: * Added support for content pack translations. diff --git a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs index 6ce50f00..085982b6 100644 --- a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs @@ -119,15 +119,28 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The language code for which to inject the asset. public override void Inject(string assetName, T value, LanguageCode language) { + // handle explicit language in asset name + { + if (this.TryParseExplicitLanguageAssetKey(assetName, out string newAssetName, out LanguageCode newLanguage)) + { + this.Inject(newAssetName, value, newLanguage); + return; + } + } base.Inject(assetName, value, language); // track whether the injected asset is translatable for is-loaded lookups - bool isTranslated = this.TryParseExplicitLanguageAssetKey(assetName, out _, out _); - string localisedKey = isTranslated ? assetName : $"{assetName}.{language}"; - if (this.Cache.ContainsKey(localisedKey)) - this.IsLocalisableLookup[localisedKey] = true; - else if (!isTranslated && this.Cache.ContainsKey(assetName)) - this.IsLocalisableLookup[localisedKey] = false; + string keyWithLocale = $"{assetName}.{this.GetLocale(language)}"; + if (this.Cache.ContainsKey(keyWithLocale)) + { + this.IsLocalisableLookup[assetName] = true; + this.IsLocalisableLookup[keyWithLocale] = true; + } + else if (this.Cache.ContainsKey(assetName)) + { + this.IsLocalisableLookup[assetName] = false; + this.IsLocalisableLookup[keyWithLocale] = false; + } else this.Monitor.Log($"Asset '{assetName}' could not be found in the cache immediately after injection.", LogLevel.Error); } @@ -174,11 +187,11 @@ namespace StardewModdingAPI.Framework.ContentManagers return this.Cache.ContainsKey(normalisedAssetName); // translated - string localisedKey = $"{normalisedAssetName}.{this.GetLocale(this.GetCurrentLanguage())}"; - if (this.IsLocalisableLookup.TryGetValue(localisedKey, out bool localisable)) + string keyWithLocale = $"{normalisedAssetName}.{this.GetLocale(this.GetCurrentLanguage())}"; + if (this.IsLocalisableLookup.TryGetValue(keyWithLocale, out bool localisable)) { return localisable - ? this.Cache.ContainsKey(localisedKey) + ? this.Cache.ContainsKey(keyWithLocale) : this.Cache.ContainsKey(normalisedAssetName); } @@ -190,6 +203,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The asset key to parse. /// The asset name without the language code. /// The language code removed from the asset name. + /// Returns whether the asset key contains an explicit language and was successfully parsed. private bool TryParseExplicitLanguageAssetKey(string rawAsset, out string assetName, out LanguageCode language) { if (string.IsNullOrWhiteSpace(rawAsset)) -- cgit From 2b12bb32f67422a7d25eb7e2d8ea8e1c3e335708 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 17 May 2019 19:41:26 -0400 Subject: batch reload assets in some cases --- docs/release-notes.md | 1 + src/SMAPI/Framework/ContentCoordinator.cs | 9 +- src/SMAPI/Metadata/CoreAssetPropagator.cs | 263 ++++++++++++++++++++---------- 3 files changed, 183 insertions(+), 90 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 3718ac38..2b03579b 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -16,6 +16,7 @@ These changes have not been released yet. * Fixed 'received message' logs shown in non-developer mode. * Fixed some assets not updated when you switch language to English. * Fixed lag in some cases due to incorrect asset caching when playing in non-English. + * Fixed lag when a mod invalidates many NPC portraits/sprites at once. * For modders: * Added support for content pack translations. diff --git a/src/SMAPI/Framework/ContentCoordinator.cs b/src/SMAPI/Framework/ContentCoordinator.cs index 25eeb2ef..15f1c163 100644 --- a/src/SMAPI/Framework/ContentCoordinator.cs +++ b/src/SMAPI/Framework/ContentCoordinator.cs @@ -258,14 +258,7 @@ namespace StardewModdingAPI.Framework } // reload core game assets - int reloaded = 0; - foreach (var pair in removedAssetNames) - { - string key = pair.Key; - Type type = pair.Value; - if (this.CoreAssets.Propagate(this.MainContentManager, key, type)) // use an intercepted content manager - reloaded++; - } + int reloaded = this.CoreAssets.Propagate(this.MainContentManager, removedAssetNames); // use an intercepted content manager // report result if (removedAssetNames.Any()) diff --git a/src/SMAPI/Metadata/CoreAssetPropagator.cs b/src/SMAPI/Metadata/CoreAssetPropagator.cs index c4086712..dbb27b14 100644 --- a/src/SMAPI/Metadata/CoreAssetPropagator.cs +++ b/src/SMAPI/Metadata/CoreAssetPropagator.cs @@ -34,6 +34,19 @@ namespace StardewModdingAPI.Metadata /// Encapsulates monitoring and logging. private readonly IMonitor Monitor; + /// Optimised bucket categories for batch reloading assets. + private enum AssetBucket + { + /// NPC overworld sprites. + Sprite, + + /// Villager dialogue portraits. + Portrait, + + /// Any other asset. + Other + }; + /********* ** Public methods @@ -51,15 +64,42 @@ namespace StardewModdingAPI.Metadata /// Reload one of the game's core assets (if applicable). /// The content manager through which to reload the asset. - /// The asset key to reload. - /// The asset type to reload. - /// Returns whether an asset was reloaded. - public bool Propagate(LocalizedContentManager content, string key, Type type) + /// The asset keys and types to reload. + /// Returns the number of reloaded assets. + public int Propagate(LocalizedContentManager content, IDictionary assets) { - object result = this.PropagateImpl(content, key, type); - if (result is bool b) - return b; - return result != null; + // group into optimised lists + var buckets = assets.GroupBy(p => + { + if (this.IsInFolder(p.Key, "Characters") || this.IsInFolder(p.Key, "Characters\\Monsters")) + return AssetBucket.Sprite; + + if (this.IsInFolder(p.Key, "Portraits")) + return AssetBucket.Portrait; + + return AssetBucket.Other; + }); + + // reload assets + int reloaded = 0; + foreach (var bucket in buckets) + { + switch (bucket.Key) + { + case AssetBucket.Sprite: + reloaded += this.ReloadNpcSprites(content, bucket.Select(p => p.Key)); + break; + + case AssetBucket.Portrait: + reloaded += this.ReloadNpcPortraits(content, bucket.Select(p => p.Key)); + break; + + default: + reloaded += bucket.Count(p => this.PropagateOther(content, p.Key, p.Value)); + break; + } + } + return reloaded; } @@ -71,7 +111,7 @@ namespace StardewModdingAPI.Metadata /// The asset key to reload. /// The asset type to reload. /// Returns whether an asset was loaded. The return value may be true or false, or a non-null value for true. - private object PropagateImpl(LocalizedContentManager content, string key, Type type) + private bool PropagateOther(LocalizedContentManager content, string key, Type type) { key = this.GetNormalisedPath(key); @@ -147,147 +187,185 @@ namespace StardewModdingAPI.Metadata ** Content\Characters\Farmer ****/ case "characters\\farmer\\accessories": // Game1.loadContent - return FarmerRenderer.accessoriesTexture = content.Load(key); + FarmerRenderer.accessoriesTexture = content.Load(key); + return true; case "characters\\farmer\\farmer_base": // Farmer if (Game1.player == null || !Game1.player.IsMale) return false; - return Game1.player.FarmerRenderer = new FarmerRenderer(key, Game1.player); + Game1.player.FarmerRenderer = new FarmerRenderer(key, Game1.player); + return true; case "characters\\farmer\\farmer_girl_base": // Farmer if (Game1.player == null || Game1.player.IsMale) return false; - return Game1.player.FarmerRenderer = new FarmerRenderer(key, Game1.player); + Game1.player.FarmerRenderer = new FarmerRenderer(key, Game1.player); + return true; case "characters\\farmer\\hairstyles": // Game1.loadContent - return FarmerRenderer.hairStylesTexture = content.Load(key); + FarmerRenderer.hairStylesTexture = content.Load(key); + return true; case "characters\\farmer\\hats": // Game1.loadContent - return FarmerRenderer.hatsTexture = content.Load(key); + FarmerRenderer.hatsTexture = content.Load(key); + return true; case "characters\\farmer\\shirts": // Game1.loadContent - return FarmerRenderer.shirtsTexture = content.Load(key); + FarmerRenderer.shirtsTexture = content.Load(key); + return true; /**** ** Content\Data ****/ case "data\\achievements": // Game1.loadContent - return Game1.achievements = content.Load>(key); + Game1.achievements = content.Load>(key); + return true; case "data\\bigcraftablesinformation": // Game1.loadContent - return Game1.bigCraftablesInformation = content.Load>(key); + Game1.bigCraftablesInformation = content.Load>(key); + return true; case "data\\cookingrecipes": // CraftingRecipe.InitShared - return CraftingRecipe.cookingRecipes = content.Load>(key); + CraftingRecipe.cookingRecipes = content.Load>(key); + return true; case "data\\craftingrecipes": // CraftingRecipe.InitShared - return CraftingRecipe.craftingRecipes = content.Load>(key); + CraftingRecipe.craftingRecipes = content.Load>(key); + return true; case "data\\npcdispositions": // NPC constructor return this.ReloadNpcDispositions(content, key); case "data\\npcgifttastes": // Game1.loadContent - return Game1.NPCGiftTastes = content.Load>(key); + Game1.NPCGiftTastes = content.Load>(key); + return true; case "data\\objectinformation": // Game1.loadContent - return Game1.objectInformation = content.Load>(key); + Game1.objectInformation = content.Load>(key); + return true; /**** ** Content\Fonts ****/ case "fonts\\spritefont1": // Game1.loadContent - return Game1.dialogueFont = content.Load(key); + Game1.dialogueFont = content.Load(key); + return true; case "fonts\\smallfont": // Game1.loadContent - return Game1.smallFont = content.Load(key); + Game1.smallFont = content.Load(key); + return true; case "fonts\\tinyfont": // Game1.loadContent - return Game1.tinyFont = content.Load(key); + Game1.tinyFont = content.Load(key); + return true; case "fonts\\tinyfontborder": // Game1.loadContent - return Game1.tinyFontBorder = content.Load(key); + Game1.tinyFontBorder = content.Load(key); + return true; /**** ** Content\Lighting ****/ case "loosesprites\\lighting\\greenlight": // Game1.loadContent - return Game1.cauldronLight = content.Load(key); + Game1.cauldronLight = content.Load(key); + return true; case "loosesprites\\lighting\\indoorwindowlight": // Game1.loadContent - return Game1.indoorWindowLight = content.Load(key); + Game1.indoorWindowLight = content.Load(key); + return true; case "loosesprites\\lighting\\lantern": // Game1.loadContent - return Game1.lantern = content.Load(key); + Game1.lantern = content.Load(key); + return true; case "loosesprites\\lighting\\sconcelight": // Game1.loadContent - return Game1.sconceLight = content.Load(key); + Game1.sconceLight = content.Load(key); + return true; case "loosesprites\\lighting\\windowlight": // Game1.loadContent - return Game1.windowLight = content.Load(key); + Game1.windowLight = content.Load(key); + return true; /**** ** Content\LooseSprites ****/ case "loosesprites\\controllermaps": // Game1.loadContent - return Game1.controllerMaps = content.Load(key); + Game1.controllerMaps = content.Load(key); + return true; case "loosesprites\\cursors": // Game1.loadContent - return Game1.mouseCursors = content.Load(key); + Game1.mouseCursors = content.Load(key); + return true; case "loosesprites\\daybg": // Game1.loadContent - return Game1.daybg = content.Load(key); + Game1.daybg = content.Load(key); + return true; case "loosesprites\\font_bold": // Game1.loadContent - return SpriteText.spriteTexture = content.Load(key); + SpriteText.spriteTexture = content.Load(key); + return true; case "loosesprites\\font_colored": // Game1.loadContent - return SpriteText.coloredTexture = content.Load(key); + SpriteText.coloredTexture = content.Load(key); + return true; case "loosesprites\\nightbg": // Game1.loadContent - return Game1.nightbg = content.Load(key); + Game1.nightbg = content.Load(key); + return true; case "loosesprites\\shadow": // Game1.loadContent - return Game1.shadowTexture = content.Load(key); + Game1.shadowTexture = content.Load(key); + return true; /**** ** Content\Critters ****/ case "tilesheets\\crops": // Game1.loadContent - return Game1.cropSpriteSheet = content.Load(key); + Game1.cropSpriteSheet = content.Load(key); + return true; case "tilesheets\\debris": // Game1.loadContent - return Game1.debrisSpriteSheet = content.Load(key); + Game1.debrisSpriteSheet = content.Load(key); + return true; case "tilesheets\\emotes": // Game1.loadContent - return Game1.emoteSpriteSheet = content.Load(key); + Game1.emoteSpriteSheet = content.Load(key); + return true; case "tilesheets\\furniture": // Game1.loadContent - return Furniture.furnitureTexture = content.Load(key); + Furniture.furnitureTexture = content.Load(key); + return true; case "tilesheets\\projectiles": // Game1.loadContent - return Projectile.projectileSheet = content.Load(key); + Projectile.projectileSheet = content.Load(key); + return true; case "tilesheets\\rain": // Game1.loadContent - return Game1.rainTexture = content.Load(key); + Game1.rainTexture = content.Load(key); + return true; case "tilesheets\\tools": // Game1.ResetToolSpriteSheet Game1.ResetToolSpriteSheet(); return true; case "tilesheets\\weapons": // Game1.loadContent - return Tool.weaponsTexture = content.Load(key); + Tool.weaponsTexture = content.Load(key); + return true; /**** ** Content\Maps ****/ case "maps\\menutiles": // Game1.loadContent - return Game1.menuTexture = content.Load(key); + Game1.menuTexture = content.Load(key); + return true; case "maps\\springobjects": // Game1.loadContent - return Game1.objectSpriteSheet = content.Load(key); + Game1.objectSpriteSheet = content.Load(key); + return true; case "maps\\walls_and_floors": // Wallpaper - return Wallpaper.wallpaperTexture = content.Load(key); + Wallpaper.wallpaperTexture = content.Load(key); + return true; /**** ** Content\Minigames @@ -315,35 +393,43 @@ namespace StardewModdingAPI.Metadata ** Content\TileSheets ****/ case "tilesheets\\animations": // Game1.loadContent - return Game1.animations = content.Load(key); + Game1.animations = content.Load(key); + return true; case "tilesheets\\buffsicons": // Game1.loadContent - return Game1.buffsIcons = content.Load(key); + Game1.buffsIcons = content.Load(key); + return true; case "tilesheets\\bushes": // new Bush() reflection.GetField>(typeof(Bush), "texture").SetValue(new Lazy(() => content.Load(key))); return true; case "tilesheets\\craftables": // Game1.loadContent - return Game1.bigCraftableSpriteSheet = content.Load(key); + Game1.bigCraftableSpriteSheet = content.Load(key); + return true; case "tilesheets\\fruittrees": // FruitTree - return FruitTree.texture = content.Load(key); + FruitTree.texture = content.Load(key); + return true; /**** ** Content\TerrainFeatures ****/ case "terrainfeatures\\flooring": // Flooring - return Flooring.floorsTexture = content.Load(key); + Flooring.floorsTexture = content.Load(key); + return true; case "terrainfeatures\\hoedirt": // from HoeDirt - return HoeDirt.lightTexture = content.Load(key); + HoeDirt.lightTexture = content.Load(key); + return true; case "terrainfeatures\\hoedirtdark": // from HoeDirt - return HoeDirt.darkTexture = content.Load(key); + HoeDirt.darkTexture = content.Load(key); + return true; case "terrainfeatures\\hoedirtsnow": // from HoeDirt - return HoeDirt.snowTexture = content.Load(key); + HoeDirt.snowTexture = content.Load(key); + return true; case "terrainfeatures\\mushroom_tree": // from Tree return this.ReloadTreeTextures(content, key, Tree.mushroomTree); @@ -376,15 +462,9 @@ namespace StardewModdingAPI.Metadata if (this.IsInFolder(key, "Buildings")) return this.ReloadBuildings(content, key); - if (this.IsInFolder(key, "Characters") || this.IsInFolder(key, "Characters\\Monsters")) - return this.ReloadNpcSprites(content, key); - if (this.KeyStartsWith(key, "LooseSprites\\Fence")) return this.ReloadFenceTextures(key); - if (this.IsInFolder(key, "Portraits")) - return this.ReloadNpcPortraits(content, key); - // dynamic data if (this.IsInFolder(key, "Characters\\Dialogue")) return this.ReloadNpcDialogue(key); @@ -536,46 +616,65 @@ namespace StardewModdingAPI.Metadata /// Reload the sprites for matching NPCs. /// The content manager through which to reload the asset. - /// The asset key to reload. - /// Returns whether any textures were reloaded. - private bool ReloadNpcSprites(LocalizedContentManager content, string key) + /// The asset keys to reload. + /// Returns the number of reloaded assets. + private int ReloadNpcSprites(LocalizedContentManager content, IEnumerable keys) { // get NPCs + HashSet lookup = new HashSet(keys, StringComparer.InvariantCultureIgnoreCase); NPC[] characters = this.GetCharacters() - .Where(npc => npc.Sprite != null && this.GetNormalisedPath(npc.Sprite.textureName.Value) == key) + .Where(npc => npc.Sprite != null && lookup.Contains(this.GetNormalisedPath(npc.Sprite.textureName.Value))) .ToArray(); if (!characters.Any()) - return false; + return 0; - // update portrait - Texture2D texture = content.Load(key); - foreach (NPC character in characters) - this.SetSpriteTexture(character.Sprite, texture); - return true; + // update sprite + int reloaded = 0; + foreach (NPC npc in characters) + { + this.SetSpriteTexture(npc.Sprite, content.Load(npc.Sprite.textureName.Value)); + reloaded++; + } + + return reloaded; } /// Reload the portraits for matching NPCs. /// The content manager through which to reload the asset. - /// The asset key to reload. - /// Returns whether any textures were reloaded. - private bool ReloadNpcPortraits(LocalizedContentManager content, string key) + /// The asset key to reload. + /// Returns the number of reloaded assets. + private int ReloadNpcPortraits(LocalizedContentManager content, IEnumerable keys) { // get NPCs - NPC[] villagers = this.GetCharacters() - .Where(npc => npc.isVillager() && this.GetNormalisedPath($"Portraits\\{this.Reflection.GetMethod(npc, "getTextureName").Invoke()}") == key) + HashSet lookup = new HashSet(keys, StringComparer.InvariantCultureIgnoreCase); + var villagers = + ( + from npc in this.GetCharacters() + where npc.isVillager() + let textureKey = this.GetNormalisedPath($"Portraits\\{this.getTextureName(npc)}") + where lookup.Contains(textureKey) + select new { npc, textureKey } + ) .ToArray(); if (!villagers.Any()) - return false; + return 0; // update portrait - Texture2D texture = content.Load(key); - foreach (NPC villager in villagers) + int reloaded = 0; + foreach (var entry in villagers) { - villager.resetPortrait(); - villager.Portrait = texture; + entry.npc.resetPortrait(); + entry.npc.Portrait = content.Load(entry.textureKey); + reloaded++; } + return reloaded; + } - return true; + private string getTextureName(NPC npc) + { + string name = npc.Name; + string str = name == "Old Mariner" ? "Mariner" : (name == "Dwarf King" ? "DwarfKing" : (name == "Mister Qi" ? "MrQi" : (name == "???" ? "Monsters\\Shadow Guy" : name))); + return str; } /// Reload tree textures. -- cgit From 24160cacdce0b2e31a3f7dc130fe84cb164bcf19 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Thu, 23 May 2019 14:56:44 -0400 Subject: fix tilesheets not seasonalised when a map is reloaded (#642) --- docs/release-notes.md | 1 + src/SMAPI/Metadata/CoreAssetPropagator.cs | 1 + 2 files changed, 2 insertions(+) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 2b03579b..513423ca 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -17,6 +17,7 @@ These changes have not been released yet. * Fixed some assets not updated when you switch language to English. * Fixed lag in some cases due to incorrect asset caching when playing in non-English. * Fixed lag when a mod invalidates many NPC portraits/sprites at once. + * Fixed seasonal tilesheet issues when a mod reloads a map. * For modders: * Added support for content pack translations. diff --git a/src/SMAPI/Metadata/CoreAssetPropagator.cs b/src/SMAPI/Metadata/CoreAssetPropagator.cs index 4f8f1427..71e51cea 100644 --- a/src/SMAPI/Metadata/CoreAssetPropagator.cs +++ b/src/SMAPI/Metadata/CoreAssetPropagator.cs @@ -139,6 +139,7 @@ namespace StardewModdingAPI.Metadata if (!string.IsNullOrWhiteSpace(location.mapPath.Value) && this.GetNormalisedPath(location.mapPath.Value) == key) { location.reloadMap(); + location.updateSeasonalTileSheets(); location.updateWarps(); this.Reflection.GetField(location, nameof(location.interiorDoors)).SetValue(new InteriorDoorDictionary(location)); anyChanged = true; -- cgit From d4e09c5a8524fad43e2ecf94ade86673a94b85a5 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 25 May 2019 01:59:32 -0400 Subject: fix tilesheets seasonalised when loading an indoor map --- docs/release-notes.md | 3 ++- src/SMAPI/Framework/ModHelpers/ContentHelper.cs | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 513423ca..6b552395 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -17,7 +17,8 @@ These changes have not been released yet. * Fixed some assets not updated when you switch language to English. * Fixed lag in some cases due to incorrect asset caching when playing in non-English. * Fixed lag when a mod invalidates many NPC portraits/sprites at once. - * Fixed seasonal tilesheet issues when a mod reloads a map. + * Fixed map reloads resetting tilesheet seasons. + * Fixed outdoor tilesheets being seasonalised when added to an indoor location. * For modders: * Added support for content pack translations. diff --git a/src/SMAPI/Framework/ModHelpers/ContentHelper.cs b/src/SMAPI/Framework/ModHelpers/ContentHelper.cs index e02748d2..5c4c3bca 100644 --- a/src/SMAPI/Framework/ModHelpers/ContentHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ContentHelper.cs @@ -13,6 +13,7 @@ using StardewModdingAPI.Toolkit.Utilities; using StardewValley; using xTile; using xTile.Format; +using xTile.ObjectModel; using xTile.Tiles; namespace StardewModdingAPI.Framework.ModHelpers @@ -247,6 +248,7 @@ namespace StardewModdingAPI.Framework.ModHelpers return; relativeMapPath = this.ModContentManager.AssertAndNormaliseAssetName(relativeMapPath); // Mono's Path.GetDirectoryName doesn't handle Windows dir separators string relativeMapFolder = Path.GetDirectoryName(relativeMapPath) ?? ""; // folder path containing the map, relative to the mod folder + bool isOutdoors = map.Properties.TryGetValue("Outdoors", out PropertyValue outdoorsProperty) && outdoorsProperty != null; // fix tilesheets foreach (TileSheet tilesheet in map.TileSheets) @@ -259,7 +261,7 @@ namespace StardewModdingAPI.Framework.ModHelpers // get seasonal name (if applicable) string seasonalImageSource = null; - if (Context.IsSaveLoaded && Game1.currentSeason != null) + if (isOutdoors && Context.IsSaveLoaded && Game1.currentSeason != null) { string filename = Path.GetFileName(imageSource) ?? throw new InvalidOperationException($"The '{imageSource}' tilesheet couldn't be loaded: filename is unexpectedly null."); bool hasSeasonalPrefix = -- cgit From bf3738eacb192492113fd968b50ff57fac26557c Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 29 May 2019 21:26:57 -0400 Subject: add separate LogNetworkTraffic option --- docs/release-notes.md | 1 + src/SMAPI/Framework/Models/SConfig.cs | 3 +++ src/SMAPI/Framework/SCore.cs | 3 ++- src/SMAPI/Framework/SGame.cs | 5 +++-- src/SMAPI/Framework/SMultiplayer.cs | 17 +++++++++++------ src/SMAPI/SMAPI.config.json | 5 +++++ 6 files changed, 25 insertions(+), 9 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 6b552395..cfd33fbc 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -25,6 +25,7 @@ These changes have not been released yet. * Added `IContentPack.HasFile` method. * Added `Context.IsGameLaunched` field. * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialised when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialised). + * Added separate `LogNetworkTraffic` option to make verbose logging less overwhelmingly verbose. * When a mod is incompatible, the trace logs now list all detected issues instead of the first one. * Removed all deprecated APIs. * Removed the `Monitor.ExitGameImmediately` method. diff --git a/src/SMAPI/Framework/Models/SConfig.cs b/src/SMAPI/Framework/Models/SConfig.cs index e2b33160..2bc71adf 100644 --- a/src/SMAPI/Framework/Models/SConfig.cs +++ b/src/SMAPI/Framework/Models/SConfig.cs @@ -34,6 +34,9 @@ namespace StardewModdingAPI.Framework.Models /// Whether SMAPI should log more information about the game context. public bool VerboseLogging { get; set; } + /// Whether SMAPI should log network traffic. Best combined with , which includes network metadata. + public bool LogNetworkTraffic { get; set; } + /// Whether to generate a file in the mods folder with detailed metadata about the detected mods. public bool DumpMetadata { get; set; } diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index 03a27fa9..60deed70 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -223,7 +223,8 @@ namespace StardewModdingAPI.Framework deprecationManager: SCore.DeprecationManager, onGameInitialised: this.InitialiseAfterGameStart, onGameExiting: this.Dispose, - cancellationToken: this.CancellationToken + cancellationToken: this.CancellationToken, + logNetworkTraffic: this.Settings.LogNetworkTraffic ); StardewValley.Program.gamePtr = this.GameInstance; diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index 1d4db834..d37ca82f 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -141,7 +141,8 @@ namespace StardewModdingAPI.Framework /// A callback to invoke after the game finishes initialising. /// A callback to invoke when the game exits. /// Propagates notification that SMAPI should exit. - internal SGame(Monitor monitor, IMonitor monitorForGame, Reflector reflection, EventManager eventManager, JsonHelper jsonHelper, ModRegistry modRegistry, DeprecationManager deprecationManager, Action onGameInitialised, Action onGameExiting, CancellationTokenSource cancellationToken) + /// Whether to log network traffic. + internal SGame(Monitor monitor, IMonitor monitorForGame, Reflector reflection, EventManager eventManager, JsonHelper jsonHelper, ModRegistry modRegistry, DeprecationManager deprecationManager, Action onGameInitialised, Action onGameExiting, CancellationTokenSource cancellationToken, bool logNetworkTraffic) { this.OnLoadingFirstAsset = SGame.ConstructorHack.OnLoadingFirstAsset; SGame.ConstructorHack = null; @@ -163,7 +164,7 @@ namespace StardewModdingAPI.Framework this.OnGameInitialised = onGameInitialised; this.OnGameExiting = onGameExiting; Game1.input = new SInputState(); - Game1.multiplayer = new SMultiplayer(monitor, eventManager, jsonHelper, modRegistry, reflection, this.OnModMessageReceived); + Game1.multiplayer = new SMultiplayer(monitor, eventManager, jsonHelper, modRegistry, reflection, this.OnModMessageReceived, logNetworkTraffic); Game1.hooks = new SModHooks(this.OnNewDayAfterFade); this.CancellationToken = cancellationToken; diff --git a/src/SMAPI/Framework/SMultiplayer.cs b/src/SMAPI/Framework/SMultiplayer.cs index 382910a0..531c229e 100644 --- a/src/SMAPI/Framework/SMultiplayer.cs +++ b/src/SMAPI/Framework/SMultiplayer.cs @@ -51,6 +51,9 @@ namespace StardewModdingAPI.Framework /// A callback to invoke when a mod message is received. private readonly Action OnModMessageReceived; + /// Whether to log network traffic. + private readonly bool LogNetworkTraffic; + /********* ** Accessors @@ -72,7 +75,8 @@ namespace StardewModdingAPI.Framework /// Tracks the installed mods. /// Simplifies access to private code. /// A callback to invoke when a mod message is received. - public SMultiplayer(IMonitor monitor, EventManager eventManager, JsonHelper jsonHelper, ModRegistry modRegistry, Reflector reflection, Action onModMessageReceived) + /// Whether to log network traffic. + public SMultiplayer(IMonitor monitor, EventManager eventManager, JsonHelper jsonHelper, ModRegistry modRegistry, Reflector reflection, Action onModMessageReceived, bool logNetworkTraffic) { this.Monitor = monitor; this.EventManager = eventManager; @@ -80,6 +84,7 @@ namespace StardewModdingAPI.Framework this.ModRegistry = modRegistry; this.Reflection = reflection; this.OnModMessageReceived = onModMessageReceived; + this.LogNetworkTraffic = logNetworkTraffic; } /// Perform cleanup needed when a multiplayer session ends. @@ -143,7 +148,7 @@ namespace StardewModdingAPI.Framework /// Resume sending the underlying message. protected void OnClientSendingMessage(OutgoingMessage message, Action sendMessage, Action resume) { - if (this.Monitor.IsVerbose) + if (this.LogNetworkTraffic) this.Monitor.Log($"CLIENT SEND {(MessageType)message.MessageType} {message.FarmerID}", LogLevel.Trace); switch (message.MessageType) @@ -167,7 +172,7 @@ namespace StardewModdingAPI.Framework /// Process the message using the game's default logic. public void OnServerProcessingMessage(IncomingMessage message, Action sendMessage, Action resume) { - if (this.Monitor.IsVerbose) + if (this.LogNetworkTraffic) this.Monitor.Log($"SERVER RECV {(MessageType)message.MessageType} {message.FarmerID}", LogLevel.Trace); switch (message.MessageType) @@ -247,7 +252,7 @@ namespace StardewModdingAPI.Framework /// Returns whether the message was handled. public void OnClientProcessingMessage(IncomingMessage message, Action sendMessage, Action resume) { - if (this.Monitor.IsVerbose) + if (this.LogNetworkTraffic) this.Monitor.Log($"CLIENT RECV {(MessageType)message.MessageType} {message.FarmerID}", LogLevel.Trace); switch (message.MessageType) @@ -371,7 +376,7 @@ namespace StardewModdingAPI.Framework string data = JsonConvert.SerializeObject(model, Formatting.None); // log message - if (this.Monitor.IsVerbose) + if (this.LogNetworkTraffic) this.Monitor.Log($"Broadcasting '{messageType}' message: {data}.", LogLevel.Trace); // send message @@ -432,7 +437,7 @@ namespace StardewModdingAPI.Framework string json = message.Reader.ReadString(); ModMessageModel model = this.JsonHelper.Deserialise(json); HashSet playerIDs = new HashSet(model.ToPlayerIDs ?? this.GetKnownPlayerIDs()); - if (this.Monitor.IsVerbose) + if (this.LogNetworkTraffic) this.Monitor.Log($"Received message: {json}.", LogLevel.Trace); // notify local mods diff --git a/src/SMAPI/SMAPI.config.json b/src/SMAPI/SMAPI.config.json index c04cceee..450a32cc 100644 --- a/src/SMAPI/SMAPI.config.json +++ b/src/SMAPI/SMAPI.config.json @@ -61,6 +61,11 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha */ "VerboseLogging": false, + /** + * Whether SMAPI should log network traffic (may be very verbose). Best combined with VerboseLogging, which includes network metadata. + */ + "LogNetworkTraffic": false, + /** * Whether to generate a 'SMAPI-latest.metadata-dump.json' file in the logs folder with the full mod * metadata for detected mods. This is only needed when troubleshooting some cases. -- cgit From fff5e8c93921449afcfd1cebf7fd5616abc15d45 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 29 May 2019 22:32:52 -0400 Subject: move most mod asset loading logic into content managers (#644) This fixes mods needing to load Map assets manually before the game could load them via internal key. --- docs/release-notes.md | 1 + src/SMAPI/Framework/ContentCoordinator.cs | 16 +- .../Framework/ContentManagers/ModContentManager.cs | 185 +++++++++++++++++- src/SMAPI/Framework/ModHelpers/ContentHelper.cs | 215 +-------------------- 4 files changed, 200 insertions(+), 217 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index cfd33fbc..f8d4cbbf 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -11,6 +11,7 @@ These changes have not been released yet. * Now ignores content files like `.txt` or `.png`, which avoids missing-manifest errors in some common cases. * Now detects XNB mods more accurately, and consolidates multi-folder XNB mods. * Updated mod compatibility list. + * Fixed mods needing to load custom `Map` assets before the game accesses them (SMAPI will now do so automatically). * Fixed Save Backup not pruning old backups if they're uncompressed. * Fixed issues when a farmhand reconnects before the game notices they're disconnected. * Fixed 'received message' logs shown in non-developer mode. diff --git a/src/SMAPI/Framework/ContentCoordinator.cs b/src/SMAPI/Framework/ContentCoordinator.cs index 15f1c163..8bb63299 100644 --- a/src/SMAPI/Framework/ContentCoordinator.cs +++ b/src/SMAPI/Framework/ContentCoordinator.cs @@ -101,9 +101,21 @@ namespace StardewModdingAPI.Framework /// Get a new content manager which handles reading files from a SMAPI mod folder with support for unpacked files. /// A name for the mod manager. Not guaranteed to be unique. /// The root directory to search for content (or null for the default). - public ModContentManager CreateModContentManager(string name, string rootDirectory) + /// The game content manager used for map tilesheets not provided by the mod. + public ModContentManager CreateModContentManager(string name, string rootDirectory, IContentManager gameContentManager) { - ModContentManager manager = new ModContentManager(name, this.MainContentManager.ServiceProvider, rootDirectory, this.MainContentManager.CurrentCulture, this, this.Monitor, this.Reflection, this.JsonHelper, this.OnDisposing); + ModContentManager manager = new ModContentManager( + name: name, + gameContentManager: gameContentManager, + serviceProvider: this.MainContentManager.ServiceProvider, + rootDirectory: rootDirectory, + currentCulture: this.MainContentManager.CurrentCulture, + coordinator: this, + monitor: this.Monitor, + reflection: this.Reflection, + jsonHelper: this.JsonHelper, + onDisposing: this.OnDisposing + ); this.ContentManagers.Add(manager); return manager; } diff --git a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs index 1df7d107..45303f6b 100644 --- a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs @@ -1,12 +1,19 @@ using System; using System.Globalization; using System.IO; +using System.Linq; using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.Framework.Exceptions; using StardewModdingAPI.Framework.Reflection; using StardewModdingAPI.Toolkit.Serialisation; +using StardewModdingAPI.Toolkit.Utilities; using StardewValley; +using xTile; +using xTile.Format; +using xTile.ObjectModel; +using xTile.Tiles; namespace StardewModdingAPI.Framework.ContentManagers { @@ -19,12 +26,16 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Encapsulates SMAPI's JSON file parsing. private readonly JsonHelper JsonHelper; + /// The game content manager used for map tilesheets not provided by the mod. + private readonly IContentManager GameContentManager; + /********* ** Public methods *********/ /// Construct an instance. /// A name for the mod manager. Not guaranteed to be unique. + /// The game content manager used for map tilesheets not provided by the mod. /// The service provider to use to locate services. /// The root directory to search for content. /// The current culture for which to localise content. @@ -33,9 +44,10 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Simplifies access to private code. /// Encapsulates SMAPI's JSON file parsing. /// A callback to invoke when the content manager is being disposed. - public ModContentManager(string name, IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action onDisposing) + public ModContentManager(string name, IContentManager gameContentManager, IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action onDisposing) : base(name, serviceProvider, rootDirectory, currentCulture, coordinator, monitor, reflection, onDisposing, isModFolder: true) { + this.GameContentManager = gameContentManager; this.JsonHelper = jsonHelper; } @@ -47,11 +59,9 @@ namespace StardewModdingAPI.Framework.ContentManagers { assetName = this.AssertAndNormaliseAssetName(assetName); - // get from cache + // get managed asset if (this.IsLoaded(assetName)) return base.Load(assetName, language); - - // get managed asset if (this.Coordinator.TryParseManagedAssetKey(assetName, out string contentManagerID, out string relativePath)) { if (contentManagerID != this.Name) @@ -64,7 +74,11 @@ namespace StardewModdingAPI.Framework.ContentManagers return this.LoadManagedAsset(assetName, contentManagerID, relativePath, language); } - throw new NotSupportedException("Can't load content folder asset from a mod content manager."); + // get local asset + string internalKey = this.GetInternalAssetKey(assetName); + if (this.IsLoaded(internalKey)) + return base.Load(internalKey, language); + return this.LoadManagedAsset(internalKey, this.Name, assetName, this.Language); } /// Create a new content manager for temporary use. @@ -73,6 +87,16 @@ namespace StardewModdingAPI.Framework.ContentManagers throw new NotSupportedException("Can't create a temporary mod content manager."); } + /// Get the underlying key in the game's content cache for an asset. This does not validate whether the asset exists. + /// The local path to a content file relative to the mod folder. + /// The is empty or contains invalid characters. + public string GetInternalAssetKey(string key) + { + FileInfo file = this.GetModFile(key); + string relativePath = PathUtilities.GetRelativePath(this.RootDirectory, file.FullName); + return Path.Combine(this.Name, relativePath); + } + /********* ** Private methods @@ -133,7 +157,18 @@ namespace StardewModdingAPI.Framework.ContentManagers // unpacked map case ".tbin": - throw GetContentError($"can't read unpacked map file directly from the underlying content manager. It must be loaded through the mod's {typeof(IModHelper)}.{nameof(IModHelper.Content)} helper."); + // validate + if (typeof(T) != typeof(Map)) + throw GetContentError($"can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Map)}'."); + + // fetch & cache + FormatManager formatManager = FormatManager.Instance; + Map map = formatManager.LoadMap(file.FullName); + this.FixCustomTilesheetPaths(map, relativeMapPath: relativePath); + + // inject map + this.Inject(internalKey, map, this.Language); + return (T)(object)map; default: throw GetContentError($"unknown file extension '{file.Extension}'; must be one of '.json', '.png', '.tbin', or '.xnb'."); @@ -186,5 +221,143 @@ namespace StardewModdingAPI.Framework.ContentManagers texture.SetData(data); return texture; } + + /// Fix custom map tilesheet paths so they can be found by the content manager. + /// The map whose tilesheets to fix. + /// The relative map path within the mod folder. + /// A map tilesheet couldn't be resolved. + /// + /// The game's logic for tilesheets in is a bit specialised. It boils + /// down to this: + /// * If the location is indoors or the desert, or the image source contains 'path' or 'object', it's loaded + /// as-is relative to the Content folder. + /// * Else it's loaded from Content\Maps with a seasonal prefix. + /// + /// That logic doesn't work well in our case, mainly because we have no location metadata at this point. + /// Instead we use a more heuristic approach: check relative to the map file first, then relative to + /// Content\Maps, then Content. If the image source filename contains a seasonal prefix, try for a + /// seasonal variation and then an exact match. + /// + /// While that doesn't exactly match the game logic, it's close enough that it's unlikely to make a difference. + /// + private void FixCustomTilesheetPaths(Map map, string relativeMapPath) + { + // get map info + if (!map.TileSheets.Any()) + return; + relativeMapPath = this.AssertAndNormaliseAssetName(relativeMapPath); // Mono's Path.GetDirectoryName doesn't handle Windows dir separators + string relativeMapFolder = Path.GetDirectoryName(relativeMapPath) ?? ""; // folder path containing the map, relative to the mod folder + bool isOutdoors = map.Properties.TryGetValue("Outdoors", out PropertyValue outdoorsProperty) && outdoorsProperty != null; + + // fix tilesheets + foreach (TileSheet tilesheet in map.TileSheets) + { + string imageSource = tilesheet.ImageSource; + + // validate tilesheet path + if (Path.IsPathRooted(imageSource) || PathUtilities.GetSegments(imageSource).Contains("..")) + throw new ContentLoadException($"The '{imageSource}' tilesheet couldn't be loaded. Tilesheet paths must be a relative path without directory climbing (../)."); + + // get seasonal name (if applicable) + string seasonalImageSource = null; + if (isOutdoors && Context.IsSaveLoaded && Game1.currentSeason != null) + { + string filename = Path.GetFileName(imageSource) ?? throw new InvalidOperationException($"The '{imageSource}' tilesheet couldn't be loaded: filename is unexpectedly null."); + bool hasSeasonalPrefix = + filename.StartsWith("spring_", StringComparison.CurrentCultureIgnoreCase) + || filename.StartsWith("summer_", StringComparison.CurrentCultureIgnoreCase) + || filename.StartsWith("fall_", StringComparison.CurrentCultureIgnoreCase) + || filename.StartsWith("winter_", StringComparison.CurrentCultureIgnoreCase); + if (hasSeasonalPrefix && !filename.StartsWith(Game1.currentSeason + "_")) + { + string dirPath = imageSource.Substring(0, imageSource.LastIndexOf(filename, StringComparison.CurrentCultureIgnoreCase)); + seasonalImageSource = $"{dirPath}{Game1.currentSeason}_{filename.Substring(filename.IndexOf("_", StringComparison.CurrentCultureIgnoreCase) + 1)}"; + } + } + + // load best match + try + { + string key = + this.GetTilesheetAssetName(relativeMapFolder, seasonalImageSource) + ?? this.GetTilesheetAssetName(relativeMapFolder, imageSource); + if (key != null) + { + tilesheet.ImageSource = key; + continue; + } + } + catch (Exception ex) + { + throw new ContentLoadException($"The '{imageSource}' tilesheet couldn't be loaded relative to either map file or the game's content folder.", ex); + } + + // none found + throw new ContentLoadException($"The '{imageSource}' tilesheet couldn't be loaded relative to either map file or the game's content folder."); + } + } + + /// Get the actual asset name for a tilesheet. + /// The folder path containing the map, relative to the mod folder. + /// The tilesheet image source to load. + /// Returns the asset name. + /// See remarks on . + private string GetTilesheetAssetName(string modRelativeMapFolder, string imageSource) + { + if (imageSource == null) + return null; + + // check relative to map file + { + string localKey = Path.Combine(modRelativeMapFolder, imageSource); + FileInfo localFile = this.GetModFile(localKey); + if (localFile.Exists) + return this.GetInternalAssetKey(localKey); + } + + // check relative to content folder + { + foreach (string candidateKey in new[] { imageSource, Path.Combine("Maps", imageSource) }) + { + string contentKey = candidateKey.EndsWith(".png") + ? candidateKey.Substring(0, candidateKey.Length - 4) + : candidateKey; + + try + { + this.GameContentManager.Load(contentKey); + return contentKey; + } + catch + { + // ignore file-not-found errors + // TODO: while it's useful to suppress an asset-not-found error here to avoid + // confusion, this is a pretty naive approach. Even if the file doesn't exist, + // the file may have been loaded through an IAssetLoader which failed. So even + // if the content file doesn't exist, that doesn't mean the error here is a + // content-not-found error. Unfortunately XNA doesn't provide a good way to + // detect the error type. + if (this.GetContentFolderFileExists(contentKey)) + throw; + } + } + } + + // not found + return null; + } + + /// Get whether a file from the game's content folder exists. + /// The asset key. + private bool GetContentFolderFileExists(string key) + { + // get file path + string path = Path.Combine(this.GameContentManager.FullRootDirectory, key); + if (!path.EndsWith(".xnb")) + path += ".xnb"; + + // get file + return new FileInfo(path).Exists; + } } } diff --git a/src/SMAPI/Framework/ModHelpers/ContentHelper.cs b/src/SMAPI/Framework/ModHelpers/ContentHelper.cs index 5c4c3bca..2d65f1f6 100644 --- a/src/SMAPI/Framework/ModHelpers/ContentHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ContentHelper.cs @@ -9,12 +9,8 @@ using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.Framework.ContentManagers; using StardewModdingAPI.Framework.Exceptions; -using StardewModdingAPI.Toolkit.Utilities; using StardewValley; using xTile; -using xTile.Format; -using xTile.ObjectModel; -using xTile.Tiles; namespace StardewModdingAPI.Framework.ModHelpers { @@ -31,10 +27,7 @@ namespace StardewModdingAPI.Framework.ModHelpers private readonly IContentManager GameContentManager; /// A content manager for this mod which manages files from the mod's folder. - private readonly IContentManager ModContentManager; - - /// The absolute path to the mod folder. - private readonly string ModFolderPath; + private readonly ModContentManager ModContentManager; /// The friendly mod name for use in errors. private readonly string ModName; @@ -79,8 +72,7 @@ namespace StardewModdingAPI.Framework.ModHelpers { this.ContentCore = contentCore; this.GameContentManager = contentCore.CreateGameContentManager(this.ContentCore.GetManagedAssetPrefix(modID) + ".content"); - this.ModContentManager = contentCore.CreateModContentManager(this.ContentCore.GetManagedAssetPrefix(modID), rootDirectory: modFolderPath); - this.ModFolderPath = modFolderPath; + this.ModContentManager = contentCore.CreateModContentManager(this.ContentCore.GetManagedAssetPrefix(modID), modFolderPath, this.GameContentManager); this.ModName = modName; this.Monitor = monitor; } @@ -93,8 +85,6 @@ namespace StardewModdingAPI.Framework.ModHelpers /// The content asset couldn't be loaded (e.g. because it doesn't exist). public T Load(string key, ContentSource source = ContentSource.ModFolder) { - SContentLoadException GetContentError(string reasonPhrase) => new SContentLoadException($"{this.ModName} failed loading content asset '{key}' from {source}: {reasonPhrase}."); - try { this.AssertAndNormaliseAssetName(key); @@ -104,38 +94,10 @@ namespace StardewModdingAPI.Framework.ModHelpers return this.GameContentManager.Load(key); case ContentSource.ModFolder: - // get file - FileInfo file = this.GetModFile(key); - if (!file.Exists) - throw GetContentError($"there's no matching file at path '{file.FullName}'."); - string internalKey = this.GetInternalModAssetKey(file); - - // try cache - if (this.ModContentManager.IsLoaded(internalKey)) - return this.ModContentManager.Load(internalKey); - - // fix map tilesheets - if (file.Extension.ToLower() == ".tbin") - { - // validate - if (typeof(T) != typeof(Map)) - throw GetContentError($"can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Map)}'."); - - // fetch & cache - FormatManager formatManager = FormatManager.Instance; - Map map = formatManager.LoadMap(file.FullName); - this.FixCustomTilesheetPaths(map, relativeMapPath: key); - - // inject map - this.ModContentManager.Inject(internalKey, map, this.CurrentLocaleConstant); - return (T)(object)map; - } - - // load through content manager - return this.ModContentManager.Load(internalKey); + return this.ModContentManager.Load(key); default: - throw GetContentError($"unknown content source '{source}'."); + throw new SContentLoadException($"{this.ModName} failed loading content asset '{key}' from {source}: unknown content source '{source}'."); } } catch (Exception ex) when (!(ex is SContentLoadException)) @@ -164,8 +126,7 @@ namespace StardewModdingAPI.Framework.ModHelpers return this.GameContentManager.AssertAndNormaliseAssetName(key); case ContentSource.ModFolder: - FileInfo file = this.GetModFile(key); - return this.GetInternalModAssetKey(file); + return this.ModContentManager.GetInternalAssetKey(key); default: throw new NotSupportedException($"Unknown content source '{source}'."); @@ -201,6 +162,7 @@ namespace StardewModdingAPI.Framework.ModHelpers return this.ContentCore.InvalidateCache(predicate).Any(); } + /********* ** Private methods *********/ @@ -214,170 +176,5 @@ namespace StardewModdingAPI.Framework.ModHelpers if (Path.IsPathRooted(key)) throw new ArgumentException("The asset key must not be an absolute path."); } - - /// Get the internal key in the content cache for a mod asset. - /// The asset file. - private string GetInternalModAssetKey(FileInfo modFile) - { - string relativePath = PathUtilities.GetRelativePath(this.ModFolderPath, modFile.FullName); - return Path.Combine(this.ModContentManager.Name, relativePath); - } - - /// Fix custom map tilesheet paths so they can be found by the content manager. - /// The map whose tilesheets to fix. - /// The relative map path within the mod folder. - /// A map tilesheet couldn't be resolved. - /// - /// The game's logic for tilesheets in is a bit specialised. It boils - /// down to this: - /// * If the location is indoors or the desert, or the image source contains 'path' or 'object', it's loaded - /// as-is relative to the Content folder. - /// * Else it's loaded from Content\Maps with a seasonal prefix. - /// - /// That logic doesn't work well in our case, mainly because we have no location metadata at this point. - /// Instead we use a more heuristic approach: check relative to the map file first, then relative to - /// Content\Maps, then Content. If the image source filename contains a seasonal prefix, try for a - /// seasonal variation and then an exact match. - /// - /// While that doesn't exactly match the game logic, it's close enough that it's unlikely to make a difference. - /// - private void FixCustomTilesheetPaths(Map map, string relativeMapPath) - { - // get map info - if (!map.TileSheets.Any()) - return; - relativeMapPath = this.ModContentManager.AssertAndNormaliseAssetName(relativeMapPath); // Mono's Path.GetDirectoryName doesn't handle Windows dir separators - string relativeMapFolder = Path.GetDirectoryName(relativeMapPath) ?? ""; // folder path containing the map, relative to the mod folder - bool isOutdoors = map.Properties.TryGetValue("Outdoors", out PropertyValue outdoorsProperty) && outdoorsProperty != null; - - // fix tilesheets - foreach (TileSheet tilesheet in map.TileSheets) - { - string imageSource = tilesheet.ImageSource; - - // validate tilesheet path - if (Path.IsPathRooted(imageSource) || PathUtilities.GetSegments(imageSource).Contains("..")) - throw new ContentLoadException($"The '{imageSource}' tilesheet couldn't be loaded. Tilesheet paths must be a relative path without directory climbing (../)."); - - // get seasonal name (if applicable) - string seasonalImageSource = null; - if (isOutdoors && Context.IsSaveLoaded && Game1.currentSeason != null) - { - string filename = Path.GetFileName(imageSource) ?? throw new InvalidOperationException($"The '{imageSource}' tilesheet couldn't be loaded: filename is unexpectedly null."); - bool hasSeasonalPrefix = - filename.StartsWith("spring_", StringComparison.CurrentCultureIgnoreCase) - || filename.StartsWith("summer_", StringComparison.CurrentCultureIgnoreCase) - || filename.StartsWith("fall_", StringComparison.CurrentCultureIgnoreCase) - || filename.StartsWith("winter_", StringComparison.CurrentCultureIgnoreCase); - if (hasSeasonalPrefix && !filename.StartsWith(Game1.currentSeason + "_")) - { - string dirPath = imageSource.Substring(0, imageSource.LastIndexOf(filename, StringComparison.CurrentCultureIgnoreCase)); - seasonalImageSource = $"{dirPath}{Game1.currentSeason}_{filename.Substring(filename.IndexOf("_", StringComparison.CurrentCultureIgnoreCase) + 1)}"; - } - } - - // load best match - try - { - string key = - this.GetTilesheetAssetName(relativeMapFolder, seasonalImageSource) - ?? this.GetTilesheetAssetName(relativeMapFolder, imageSource); - if (key != null) - { - tilesheet.ImageSource = key; - continue; - } - } - catch (Exception ex) - { - throw new ContentLoadException($"The '{imageSource}' tilesheet couldn't be loaded relative to either map file or the game's content folder.", ex); - } - - // none found - throw new ContentLoadException($"The '{imageSource}' tilesheet couldn't be loaded relative to either map file or the game's content folder."); - } - } - - /// Get the actual asset name for a tilesheet. - /// The folder path containing the map, relative to the mod folder. - /// The tilesheet image source to load. - /// Returns the asset name. - /// See remarks on . - private string GetTilesheetAssetName(string modRelativeMapFolder, string imageSource) - { - if (imageSource == null) - return null; - - // check relative to map file - { - string localKey = Path.Combine(modRelativeMapFolder, imageSource); - FileInfo localFile = this.GetModFile(localKey); - if (localFile.Exists) - return this.GetActualAssetKey(localKey); - } - - // check relative to content folder - { - foreach (string candidateKey in new[] { imageSource, Path.Combine("Maps", imageSource) }) - { - string contentKey = candidateKey.EndsWith(".png") - ? candidateKey.Substring(0, candidateKey.Length - 4) - : candidateKey; - - try - { - this.Load(contentKey, ContentSource.GameContent); - return contentKey; - } - catch - { - // ignore file-not-found errors - // TODO: while it's useful to suppress an asset-not-found error here to avoid - // confusion, this is a pretty naive approach. Even if the file doesn't exist, - // the file may have been loaded through an IAssetLoader which failed. So even - // if the content file doesn't exist, that doesn't mean the error here is a - // content-not-found error. Unfortunately XNA doesn't provide a good way to - // detect the error type. - if (this.GetContentFolderFile(contentKey).Exists) - throw; - } - } - } - - // not found - return null; - } - - /// Get a file from the mod folder. - /// The asset path relative to the mod folder. - private FileInfo GetModFile(string path) - { - // try exact match - path = Path.Combine(this.ModFolderPath, this.ModContentManager.NormalisePathSeparators(path)); - FileInfo file = new FileInfo(path); - - // try with default extension - if (!file.Exists && file.Extension.ToLower() != ".xnb") - { - FileInfo result = new FileInfo(path + ".xnb"); - if (result.Exists) - file = result; - } - - return file; - } - - /// Get a file from the game's content folder. - /// The asset key. - private FileInfo GetContentFolderFile(string key) - { - // get file path - string path = Path.Combine(this.GameContentManager.FullRootDirectory, key); - if (!path.EndsWith(".xnb")) - path += ".xnb"; - - // get file - return new FileInfo(path); - } } } -- cgit From c37fe62ca2ea8a072a16acd28bb38bc69911fd5b Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 29 May 2019 23:17:13 -0400 Subject: no longer forward managed asset keys loaded through a mod content manager (#644) That isn't needed for any documented functionality, and allowed mods to load (and in some cases edit) a different mod's local assets. --- docs/release-notes.md | 1 + .../Framework/ContentManagers/ModContentManager.cs | 25 ++++++++-------------- 2 files changed, 10 insertions(+), 16 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index f8d4cbbf..d478bfa2 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -20,6 +20,7 @@ These changes have not been released yet. * Fixed lag when a mod invalidates many NPC portraits/sprites at once. * Fixed map reloads resetting tilesheet seasons. * Fixed outdoor tilesheets being seasonalised when added to an indoor location. + * Fixed mods able to directly load (and in some cases edit) a different mod's local assets using internal asset key forwarding. * For modders: * Added support for content pack translations. diff --git a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs index 45303f6b..d6f077cb 100644 --- a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs @@ -59,26 +59,19 @@ namespace StardewModdingAPI.Framework.ContentManagers { assetName = this.AssertAndNormaliseAssetName(assetName); - // get managed asset - if (this.IsLoaded(assetName)) - return base.Load(assetName, language); + // resolve managed asset key if (this.Coordinator.TryParseManagedAssetKey(assetName, out string contentManagerID, out string relativePath)) { if (contentManagerID != this.Name) - { - T data = this.Coordinator.LoadAndCloneManagedAsset(assetName, contentManagerID, relativePath, language); - this.Inject(assetName, data, language); - return data; - } - - return this.LoadManagedAsset(assetName, contentManagerID, relativePath, language); + throw new SContentLoadException($"Can't load managed asset key '{assetName}' through content manager '{this.Name}' for a different mod."); + assetName = relativePath; } // get local asset string internalKey = this.GetInternalAssetKey(assetName); if (this.IsLoaded(internalKey)) return base.Load(internalKey, language); - return this.LoadManagedAsset(internalKey, this.Name, assetName, this.Language); + return this.LoadImpl(internalKey, this.Name, assetName, this.Language); } /// Create a new content manager for temporary use. @@ -108,13 +101,13 @@ namespace StardewModdingAPI.Framework.ContentManagers return this.Cache.ContainsKey(normalisedAssetName); } - /// Load a managed mod asset. + /// Load a local mod asset. /// The type of asset to load. - /// The internal asset key. + /// The mod asset cache key to save. /// The unique name for the content manager which should load this asset. /// The relative path within the mod folder. /// The language code for which to load content. - private T LoadManagedAsset(string internalKey, string contentManagerID, string relativePath, LanguageCode language) + private T LoadImpl(string cacheKey, string contentManagerID, string relativePath, LanguageCode language) { SContentLoadException GetContentError(string reasonPhrase) => new SContentLoadException($"Failed loading asset '{relativePath}' from {contentManagerID}: {reasonPhrase}"); try @@ -151,7 +144,7 @@ namespace StardewModdingAPI.Framework.ContentManagers { Texture2D texture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream); texture = this.PremultiplyTransparency(texture); - this.Inject(internalKey, texture, language); + this.Inject(cacheKey, texture, language); return (T)(object)texture; } @@ -167,7 +160,7 @@ namespace StardewModdingAPI.Framework.ContentManagers this.FixCustomTilesheetPaths(map, relativeMapPath: relativePath); // inject map - this.Inject(internalKey, map, this.Language); + this.Inject(cacheKey, map, this.Language); return (T)(object)map; default: -- cgit From b9dec734693f50b3b32977cd505f091a2c8b8382 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Thu, 30 May 2019 17:40:21 -0400 Subject: disable mod-level asset caching (#644) This fixes an issue where some asset references could be shared between content managers, causing changes to propagate unintentionally. --- docs/release-notes.md | 3 +- src/SMAPI/Framework/ContentCoordinator.cs | 7 +- .../ContentManagers/BaseContentManager.cs | 123 +++++++++++--------- .../ContentManagers/GameContentManager.cs | 120 ++++++++++++------- .../Framework/ContentManagers/IContentManager.cs | 20 +--- .../Framework/ContentManagers/ModContentManager.cs | 129 ++++++++++++--------- src/SMAPI/Framework/ModHelpers/ContentHelper.cs | 4 +- 7 files changed, 231 insertions(+), 175 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index d478bfa2..3edfec44 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -20,7 +20,6 @@ These changes have not been released yet. * Fixed lag when a mod invalidates many NPC portraits/sprites at once. * Fixed map reloads resetting tilesheet seasons. * Fixed outdoor tilesheets being seasonalised when added to an indoor location. - * Fixed mods able to directly load (and in some cases edit) a different mod's local assets using internal asset key forwarding. * For modders: * Added support for content pack translations. @@ -52,6 +51,8 @@ Released 13 September 2019 for Stardew Valley 1.3.36. * For modders: * `this.Monitor.Log` now defaults to the `Trace` log level instead of `Debug`. The change will only take effect when you recompile the mod. * Fixed 'location list changed' verbose log not correctly listing changes. + * Fixed mods able to directly load (and in some cases edit) a different mod's local assets using internal asset key forwarding. + * Fixed changes to a map loaded by a mod being persisted across content managers. ## 2.11.2 Released 23 April 2019 for Stardew Valley 1.3.36. diff --git a/src/SMAPI/Framework/ContentCoordinator.cs b/src/SMAPI/Framework/ContentCoordinator.cs index 0a91ccd5..2dfe1f1c 100644 --- a/src/SMAPI/Framework/ContentCoordinator.cs +++ b/src/SMAPI/Framework/ContentCoordinator.cs @@ -176,16 +176,15 @@ namespace StardewModdingAPI.Framework /// The unique name for the content manager which should load this asset. /// The internal SMAPI asset key. /// The language code for which to load content. - public T LoadAndCloneManagedAsset(string internalKey, string contentManagerID, string relativePath, LocalizedContentManager.LanguageCode language) + public T LoadManagedAsset(string internalKey, string contentManagerID, string relativePath, LocalizedContentManager.LanguageCode language) { // get content manager IContentManager contentManager = this.ContentManagers.FirstOrDefault(p => p.IsNamespaced && p.Name == contentManagerID); if (contentManager == null) throw new InvalidOperationException($"The '{contentManagerID}' prefix isn't handled by any mod."); - // get cloned asset - T data = contentManager.Load(internalKey, language); - return contentManager.CloneIfPossible(data); + // get fresh asset + return contentManager.Load(relativePath, language, useCache: false); } /// Purge assets from the cache that match one of the interceptors. diff --git a/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs b/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs index 3f7c2cee..fc558eb9 100644 --- a/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs @@ -6,7 +6,6 @@ using System.Globalization; using System.IO; using System.Linq; using Microsoft.Xna.Framework.Content; -using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.Framework.Content; using StardewModdingAPI.Framework.Exceptions; using StardewModdingAPI.Framework.Reflection; @@ -38,6 +37,9 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The language enum values indexed by locale code. protected IDictionary LanguageCodes { get; } + /// A list of disposable assets. + private readonly List> Disposables = new List>(); + /********* ** Accessors @@ -88,54 +90,32 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The asset path relative to the loader root directory, not including the .xnb extension. public override T Load(string assetName) { - return this.Load(assetName, LocalizedContentManager.CurrentLanguageCode); + return this.Load(assetName, this.Language, useCache: true); } - /// Load the base asset without localisation. + /// Load an asset that has been processed by the content pipeline. /// The type of asset to load. /// The asset path relative to the loader root directory, not including the .xnb extension. - public override T LoadBase(string assetName) + /// The language code for which to load content. + public override T Load(string assetName, LanguageCode language) { - return this.Load(assetName, LanguageCode.en); + return this.Load(assetName, language, useCache: true); } - /// Inject an asset into the cache. - /// The type of asset to inject. + /// Load an asset that has been processed by the content pipeline. + /// The type of asset to load. /// The asset path relative to the loader root directory, not including the .xnb extension. - /// The asset value. - /// The language code for which to inject the asset. - public virtual void Inject(string assetName, T value, LanguageCode language) - { - assetName = this.AssertAndNormaliseAssetName(assetName); - this.Cache[assetName] = value; - } + /// The language code for which to load content. + /// Whether to read/write the loaded asset to the asset cache. + public abstract T Load(string assetName, LocalizedContentManager.LanguageCode language, bool useCache); - /// Get a copy of the given asset if supported. - /// The asset type. - /// The asset to clone. - public T CloneIfPossible(T asset) + /// Load the base asset without localisation. + /// The type of asset to load. + /// The asset path relative to the loader root directory, not including the .xnb extension. + [Obsolete("This method is implemented for the base game and should not be used directly. To load an asset from the underlying content manager directly, use " + nameof(BaseContentManager.RawLoad) + " instead.")] + public override T LoadBase(string assetName) { - switch (asset as object) - { - case Texture2D source: - { - int[] pixels = new int[source.Width * source.Height]; - source.GetData(pixels); - - Texture2D clone = new Texture2D(source.GraphicsDevice, source.Width, source.Height); - clone.SetData(pixels); - return (T)(object)clone; - } - - case Dictionary source: - return (T)(object)new Dictionary(source); - - case Dictionary source: - return (T)(object)new Dictionary(source); - - default: - return asset; - } + return this.Load(assetName, LanguageCode.en, useCache: true); } /// Perform any cleanup needed when the locale changes. @@ -228,11 +208,28 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Whether the content manager is being disposed (rather than finalized). protected override void Dispose(bool isDisposing) { + // ignore if disposed if (this.IsDisposed) return; this.IsDisposed = true; + // dispose uncached assets + foreach (WeakReference reference in this.Disposables) + { + if (reference.TryGetTarget(out IDisposable disposable)) + { + try + { + disposable.Dispose(); + } + catch { /* ignore dispose errors */ } + } + } + this.Disposables.Clear(); + + // raise event this.OnDisposing(this); + base.Dispose(isDisposing); } @@ -249,23 +246,26 @@ namespace StardewModdingAPI.Framework.ContentManagers /********* ** Private methods *********/ - /// Get the locale codes (like ja-JP) used in asset keys. - private IDictionary GetKeyLocales() + /// Load an asset file directly from the underlying content manager. + /// The type of asset to load. + /// The normalised asset key. + /// Whether to read/write the loaded asset to the asset cache. + protected virtual T RawLoad(string assetName, bool useCache) { - // create locale => code map - IDictionary map = new Dictionary(); - foreach (LanguageCode code in Enum.GetValues(typeof(LanguageCode))) - map[code] = this.GetLocale(code); - - return map; + return useCache + ? base.LoadBase(assetName) + : base.ReadAsset(assetName, disposable => this.Disposables.Add(new WeakReference(disposable))); } - /// Get the asset name from a cache key. - /// The input cache key. - private string GetAssetName(string cacheKey) + /// Inject an asset into the cache. + /// The type of asset to inject. + /// The asset path relative to the loader root directory, not including the .xnb extension. + /// The asset value. + /// The language code for which to inject the asset. + protected virtual void Inject(string assetName, T value, LanguageCode language) { - this.ParseCacheKey(cacheKey, out string assetName, out string _); - return assetName; + assetName = this.AssertAndNormaliseAssetName(assetName); + this.Cache[assetName] = value; } /// Parse a cache key into its component parts. @@ -298,5 +298,24 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Get whether an asset has already been loaded. /// The normalised asset name. protected abstract bool IsNormalisedKeyLoaded(string normalisedAssetName); + + /// Get the locale codes (like ja-JP) used in asset keys. + private IDictionary GetKeyLocales() + { + // create locale => code map + IDictionary map = new Dictionary(); + foreach (LanguageCode code in Enum.GetValues(typeof(LanguageCode))) + map[code] = this.GetLocale(code); + + return map; + } + + /// Get the asset name from a cache key. + /// The input cache key. + private string GetAssetName(string cacheKey) + { + this.ParseCacheKey(cacheKey, out string assetName, out string _); + return assetName; + } } } diff --git a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs index 90278c36..ecabcaca 100644 --- a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; +using Microsoft.Xna.Framework.Content; using StardewModdingAPI.Framework.Content; using StardewModdingAPI.Framework.Exceptions; using StardewModdingAPI.Framework.Reflection; @@ -59,7 +60,8 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The type of asset to load. /// The asset path relative to the loader root directory, not including the .xnb extension. /// The language code for which to load content. - public override T Load(string assetName, LanguageCode language) + /// Whether to read/write the loaded asset to the asset cache. + public override T Load(string assetName, LocalizedContentManager.LanguageCode language, bool useCache) { // raise first-load callback if (GameContentManager.IsFirstLoad) @@ -71,17 +73,18 @@ namespace StardewModdingAPI.Framework.ContentManagers // normalise asset name assetName = this.AssertAndNormaliseAssetName(assetName); if (this.TryParseExplicitLanguageAssetKey(assetName, out string newAssetName, out LanguageCode newLanguage)) - return this.Load(newAssetName, newLanguage); + return this.Load(newAssetName, newLanguage, useCache); // get from cache - if (this.IsLoaded(assetName)) - return base.Load(assetName, language); + if (useCache && this.IsLoaded(assetName)) + return this.RawLoad(assetName, language, useCache: true); // get managed asset if (this.Coordinator.TryParseManagedAssetKey(assetName, out string contentManagerID, out string relativePath)) { - T managedAsset = this.Coordinator.LoadAndCloneManagedAsset(assetName, contentManagerID, relativePath, language); - this.Inject(assetName, managedAsset, language); + T managedAsset = this.Coordinator.LoadManagedAsset(assetName, contentManagerID, relativePath, language); + if (useCache) + this.Inject(assetName, managedAsset, language); return managedAsset; } @@ -91,7 +94,7 @@ namespace StardewModdingAPI.Framework.ContentManagers { this.Monitor.Log($"Broke loop while loading asset '{assetName}'.", LogLevel.Warn); this.Monitor.Log($"Bypassing mod loaders for this asset. Stack trace:\n{Environment.StackTrace}", LogLevel.Trace); - data = base.Load(assetName, language); + data = this.RawLoad(assetName, language, useCache); } else { @@ -101,7 +104,7 @@ namespace StardewModdingAPI.Framework.ContentManagers IAssetInfo info = new AssetInfo(locale, assetName, typeof(T), this.AssertAndNormaliseAssetName); IAssetData asset = this.ApplyLoader(info) - ?? new AssetDataForObject(info, base.Load(assetName, language), this.AssertAndNormaliseAssetName); + ?? new AssetDataForObject(info, this.RawLoad(assetName, language, useCache), this.AssertAndNormaliseAssetName); asset = this.ApplyEditors(info, asset); return (T)asset.Data; }); @@ -112,39 +115,6 @@ namespace StardewModdingAPI.Framework.ContentManagers return data; } - /// Inject an asset into the cache. - /// The type of asset to inject. - /// The asset path relative to the loader root directory, not including the .xnb extension. - /// The asset value. - /// The language code for which to inject the asset. - public override void Inject(string assetName, T value, LanguageCode language) - { - // handle explicit language in asset name - { - if (this.TryParseExplicitLanguageAssetKey(assetName, out string newAssetName, out LanguageCode newLanguage)) - { - this.Inject(newAssetName, value, newLanguage); - return; - } - } - base.Inject(assetName, value, language); - - // track whether the injected asset is translatable for is-loaded lookups - string keyWithLocale = $"{assetName}.{this.GetLocale(language)}"; - if (this.Cache.ContainsKey(keyWithLocale)) - { - this.IsLocalisableLookup[assetName] = true; - this.IsLocalisableLookup[keyWithLocale] = true; - } - else if (this.Cache.ContainsKey(assetName)) - { - this.IsLocalisableLookup[assetName] = false; - this.IsLocalisableLookup[keyWithLocale] = false; - } - else - this.Monitor.Log($"Asset '{assetName}' could not be found in the cache immediately after injection.", LogLevel.Error); - } - /// Perform any cleanup needed when the locale changes. public override void OnLocaleChanged() { @@ -199,6 +169,72 @@ namespace StardewModdingAPI.Framework.ContentManagers return false; } + /// Inject an asset into the cache. + /// The type of asset to inject. + /// The asset path relative to the loader root directory, not including the .xnb extension. + /// The asset value. + /// The language code for which to inject the asset. + protected override void Inject(string assetName, T value, LanguageCode language) + { + // handle explicit language in asset name + { + if (this.TryParseExplicitLanguageAssetKey(assetName, out string newAssetName, out LanguageCode newLanguage)) + { + this.Inject(newAssetName, value, newLanguage); + return; + } + } + base.Inject(assetName, value, language); + + // track whether the injected asset is translatable for is-loaded lookups + string keyWithLocale = $"{assetName}.{this.GetLocale(language)}"; + if (this.Cache.ContainsKey(keyWithLocale)) + { + this.IsLocalisableLookup[assetName] = true; + this.IsLocalisableLookup[keyWithLocale] = true; + } + else if (this.Cache.ContainsKey(assetName)) + { + this.IsLocalisableLookup[assetName] = false; + this.IsLocalisableLookup[keyWithLocale] = false; + } + else + this.Monitor.Log($"Asset '{assetName}' could not be found in the cache immediately after injection.", LogLevel.Error); + } + + /// Load an asset file directly from the underlying content manager. + /// The type of asset to load. + /// The normalised asset key. + /// The language code for which to load content. + /// Whether to read/write the loaded asset to the asset cache. + /// Derived from . + private T RawLoad(string assetName, LanguageCode language, bool useCache) + { + // try translated asset + if (language != LocalizedContentManager.LanguageCode.en) + { + string translatedKey = $"{assetName}.{this.GetLocale(language)}"; + if (!this.IsLocalisableLookup.TryGetValue(translatedKey, out bool isTranslatable) || isTranslatable) + { + try + { + T obj = base.RawLoad(translatedKey, useCache); + this.IsLocalisableLookup[assetName] = true; + this.IsLocalisableLookup[translatedKey] = true; + return obj; + } + catch (ContentLoadException) + { + this.IsLocalisableLookup[assetName] = false; + this.IsLocalisableLookup[translatedKey] = false; + } + } + } + + // try base asset + return base.RawLoad(assetName, useCache); + } + /// Parse an asset key that contains an explicit language into its asset name and language, if applicable. /// The asset key to parse. /// The asset name without the language code. @@ -260,7 +296,7 @@ namespace StardewModdingAPI.Framework.ContentManagers T data; try { - data = this.CloneIfPossible(loader.Load(info)); + data = loader.Load(info); this.Monitor.Log($"{mod.DisplayName} loaded asset '{info.AssetName}'.", LogLevel.Trace); } catch (Exception ex) diff --git a/src/SMAPI/Framework/ContentManagers/IContentManager.cs b/src/SMAPI/Framework/ContentManagers/IContentManager.cs index 2365789b..78211821 100644 --- a/src/SMAPI/Framework/ContentManagers/IContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/IContentManager.cs @@ -29,28 +29,12 @@ namespace StardewModdingAPI.Framework.ContentManagers /********* ** Methods *********/ - /// Load an asset that has been processed by the content pipeline. - /// The type of asset to load. - /// The asset path relative to the loader root directory, not including the .xnb extension. - T Load(string assetName); - /// Load an asset that has been processed by the content pipeline. /// The type of asset to load. /// The asset path relative to the loader root directory, not including the .xnb extension. /// The language code for which to load content. - T Load(string assetName, LocalizedContentManager.LanguageCode language); - - /// Inject an asset into the cache. - /// The type of asset to inject. - /// The asset path relative to the loader root directory, not including the .xnb extension. - /// The asset value. - /// The language code for which to inject the asset. - void Inject(string assetName, T value, LocalizedContentManager.LanguageCode language); - - /// Get a copy of the given asset if supported. - /// The asset type. - /// The asset to clone. - T CloneIfPossible(T asset); + /// Whether to read/write the loaded asset to the asset cache. + T Load(string assetName, LocalizedContentManager.LanguageCode language, bool useCache); /// Perform any cleanup needed when the locale changes. void OnLocaleChanged(); diff --git a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs index 064a7907..1d015138 100644 --- a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs @@ -29,6 +29,9 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The game content manager used for map tilesheets not provided by the mod. private readonly IContentManager GameContentManager; + /// The language code for language-agnostic mod assets. + private const LanguageCode NoLanguage = LanguageCode.en; + /********* ** Public methods @@ -54,66 +57,58 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Load an asset that has been processed by the content pipeline. /// The type of asset to load. /// The asset path relative to the loader root directory, not including the .xnb extension. - /// The language code for which to load content. - public override T Load(string assetName, LanguageCode language) + public override T Load(string assetName) { - assetName = this.AssertAndNormaliseAssetName(assetName); - - // resolve managed asset key - if (this.Coordinator.TryParseManagedAssetKey(assetName, out string contentManagerID, out string relativePath)) - { - if (contentManagerID != this.Name) - throw new SContentLoadException($"Can't load managed asset key '{assetName}' through content manager '{this.Name}' for a different mod."); - assetName = relativePath; - } - - // get local asset - string internalKey = this.GetInternalAssetKey(assetName); - if (this.IsLoaded(internalKey)) - return base.Load(internalKey, language); - return this.LoadImpl(internalKey, this.Name, assetName, this.Language); + return this.Load(assetName, ModContentManager.NoLanguage, useCache: false); } - /// Create a new content manager for temporary use. - public override LocalizedContentManager CreateTemporary() + /// Load an asset that has been processed by the content pipeline. + /// The type of asset to load. + /// The asset path relative to the loader root directory, not including the .xnb extension. + /// The language code for which to load content. + public override T Load(string assetName, LanguageCode language) { - throw new NotSupportedException("Can't create a temporary mod content manager."); + return this.Load(assetName, language, useCache: false); } - /// Get the underlying key in the game's content cache for an asset. This does not validate whether the asset exists. - /// The local path to a content file relative to the mod folder. - /// The is empty or contains invalid characters. - public string GetInternalAssetKey(string key) + /// Load an asset that has been processed by the content pipeline. + /// The type of asset to load. + /// The asset path relative to the loader root directory, not including the .xnb extension. + /// The language code for which to load content. + /// Whether to read/write the loaded asset to the asset cache. + public override T Load(string assetName, LanguageCode language, bool useCache) { - FileInfo file = this.GetModFile(key); - string relativePath = PathUtilities.GetRelativePath(this.RootDirectory, file.FullName); - return Path.Combine(this.Name, relativePath); - } + assetName = this.AssertAndNormaliseAssetName(assetName); + // disable caching + // This is necessary to avoid assets being shared between content managers, which can + // cause changes to an asset through one content manager affecting the same asset in + // others (or even fresh content managers). See https://www.patreon.com/posts/27247161 + // for more background info. + if (useCache) + throw new InvalidOperationException("Mod content managers don't support asset caching."); - /********* - ** Private methods - *********/ - /// Get whether an asset has already been loaded. - /// The normalised asset name. - protected override bool IsNormalisedKeyLoaded(string normalisedAssetName) - { - return this.Cache.ContainsKey(normalisedAssetName); - } + // disable language handling + // Mod files don't support automatic translation logic, so this should never happen. + if (language != ModContentManager.NoLanguage) + throw new InvalidOperationException("Caching is not supported by the mod content manager."); - /// Load a local mod asset. - /// The type of asset to load. - /// The mod asset cache key to save. - /// The unique name for the content manager which should load this asset. - /// The relative path within the mod folder. - /// The language code for which to load content. - private T LoadImpl(string cacheKey, string contentManagerID, string relativePath, LanguageCode language) - { - SContentLoadException GetContentError(string reasonPhrase) => new SContentLoadException($"Failed loading asset '{relativePath}' from {contentManagerID}: {reasonPhrase}"); + // resolve managed asset key + { + if (this.Coordinator.TryParseManagedAssetKey(assetName, out string contentManagerID, out string relativePath)) + { + if (contentManagerID != this.Name) + throw new SContentLoadException($"Can't load managed asset key '{assetName}' through content manager '{this.Name}' for a different mod."); + assetName = relativePath; + } + } + + // get local asset + SContentLoadException GetContentError(string reasonPhrase) => new SContentLoadException($"Failed loading asset '{assetName}' from {this.Name}: {reasonPhrase}"); try { // get file - FileInfo file = this.GetModFile(relativePath); + FileInfo file = this.GetModFile(assetName); if (!file.Exists) throw GetContentError("the specified path doesn't exist."); @@ -122,14 +117,13 @@ namespace StardewModdingAPI.Framework.ContentManagers { // XNB file case ".xnb": - return base.Load(relativePath, language); + return this.RawLoad(assetName, useCache: false); // unpacked data case ".json": { if (!this.JsonHelper.ReadJsonFileIfExists(file.FullName, out T data)) throw GetContentError("the JSON file is invalid."); // should never happen since we check for file existence above - return data; } @@ -144,7 +138,6 @@ namespace StardewModdingAPI.Framework.ContentManagers { Texture2D texture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream); texture = this.PremultiplyTransparency(texture); - this.Inject(cacheKey, texture, language); return (T)(object)texture; } @@ -157,10 +150,7 @@ namespace StardewModdingAPI.Framework.ContentManagers // fetch & cache FormatManager formatManager = FormatManager.Instance; Map map = formatManager.LoadMap(file.FullName); - this.FixCustomTilesheetPaths(map, relativeMapPath: relativePath); - - // inject map - this.Inject(cacheKey, map, this.Language); + this.FixCustomTilesheetPaths(map, relativeMapPath: assetName); return (T)(object)map; default: @@ -171,10 +161,37 @@ namespace StardewModdingAPI.Framework.ContentManagers { if (ex.GetInnermostException() is DllNotFoundException dllEx && dllEx.Message == "libgdiplus.dylib") throw GetContentError("couldn't find libgdiplus, which is needed to load mod images. Make sure Mono is installed and you're running the game through the normal launcher."); - throw new SContentLoadException($"The content manager failed loading content asset '{relativePath}' from {contentManagerID}.", ex); + throw new SContentLoadException($"The content manager failed loading content asset '{assetName}' from {this.Name}.", ex); } } + /// Create a new content manager for temporary use. + public override LocalizedContentManager CreateTemporary() + { + throw new NotSupportedException("Can't create a temporary mod content manager."); + } + + /// Get the underlying key in the game's content cache for an asset. This does not validate whether the asset exists. + /// The local path to a content file relative to the mod folder. + /// The is empty or contains invalid characters. + public string GetInternalAssetKey(string key) + { + FileInfo file = this.GetModFile(key); + string relativePath = PathUtilities.GetRelativePath(this.RootDirectory, file.FullName); + return Path.Combine(this.Name, relativePath); + } + + + /********* + ** Private methods + *********/ + /// Get whether an asset has already been loaded. + /// The normalised asset name. + protected override bool IsNormalisedKeyLoaded(string normalisedAssetName) + { + return this.Cache.ContainsKey(normalisedAssetName); + } + /// Get a file from the mod folder. /// The asset path relative to the content folder. private FileInfo GetModFile(string path) @@ -318,7 +335,7 @@ namespace StardewModdingAPI.Framework.ContentManagers try { - this.GameContentManager.Load(contentKey); + this.GameContentManager.Load(contentKey, this.Language, useCache: true); // no need to bypass cache here, since we're not storing the asset return contentKey; } catch diff --git a/src/SMAPI/Framework/ModHelpers/ContentHelper.cs b/src/SMAPI/Framework/ModHelpers/ContentHelper.cs index 2d65f1f6..0be9aea5 100644 --- a/src/SMAPI/Framework/ModHelpers/ContentHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ContentHelper.cs @@ -91,10 +91,10 @@ namespace StardewModdingAPI.Framework.ModHelpers switch (source) { case ContentSource.GameContent: - return this.GameContentManager.Load(key); + return this.GameContentManager.Load(key, this.CurrentLocaleConstant, useCache: false); case ContentSource.ModFolder: - return this.ModContentManager.Load(key); + return this.ModContentManager.Load(key, this.CurrentLocaleConstant, useCache: false); default: throw new SContentLoadException($"{this.ModName} failed loading content asset '{key}' from {source}: unknown content source '{source}'."); -- cgit From b47329d5b83db3b5ec2338af1f17d628610b05f2 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 9 Jun 2019 16:26:01 -0400 Subject: fix year edge case in date calculations --- docs/release-notes.md | 1 + src/SMAPI.Tests/Utilities/SDateTests.cs | 2 +- src/SMAPI/Utilities/SDate.cs | 4 ++-- 3 files changed, 4 insertions(+), 3 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 3edfec44..2cb477fd 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -53,6 +53,7 @@ Released 13 September 2019 for Stardew Valley 1.3.36. * Fixed 'location list changed' verbose log not correctly listing changes. * Fixed mods able to directly load (and in some cases edit) a different mod's local assets using internal asset key forwarding. * Fixed changes to a map loaded by a mod being persisted across content managers. + * Fixed `SDate.AddDays` incorrectly changing year when the result is exactly winter 28. ## 2.11.2 Released 23 April 2019 for Stardew Valley 1.3.36. diff --git a/src/SMAPI.Tests/Utilities/SDateTests.cs b/src/SMAPI.Tests/Utilities/SDateTests.cs index 1f31168e..642f11f6 100644 --- a/src/SMAPI.Tests/Utilities/SDateTests.cs +++ b/src/SMAPI.Tests/Utilities/SDateTests.cs @@ -159,7 +159,7 @@ namespace StardewModdingAPI.Tests.Utilities [TestCase("15 summer Y1", -28, ExpectedResult = "15 spring Y1")] // negative season transition [TestCase("15 summer Y2", -28 * 4, ExpectedResult = "15 summer Y1")] // negative year transition [TestCase("01 spring Y3", -(28 * 7 + 17), ExpectedResult = "12 spring Y1")] // negative year transition - [TestCase("06 fall Y2", 50, ExpectedResult = "28 winter Y3")] // test for zero-index errors + [TestCase("06 fall Y2", 50, ExpectedResult = "28 winter Y2")] // test for zero-index errors [TestCase("06 fall Y2", 51, ExpectedResult = "01 spring Y3")] // test for zero-index errors public string AddDays(string dateStr, int addDays) { diff --git a/src/SMAPI/Utilities/SDate.cs b/src/SMAPI/Utilities/SDate.cs index ec54f84a..9ea4f370 100644 --- a/src/SMAPI/Utilities/SDate.cs +++ b/src/SMAPI/Utilities/SDate.cs @@ -86,7 +86,7 @@ namespace StardewModdingAPI.Utilities seasonIndex %= 4; // get year - int year = hashCode / (this.Seasons.Length * this.DaysInSeason) + 1; + int year = (int)Math.Ceiling(hashCode / (this.Seasons.Length * this.DaysInSeason * 1m)); // create date return new SDate(day, this.Seasons[seasonIndex], year); @@ -192,7 +192,7 @@ namespace StardewModdingAPI.Utilities throw new ArgumentException($"Unknown season '{season}', must be one of [{string.Join(", ", this.Seasons)}]."); if (day < 0 || day > this.DaysInSeason) throw new ArgumentException($"Invalid day '{day}', must be a value from 1 to {this.DaysInSeason}."); - if(day == 0 && !(allowDayZero && this.IsDayZero(day, season, year))) + if (day == 0 && !(allowDayZero && this.IsDayZero(day, season, year))) throw new ArgumentException($"Invalid day '{day}', must be a value from 1 to {this.DaysInSeason}."); if (year < 1) throw new ArgumentException($"Invalid year '{year}', must be at least 1."); -- cgit From 31c882c8cea66bbd2805cc5aab11abbce248782c Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Thu, 13 Jun 2019 19:35:51 -0400 Subject: fix map reloads not updating door warps (#643) --- docs/release-notes.md | 1 + src/SMAPI/Metadata/CoreAssetPropagator.cs | 31 ++++++++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 2cb477fd..b7cd61c6 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -19,6 +19,7 @@ These changes have not been released yet. * Fixed lag in some cases due to incorrect asset caching when playing in non-English. * Fixed lag when a mod invalidates many NPC portraits/sprites at once. * Fixed map reloads resetting tilesheet seasons. + * Fixed map reloads not updating door warps. * Fixed outdoor tilesheets being seasonalised when added to an indoor location. * For modders: diff --git a/src/SMAPI/Metadata/CoreAssetPropagator.cs b/src/SMAPI/Metadata/CoreAssetPropagator.cs index bb269643..186cd4ee 100644 --- a/src/SMAPI/Metadata/CoreAssetPropagator.cs +++ b/src/SMAPI/Metadata/CoreAssetPropagator.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.Framework.Reflection; using StardewValley; @@ -14,6 +15,7 @@ using StardewValley.Objects; using StardewValley.Projectiles; using StardewValley.TerrainFeatures; using xTile; +using xTile.ObjectModel; using xTile.Tiles; namespace StardewModdingAPI.Metadata @@ -138,10 +140,37 @@ namespace StardewModdingAPI.Metadata { if (!string.IsNullOrWhiteSpace(location.mapPath.Value) && this.GetNormalisedPath(location.mapPath.Value) == key) { + // general updates location.reloadMap(); location.updateSeasonalTileSheets(); location.updateWarps(); - this.Reflection.GetField(location, nameof(location.interiorDoors)).SetValue(new InteriorDoorDictionary(location)); + + // update interior doors + location.interiorDoors.Clear(); + foreach (var entry in new InteriorDoorDictionary(location)) + location.interiorDoors.Add(entry); + + // update doors (derived from GameLocation.loadObjects) + location.doors.Clear(); + for (int x = 0; x < location.map.Layers[0].LayerWidth; ++x) + { + for (int y = 0; y < location.map.Layers[0].LayerHeight; ++y) + { + if (location.map.GetLayer("Buildings").Tiles[x, y] != null) + { + location.map.GetLayer("Buildings").Tiles[x, y].Properties.TryGetValue("Action", out PropertyValue action); + if (action != null && action.ToString().Contains("Warp")) + { + string[] strArray = action.ToString().Split(' '); + if (strArray[0] == "WarpCommunityCenter") + location.doors.Add(new Point(x, y), "CommunityCenter"); + else if ((location.Name != "Mountain" || x != 8 || y != 20) && strArray.Length > 2) + location.doors.Add(new Point(x, y), strArray[3]); + } + } + } + } + anyChanged = true; } } -- cgit From d3209b17de4e46ee1d604aac24642af80ce855cc Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 14 Jun 2019 01:16:50 -0400 Subject: decouple updating watchers & raising event to fix some mod changes not being tracked correctly (#648) --- docs/release-notes.md | 1 + src/SMAPI/Framework/SGame.cs | 240 +++++++-------------- src/SMAPI/Framework/SnapshotDiff.cs | 43 ++++ src/SMAPI/Framework/SnapshotListDiff.cs | 58 +++++ src/SMAPI/Framework/StateTracking/PlayerTracker.cs | 35 +-- .../StateTracking/Snapshots/LocationSnapshot.cs | 59 +++++ .../StateTracking/Snapshots/PlayerSnapshot.cs | 53 +++++ .../StateTracking/Snapshots/WatcherSnapshot.cs | 66 ++++++ .../Snapshots/WorldLocationsSnapshot.cs | 52 +++++ .../StateTracking/WorldLocationsTracker.cs | 7 + 10 files changed, 413 insertions(+), 201 deletions(-) create mode 100644 src/SMAPI/Framework/SnapshotDiff.cs create mode 100644 src/SMAPI/Framework/SnapshotListDiff.cs create mode 100644 src/SMAPI/Framework/StateTracking/Snapshots/LocationSnapshot.cs create mode 100644 src/SMAPI/Framework/StateTracking/Snapshots/PlayerSnapshot.cs create mode 100644 src/SMAPI/Framework/StateTracking/Snapshots/WatcherSnapshot.cs create mode 100644 src/SMAPI/Framework/StateTracking/Snapshots/WorldLocationsSnapshot.cs (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index b7cd61c6..6d883baf 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -32,6 +32,7 @@ These changes have not been released yet. * Removed all deprecated APIs. * Removed the `Monitor.ExitGameImmediately` method. * Updated to Json.NET 12.0.1. + * Fixed issue where mod changes weren't tracked correctly for raising events in some cases. Events now reflect a frozen snapshot of the game state, and any mod changes are reflected in the next event tick. * Fixed `LoadStageChanged` event not raising correct flags in some cases when creating a new save. ## 2.11.3 diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index 1145207f..7222899a 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -16,19 +16,16 @@ using StardewModdingAPI.Framework.Events; using StardewModdingAPI.Framework.Input; using StardewModdingAPI.Framework.Networking; using StardewModdingAPI.Framework.Reflection; -using StardewModdingAPI.Framework.StateTracking; +using StardewModdingAPI.Framework.StateTracking.Snapshots; using StardewModdingAPI.Framework.Utilities; using StardewModdingAPI.Toolkit.Serialisation; using StardewValley; using StardewValley.BellsAndWhistles; -using StardewValley.Buildings; using StardewValley.Events; using StardewValley.Locations; using StardewValley.Menus; -using StardewValley.TerrainFeatures; using StardewValley.Tools; using xTile.Dimensions; -using SObject = StardewValley.Object; namespace StardewModdingAPI.Framework { @@ -93,6 +90,9 @@ namespace StardewModdingAPI.Framework /// Monitors the entire game state for changes. private WatcherCore Watchers; + /// A snapshot of the current state. + private WatcherSnapshot WatcherSnapshot = new WatcherSnapshot(); + /// Whether post-game-startup initialisation has been performed. private bool IsInitialised; @@ -443,8 +443,12 @@ namespace StardewModdingAPI.Framework /********* ** Update watchers + ** (Watchers need to be updated, checked, and reset in one go so we can detect any changes mods make in event handlers.) *********/ this.Watchers.Update(); + this.WatcherSnapshot.Update(this.Watchers); + this.Watchers.Reset(); + WatcherSnapshot state = this.WatcherSnapshot; /********* ** Pre-update events @@ -473,12 +477,8 @@ namespace StardewModdingAPI.Framework /********* ** Locale changed events *********/ - if (this.Watchers.LocaleWatcher.IsChanged) - { - this.Monitor.Log($"Context: locale set to {this.Watchers.LocaleWatcher.CurrentValue}.", LogLevel.Trace); - - this.Watchers.LocaleWatcher.Reset(); - } + if (state.Locale.IsChanged) + this.Monitor.Log($"Context: locale set to {state.Locale.New}.", LogLevel.Trace); /********* ** Load / return-to-title events @@ -511,16 +511,12 @@ namespace StardewModdingAPI.Framework // event because we need to notify mods after the game handles the resize, so the // game's metadata (like Game1.viewport) are updated. That's a bit complicated // since the game adds & removes its own handler on the fly. - if (this.Watchers.WindowSizeWatcher.IsChanged) + if (state.WindowSize.IsChanged) { if (this.Monitor.IsVerbose) - this.Monitor.Log($"Events: window size changed to {this.Watchers.WindowSizeWatcher.CurrentValue}.", LogLevel.Trace); + this.Monitor.Log($"Events: window size changed to {state.WindowSize.New}.", LogLevel.Trace); - Point oldSize = this.Watchers.WindowSizeWatcher.PreviousValue; - Point newSize = this.Watchers.WindowSizeWatcher.CurrentValue; - - events.WindowResized.Raise(new WindowResizedEventArgs(oldSize, newSize)); - this.Watchers.WindowSizeWatcher.Reset(); + events.WindowResized.Raise(new WindowResizedEventArgs(state.WindowSize.Old, state.WindowSize.New)); } /********* @@ -535,35 +531,15 @@ namespace StardewModdingAPI.Framework ICursorPosition cursor = this.Input.CursorPosition; // raise cursor moved event - if (this.Watchers.CursorWatcher.IsChanged) - { - if (events.CursorMoved.HasListeners()) - { - ICursorPosition was = this.Watchers.CursorWatcher.PreviousValue; - ICursorPosition now = this.Watchers.CursorWatcher.CurrentValue; - this.Watchers.CursorWatcher.Reset(); - - events.CursorMoved.Raise(new CursorMovedEventArgs(was, now)); - } - else - this.Watchers.CursorWatcher.Reset(); - } + if (state.Cursor.IsChanged) + events.CursorMoved.Raise(new CursorMovedEventArgs(state.Cursor.Old, state.Cursor.New)); // raise mouse wheel scrolled - if (this.Watchers.MouseWheelScrollWatcher.IsChanged) + if (state.MouseWheelScroll.IsChanged) { - if (events.MouseWheelScrolled.HasListeners() || this.Monitor.IsVerbose) - { - int was = this.Watchers.MouseWheelScrollWatcher.PreviousValue; - int now = this.Watchers.MouseWheelScrollWatcher.CurrentValue; - this.Watchers.MouseWheelScrollWatcher.Reset(); - - if (this.Monitor.IsVerbose) - this.Monitor.Log($"Events: mouse wheel scrolled to {now}.", LogLevel.Trace); - events.MouseWheelScrolled.Raise(new MouseWheelScrolledEventArgs(cursor, was, now)); - } - else - this.Watchers.MouseWheelScrollWatcher.Reset(); + if (this.Monitor.IsVerbose) + this.Monitor.Log($"Events: mouse wheel scrolled to {state.MouseWheelScroll.New}.", LogLevel.Trace); + events.MouseWheelScrolled.Raise(new MouseWheelScrolledEventArgs(cursor, state.MouseWheelScroll.Old, state.MouseWheelScroll.New)); } // raise input button events @@ -593,17 +569,13 @@ namespace StardewModdingAPI.Framework /********* ** Menu events *********/ - if (this.Watchers.ActiveMenuWatcher.IsChanged) + if (state.ActiveMenu.IsChanged) { - IClickableMenu was = this.Watchers.ActiveMenuWatcher.PreviousValue; - IClickableMenu now = this.Watchers.ActiveMenuWatcher.CurrentValue; - this.Watchers.ActiveMenuWatcher.Reset(); // reset here so a mod changing the menu will be raised as a new event afterwards - if (this.Monitor.IsVerbose) - this.Monitor.Log($"Context: menu changed from {was?.GetType().FullName ?? "none"} to {now?.GetType().FullName ?? "none"}.", LogLevel.Trace); + this.Monitor.Log($"Context: menu changed from {state.ActiveMenu.Old?.GetType().FullName ?? "none"} to {state.ActiveMenu.New?.GetType().FullName ?? "none"}.", LogLevel.Trace); // raise menu events - events.MenuChanged.Raise(new MenuChangedEventArgs(was, now)); + events.MenuChanged.Raise(new MenuChangedEventArgs(state.ActiveMenu.Old, state.ActiveMenu.New)); } /********* @@ -611,163 +583,97 @@ namespace StardewModdingAPI.Framework *********/ if (Context.IsWorldReady) { - bool raiseWorldEvents = !this.Watchers.SaveIdWatcher.IsChanged; // don't report changes from unloaded => loaded + bool raiseWorldEvents = !state.SaveID.IsChanged; // don't report changes from unloaded => loaded - // raise location changes - if (this.Watchers.LocationsWatcher.IsChanged) + // location list changes + if (state.Locations.LocationList.IsChanged && (events.LocationListChanged.HasListeners() || this.Monitor.IsVerbose)) { - // location list changes - if (this.Watchers.LocationsWatcher.IsLocationListChanged) - { - GameLocation[] added = this.Watchers.LocationsWatcher.Added.ToArray(); - GameLocation[] removed = this.Watchers.LocationsWatcher.Removed.ToArray(); - this.Watchers.LocationsWatcher.ResetLocationList(); - - if (this.Monitor.IsVerbose) - { - string addedText = added.Any() ? string.Join(", ", added.Select(p => p.Name)) : "none"; - string removedText = removed.Any() ? string.Join(", ", removed.Select(p => p.Name)) : "none"; - this.Monitor.Log($"Context: location list changed (added {addedText}; removed {removedText}).", LogLevel.Trace); - } + var added = state.Locations.LocationList.Added.ToArray(); + var removed = state.Locations.LocationList.Removed.ToArray(); - events.LocationListChanged.Raise(new LocationListChangedEventArgs(added, removed)); - } - - // raise location contents changed - if (raiseWorldEvents) + if (this.Monitor.IsVerbose) { - foreach (LocationTracker watcher in this.Watchers.LocationsWatcher.Locations) - { - // buildings changed - if (watcher.BuildingsWatcher.IsChanged) - { - GameLocation location = watcher.Location; - Building[] added = watcher.BuildingsWatcher.Added.ToArray(); - Building[] removed = watcher.BuildingsWatcher.Removed.ToArray(); - watcher.BuildingsWatcher.Reset(); - - events.BuildingListChanged.Raise(new BuildingListChangedEventArgs(location, added, removed)); - } - - // debris changed - if (watcher.DebrisWatcher.IsChanged) - { - GameLocation location = watcher.Location; - Debris[] added = watcher.DebrisWatcher.Added.ToArray(); - Debris[] removed = watcher.DebrisWatcher.Removed.ToArray(); - watcher.DebrisWatcher.Reset(); - - events.DebrisListChanged.Raise(new DebrisListChangedEventArgs(location, added, removed)); - } + string addedText = added.Any() ? string.Join(", ", added.Select(p => p.Name)) : "none"; + string removedText = removed.Any() ? string.Join(", ", removed.Select(p => p.Name)) : "none"; + this.Monitor.Log($"Context: location list changed (added {addedText}; removed {removedText}).", LogLevel.Trace); + } - // large terrain features changed - if (watcher.LargeTerrainFeaturesWatcher.IsChanged) - { - GameLocation location = watcher.Location; - LargeTerrainFeature[] added = watcher.LargeTerrainFeaturesWatcher.Added.ToArray(); - LargeTerrainFeature[] removed = watcher.LargeTerrainFeaturesWatcher.Removed.ToArray(); - watcher.LargeTerrainFeaturesWatcher.Reset(); + events.LocationListChanged.Raise(new LocationListChangedEventArgs(added, removed)); + } - events.LargeTerrainFeatureListChanged.Raise(new LargeTerrainFeatureListChangedEventArgs(location, added, removed)); - } + // raise location contents changed + if (raiseWorldEvents) + { + foreach (LocationSnapshot locState in state.Locations.Locations) + { + var location = locState.Location; - // NPCs changed - if (watcher.NpcsWatcher.IsChanged) - { - GameLocation location = watcher.Location; - NPC[] added = watcher.NpcsWatcher.Added.ToArray(); - NPC[] removed = watcher.NpcsWatcher.Removed.ToArray(); - watcher.NpcsWatcher.Reset(); + // buildings changed + if (locState.Buildings.IsChanged) + events.BuildingListChanged.Raise(new BuildingListChangedEventArgs(location, locState.Buildings.Added, locState.Buildings.Removed)); - events.NpcListChanged.Raise(new NpcListChangedEventArgs(location, added, removed)); - } + // debris changed + if (locState.Debris.IsChanged) + events.DebrisListChanged.Raise(new DebrisListChangedEventArgs(location, locState.Debris.Added, locState.Debris.Removed)); - // objects changed - if (watcher.ObjectsWatcher.IsChanged) - { - GameLocation location = watcher.Location; - KeyValuePair[] added = watcher.ObjectsWatcher.Added.ToArray(); - KeyValuePair[] removed = watcher.ObjectsWatcher.Removed.ToArray(); - watcher.ObjectsWatcher.Reset(); + // large terrain features changed + if (locState.LargeTerrainFeatures.IsChanged) + events.LargeTerrainFeatureListChanged.Raise(new LargeTerrainFeatureListChangedEventArgs(location, locState.LargeTerrainFeatures.Added, locState.LargeTerrainFeatures.Removed)); - events.ObjectListChanged.Raise(new ObjectListChangedEventArgs(location, added, removed)); - } + // NPCs changed + if (locState.Npcs.IsChanged) + events.NpcListChanged.Raise(new NpcListChangedEventArgs(location, locState.Npcs.Added, locState.Npcs.Removed)); - // terrain features changed - if (watcher.TerrainFeaturesWatcher.IsChanged) - { - GameLocation location = watcher.Location; - KeyValuePair[] added = watcher.TerrainFeaturesWatcher.Added.ToArray(); - KeyValuePair[] removed = watcher.TerrainFeaturesWatcher.Removed.ToArray(); - watcher.TerrainFeaturesWatcher.Reset(); + // objects changed + if (locState.Objects.IsChanged) + events.ObjectListChanged.Raise(new ObjectListChangedEventArgs(location, locState.Objects.Added, locState.Objects.Removed)); - events.TerrainFeatureListChanged.Raise(new TerrainFeatureListChangedEventArgs(location, added, removed)); - } - } + // terrain features changed + if (locState.TerrainFeatures.IsChanged) + events.TerrainFeatureListChanged.Raise(new TerrainFeatureListChangedEventArgs(location, locState.TerrainFeatures.Added, locState.TerrainFeatures.Removed)); } - else - this.Watchers.LocationsWatcher.Reset(); } // raise time changed - if (raiseWorldEvents && this.Watchers.TimeWatcher.IsChanged) - { - int was = this.Watchers.TimeWatcher.PreviousValue; - int now = this.Watchers.TimeWatcher.CurrentValue; - this.Watchers.TimeWatcher.Reset(); - - if (this.Monitor.IsVerbose) - this.Monitor.Log($"Events: time changed from {was} to {now}.", LogLevel.Trace); - - events.TimeChanged.Raise(new TimeChangedEventArgs(was, now)); - } - else - this.Watchers.TimeWatcher.Reset(); + if (raiseWorldEvents && state.Time.IsChanged) + events.TimeChanged.Raise(new TimeChangedEventArgs(state.Time.Old, state.Time.New)); // raise player events if (raiseWorldEvents) { - PlayerTracker playerTracker = this.Watchers.CurrentPlayerTracker; + PlayerSnapshot playerState = state.CurrentPlayer; + Farmer player = playerState.Player; // raise current location changed - if (playerTracker.TryGetNewLocation(out GameLocation newLocation)) + if (playerState.Location.IsChanged) { if (this.Monitor.IsVerbose) - this.Monitor.Log($"Context: set location to {newLocation.Name}.", LogLevel.Trace); + this.Monitor.Log($"Context: set location to {playerState.Location.New}.", LogLevel.Trace); - GameLocation oldLocation = playerTracker.LocationWatcher.PreviousValue; - events.Warped.Raise(new WarpedEventArgs(playerTracker.Player, oldLocation, newLocation)); + events.Warped.Raise(new WarpedEventArgs(player, playerState.Location.Old, playerState.Location.New)); } // raise player leveled up a skill - foreach (KeyValuePair> pair in playerTracker.GetChangedSkills()) + foreach (var pair in playerState.Skills) { + if (!pair.Value.IsChanged) + continue; + if (this.Monitor.IsVerbose) - this.Monitor.Log($"Events: player skill '{pair.Key}' changed from {pair.Value.PreviousValue} to {pair.Value.CurrentValue}.", LogLevel.Trace); + this.Monitor.Log($"Events: player skill '{pair.Key}' changed from {pair.Value.Old} to {pair.Value.New}.", LogLevel.Trace); - events.LevelChanged.Raise(new LevelChangedEventArgs(playerTracker.Player, pair.Key, pair.Value.PreviousValue, pair.Value.CurrentValue)); + events.LevelChanged.Raise(new LevelChangedEventArgs(player, pair.Key, pair.Value.Old, pair.Value.New)); } // raise player inventory changed - ItemStackChange[] changedItems = playerTracker.GetInventoryChanges().ToArray(); + ItemStackChange[] changedItems = playerState.InventoryChanges.ToArray(); if (changedItems.Any()) { if (this.Monitor.IsVerbose) this.Monitor.Log("Events: player inventory changed.", LogLevel.Trace); - events.InventoryChanged.Raise(new InventoryChangedEventArgs(playerTracker.Player, changedItems)); - } - - // raise mine level changed - if (playerTracker.TryGetNewMineLevel(out int mineLevel)) - { - if (this.Monitor.IsVerbose) - this.Monitor.Log($"Context: mine level changed to {mineLevel}.", LogLevel.Trace); + events.InventoryChanged.Raise(new InventoryChangedEventArgs(player, changedItems)); } } - this.Watchers.CurrentPlayerTracker?.Reset(); - - // update save ID watcher - this.Watchers.SaveIdWatcher.Reset(); } /********* diff --git a/src/SMAPI/Framework/SnapshotDiff.cs b/src/SMAPI/Framework/SnapshotDiff.cs new file mode 100644 index 00000000..5b6288ff --- /dev/null +++ b/src/SMAPI/Framework/SnapshotDiff.cs @@ -0,0 +1,43 @@ +using StardewModdingAPI.Framework.StateTracking; + +namespace StardewModdingAPI.Framework +{ + /// A snapshot of a tracked value. + /// The tracked value type. + internal class SnapshotDiff + { + /********* + ** Accessors + *********/ + /// Whether the value changed since the last update. + public bool IsChanged { get; private set; } + + /// The previous value. + public T Old { get; private set; } + + /// The current value. + public T New { get; private set; } + + + /********* + ** Public methods + *********/ + /// Update the snapshot. + /// Whether the value changed since the last update. + /// The previous value. + /// The current value. + public void Update(bool isChanged, T old, T now) + { + this.IsChanged = isChanged; + this.Old = old; + this.New = now; + } + + /// Update the snapshot. + /// The value watcher to snapshot. + public void Update(IValueWatcher watcher) + { + this.Update(watcher.IsChanged, watcher.PreviousValue, watcher.CurrentValue); + } + } +} diff --git a/src/SMAPI/Framework/SnapshotListDiff.cs b/src/SMAPI/Framework/SnapshotListDiff.cs new file mode 100644 index 00000000..d4d5df50 --- /dev/null +++ b/src/SMAPI/Framework/SnapshotListDiff.cs @@ -0,0 +1,58 @@ +using System.Collections.Generic; +using StardewModdingAPI.Framework.StateTracking; + +namespace StardewModdingAPI.Framework +{ + /// A snapshot of a tracked list. + /// The tracked list value type. + internal class SnapshotListDiff + { + /********* + ** Fields + *********/ + /// The removed values. + private readonly List RemovedImpl = new List(); + + /// The added values. + private readonly List AddedImpl = new List(); + + + /********* + ** Accessors + *********/ + /// Whether the value changed since the last update. + public bool IsChanged { get; private set; } + + /// The removed values. + public IEnumerable Removed => this.RemovedImpl; + + /// The added values. + public IEnumerable Added => this.AddedImpl; + + + /********* + ** Public methods + *********/ + /// Update the snapshot. + /// Whether the value changed since the last update. + /// The removed values. + /// The added values. + public void Update(bool isChanged, IEnumerable removed, IEnumerable added) + { + this.IsChanged = isChanged; + + this.RemovedImpl.Clear(); + this.RemovedImpl.AddRange(removed); + + this.AddedImpl.Clear(); + this.AddedImpl.AddRange(added); + } + + /// Update the snapshot. + /// The value watcher to snapshot. + public void Update(ICollectionWatcher watcher) + { + this.Update(watcher.IsChanged, watcher.Removed, watcher.Added); + } + } +} diff --git a/src/SMAPI/Framework/StateTracking/PlayerTracker.cs b/src/SMAPI/Framework/StateTracking/PlayerTracker.cs index abb4fa24..6302a889 100644 --- a/src/SMAPI/Framework/StateTracking/PlayerTracker.cs +++ b/src/SMAPI/Framework/StateTracking/PlayerTracker.cs @@ -5,7 +5,6 @@ using StardewModdingAPI.Enums; using StardewModdingAPI.Events; using StardewModdingAPI.Framework.StateTracking.FieldWatchers; using StardewValley; -using StardewValley.Locations; using ChangeType = StardewModdingAPI.Events.ChangeType; namespace StardewModdingAPI.Framework.StateTracking @@ -38,9 +37,6 @@ namespace StardewModdingAPI.Framework.StateTracking /// The player's current location. public IValueWatcher LocationWatcher { get; } - /// The player's current mine level. - public IValueWatcher MineLevelWatcher { get; } - /// Tracks changes to the player's skill levels. public IDictionary> SkillWatchers { get; } @@ -58,7 +54,6 @@ namespace StardewModdingAPI.Framework.StateTracking // init trackers this.LocationWatcher = WatcherFactory.ForReference(this.GetCurrentLocation); - this.MineLevelWatcher = WatcherFactory.ForEquatable(() => this.LastValidLocation is MineShaft mine ? mine.mineLevel : 0); this.SkillWatchers = new Dictionary> { [SkillType.Combat] = WatcherFactory.ForNetValue(player.combatLevel), @@ -70,11 +65,7 @@ namespace StardewModdingAPI.Framework.StateTracking }; // track watchers for convenience - this.Watchers.AddRange(new IWatcher[] - { - this.LocationWatcher, - this.MineLevelWatcher - }); + this.Watchers.Add(this.LocationWatcher); this.Watchers.AddRange(this.SkillWatchers.Values); } @@ -124,30 +115,6 @@ namespace StardewModdingAPI.Framework.StateTracking } } - /// Get the player skill levels which changed. - public IEnumerable>> GetChangedSkills() - { - return this.SkillWatchers.Where(p => p.Value.IsChanged); - } - - /// Get the player's new location if it changed. - /// The player's current location. - /// Returns whether it changed. - public bool TryGetNewLocation(out GameLocation location) - { - location = this.LocationWatcher.CurrentValue; - return this.LocationWatcher.IsChanged; - } - - /// Get the player's new mine level if it changed. - /// The player's current mine level. - /// Returns whether it changed. - public bool TryGetNewMineLevel(out int mineLevel) - { - mineLevel = this.MineLevelWatcher.CurrentValue; - return this.MineLevelWatcher.IsChanged; - } - /// Stop watching the player fields and release all references. public void Dispose() { diff --git a/src/SMAPI/Framework/StateTracking/Snapshots/LocationSnapshot.cs b/src/SMAPI/Framework/StateTracking/Snapshots/LocationSnapshot.cs new file mode 100644 index 00000000..d3029540 --- /dev/null +++ b/src/SMAPI/Framework/StateTracking/Snapshots/LocationSnapshot.cs @@ -0,0 +1,59 @@ +using System.Collections.Generic; +using Microsoft.Xna.Framework; +using StardewValley; +using StardewValley.Buildings; +using StardewValley.TerrainFeatures; + +namespace StardewModdingAPI.Framework.StateTracking.Snapshots +{ + /// A frozen snapshot of a tracked game location. + internal class LocationSnapshot + { + /********* + ** Accessors + *********/ + /// The tracked location. + public GameLocation Location { get; } + + /// Tracks added or removed buildings. + public SnapshotListDiff Buildings { get; } = new SnapshotListDiff(); + + /// Tracks added or removed debris. + public SnapshotListDiff Debris { get; } = new SnapshotListDiff(); + + /// Tracks added or removed large terrain features. + public SnapshotListDiff LargeTerrainFeatures { get; } = new SnapshotListDiff(); + + /// Tracks added or removed NPCs. + public SnapshotListDiff Npcs { get; } = new SnapshotListDiff(); + + /// Tracks added or removed objects. + public SnapshotListDiff> Objects { get; } = new SnapshotListDiff>(); + + /// Tracks added or removed terrain features. + public SnapshotListDiff> TerrainFeatures { get; } = new SnapshotListDiff>(); + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The tracked location. + public LocationSnapshot(GameLocation location) + { + this.Location = location; + } + + /// Update the tracked values. + /// The watcher to snapshot. + public void Update(LocationTracker watcher) + { + this.Buildings.Update(watcher.BuildingsWatcher); + this.Debris.Update(watcher.DebrisWatcher); + this.LargeTerrainFeatures.Update(watcher.LargeTerrainFeaturesWatcher); + this.Npcs.Update(watcher.NpcsWatcher); + this.Objects.Update(watcher.ObjectsWatcher); + this.TerrainFeatures.Update(watcher.TerrainFeaturesWatcher); + } + } +} diff --git a/src/SMAPI/Framework/StateTracking/Snapshots/PlayerSnapshot.cs b/src/SMAPI/Framework/StateTracking/Snapshots/PlayerSnapshot.cs new file mode 100644 index 00000000..7bcd9f82 --- /dev/null +++ b/src/SMAPI/Framework/StateTracking/Snapshots/PlayerSnapshot.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using StardewModdingAPI.Enums; +using StardewModdingAPI.Events; +using StardewValley; + +namespace StardewModdingAPI.Framework.StateTracking.Snapshots +{ + /// A frozen snapshot of a tracked player. + internal class PlayerSnapshot + { + /********* + ** Accessors + *********/ + /// The player being tracked. + public Farmer Player { get; } + + /// The player's current location. + public SnapshotDiff Location { get; } = new SnapshotDiff(); + + /// Tracks changes to the player's skill levels. + public IDictionary> Skills { get; } = + Enum + .GetValues(typeof(SkillType)) + .Cast() + .ToDictionary(skill => skill, skill => new SnapshotDiff()); + + /// Get a list of inventory changes. + public IEnumerable InventoryChanges { get; private set; } + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The player being tracked. + public PlayerSnapshot(Farmer player) + { + this.Player = player; + } + + /// Update the tracked values. + /// The player watcher to snapshot. + public void Update(PlayerTracker watcher) + { + this.Location.Update(watcher.LocationWatcher); + foreach (var pair in this.Skills) + pair.Value.Update(watcher.SkillWatchers[pair.Key]); + this.InventoryChanges = watcher.GetInventoryChanges().ToArray(); + } + } +} diff --git a/src/SMAPI/Framework/StateTracking/Snapshots/WatcherSnapshot.cs b/src/SMAPI/Framework/StateTracking/Snapshots/WatcherSnapshot.cs new file mode 100644 index 00000000..cf51e040 --- /dev/null +++ b/src/SMAPI/Framework/StateTracking/Snapshots/WatcherSnapshot.cs @@ -0,0 +1,66 @@ +using Microsoft.Xna.Framework; +using StardewValley; +using StardewValley.Menus; + +namespace StardewModdingAPI.Framework.StateTracking.Snapshots +{ + /// A frozen snapshot of the game state watchers. + internal class WatcherSnapshot + { + /********* + ** Accessors + *********/ + /// Tracks changes to the window size. + public SnapshotDiff WindowSize { get; } = new SnapshotDiff(); + + /// Tracks changes to the current player. + public PlayerSnapshot CurrentPlayer { get; private set; } + + /// Tracks changes to the time of day (in 24-hour military format). + public SnapshotDiff Time { get; } = new SnapshotDiff(); + + /// Tracks changes to the save ID. + public SnapshotDiff SaveID { get; } = new SnapshotDiff(); + + /// Tracks changes to the game's locations. + public WorldLocationsSnapshot Locations { get; } = new WorldLocationsSnapshot(); + + /// Tracks changes to . + public SnapshotDiff ActiveMenu { get; } = new SnapshotDiff(); + + /// Tracks changes to the cursor position. + public SnapshotDiff Cursor { get; } = new SnapshotDiff(); + + /// Tracks changes to the mouse wheel scroll. + public SnapshotDiff MouseWheelScroll { get; } = new SnapshotDiff(); + + /// Tracks changes to the content locale. + public SnapshotDiff Locale { get; } = new SnapshotDiff(); + + + /********* + ** Public methods + *********/ + /// Update the tracked values. + /// The watchers to snapshot. + public void Update(WatcherCore watchers) + { + // update player instance + if (watchers.CurrentPlayerTracker == null) + this.CurrentPlayer = null; + else if (watchers.CurrentPlayerTracker.Player != this.CurrentPlayer?.Player) + this.CurrentPlayer = new PlayerSnapshot(watchers.CurrentPlayerTracker.Player); + + // update snapshots + this.WindowSize.Update(watchers.WindowSizeWatcher); + this.Locale.Update(watchers.LocaleWatcher); + this.CurrentPlayer?.Update(watchers.CurrentPlayerTracker); + this.Time.Update(watchers.TimeWatcher); + this.SaveID.Update(watchers.SaveIdWatcher); + this.Locations.Update(watchers.LocationsWatcher); + this.ActiveMenu.Update(watchers.ActiveMenuWatcher); + this.Cursor.Update(watchers.CursorWatcher); + this.MouseWheelScroll.Update(watchers.MouseWheelScrollWatcher); + } + } +} diff --git a/src/SMAPI/Framework/StateTracking/Snapshots/WorldLocationsSnapshot.cs b/src/SMAPI/Framework/StateTracking/Snapshots/WorldLocationsSnapshot.cs new file mode 100644 index 00000000..73ed2d8f --- /dev/null +++ b/src/SMAPI/Framework/StateTracking/Snapshots/WorldLocationsSnapshot.cs @@ -0,0 +1,52 @@ +using System.Collections.Generic; +using System.Linq; +using StardewModdingAPI.Framework.StateTracking.Comparers; +using StardewValley; + +namespace StardewModdingAPI.Framework.StateTracking.Snapshots +{ + /// A frozen snapshot of the tracked game locations. + internal class WorldLocationsSnapshot + { + /********* + ** Fields + *********/ + /// A map of tracked locations. + private readonly Dictionary LocationsDict = new Dictionary(new ObjectReferenceComparer()); + + + /********* + ** Accessors + *********/ + /// Tracks changes to the location list. + public SnapshotListDiff LocationList { get; } = new SnapshotListDiff(); + + /// The tracked locations. + public IEnumerable Locations => this.LocationsDict.Values; + + + /********* + ** Public methods + *********/ + /// Update the tracked values. + /// The watcher to snapshot. + public void Update(WorldLocationsTracker watcher) + { + // update location list + this.LocationList.Update(watcher.IsLocationListChanged, watcher.Added, watcher.Removed); + + // remove missing locations + foreach (var key in this.LocationsDict.Keys.Where(key => !watcher.HasLocationTracker(key)).ToArray()) + this.LocationsDict.Remove(key); + + // update locations + foreach (LocationTracker locationWatcher in watcher.Locations) + { + if (!this.LocationsDict.TryGetValue(locationWatcher.Location, out LocationSnapshot snapshot)) + this.LocationsDict[locationWatcher.Location] = snapshot = new LocationSnapshot(locationWatcher.Location); + + snapshot.Update(locationWatcher); + } + } + } +} diff --git a/src/SMAPI/Framework/StateTracking/WorldLocationsTracker.cs b/src/SMAPI/Framework/StateTracking/WorldLocationsTracker.cs index f09c69c1..303a4f3a 100644 --- a/src/SMAPI/Framework/StateTracking/WorldLocationsTracker.cs +++ b/src/SMAPI/Framework/StateTracking/WorldLocationsTracker.cs @@ -117,6 +117,13 @@ namespace StardewModdingAPI.Framework.StateTracking watcher.Reset(); } + /// Get whether the given location is tracked. + /// The location to check. + public bool HasLocationTracker(GameLocation location) + { + return this.LocationDict.ContainsKey(location); + } + /// Stop watching the player fields and release all references. public void Dispose() { -- cgit From 1a8c7345c3986acd172f91716bbf04fc7192317b Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 17 Jun 2019 18:51:31 -0400 Subject: add stardewvalley.targets support to toolkit --- docs/release-notes.md | 1 + .../Framework/GameScanning/GameScanner.cs | 46 ++++++++++++++++++++-- 2 files changed, 44 insertions(+), 3 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 6d883baf..efac8f41 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -28,6 +28,7 @@ These changes have not been released yet. * Added `Context.IsGameLaunched` field. * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialised when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialised). * Added separate `LogNetworkTraffic` option to make verbose logging less overwhelmingly verbose. + * The installer now recognises custom game paths stored in `stardewvalley.targets`, if any. * When a mod is incompatible, the trace logs now list all detected issues instead of the first one. * Removed all deprecated APIs. * Removed the `Monitor.ExitGameImmediately` method. diff --git a/src/SMAPI.Toolkit/Framework/GameScanning/GameScanner.cs b/src/SMAPI.Toolkit/Framework/GameScanning/GameScanner.cs index 1755a7db..60c7a682 100644 --- a/src/SMAPI.Toolkit/Framework/GameScanning/GameScanner.cs +++ b/src/SMAPI.Toolkit/Framework/GameScanning/GameScanner.cs @@ -2,6 +2,8 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Xml.Linq; +using System.Xml.XPath; using StardewModdingAPI.Toolkit.Utilities; #if SMAPI_FOR_WINDOWS using Microsoft.Win32; @@ -19,12 +21,18 @@ namespace StardewModdingAPI.Toolkit.Framework.GameScanning /// This checks default game locations, and on Windows checks the Windows registry for GOG/Steam install data. A folder is considered 'valid' if it contains the Stardew Valley executable for the current OS. public IEnumerable Scan() { - // get unique candidate paths + // get OS info Platform platform = EnvironmentUtility.DetectPlatform(); string executableFilename = EnvironmentUtility.GetExecutableName(platform); - IEnumerable paths = this.GetDefaultInstallPaths(platform).Select(PathUtilities.NormalisePathSeparators).Distinct(StringComparer.InvariantCultureIgnoreCase); - // get valid folders + // get install paths + IEnumerable paths = this + .GetCustomInstallPaths(platform) + .Concat(this.GetDefaultInstallPaths(platform)) + .Select(PathUtilities.NormalisePathSeparators) + .Distinct(StringComparer.InvariantCultureIgnoreCase); + + // yield valid folders foreach (string path in paths) { DirectoryInfo folder = new DirectoryInfo(path); @@ -98,6 +106,38 @@ namespace StardewModdingAPI.Toolkit.Framework.GameScanning } } + /// Get the custom install path from the stardewvalley.targets file in the home directory, if any. + /// The target platform. + private IEnumerable GetCustomInstallPaths(Platform platform) + { + // get home path + string homePath = Environment.GetEnvironmentVariable(platform == Platform.Windows ? "USERPROFILE" : "HOME"); + if (string.IsNullOrWhiteSpace(homePath)) + yield break; + + // get targets file + FileInfo file = new FileInfo(Path.Combine(homePath, "stardewvalley.targets")); + if (!file.Exists) + yield break; + + // parse file + XElement root; + try + { + using (FileStream stream = file.OpenRead()) + root = XElement.Load(stream); + } + catch + { + yield break; + } + + // get install path + XElement element = root.XPathSelectElement("//*[local-name() = 'GamePath']"); // can't use '//GamePath' due to the default namespace + if (!string.IsNullOrWhiteSpace(element?.Value)) + yield return element.Value.Trim(); + } + #if SMAPI_FOR_WINDOWS /// Get the value of a key in the Windows HKLM registry. /// The full path of the registry key relative to HKLM. -- cgit From 1dde811c36c2d03c17df4d09d978907bbd608787 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 6 Jul 2019 01:04:05 -0400 Subject: group technical docs, add general shortcut for mod build package docs (#651) --- build/common.targets | 2 +- docs/README.md | 8 +- docs/mod-build-config.md | 369 -------------------- docs/release-notes.md | 4 +- docs/screenshots/code-analyzer-example.png | Bin 3473 -> 0 bytes docs/technical-docs.md | 105 ------ docs/technical/mod-package.md | 371 +++++++++++++++++++++ .../screenshots/code-analyzer-example.png | Bin 0 -> 3473 bytes docs/technical/smapi.md | 105 ++++++ docs/technical/web.md | 106 ++++++ docs/web-services.md | 104 ------ .../NetFieldAnalyzerTests.cs | 4 +- .../ObsoleteFieldAnalyzerTests.cs | 2 +- .../NetFieldAnalyzer.cs | 8 +- .../ObsoleteFieldAnalyzer.cs | 4 +- .../SMAPI.ModBuildConfig.csproj | 4 +- src/SMAPI.ModBuildConfig/build/smapi.targets | 2 +- src/SMAPI.ModBuildConfig/package.nuspec | 4 +- src/SMAPI.Web/Startup.cs | 2 +- src/SMAPI.sln | 11 +- 20 files changed, 612 insertions(+), 603 deletions(-) delete mode 100644 docs/mod-build-config.md delete mode 100644 docs/screenshots/code-analyzer-example.png delete mode 100644 docs/technical-docs.md create mode 100644 docs/technical/mod-package.md create mode 100644 docs/technical/screenshots/code-analyzer-example.png create mode 100644 docs/technical/smapi.md create mode 100644 docs/technical/web.md delete mode 100644 docs/web-services.md (limited to 'docs/release-notes.md') diff --git a/build/common.targets b/build/common.targets index 804f1ed3..59d5bfd2 100644 --- a/build/common.targets +++ b/build/common.targets @@ -10,7 +10,7 @@ - + diff --git a/docs/README.md b/docs/README.md index e4220de2..4b9c97a1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -38,16 +38,16 @@ doesn't change any of your game files. It serves eight main purposes: something goes wrong. (Via the bundled SaveBackup mod.)_ ## Documentation -Have questions? Come [chat on Discord](https://discord.gg/KCJHWhX) with SMAPI developers and other -modders! +Have questions? Come [chat on Discord](https://stardewvalleywiki.com/Modding:Community) with SMAPI +developers and other modders! ### For players * [Player guide](https://stardewvalleywiki.com/Modding:Player_Guide) ### For modders * [Modding documentation](https://stardewvalleywiki.com/Modding:Index) -* [Mod build configuration](mod-build-config.md) +* [Mod build configuration](technical/mod-package.md) * [Release notes](release-notes.md) ### For SMAPI developers -* [Technical docs](technical-docs.md) +* [Technical docs](technical/smapi.md) diff --git a/docs/mod-build-config.md b/docs/mod-build-config.md deleted file mode 100644 index 6c8ea2fa..00000000 --- a/docs/mod-build-config.md +++ /dev/null @@ -1,369 +0,0 @@ -The **mod build package** is an open-source NuGet package which automates the MSBuild configuration -for SMAPI mods and related tools. The package is fully compatible with Linux, Mac, and Windows. - -## Contents -* [Use](#use) -* [Features](#features) - * [Detect game path](#detect-game-path) - * [Add assembly references](#add-assembly-references) - * [Copy files into the `Mods` folder and create release zip](#copy-files-into-the-mods-folder-and-create-release-zip) - * [Launch or debug game](#launch-or-debug-game) - * [Preconfigure common settings](#preconfigure-common-settings) - * [Add code warnings](#add-code-warnings) -* [Code warnings](#code-warnings) -* [Special cases](#special-cases) - * [Custom game path](#custom-game-path) - * [Non-mod projects](#non-mod-projects) -* [For SMAPI developers](#for-smapi-developers) -* [Release notes](#release-notes) - -## Use -1. Create an empty library project. -2. Reference the [`Pathoschild.Stardew.ModBuildConfig` NuGet package](https://www.nuget.org/packages/Pathoschild.Stardew.ModBuildConfig). -3. [Write your code](https://stardewvalleywiki.com/Modding:Creating_a_SMAPI_mod). -4. Compile on any platform. -5. Run the game to play with your mod. - -## Features -The package automatically makes the changes listed below. In some cases you can configure how it -works by editing your mod's `.csproj` file, and adding the given properties between the first -`` and `` tags. - -### Detect game path -The package finds your game folder by scanning the default install paths and Windows registry. It -adds two MSBuild properties for use in your `.csproj` file if needed: - -property | description --------- | ----------- -`$(GamePath)` | The absolute path to the detected game folder. -`$(GameExecutableName)` | The game's executable name for the current OS (`Stardew Valley` on Windows, or `StardewValley` on Linux/Mac). - -If you get a build error saying it can't find your game, see [_set the game path_](#set-the-game-path). - -### Add assembly references -The package adds assembly references to SMAPI, Stardew Valley, xTile, and MonoGame (Linux/Mac) or XNA -Framework (Windows). It automatically adjusts depending on which OS you're compiling it on. - -The assemblies aren't copied to the build output, since mods loaded by SMAPI won't need them. For -non-mod projects like unit tests, you can set this property: -```xml -true -``` - -If your mod uses [Harmony](https://github.com/pardeike/Harmony) (not recommended for most mods), -the package can add a reference to SMAPI's Harmony DLL for you: -```xml -true -``` - -### Copy files into the `Mods` folder and create release zip -
-
Files considered part of your mod
-
- -These files are selected by default: `manifest.json`, -[`i18n` files](https://stardewvalleywiki.com/Modding:Translations) (if any), the `assets` folder -(if any), and all files in the build output. You can select custom files by [adding them to the -build output](https://stackoverflow.com/a/10828462/262123). (If your project references another mod, -make sure the reference is [_not_ marked 'copy local'](https://msdn.microsoft.com/en-us/library/t1zz5y8c(v=vs.100).aspx).) - -You can deselect a file by removing it from the build output. For a default file, you can set the -property below to a comma-delimited list of regex patterns to ignore. For crossplatform -compatibility, you should replace path delimiters with `[/\\]`. - -```xml -\.txt$, \.pdf$, assets[/\\]paths.png -``` - -
-
Copy files into the `Mods` folder
-
- -The package copies the selected files into your game's `Mods` folder when you rebuild the code, -with a subfolder matching the mod's project name. - -You can change the folder name: -```xml -YourModName -``` - -Or disable deploying the files: -```xml -false -``` - -
-
Create release zip
-
- -The package adds a zip file in your project's `bin` folder when you rebuild the code, in the format -recommended for sites like Nexus Mods. The zip filename can be changed using `ModFolderName` above. - -You can change the folder path where the zip is created: -```xml -$(SolutionDir)\_releases -``` - -Or disable zip creation: -```xml -false -``` - -
-
- -### Launch or debug game -On Windows only, the package configures Visual Studio so you can launch the game and attach a -debugger using _Debug > Start Debugging_ or _Debug > Start Without Debugging_. This lets you [set -breakpoints](https://docs.microsoft.com/en-us/visualstudio/debugger/using-breakpoints?view=vs-2019) -in your code while the game is running, or [make simple changes to the mod code without needing to -restart the game](https://docs.microsoft.com/en-us/visualstudio/debugger/edit-and-continue?view=vs-2019). - -This is disabled on Linux/Mac due to limitations with the Mono wrapper. - -To disable game debugging (only needed for some non-mod projects): - -```xml -false -``` - -### Preconfigure common settings -The package automatically enables PDB files, so error logs show line numbers for simpler debugging. - -For projects using the simplified `.csproj` format, it also enables the GAC (to support XNA -Framework) and sets the build to x86 mode (to avoid 'mismatch between the processor architecture' warnings due to - the game being x86). - -### Add code warnings -The package runs code analysis on your mod and raises warnings for some common errors or pitfalls. -See [_code warnings_](#code-warnings) for more info. - -## Code warnings -### Overview -The NuGet package adds code warnings in Visual Studio specific to Stardew Valley. For example: -![](screenshots/code-analyzer-example.png) - -You can hide the warnings using the warning ID (shown under 'code' in the Error List). See... -* [for specific code](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-pragma-warning); -* for a method using this attribute: - ```cs - [System.Diagnostics.CodeAnalysis.SuppressMessage("SMAPI.CommonErrors", "AvoidNetField")] - ``` -* for an entire project: - 1. Expand the _References_ node for the project in Visual Studio. - 2. Right-click on _Analyzers_ and choose _Open Active Rule Set_. - 4. Expand _StardewModdingAPI.ModBuildConfig.Analyzer_ and uncheck the warnings you want to hide. - -See below for help with each specific warning. - -### Avoid implicit net field cast -Warning text: -> This implicitly converts '{{expression}}' from {{net type}} to {{other type}}, but -> {{net type}} has unintuitive implicit conversion rules. Consider comparing against the actual -> value instead to avoid bugs. - -Stardew Valley uses net types (like `NetBool` and `NetInt`) to handle multiplayer sync. These types -can implicitly convert to their equivalent normal values (like `bool x = new NetBool()`), but their -conversion rules are unintuitive and error-prone. For example, -`item?.category == null && item?.category != null` can both be true at once, and -`building.indoors != null` can be true for a null value. - -Suggested fix: -* Some net fields have an equivalent non-net property like `monster.Health` (`int`) instead of - `monster.health` (`NetInt`). The package will add a separate [AvoidNetField](#avoid-net-field) warning for - these. Use the suggested property instead. -* For a reference type (i.e. one that can contain `null`), you can use the `.Value` property: - ```c# - if (building.indoors.Value == null) - ``` - Or convert the value before comparison: - ```c# - GameLocation indoors = building.indoors; - if(indoors == null) - // ... - ``` -* For a value type (i.e. one that can't contain `null`), check if the object is null (if applicable) - and compare with `.Value`: - ```cs - if (item != null && item.category.Value == 0) - ``` - -### Avoid net field -Warning text: -> '{{expression}}' is a {{net type}} field; consider using the {{property name}} property instead. - -Your code accesses a net field, which has some unusual behavior (see [AvoidImplicitNetFieldCast](#avoid-implicit-net-field-cast)). -This field has an equivalent non-net property that avoids those issues. - -Suggested fix: access the suggested property name instead. - -### Avoid obsolete field -Warning text: -> The '{{old field}}' field is obsolete and should be replaced with '{{new field}}'. - -Your code accesses a field which is obsolete or no longer works. Use the suggested field instead. - -## Special cases -### Custom game path -The package usually detects where your game is installed automatically. If it can't find your game -or you have multiple installs, you can specify the path yourself. There's two ways to do that: - -* **Option 1: global game path (recommended).** - _This will apply to every project that uses the package._ - - 1. Get the full folder path containing the Stardew Valley executable. - 2. Create this file: - - platform | path - --------- | ---- - Linux/Mac | `~/stardewvalley.targets` - Windows | `%USERPROFILE%\stardewvalley.targets` - - 3. Save the file with this content: - - ```xml - - - PATH_HERE - - - ``` - - 4. Replace `PATH_HERE` with your game path. - -* **Option 2: path in the project file.** - _You'll need to do this for each project that uses the package._ - - 1. Get the folder path containing the Stardew Valley `.exe` file. - 2. Add this to your `.csproj` file under the ` - PATH_HERE - - ``` - - 3. Replace `PATH_HERE` with your custom game install path. - -The configuration will check your custom path first, then fall back to the default paths (so it'll -still compile on a different computer). - -You access the game path via `$(GamePath)` in MSBuild properties, if you need to reference another -file in the game folder. - -### Non-mod projects -You can use the package in non-mod projects too (e.g. unit tests or framework DLLs). Just disable -the mod-related package features: - -```xml -false -false -false -``` - -If you need to copy the referenced DLLs into your build output, add this too: -```xml -true -``` - -## For SMAPI developers -The mod build package consists of three projects: - -project | purpose -------------------------------------------------- | ---------------- -`StardewModdingAPI.ModBuildConfig` | Configures the build (references, deploying the mod files, setting up debugging, etc). -`StardewModdingAPI.ModBuildConfig.Analyzer` | Adds C# analyzers which show code warnings in Visual Studio. -`StardewModdingAPI.ModBuildConfig.Analyzer.Tests` | Unit tests for the C# analyzers. - -To prepare a build of the NuGet package: -1. Install the [NuGet CLI](https://docs.microsoft.com/en-us/nuget/install-nuget-client-tools#nugetexe-cli). -1. Change the version and release notes in `package.nuspec`. -2. Rebuild the solution in _Release_ mode. -3. Open a terminal in the `bin/Pathoschild.Stardew.ModBuildConfig` package and run this command: - ```bash - nuget.exe pack - ``` - -That will create a `Pathoschild.Stardew.ModBuildConfig-.nupkg` file in the same directory -which can be uploaded to NuGet or referenced directly. - -## Release notes -### Upcoming release -* Updated for SMAPI 3.0 and Stardew Valley 1.4. -* Added automatic support for `assets` folders. -* Added `$(GameExecutableName)` MSBuild variable. -* Added support for projects using the simplified `.csproj` format: - * platform target is now set to x86 automatically to avoid mismatching platform target warnings; - * added GAC to assembly search paths to fix references to XNA Framework. -* Added option to disable game debugging config. -* Added `.pdb` files to builds by default (to enable line numbers in error stack traces). -* Added optional Harmony reference. -* Fixed `Newtonsoft.Json.pdb` included in release zips when Json.NET is referenced directly. -* Fixed `` not working for `i18n` files. -* Dropped support for older versions of SMAPI and Visual Studio. - -### 2.2 -* Added support for SMAPI 2.8+ (still compatible with earlier versions). -* Added default game paths for 32-bit Windows. -* Fixed valid manifests marked invalid in some cases. - -### 2.1 -* Added support for Stardew Valley 1.3. -* Added support for non-mod projects. -* Added C# analyzers to warn about implicit conversions of Netcode fields in Stardew Valley 1.3. -* Added option to ignore files by regex pattern. -* Added reference to new SMAPI DLL. -* Fixed some game paths not detected by NuGet package. - -### 2.0.2 -* Fixed compatibility issue on Linux. - -### 2.0.1 -* Fixed mod deploy failing to create subfolders if they don't already exist. - -### 2.0 -* Added: mods are now copied into the `Mods` folder automatically (configurable). -* Added: release zips are now created automatically in your build output folder (configurable). -* Added: mod deploy and release zips now exclude Json.NET automatically, since it's provided by SMAPI. -* Added mod's version to release zip filename. -* Improved errors to simplify troubleshooting. -* Fixed release zip not having a mod folder. -* Fixed release zip failing if mod name contains characters that aren't valid in a filename. - -### 1.7.1 -* Fixed issue where i18n folders were flattened. -* The manifest/i18n files in the project now take precedence over those in the build output if both - are present. - -### 1.7 -* Added option to create release zips on build. -* Added reference to XNA's XACT library for audio-related mods. - -### 1.6 -* Added support for deploying mod files into `Mods` automatically. -* Added a build error if a game folder is found, but doesn't contain Stardew Valley or SMAPI. - -### 1.5 -* Added support for setting a custom game path globally. -* Added default GOG path on Mac. - -### 1.4 -* Fixed detection of non-default game paths on 32-bit Windows. -* Removed support for SilVerPLuM (discontinued). -* Removed support for overriding the target platform (no longer needed since SMAPI crossplatforms - mods automatically). - -### 1.3 -* Added support for non-default game paths on Windows. - -### 1.2 -* Exclude game binaries from mod build output. - -### 1.1 -* Added support for overriding the target platform. - -### 1.0 -* Initial release. -* Added support for detecting the game path automatically. -* Added support for injecting XNA/MonoGame references automatically based on the OS. -* Added support for mod builders like SilVerPLuM. diff --git a/docs/release-notes.md b/docs/release-notes.md index efac8f41..3f955e78 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -1,3 +1,5 @@ +← [README](README.md) + # Release notes ## 3.0 (upcoming release) These changes have not been released yet. @@ -674,7 +676,7 @@ Released 14 October 2017 for Stardew Valley 1.2.30–1.2.33. * **Command-line install** For power users and mod managers, the SMAPI installer can now be scripted using command-line arguments - (see [technical docs](technical-docs.md#command-line-arguments)). + (see [technical docs](technical/smapi.md#command-line-arguments)). ### Change log For players: diff --git a/docs/screenshots/code-analyzer-example.png b/docs/screenshots/code-analyzer-example.png deleted file mode 100644 index de38f643..00000000 Binary files a/docs/screenshots/code-analyzer-example.png and /dev/null differ diff --git a/docs/technical-docs.md b/docs/technical-docs.md deleted file mode 100644 index 5ef6dfb1..00000000 --- a/docs/technical-docs.md +++ /dev/null @@ -1,105 +0,0 @@ -← [README](README.md) - -This file provides more technical documentation about SMAPI. If you only want to use or create -mods, this section isn't relevant to you; see the main README to use or create mods. - -This document is about SMAPI itself; see also [mod build package](mod-build-config.md) and -[web services](web-services.md). - -# Contents -* [Customisation](#customisation) - * [Configuration file](#configuration-file) - * [Command-line arguments](#command-line-arguments) - * [Compile flags](#compile-flags) -* [For SMAPI developers](#for-smapi-developers) - * [Compiling from source](#compiling-from-source) - * [Debugging a local build](#debugging-a-local-build) - * [Preparing a release](#preparing-a-release) -* [Release notes](#release-notes) - -## Customisation -### Configuration file -You can customise the SMAPI behaviour by editing the `smapi-internal/config.json` file in your game -folder. - -Basic fields: - -field | purpose ------------------ | ------- -`DeveloperMode` | Default `false` (except in _SMAPI for developers_ releases). Whether to enable features intended for mod developers (mainly more detailed console logging). -`CheckForUpdates` | Default `true`. Whether SMAPI should check for a newer version when you load the game. If a new version is available, a small message will appear in the console. This doesn't affect the load time even if your connection is offline or slow, because it happens in the background. -`VerboseLogging` | Default `false`. Whether SMAPI should log more information about the game context. -`ModData` | Internal metadata about SMAPI mods. Changing this isn't recommended and may destabilise your game. See documentation in the file. - -### Command-line arguments -The SMAPI installer recognises three command-line arguments: - -argument | purpose --------- | ------- -`--install` | Preselects the install action, skipping the prompt asking what the user wants to do. -`--uninstall` | Preselects the uninstall action, skipping the prompt asking what the user wants to do. -`--game-path "path"` | Specifies the full path to the folder containing the Stardew Valley executable, skipping automatic detection and any prompt to choose a path. If the path is not valid, the installer displays an error. - -SMAPI itself recognises two arguments, but these are intended for internal use or testing and may -change without warning. - -argument | purpose --------- | ------- -`--no-terminal` | SMAPI won't write anything to the console window. (Messages will still be written to the log file.) -`--mods-path` | The path to search for mods, if not the standard `Mods` folder. This can be a path relative to the game folder (like `--mods-path "Mods (test)"`) or an absolute path. - -### Compile flags -SMAPI uses a small number of conditional compilation constants, which you can set by editing the -`` element in `StardewModdingAPI.csproj`. Supported constants: - -flag | purpose ----- | ------- -`SMAPI_FOR_WINDOWS` | Whether SMAPI is being compiled on Windows for players on Windows. Set automatically in `crossplatform.targets`. - -## For SMAPI developers -### Compiling from source -Using an official SMAPI release is recommended for most users. - -SMAPI uses some C# 7 code, so you'll need at least -[Visual Studio 2017](https://www.visualstudio.com/vs/community/) on Windows, -[MonoDevelop 7.0](https://www.monodevelop.com/) on Linux, -[Visual Studio 2017 for Mac](https://www.visualstudio.com/vs/visual-studio-mac/), or an equivalent -IDE to compile it. It uses build configuration derived from the -[crossplatform mod config](https://github.com/Pathoschild/Stardew.ModBuildConfig#readme) to detect -your current OS automatically and load the correct references. Compile output will be placed in a -`bin` folder at the root of the git repository. - -### Debugging a local build -Rebuilding the solution in debug mode will copy the SMAPI files into your game folder. Starting -the `StardewModdingAPI` project with debugging from Visual Studio (on Mac or Windows) will launch -SMAPI with the debugger attached, so you can intercept errors and step through the code being -executed. This doesn't work in MonoDevelop on Linux, unfortunately. - -### Preparing a release -To prepare a crossplatform SMAPI release, you'll need to compile it on two platforms. See -[crossplatforming info](https://stardewvalleywiki.com/Modding:Modder_Guide/Test_and_Troubleshoot#Testing_on_all_platforms) -on the wiki for the first-time setup. - -1. Update the version number in `GlobalAssemblyInfo.cs` and `Constants::Version`. Make sure you use a - [semantic version](https://semver.org). Recommended format: - - build type | format | example - :--------- | :----------------------- | :------ - dev build | `-alpha.` | `3.0-alpha.20171230` - prerelease | `-beta.` | `3.0-beta.2` - release | `` | `3.0` - -2. In Windows: - 1. Rebuild the solution in Release mode. - 2. Copy `windows-install.*` from `bin/SMAPI installer` and `bin/SMAPI installer for developers` to - Linux/Mac. - -3. In Linux/Mac: - 1. Rebuild the solution in Release mode. - 2. Add the `windows-install.*` files to the `bin/SMAPI installer` and - `bin/SMAPI installer for developers` folders. - 3. Rename the folders to `SMAPI installer` and `SMAPI installer for developers`. - 4. Zip the two folders. - -## Release notes -See [release notes](release-notes.md). diff --git a/docs/technical/mod-package.md b/docs/technical/mod-package.md new file mode 100644 index 00000000..43682bfb --- /dev/null +++ b/docs/technical/mod-package.md @@ -0,0 +1,371 @@ +← [SMAPI](../README.md) + +The **mod build package** is an open-source NuGet package which automates the MSBuild configuration +for SMAPI mods and related tools. The package is fully compatible with Linux, Mac, and Windows. + +## Contents +* [Use](#use) +* [Features](#features) + * [Detect game path](#detect-game-path) + * [Add assembly references](#add-assembly-references) + * [Copy files into the `Mods` folder and create release zip](#copy-files-into-the-mods-folder-and-create-release-zip) + * [Launch or debug game](#launch-or-debug-game) + * [Preconfigure common settings](#preconfigure-common-settings) + * [Add code warnings](#add-code-warnings) +* [Code warnings](#code-warnings) +* [Special cases](#special-cases) + * [Custom game path](#custom-game-path) + * [Non-mod projects](#non-mod-projects) +* [For SMAPI developers](#for-smapi-developers) +* [Release notes](#release-notes) + +## Use +1. Create an empty library project. +2. Reference the [`Pathoschild.Stardew.ModBuildConfig` NuGet package](https://www.nuget.org/packages/Pathoschild.Stardew.ModBuildConfig). +3. [Write your code](https://stardewvalleywiki.com/Modding:Creating_a_SMAPI_mod). +4. Compile on any platform. +5. Run the game to play with your mod. + +## Features +The package automatically makes the changes listed below. In some cases you can configure how it +works by editing your mod's `.csproj` file, and adding the given properties between the first +`` and `` tags. + +### Detect game path +The package finds your game folder by scanning the default install paths and Windows registry. It +adds two MSBuild properties for use in your `.csproj` file if needed: + +property | description +-------- | ----------- +`$(GamePath)` | The absolute path to the detected game folder. +`$(GameExecutableName)` | The game's executable name for the current OS (`Stardew Valley` on Windows, or `StardewValley` on Linux/Mac). + +If you get a build error saying it can't find your game, see [_set the game path_](#set-the-game-path). + +### Add assembly references +The package adds assembly references to SMAPI, Stardew Valley, xTile, and MonoGame (Linux/Mac) or XNA +Framework (Windows). It automatically adjusts depending on which OS you're compiling it on. + +The assemblies aren't copied to the build output, since mods loaded by SMAPI won't need them. For +non-mod projects like unit tests, you can set this property: +```xml +true +``` + +If your mod uses [Harmony](https://github.com/pardeike/Harmony) (not recommended for most mods), +the package can add a reference to SMAPI's Harmony DLL for you: +```xml +true +``` + +### Copy files into the `Mods` folder and create release zip +
+
Files considered part of your mod
+
+ +These files are selected by default: `manifest.json`, +[`i18n` files](https://stardewvalleywiki.com/Modding:Translations) (if any), the `assets` folder +(if any), and all files in the build output. You can select custom files by [adding them to the +build output](https://stackoverflow.com/a/10828462/262123). (If your project references another mod, +make sure the reference is [_not_ marked 'copy local'](https://msdn.microsoft.com/en-us/library/t1zz5y8c(v=vs.100).aspx).) + +You can deselect a file by removing it from the build output. For a default file, you can set the +property below to a comma-delimited list of regex patterns to ignore. For crossplatform +compatibility, you should replace path delimiters with `[/\\]`. + +```xml +\.txt$, \.pdf$, assets[/\\]paths.png +``` + +
+
Copy files into the `Mods` folder
+
+ +The package copies the selected files into your game's `Mods` folder when you rebuild the code, +with a subfolder matching the mod's project name. + +You can change the folder name: +```xml +YourModName +``` + +Or disable deploying the files: +```xml +false +``` + +
+
Create release zip
+
+ +The package adds a zip file in your project's `bin` folder when you rebuild the code, in the format +recommended for sites like Nexus Mods. The zip filename can be changed using `ModFolderName` above. + +You can change the folder path where the zip is created: +```xml +$(SolutionDir)\_releases +``` + +Or disable zip creation: +```xml +false +``` + +
+
+ +### Launch or debug game +On Windows only, the package configures Visual Studio so you can launch the game and attach a +debugger using _Debug > Start Debugging_ or _Debug > Start Without Debugging_. This lets you [set +breakpoints](https://docs.microsoft.com/en-us/visualstudio/debugger/using-breakpoints?view=vs-2019) +in your code while the game is running, or [make simple changes to the mod code without needing to +restart the game](https://docs.microsoft.com/en-us/visualstudio/debugger/edit-and-continue?view=vs-2019). + +This is disabled on Linux/Mac due to limitations with the Mono wrapper. + +To disable game debugging (only needed for some non-mod projects): + +```xml +false +``` + +### Preconfigure common settings +The package automatically enables PDB files, so error logs show line numbers for simpler debugging. + +For projects using the simplified `.csproj` format, it also enables the GAC (to support XNA +Framework) and sets the build to x86 mode (to avoid 'mismatch between the processor architecture' warnings due to + the game being x86). + +### Add code warnings +The package runs code analysis on your mod and raises warnings for some common errors or pitfalls. +See [_code warnings_](#code-warnings) for more info. + +## Code warnings +### Overview +The NuGet package adds code warnings in Visual Studio specific to Stardew Valley. For example: +![](screenshots/code-analyzer-example.png) + +You can hide the warnings using the warning ID (shown under 'code' in the Error List). See... +* [for specific code](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-pragma-warning); +* for a method using this attribute: + ```cs + [System.Diagnostics.CodeAnalysis.SuppressMessage("SMAPI.CommonErrors", "AvoidNetField")] + ``` +* for an entire project: + 1. Expand the _References_ node for the project in Visual Studio. + 2. Right-click on _Analyzers_ and choose _Open Active Rule Set_. + 4. Expand _StardewModdingAPI.ModBuildConfig.Analyzer_ and uncheck the warnings you want to hide. + +See below for help with each specific warning. + +### Avoid implicit net field cast +Warning text: +> This implicitly converts '{{expression}}' from {{net type}} to {{other type}}, but +> {{net type}} has unintuitive implicit conversion rules. Consider comparing against the actual +> value instead to avoid bugs. + +Stardew Valley uses net types (like `NetBool` and `NetInt`) to handle multiplayer sync. These types +can implicitly convert to their equivalent normal values (like `bool x = new NetBool()`), but their +conversion rules are unintuitive and error-prone. For example, +`item?.category == null && item?.category != null` can both be true at once, and +`building.indoors != null` can be true for a null value. + +Suggested fix: +* Some net fields have an equivalent non-net property like `monster.Health` (`int`) instead of + `monster.health` (`NetInt`). The package will add a separate [AvoidNetField](#avoid-net-field) warning for + these. Use the suggested property instead. +* For a reference type (i.e. one that can contain `null`), you can use the `.Value` property: + ```c# + if (building.indoors.Value == null) + ``` + Or convert the value before comparison: + ```c# + GameLocation indoors = building.indoors; + if(indoors == null) + // ... + ``` +* For a value type (i.e. one that can't contain `null`), check if the object is null (if applicable) + and compare with `.Value`: + ```cs + if (item != null && item.category.Value == 0) + ``` + +### Avoid net field +Warning text: +> '{{expression}}' is a {{net type}} field; consider using the {{property name}} property instead. + +Your code accesses a net field, which has some unusual behavior (see [AvoidImplicitNetFieldCast](#avoid-implicit-net-field-cast)). +This field has an equivalent non-net property that avoids those issues. + +Suggested fix: access the suggested property name instead. + +### Avoid obsolete field +Warning text: +> The '{{old field}}' field is obsolete and should be replaced with '{{new field}}'. + +Your code accesses a field which is obsolete or no longer works. Use the suggested field instead. + +## Special cases +### Custom game path +The package usually detects where your game is installed automatically. If it can't find your game +or you have multiple installs, you can specify the path yourself. There's two ways to do that: + +* **Option 1: global game path (recommended).** + _This will apply to every project that uses the package._ + + 1. Get the full folder path containing the Stardew Valley executable. + 2. Create this file: + + platform | path + --------- | ---- + Linux/Mac | `~/stardewvalley.targets` + Windows | `%USERPROFILE%\stardewvalley.targets` + + 3. Save the file with this content: + + ```xml + + + PATH_HERE + + + ``` + + 4. Replace `PATH_HERE` with your game path. + +* **Option 2: path in the project file.** + _You'll need to do this for each project that uses the package._ + + 1. Get the folder path containing the Stardew Valley `.exe` file. + 2. Add this to your `.csproj` file under the ` + PATH_HERE + + ``` + + 3. Replace `PATH_HERE` with your custom game install path. + +The configuration will check your custom path first, then fall back to the default paths (so it'll +still compile on a different computer). + +You access the game path via `$(GamePath)` in MSBuild properties, if you need to reference another +file in the game folder. + +### Non-mod projects +You can use the package in non-mod projects too (e.g. unit tests or framework DLLs). Just disable +the mod-related package features: + +```xml +false +false +false +``` + +If you need to copy the referenced DLLs into your build output, add this too: +```xml +true +``` + +## For SMAPI developers +The mod build package consists of three projects: + +project | purpose +------------------------------------------------- | ---------------- +`StardewModdingAPI.ModBuildConfig` | Configures the build (references, deploying the mod files, setting up debugging, etc). +`StardewModdingAPI.ModBuildConfig.Analyzer` | Adds C# analyzers which show code warnings in Visual Studio. +`StardewModdingAPI.ModBuildConfig.Analyzer.Tests` | Unit tests for the C# analyzers. + +To prepare a build of the NuGet package: +1. Install the [NuGet CLI](https://docs.microsoft.com/en-us/nuget/install-nuget-client-tools#nugetexe-cli). +1. Change the version and release notes in `package.nuspec`. +2. Rebuild the solution in _Release_ mode. +3. Open a terminal in the `bin/Pathoschild.Stardew.ModBuildConfig` package and run this command: + ```bash + nuget.exe pack + ``` + +That will create a `Pathoschild.Stardew.ModBuildConfig-.nupkg` file in the same directory +which can be uploaded to NuGet or referenced directly. + +## Release notes +### Upcoming release +* Updated for SMAPI 3.0 and Stardew Valley 1.4. +* Added automatic support for `assets` folders. +* Added `$(GameExecutableName)` MSBuild variable. +* Added support for projects using the simplified `.csproj` format: + * platform target is now set to x86 automatically to avoid mismatching platform target warnings; + * added GAC to assembly search paths to fix references to XNA Framework. +* Added option to disable game debugging config. +* Added `.pdb` files to builds by default (to enable line numbers in error stack traces). +* Added optional Harmony reference. +* Fixed `Newtonsoft.Json.pdb` included in release zips when Json.NET is referenced directly. +* Fixed `` not working for `i18n` files. +* Dropped support for older versions of SMAPI and Visual Studio. + +### 2.2 +* Added support for SMAPI 2.8+ (still compatible with earlier versions). +* Added default game paths for 32-bit Windows. +* Fixed valid manifests marked invalid in some cases. + +### 2.1 +* Added support for Stardew Valley 1.3. +* Added support for non-mod projects. +* Added C# analyzers to warn about implicit conversions of Netcode fields in Stardew Valley 1.3. +* Added option to ignore files by regex pattern. +* Added reference to new SMAPI DLL. +* Fixed some game paths not detected by NuGet package. + +### 2.0.2 +* Fixed compatibility issue on Linux. + +### 2.0.1 +* Fixed mod deploy failing to create subfolders if they don't already exist. + +### 2.0 +* Added: mods are now copied into the `Mods` folder automatically (configurable). +* Added: release zips are now created automatically in your build output folder (configurable). +* Added: mod deploy and release zips now exclude Json.NET automatically, since it's provided by SMAPI. +* Added mod's version to release zip filename. +* Improved errors to simplify troubleshooting. +* Fixed release zip not having a mod folder. +* Fixed release zip failing if mod name contains characters that aren't valid in a filename. + +### 1.7.1 +* Fixed issue where i18n folders were flattened. +* The manifest/i18n files in the project now take precedence over those in the build output if both + are present. + +### 1.7 +* Added option to create release zips on build. +* Added reference to XNA's XACT library for audio-related mods. + +### 1.6 +* Added support for deploying mod files into `Mods` automatically. +* Added a build error if a game folder is found, but doesn't contain Stardew Valley or SMAPI. + +### 1.5 +* Added support for setting a custom game path globally. +* Added default GOG path on Mac. + +### 1.4 +* Fixed detection of non-default game paths on 32-bit Windows. +* Removed support for SilVerPLuM (discontinued). +* Removed support for overriding the target platform (no longer needed since SMAPI crossplatforms + mods automatically). + +### 1.3 +* Added support for non-default game paths on Windows. + +### 1.2 +* Exclude game binaries from mod build output. + +### 1.1 +* Added support for overriding the target platform. + +### 1.0 +* Initial release. +* Added support for detecting the game path automatically. +* Added support for injecting XNA/MonoGame references automatically based on the OS. +* Added support for mod builders like SilVerPLuM. diff --git a/docs/technical/screenshots/code-analyzer-example.png b/docs/technical/screenshots/code-analyzer-example.png new file mode 100644 index 00000000..de38f643 Binary files /dev/null and b/docs/technical/screenshots/code-analyzer-example.png differ diff --git a/docs/technical/smapi.md b/docs/technical/smapi.md new file mode 100644 index 00000000..a006ff1a --- /dev/null +++ b/docs/technical/smapi.md @@ -0,0 +1,105 @@ +← [README](../README.md) + +This file provides more technical documentation about SMAPI. If you only want to use or create +mods, this section isn't relevant to you; see the main README to use or create mods. + +This document is about SMAPI itself; see also [mod build package](mod-package.md) and +[web services](web.md). + +# Contents +* [Customisation](#customisation) + * [Configuration file](#configuration-file) + * [Command-line arguments](#command-line-arguments) + * [Compile flags](#compile-flags) +* [For SMAPI developers](#for-smapi-developers) + * [Compiling from source](#compiling-from-source) + * [Debugging a local build](#debugging-a-local-build) + * [Preparing a release](#preparing-a-release) +* [Release notes](#release-notes) + +## Customisation +### Configuration file +You can customise the SMAPI behaviour by editing the `smapi-internal/config.json` file in your game +folder. + +Basic fields: + +field | purpose +----------------- | ------- +`DeveloperMode` | Default `false` (except in _SMAPI for developers_ releases). Whether to enable features intended for mod developers (mainly more detailed console logging). +`CheckForUpdates` | Default `true`. Whether SMAPI should check for a newer version when you load the game. If a new version is available, a small message will appear in the console. This doesn't affect the load time even if your connection is offline or slow, because it happens in the background. +`VerboseLogging` | Default `false`. Whether SMAPI should log more information about the game context. +`ModData` | Internal metadata about SMAPI mods. Changing this isn't recommended and may destabilise your game. See documentation in the file. + +### Command-line arguments +The SMAPI installer recognises three command-line arguments: + +argument | purpose +-------- | ------- +`--install` | Preselects the install action, skipping the prompt asking what the user wants to do. +`--uninstall` | Preselects the uninstall action, skipping the prompt asking what the user wants to do. +`--game-path "path"` | Specifies the full path to the folder containing the Stardew Valley executable, skipping automatic detection and any prompt to choose a path. If the path is not valid, the installer displays an error. + +SMAPI itself recognises two arguments, but these are intended for internal use or testing and may +change without warning. + +argument | purpose +-------- | ------- +`--no-terminal` | SMAPI won't write anything to the console window. (Messages will still be written to the log file.) +`--mods-path` | The path to search for mods, if not the standard `Mods` folder. This can be a path relative to the game folder (like `--mods-path "Mods (test)"`) or an absolute path. + +### Compile flags +SMAPI uses a small number of conditional compilation constants, which you can set by editing the +`` element in `StardewModdingAPI.csproj`. Supported constants: + +flag | purpose +---- | ------- +`SMAPI_FOR_WINDOWS` | Whether SMAPI is being compiled on Windows for players on Windows. Set automatically in `crossplatform.targets`. + +## For SMAPI developers +### Compiling from source +Using an official SMAPI release is recommended for most users. + +SMAPI uses some C# 7 code, so you'll need at least +[Visual Studio 2017](https://www.visualstudio.com/vs/community/) on Windows, +[MonoDevelop 7.0](https://www.monodevelop.com/) on Linux, +[Visual Studio 2017 for Mac](https://www.visualstudio.com/vs/visual-studio-mac/), or an equivalent +IDE to compile it. It uses build configuration derived from the +[crossplatform mod config](https://github.com/Pathoschild/Stardew.ModBuildConfig#readme) to detect +your current OS automatically and load the correct references. Compile output will be placed in a +`bin` folder at the root of the git repository. + +### Debugging a local build +Rebuilding the solution in debug mode will copy the SMAPI files into your game folder. Starting +the `StardewModdingAPI` project with debugging from Visual Studio (on Mac or Windows) will launch +SMAPI with the debugger attached, so you can intercept errors and step through the code being +executed. This doesn't work in MonoDevelop on Linux, unfortunately. + +### Preparing a release +To prepare a crossplatform SMAPI release, you'll need to compile it on two platforms. See +[crossplatforming info](https://stardewvalleywiki.com/Modding:Modder_Guide/Test_and_Troubleshoot#Testing_on_all_platforms) +on the wiki for the first-time setup. + +1. Update the version number in `GlobalAssemblyInfo.cs` and `Constants::Version`. Make sure you use a + [semantic version](https://semver.org). Recommended format: + + build type | format | example + :--------- | :----------------------- | :------ + dev build | `-alpha.` | `3.0-alpha.20171230` + prerelease | `-beta.` | `3.0-beta.2` + release | `` | `3.0` + +2. In Windows: + 1. Rebuild the solution in Release mode. + 2. Copy `windows-install.*` from `bin/SMAPI installer` and `bin/SMAPI installer for developers` to + Linux/Mac. + +3. In Linux/Mac: + 1. Rebuild the solution in Release mode. + 2. Add the `windows-install.*` files to the `bin/SMAPI installer` and + `bin/SMAPI installer for developers` folders. + 3. Rename the folders to `SMAPI installer` and `SMAPI installer for developers`. + 4. Zip the two folders. + +## Release notes +See [release notes](../release-notes.md). diff --git a/docs/technical/web.md b/docs/technical/web.md new file mode 100644 index 00000000..c8888623 --- /dev/null +++ b/docs/technical/web.md @@ -0,0 +1,106 @@ +← [README](../README.md) + +**SMAPI.Web** contains the code for the `smapi.io` website, including the mod compatibility list +and update check API. + +## Contents +* [Overview](#overview) + * [Log parser](#log-parser) + * [Web API](#web-api) +* [For SMAPI developers](#for-smapi-developers) + * [Local development](#local-development) + * [Deploying to Amazon Beanstalk](#deploying-to-amazon-beanstalk) + +## Overview +The `StardewModdingAPI.Web` project provides an API and web UI hosted at `*.smapi.io`. + +### Log parser +The log parser provides a web UI for uploading, parsing, and sharing SMAPI logs. The logs are +persisted in a compressed form to Pastebin. + +The log parser lives at https://log.smapi.io. + +### Web API +SMAPI provides a web API at `api.smapi.io` for use by SMAPI and external tools. The URL includes a +`{version}` token, which is the SMAPI version for backwards compatibility. This API is publicly +accessible but not officially released; it may change at any time. + +The API has one `/mods` endpoint. This provides mod info, including official versions and URLs +(from Chucklefish, GitHub, or Nexus), unofficial versions from the wiki, and optional mod metadata +from the wiki and SMAPI's internal data. This is used by SMAPI to perform update checks, and by +external tools to fetch mod data. + +The API accepts a `POST` request with the mods to match, each of which **must** specify an ID and +may _optionally_ specify [update keys](https://stardewvalleywiki.com/Modding:Modder_Guide/APIs/Manifest#Update_checks). +The API will automatically try to fetch known update keys from the wiki and internal data based on +the given ID. + +``` +POST https://api.smapi.io/v2.0/mods +{ + "mods": [ + { + "id": "Pathoschild.LookupAnything", + "updateKeys": [ "nexus:541", "chucklefish:4250" ] + } + ], + "includeExtendedMetadata": true +} +``` + +The API will automatically aggregate versions and errors. Each mod will include... +* an `id` (matching what you passed in); +* up to three versions: `main` (e.g. 'latest version' field on Nexus), `optional` if newer (e.g. + optional files on Nexus), and `unofficial` if newer (from the wiki); +* `metadata` with mod info crossreferenced from the wiki and internal data (only if you specified + `includeExtendedMetadata: true`); +* and `errors` containing any error messages that occurred while fetching data. + +For example: +``` +[ + { + "id": "Pathoschild.LookupAnything", + "main": { + "version": "1.19", + "url": "https://www.nexusmods.com/stardewvalley/mods/541" + }, + "metadata": { + "id": [ + "Pathoschild.LookupAnything", + "LookupAnything" + ], + "name": "Lookup Anything", + "nexusID": 541, + "gitHubRepo": "Pathoschild/StardewMods", + "compatibilityStatus": "Ok", + "compatibilitySummary": "✓ use latest version." + }, + "errors": [] + } +] +``` + +## For SMAPI developers +### Local development +`StardewModdingAPI.Web` is a regular ASP.NET MVC Core app, so you can just launch it from within +Visual Studio to run a local version. + +There are two differences when it's run locally: all endpoints use HTTP instead of HTTPS, and the +subdomain portion becomes a route (e.g. `log.smapi.io` → `localhost:59482/log`). + +Before running it locally, you need to enter your credentials in the `appsettings.Development.json` +file. See the next section for a description of each setting. This file is listed in `.gitignore` +to prevent accidentally committing credentials. + +### Deploying to Amazon Beanstalk +The app can be deployed to a standard Amazon Beanstalk IIS environment. When creating the +environment, make sure to specify the following environment properties: + +property name | description +------------------------------- | ----------------- +`LogParser:PastebinDevKey` | The [Pastebin developer key](https://pastebin.com/api#1) used to authenticate with the Pastebin API. +`LogParser:PastebinUserKey` | The [Pastebin user key](https://pastebin.com/api#8) used to authenticate with the Pastebin API. Can be left blank to post anonymously. +`LogParser:SectionUrl` | The root URL of the log page, like `https://log.smapi.io/`. +`ModUpdateCheck:GitHubPassword` | The password with which to authenticate to GitHub when fetching release info. +`ModUpdateCheck:GitHubUsername` | The username with which to authenticate to GitHub when fetching release info. diff --git a/docs/web-services.md b/docs/web-services.md deleted file mode 100644 index 601152de..00000000 --- a/docs/web-services.md +++ /dev/null @@ -1,104 +0,0 @@ -**SMAPI.Web** contains the code for the `smapi.io` website, including the mod compatibility list -and update check API. - -## Contents -* [Overview](#overview) - * [Log parser](#log-parser) - * [Web API](#web-api) -* [For SMAPI developers](#for-smapi-developers) - * [Local development](#local-development) - * [Deploying to Amazon Beanstalk](#deploying-to-amazon-beanstalk) - -## Overview -The `StardewModdingAPI.Web` project provides an API and web UI hosted at `*.smapi.io`. - -### Log parser -The log parser provides a web UI for uploading, parsing, and sharing SMAPI logs. The logs are -persisted in a compressed form to Pastebin. - -The log parser lives at https://log.smapi.io. - -### Web API -SMAPI provides a web API at `api.smapi.io` for use by SMAPI and external tools. The URL includes a -`{version}` token, which is the SMAPI version for backwards compatibility. This API is publicly -accessible but not officially released; it may change at any time. - -The API has one `/mods` endpoint. This provides mod info, including official versions and URLs -(from Chucklefish, GitHub, or Nexus), unofficial versions from the wiki, and optional mod metadata -from the wiki and SMAPI's internal data. This is used by SMAPI to perform update checks, and by -external tools to fetch mod data. - -The API accepts a `POST` request with the mods to match, each of which **must** specify an ID and -may _optionally_ specify [update keys](https://stardewvalleywiki.com/Modding:Modder_Guide/APIs/Manifest#Update_checks). -The API will automatically try to fetch known update keys from the wiki and internal data based on -the given ID. - -``` -POST https://api.smapi.io/v2.0/mods -{ - "mods": [ - { - "id": "Pathoschild.LookupAnything", - "updateKeys": [ "nexus:541", "chucklefish:4250" ] - } - ], - "includeExtendedMetadata": true -} -``` - -The API will automatically aggregate versions and errors. Each mod will include... -* an `id` (matching what you passed in); -* up to three versions: `main` (e.g. 'latest version' field on Nexus), `optional` if newer (e.g. - optional files on Nexus), and `unofficial` if newer (from the wiki); -* `metadata` with mod info crossreferenced from the wiki and internal data (only if you specified - `includeExtendedMetadata: true`); -* and `errors` containing any error messages that occurred while fetching data. - -For example: -``` -[ - { - "id": "Pathoschild.LookupAnything", - "main": { - "version": "1.19", - "url": "https://www.nexusmods.com/stardewvalley/mods/541" - }, - "metadata": { - "id": [ - "Pathoschild.LookupAnything", - "LookupAnything" - ], - "name": "Lookup Anything", - "nexusID": 541, - "gitHubRepo": "Pathoschild/StardewMods", - "compatibilityStatus": "Ok", - "compatibilitySummary": "✓ use latest version." - }, - "errors": [] - } -] -``` - -## For SMAPI developers -### Local development -`StardewModdingAPI.Web` is a regular ASP.NET MVC Core app, so you can just launch it from within -Visual Studio to run a local version. - -There are two differences when it's run locally: all endpoints use HTTP instead of HTTPS, and the -subdomain portion becomes a route (e.g. `log.smapi.io` → `localhost:59482/log`). - -Before running it locally, you need to enter your credentials in the `appsettings.Development.json` -file. See the next section for a description of each setting. This file is listed in `.gitignore` -to prevent accidentally committing credentials. - -### Deploying to Amazon Beanstalk -The app can be deployed to a standard Amazon Beanstalk IIS environment. When creating the -environment, make sure to specify the following environment properties: - -property name | description -------------------------------- | ----------------- -`LogParser:PastebinDevKey` | The [Pastebin developer key](https://pastebin.com/api#1) used to authenticate with the Pastebin API. -`LogParser:PastebinUserKey` | The [Pastebin user key](https://pastebin.com/api#8) used to authenticate with the Pastebin API. Can be left blank to post anonymously. -`LogParser:SectionUrl` | The root URL of the log page, like `https://log.smapi.io/`. -`ModUpdateCheck:GitHubPassword` | The password with which to authenticate to GitHub when fetching release info. -`ModUpdateCheck:GitHubUsername` | The username with which to authenticate to GitHub when fetching release info. diff --git a/src/SMAPI.ModBuildConfig.Analyzer.Tests/NetFieldAnalyzerTests.cs b/src/SMAPI.ModBuildConfig.Analyzer.Tests/NetFieldAnalyzerTests.cs index 85a77d15..89bd1be5 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer.Tests/NetFieldAnalyzerTests.cs +++ b/src/SMAPI.ModBuildConfig.Analyzer.Tests/NetFieldAnalyzerTests.cs @@ -96,7 +96,7 @@ namespace SMAPI.ModBuildConfig.Analyzer.Tests DiagnosticResult expected = new DiagnosticResult { Id = "AvoidImplicitNetFieldCast", - Message = $"This implicitly converts '{expression}' from {fromType} to {toType}, but {fromType} has unintuitive implicit conversion rules. Consider comparing against the actual value instead to avoid bugs. See https://smapi.io/buildmsg/avoid-implicit-net-field-cast for details.", + Message = $"This implicitly converts '{expression}' from {fromType} to {toType}, but {fromType} has unintuitive implicit conversion rules. Consider comparing against the actual value instead to avoid bugs. See https://smapi.io/package/avoid-implicit-net-field-cast for details.", Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", NetFieldAnalyzerTests.SampleCodeLine, NetFieldAnalyzerTests.SampleCodeColumn + column) } }; @@ -138,7 +138,7 @@ namespace SMAPI.ModBuildConfig.Analyzer.Tests DiagnosticResult expected = new DiagnosticResult { Id = "AvoidNetField", - Message = $"'{expression}' is a {netType} field; consider using the {suggestedProperty} property instead. See https://smapi.io/buildmsg/avoid-net-field for details.", + Message = $"'{expression}' is a {netType} field; consider using the {suggestedProperty} property instead. See https://smapi.io/package/avoid-net-field for details.", Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", NetFieldAnalyzerTests.SampleCodeLine, NetFieldAnalyzerTests.SampleCodeColumn + column) } }; diff --git a/src/SMAPI.ModBuildConfig.Analyzer.Tests/ObsoleteFieldAnalyzerTests.cs b/src/SMAPI.ModBuildConfig.Analyzer.Tests/ObsoleteFieldAnalyzerTests.cs index fa9235a3..12641e1a 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer.Tests/ObsoleteFieldAnalyzerTests.cs +++ b/src/SMAPI.ModBuildConfig.Analyzer.Tests/ObsoleteFieldAnalyzerTests.cs @@ -67,7 +67,7 @@ namespace SMAPI.ModBuildConfig.Analyzer.Tests DiagnosticResult expected = new DiagnosticResult { Id = "AvoidObsoleteField", - Message = $"The '{oldName}' field is obsolete and should be replaced with '{newName}'. See https://smapi.io/buildmsg/avoid-obsolete-field for details.", + Message = $"The '{oldName}' field is obsolete and should be replaced with '{newName}'. See https://smapi.io/package/avoid-obsolete-field for details.", Severity = DiagnosticSeverity.Warning, Locations = new[] { new DiagnosticResultLocation("Test0.cs", ObsoleteFieldAnalyzerTests.SampleCodeLine, ObsoleteFieldAnalyzerTests.SampleCodeColumn + column) } }; diff --git a/src/SMAPI.ModBuildConfig.Analyzer/NetFieldAnalyzer.cs b/src/SMAPI.ModBuildConfig.Analyzer/NetFieldAnalyzer.cs index f2608348..70c01418 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer/NetFieldAnalyzer.cs +++ b/src/SMAPI.ModBuildConfig.Analyzer/NetFieldAnalyzer.cs @@ -135,22 +135,22 @@ namespace StardewModdingAPI.ModBuildConfig.Analyzer private readonly DiagnosticDescriptor AvoidImplicitNetFieldCastRule = new DiagnosticDescriptor( id: "AvoidImplicitNetFieldCast", title: "Netcode types shouldn't be implicitly converted", - messageFormat: "This implicitly converts '{0}' from {1} to {2}, but {1} has unintuitive implicit conversion rules. Consider comparing against the actual value instead to avoid bugs. See https://smapi.io/buildmsg/avoid-implicit-net-field-cast for details.", + messageFormat: "This implicitly converts '{0}' from {1} to {2}, but {1} has unintuitive implicit conversion rules. Consider comparing against the actual value instead to avoid bugs. See https://smapi.io/package/avoid-implicit-net-field-cast for details.", category: "SMAPI.CommonErrors", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, - helpLinkUri: "https://smapi.io/buildmsg/avoid-implicit-net-field-cast" + helpLinkUri: "https://smapi.io/package/avoid-implicit-net-field-cast" ); /// The diagnostic info for an avoidable net field access. private readonly DiagnosticDescriptor AvoidNetFieldRule = new DiagnosticDescriptor( id: "AvoidNetField", title: "Avoid Netcode types when possible", - messageFormat: "'{0}' is a {1} field; consider using the {2} property instead. See https://smapi.io/buildmsg/avoid-net-field for details.", + messageFormat: "'{0}' is a {1} field; consider using the {2} property instead. See https://smapi.io/package/avoid-net-field for details.", category: "SMAPI.CommonErrors", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, - helpLinkUri: "https://smapi.io/buildmsg/avoid-net-field" + helpLinkUri: "https://smapi.io/package/avoid-net-field" ); diff --git a/src/SMAPI.ModBuildConfig.Analyzer/ObsoleteFieldAnalyzer.cs b/src/SMAPI.ModBuildConfig.Analyzer/ObsoleteFieldAnalyzer.cs index f1a3ef75..6b935caa 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer/ObsoleteFieldAnalyzer.cs +++ b/src/SMAPI.ModBuildConfig.Analyzer/ObsoleteFieldAnalyzer.cs @@ -27,11 +27,11 @@ namespace StardewModdingAPI.ModBuildConfig.Analyzer ["AvoidObsoleteField"] = new DiagnosticDescriptor( id: "AvoidObsoleteField", title: "Reference to obsolete field", - messageFormat: "The '{0}' field is obsolete and should be replaced with '{1}'. See https://smapi.io/buildmsg/avoid-obsolete-field for details.", + messageFormat: "The '{0}' field is obsolete and should be replaced with '{1}'. See https://smapi.io/package/avoid-obsolete-field for details.", category: "SMAPI.CommonErrors", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, - helpLinkUri: "https://smapi.io/buildmsg/avoid-obsolete-field" + helpLinkUri: "https://smapi.io/package/avoid-obsolete-field" ) }; diff --git a/src/SMAPI.ModBuildConfig/SMAPI.ModBuildConfig.csproj b/src/SMAPI.ModBuildConfig/SMAPI.ModBuildConfig.csproj index 70636937..e13526f9 100644 --- a/src/SMAPI.ModBuildConfig/SMAPI.ModBuildConfig.csproj +++ b/src/SMAPI.ModBuildConfig/SMAPI.ModBuildConfig.csproj @@ -16,9 +16,7 @@ - - mod-build-config.md - + diff --git a/src/SMAPI.ModBuildConfig/build/smapi.targets b/src/SMAPI.ModBuildConfig/build/smapi.targets index 51432d96..5eeea91e 100644 --- a/src/SMAPI.ModBuildConfig/build/smapi.targets +++ b/src/SMAPI.ModBuildConfig/build/smapi.targets @@ -107,7 +107,7 @@ - + diff --git a/src/SMAPI.ModBuildConfig/package.nuspec b/src/SMAPI.ModBuildConfig/package.nuspec index 6779798d..ffa47fdb 100644 --- a/src/SMAPI.ModBuildConfig/package.nuspec +++ b/src/SMAPI.ModBuildConfig/package.nuspec @@ -9,9 +9,9 @@ false MIT - https://github.com/Pathoschild/SMAPI/blob/develop/docs/mod-build-config.md#readme + https://smapi.io/package/readme https://raw.githubusercontent.com/Pathoschild/SMAPI/develop/src/SMAPI.ModBuildConfig/assets/nuget-icon.png - Automates the build configuration for crossplatform Stardew Valley SMAPI mods. For SMAPI 2.11 or later. + Automates the build configuration for crossplatform Stardew Valley SMAPI mods. For SMAPI 3.0 or later. 3.0.0: - Updated for SMAPI 3.0 and Stardew Valley 1.4. diff --git a/src/SMAPI.Web/Startup.cs b/src/SMAPI.Web/Startup.cs index a2e47482..b409a81d 100644 --- a/src/SMAPI.Web/Startup.cs +++ b/src/SMAPI.Web/Startup.cs @@ -162,7 +162,7 @@ namespace StardewModdingAPI.Web // shortcut redirects redirects.Add(new RedirectToUrlRule(@"^/3\.0\.?$", "https://stardewvalleywiki.com/Modding:Migrate_to_SMAPI_3.0")); - redirects.Add(new RedirectToUrlRule(@"^/buildmsg(?:/?(.*))$", "https://github.com/Pathoschild/SMAPI/blob/develop/docs/mod-build-config.md#$1")); + redirects.Add(new RedirectToUrlRule(@"^/(?:buildmsg|package)(?:/?(.*))$", "https://github.com/Pathoschild/SMAPI/blob/develop/docs/technical/mod-package.md#$1")); // buildmsg deprecated, remove when SDV 1.4 is released redirects.Add(new RedirectToUrlRule(@"^/compat\.?$", "https://mods.smapi.io")); redirects.Add(new RedirectToUrlRule(@"^/docs\.?$", "https://stardewvalleywiki.com/Modding:Index")); redirects.Add(new RedirectToUrlRule(@"^/install\.?$", "https://stardewvalleywiki.com/Modding:Player_Guide/Getting_Started#Install_SMAPI")); diff --git a/src/SMAPI.sln b/src/SMAPI.sln index 08a47a46..8ee91b11 100644 --- a/src/SMAPI.sln +++ b/src/SMAPI.sln @@ -35,11 +35,15 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "build", "build", "{09CF91E5 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "docs", "docs", "{EB35A917-67B9-4EFA-8DFC-4FB49B3949BB}" ProjectSection(SolutionItems) = preProject - ..\docs\mod-build-config.md = ..\docs\mod-build-config.md ..\docs\README.md = ..\docs\README.md ..\docs\release-notes.md = ..\docs\release-notes.md - ..\docs\technical-docs.md = ..\docs\technical-docs.md - ..\docs\web-services.md = ..\docs\web-services.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "technical", "technical", "{5947303D-3512-413A-9009-7AC43F5D3513}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\mod-package.md = ..\docs\technical\mod-package.md + ..\docs\technical\smapi.md = ..\docs\technical\smapi.md + ..\docs\technical\web.md = ..\docs\technical\web.md EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Internal", "Internal", "{82D22ED7-A0A7-4D64-8E92-4B6A5E74ED11}" @@ -135,6 +139,7 @@ Global {F4453AB6-D7D6-447F-A973-956CC777968F} = {4B1CEB70-F756-4A57-AAE8-8CD78C475F25} {09CF91E5-5BAB-4650-A200-E5EA9A633046} = {86C452BE-D2D8-45B4-B63F-E329EB06CEDA} {EB35A917-67B9-4EFA-8DFC-4FB49B3949BB} = {86C452BE-D2D8-45B4-B63F-E329EB06CEDA} + {5947303D-3512-413A-9009-7AC43F5D3513} = {EB35A917-67B9-4EFA-8DFC-4FB49B3949BB} {85208F8D-6FD1-4531-BE05-7142490F59FE} = {82D22ED7-A0A7-4D64-8E92-4B6A5E74ED11} {680B2641-81EA-467C-86A5-0E81CDC57ED0} = {82D22ED7-A0A7-4D64-8E92-4B6A5E74ED11} {AA95884B-7097-476E-92C8-D0500DE9D6D1} = {82D22ED7-A0A7-4D64-8E92-4B6A5E74ED11} -- cgit From e2f545484e1a63d55154e2b6a924dfb6d94f7a5a Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 12 Jul 2019 20:51:46 -0400 Subject: add asset propagation for critter textures (#652) --- docs/release-notes.md | 3 ++- src/SMAPI/Metadata/CoreAssetPropagator.cs | 34 ++++++++++++++++++++++++++++++- 2 files changed, 35 insertions(+), 2 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 3f955e78..49bc2eab 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -25,11 +25,12 @@ These changes have not been released yet. * Fixed outdoor tilesheets being seasonalised when added to an indoor location. * For modders: + * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialised when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialised). * Added support for content pack translations. * Added `IContentPack.HasFile` method. * Added `Context.IsGameLaunched` field. - * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialised when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialised). * Added separate `LogNetworkTraffic` option to make verbose logging less overwhelmingly verbose. + * Added asset propagation for critter textures. * The installer now recognises custom game paths stored in `stardewvalley.targets`, if any. * When a mod is incompatible, the trace logs now list all detected issues instead of the first one. * Removed all deprecated APIs. diff --git a/src/SMAPI/Metadata/CoreAssetPropagator.cs b/src/SMAPI/Metadata/CoreAssetPropagator.cs index 9e84c67f..b000d503 100644 --- a/src/SMAPI/Metadata/CoreAssetPropagator.cs +++ b/src/SMAPI/Metadata/CoreAssetPropagator.cs @@ -316,8 +316,12 @@ namespace StardewModdingAPI.Metadata return true; /**** - ** Content\Critters + ** Content\TileSheets ****/ + case "tilesheets\\critters": // Critter constructor + this.ReloadCritterTextures(content, key); + return true; + case "tilesheets\\crops": // Game1.LoadContent Game1.cropSpriteSheet = content.Load(key); return true; @@ -562,6 +566,34 @@ namespace StardewModdingAPI.Metadata return false; } + /// Reload critter textures. + /// The content manager through which to reload the asset. + /// The asset key to reload. + /// Returns the number of reloaded assets. + private int ReloadCritterTextures(LocalizedContentManager content, string key) + { + // get critters + Critter[] critters = + ( + from location in this.GetLocations() + let locCritters = this.Reflection.GetField>(location, "critters").GetValue() + where locCritters != null + from Critter critter in locCritters + where this.GetNormalisedPath(critter.sprite.textureName) == key + select critter + ) + .ToArray(); + if (!critters.Any()) + return 0; + + // update sprites + Texture2D texture = content.Load(key); + foreach (var entry in critters) + this.SetSpriteTexture(entry.sprite, texture); + + return critters.Length; + } + /// Reload the sprites for a fence type. /// The asset key to reload. /// Returns whether any textures were reloaded. -- cgit From 4f7d861ce4767259a556607a167481e074ec4f4c Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 13 Jul 2019 22:45:48 -0400 Subject: make SemanticVersion.TryParse public --- docs/release-notes.md | 3 +-- src/SMAPI/SemanticVersion.cs | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 49bc2eab..9980c310 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -27,8 +27,7 @@ These changes have not been released yet. * For modders: * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialised when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialised). * Added support for content pack translations. - * Added `IContentPack.HasFile` method. - * Added `Context.IsGameLaunched` field. + * Added fields and methods: `IContentPack.HasFile`, `Context.IsGameLaunched`, and `SemanticVersion.TryParse`. * Added separate `LogNetworkTraffic` option to make verbose logging less overwhelmingly verbose. * Added asset propagation for critter textures. * The installer now recognises custom game paths stored in `stardewvalley.targets`, if any. diff --git a/src/SMAPI/SemanticVersion.cs b/src/SMAPI/SemanticVersion.cs index acdc92f8..b346cfdd 100644 --- a/src/SMAPI/SemanticVersion.cs +++ b/src/SMAPI/SemanticVersion.cs @@ -141,7 +141,7 @@ namespace StardewModdingAPI /// The version string. /// The parsed representation. /// Returns whether parsing the version succeeded. - internal static bool TryParse(string version, out ISemanticVersion parsed) + public static bool TryParse(string version, out ISemanticVersion parsed) { if (Toolkit.SemanticVersion.TryParse(version, out ISemanticVersion versionImpl)) { -- cgit From 1053232c2039a2815baf2cfa99fe8c554d1350a9 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 14 Jul 2019 14:55:31 -0400 Subject: add asset propagation for DayTimeMoneyBox buttons --- docs/release-notes.md | 2 +- src/SMAPI/Metadata/CoreAssetPropagator.cs | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 9980c310..404424e7 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -29,7 +29,7 @@ These changes have not been released yet. * Added support for content pack translations. * Added fields and methods: `IContentPack.HasFile`, `Context.IsGameLaunched`, and `SemanticVersion.TryParse`. * Added separate `LogNetworkTraffic` option to make verbose logging less overwhelmingly verbose. - * Added asset propagation for critter textures. + * Added asset propagation for critter textures and `DayTimeMoneyBox` buttons. * The installer now recognises custom game paths stored in `stardewvalley.targets`, if any. * When a mod is incompatible, the trace logs now list all detected issues instead of the first one. * Removed all deprecated APIs. diff --git a/src/SMAPI/Metadata/CoreAssetPropagator.cs b/src/SMAPI/Metadata/CoreAssetPropagator.cs index b000d503..3fbca04a 100644 --- a/src/SMAPI/Metadata/CoreAssetPropagator.cs +++ b/src/SMAPI/Metadata/CoreAssetPropagator.cs @@ -293,6 +293,11 @@ namespace StardewModdingAPI.Metadata case "loosesprites\\cursors": // Game1.LoadContent Game1.mouseCursors = content.Load(key); + foreach (DayTimeMoneyBox menu in Game1.onScreenMenus.OfType()) + { + foreach (ClickableTextureComponent button in new[] { menu.questButton, menu.zoomInButton, menu.zoomOutButton }) + button.texture = Game1.mouseCursors; + } return true; case "loosesprites\\daybg": // Game1.LoadContent -- cgit From 48f211f5447ec7580b9f9bba63eab0ec6b1ec5c7 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 14 Jul 2019 17:49:33 -0400 Subject: add metadata links to mod compatibility list --- docs/release-notes.md | 4 ++++ src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs | 10 ++++++++++ src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs | 6 ++++++ src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMod.cs | 5 +++++ src/SMAPI.Web/ViewModels/ModModel.cs | 5 +++++ src/SMAPI.Web/Views/Mods/Index.cshtml | 9 ++++++++- 6 files changed, 38 insertions(+), 1 deletion(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 404424e7..c07ae750 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -24,6 +24,10 @@ These changes have not been released yet. * Fixed map reloads not updating door warps. * Fixed outdoor tilesheets being seasonalised when added to an indoor location. +* For the mod compatibility list: + * Clicking a mod link now automatically adds it to the visible mods when the list is filtered. + * Added metadata links to advanced info, if any. + * For modders: * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialised when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialised). * Added support for content pack translations. diff --git a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs index 3e9b8ea6..24aea5e8 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs @@ -127,6 +127,15 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki } } + // parse links + List> metadataLinks = new List>(); + foreach (HtmlNode linkElement in node.Descendants("td").Last().Descendants("a").Skip(1)) // skip anchor link + { + string text = linkElement.InnerText.Trim(); + Uri url = new Uri(linkElement.GetAttributeValue("href", "")); + metadataLinks.Add(Tuple.Create(url, text)); + } + // yield model yield return new WikiModEntry { @@ -143,6 +152,7 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki Compatibility = compatibility, BetaCompatibility = betaCompatibility, Warnings = warnings, + MetadataLinks = metadataLinks.ToArray(), Anchor = anchor }; } diff --git a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs index cf416cc6..556796c5 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs @@ -1,3 +1,6 @@ +using System; +using System.Collections.Generic; + namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki { /// A mod entry in the wiki list. @@ -48,6 +51,9 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki /// The human-readable warnings for players about this mod. public string[] Warnings { get; set; } + /// Extra metadata links (usually for open pull requests). + public Tuple[] MetadataLinks { get; set; } + /// The link anchor for the mod entry in the wiki compatibility list. public string Anchor { get; set; } } diff --git a/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMod.cs b/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMod.cs index f4331f8d..850272eb 100644 --- a/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMod.cs +++ b/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMod.cs @@ -58,6 +58,9 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki /// The human-readable warnings for players about this mod. public string[] Warnings { get; set; } + /// Extra metadata links (usually for open pull requests). + public Tuple[] MetadataLinks { get; set; } + /// The link anchor for the mod entry in the wiki compatibility list. public string Anchor { get; set; } @@ -122,6 +125,7 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki this.CustomSourceUrl = mod.CustomSourceUrl; this.CustomUrl = mod.CustomUrl; this.ContentPackFor = mod.ContentPackFor; + this.MetadataLinks = mod.MetadataLinks; this.Warnings = mod.Warnings; this.Anchor = mod.Anchor; @@ -156,6 +160,7 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki CustomUrl = this.CustomUrl, ContentPackFor = this.ContentPackFor, Warnings = this.Warnings, + MetadataLinks = this.MetadataLinks, Anchor = this.Anchor, // stable compatibility diff --git a/src/SMAPI.Web/ViewModels/ModModel.cs b/src/SMAPI.Web/ViewModels/ModModel.cs index 8668f67b..b57e03f8 100644 --- a/src/SMAPI.Web/ViewModels/ModModel.cs +++ b/src/SMAPI.Web/ViewModels/ModModel.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using StardewModdingAPI.Toolkit.Framework.Clients.Wiki; @@ -37,6 +38,9 @@ namespace StardewModdingAPI.Web.ViewModels /// The human-readable warnings for players about this mod. public string[] Warnings { get; set; } + /// Extra metadata links (usually for open pull requests). + public Tuple[] MetadataLinks { get; set; } + /// A unique identifier for the mod that can be used in an anchor URL. public string Slug { get; set; } @@ -61,6 +65,7 @@ namespace StardewModdingAPI.Web.ViewModels this.BetaCompatibility = entry.BetaCompatibility != null ? new ModCompatibilityModel(entry.BetaCompatibility) : null; this.ModPages = this.GetModPageUrls(entry).ToArray(); this.Warnings = entry.Warnings; + this.MetadataLinks = entry.MetadataLinks; this.Slug = entry.Anchor; } diff --git a/src/SMAPI.Web/Views/Mods/Index.cshtml b/src/SMAPI.Web/Views/Mods/Index.cshtml index 8293fbe2..2bc135c3 100644 --- a/src/SMAPI.Web/Views/Mods/Index.cshtml +++ b/src/SMAPI.Web/Views/Mods/Index.cshtml @@ -92,7 +92,14 @@ no source - # + + # + + + + -- cgit From 1bf399ec23368a0666203298768a4b24b63d6a88 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 14 Jul 2019 22:27:00 -0400 Subject: add dev note field to compatibility list --- docs/release-notes.md | 2 +- src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs | 2 ++ src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs | 3 +++ src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMod.cs | 5 +++++ src/SMAPI.Web/ViewModels/ModModel.cs | 4 ++++ src/SMAPI.Web/Views/Mods/Index.cshtml | 2 ++ 6 files changed, 17 insertions(+), 1 deletion(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index c07ae750..bc5e5a89 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -26,7 +26,7 @@ These changes have not been released yet. * For the mod compatibility list: * Clicking a mod link now automatically adds it to the visible mods when the list is filtered. - * Added metadata links to advanced info, if any. + * Added metadata links and dev notes (if any) to advanced info. * For modders: * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialised when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialised). diff --git a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs index 24aea5e8..ab6a2517 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs @@ -99,6 +99,7 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki string customUrl = this.GetAttribute(node, "data-url"); string anchor = this.GetAttribute(node, "id"); string contentPackFor = this.GetAttribute(node, "data-content-pack-for"); + string devNote = this.GetAttribute(node, "data-dev-note"); // parse stable compatibility WikiCompatibilityInfo compatibility = new WikiCompatibilityInfo @@ -153,6 +154,7 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki BetaCompatibility = betaCompatibility, Warnings = warnings, MetadataLinks = metadataLinks.ToArray(), + DevNote = devNote, Anchor = anchor }; } diff --git a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs index 556796c5..fff86891 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs @@ -54,6 +54,9 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki /// Extra metadata links (usually for open pull requests). public Tuple[] MetadataLinks { get; set; } + /// Special notes intended for developers who maintain unofficial updates or submit pull requests. + public string DevNote { get; set; } + /// The link anchor for the mod entry in the wiki compatibility list. public string Anchor { get; set; } } diff --git a/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMod.cs b/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMod.cs index 850272eb..bf1e2be2 100644 --- a/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMod.cs +++ b/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMod.cs @@ -61,6 +61,9 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki /// Extra metadata links (usually for open pull requests). public Tuple[] MetadataLinks { get; set; } + /// Special notes intended for developers who maintain unofficial updates or submit pull requests. + public string DevNote { get; set; } + /// The link anchor for the mod entry in the wiki compatibility list. public string Anchor { get; set; } @@ -127,6 +130,7 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki this.ContentPackFor = mod.ContentPackFor; this.MetadataLinks = mod.MetadataLinks; this.Warnings = mod.Warnings; + this.DevNote = mod.DevNote; this.Anchor = mod.Anchor; // stable compatibility @@ -161,6 +165,7 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki ContentPackFor = this.ContentPackFor, Warnings = this.Warnings, MetadataLinks = this.MetadataLinks, + DevNote = this.DevNote, Anchor = this.Anchor, // stable compatibility diff --git a/src/SMAPI.Web/ViewModels/ModModel.cs b/src/SMAPI.Web/ViewModels/ModModel.cs index b57e03f8..5a343640 100644 --- a/src/SMAPI.Web/ViewModels/ModModel.cs +++ b/src/SMAPI.Web/ViewModels/ModModel.cs @@ -41,6 +41,9 @@ namespace StardewModdingAPI.Web.ViewModels /// Extra metadata links (usually for open pull requests). public Tuple[] MetadataLinks { get; set; } + /// Special notes intended for developers who maintain unofficial updates or submit pull requests. + public string DevNote { get; set; } + /// A unique identifier for the mod that can be used in an anchor URL. public string Slug { get; set; } @@ -66,6 +69,7 @@ namespace StardewModdingAPI.Web.ViewModels this.ModPages = this.GetModPageUrls(entry).ToArray(); this.Warnings = entry.Warnings; this.MetadataLinks = entry.MetadataLinks; + this.DevNote = entry.DevNote; this.Slug = entry.Anchor; } diff --git a/src/SMAPI.Web/Views/Mods/Index.cshtml b/src/SMAPI.Web/Views/Mods/Index.cshtml index 2bc135c3..2d45a64d 100644 --- a/src/SMAPI.Web/Views/Mods/Index.cshtml +++ b/src/SMAPI.Web/Views/Mods/Index.cshtml @@ -98,6 +98,8 @@ + + [dev note] -- cgit From b2134035b78c06362a4b973502e679be0b5a0de3 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 17 Jul 2019 13:07:59 -0400 Subject: update NuGet packages --- docs/release-notes.md | 2 +- .../SMAPI.ModBuildConfig.Analyzer.Tests.csproj | 6 +++--- src/SMAPI.Tests/SMAPI.Tests.csproj | 10 +++------- src/SMAPI.Toolkit/SMAPI.Toolkit.csproj | 6 +++--- src/SMAPI.Web/SMAPI.Web.csproj | 16 ++++++++-------- src/SMAPI/SMAPI.csproj | 2 +- 6 files changed, 19 insertions(+), 23 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index bc5e5a89..e22d3718 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -38,7 +38,7 @@ These changes have not been released yet. * When a mod is incompatible, the trace logs now list all detected issues instead of the first one. * Removed all deprecated APIs. * Removed the `Monitor.ExitGameImmediately` method. - * Updated to Json.NET 12.0.1. + * Updated to Json.NET 12.0.2. * Fixed issue where mod changes weren't tracked correctly for raising events in some cases. Events now reflect a frozen snapshot of the game state, and any mod changes are reflected in the next event tick. * Fixed `LoadStageChanged` event not raising correct flags in some cases when creating a new save. diff --git a/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj b/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj index 44e7ffab..8edd5b1e 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj +++ b/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj @@ -7,9 +7,9 @@ - - - + + + diff --git a/src/SMAPI.Tests/SMAPI.Tests.csproj b/src/SMAPI.Tests/SMAPI.Tests.csproj index 2f632a49..41e12d7d 100644 --- a/src/SMAPI.Tests/SMAPI.Tests.csproj +++ b/src/SMAPI.Tests/SMAPI.Tests.csproj @@ -16,13 +16,9 @@ - - - - - - - + + + diff --git a/src/SMAPI.Toolkit/SMAPI.Toolkit.csproj b/src/SMAPI.Toolkit/SMAPI.Toolkit.csproj index 53bbe1ac..ad7ecd20 100644 --- a/src/SMAPI.Toolkit/SMAPI.Toolkit.csproj +++ b/src/SMAPI.Toolkit/SMAPI.Toolkit.csproj @@ -15,9 +15,9 @@ - - - + + + diff --git a/src/SMAPI.Web/SMAPI.Web.csproj b/src/SMAPI.Web/SMAPI.Web.csproj index 90641611..2f90389b 100644 --- a/src/SMAPI.Web/SMAPI.Web.csproj +++ b/src/SMAPI.Web/SMAPI.Web.csproj @@ -16,15 +16,15 @@ - - - - - - - + + + + + + + - + diff --git a/src/SMAPI/SMAPI.csproj b/src/SMAPI/SMAPI.csproj index 994a8715..d518b158 100644 --- a/src/SMAPI/SMAPI.csproj +++ b/src/SMAPI/SMAPI.csproj @@ -19,7 +19,7 @@ - + -- cgit From 79622d79b8b0ef6850b9431392dc57819cb89346 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 17 Jul 2019 13:15:48 -0400 Subject: Update Mono.Cecil package --- docs/release-notes.md | 2 +- src/SMAPI/SMAPI.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index e22d3718..ea988fe5 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -38,7 +38,7 @@ These changes have not been released yet. * When a mod is incompatible, the trace logs now list all detected issues instead of the first one. * Removed all deprecated APIs. * Removed the `Monitor.ExitGameImmediately` method. - * Updated to Json.NET 12.0.2. + * Updated dependencies (including Json.NET 11.0.2 → 12.0.2, Mono.Cecil 0.10.1 → 0.10.4). * Fixed issue where mod changes weren't tracked correctly for raising events in some cases. Events now reflect a frozen snapshot of the game state, and any mod changes are reflected in the next event tick. * Fixed `LoadStageChanged` event not raising correct flags in some cases when creating a new save. diff --git a/src/SMAPI/SMAPI.csproj b/src/SMAPI/SMAPI.csproj index d518b158..0157e66a 100644 --- a/src/SMAPI/SMAPI.csproj +++ b/src/SMAPI/SMAPI.csproj @@ -18,7 +18,7 @@ - + -- cgit From ce6cedaf4be53d52f2e558055b91e515b92e4c83 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 19 Jul 2019 13:15:45 -0400 Subject: add background fetch for mod compatibility list (#651) --- docs/release-notes.md | 2 + src/SMAPI.Web/BackgroundService.cs | 92 +++++++++++ src/SMAPI.Web/Controllers/ModsController.cs | 33 ++-- .../Framework/Caching/BaseCacheRepository.cs | 6 +- .../Framework/Caching/Wiki/CachedWikiMetadata.cs | 2 +- .../Framework/Caching/Wiki/IWikiCacheRepository.cs | 4 +- .../ConfigModels/BackgroundServicesConfig.cs | 12 ++ .../ConfigModels/ModCompatibilityListConfig.cs | 6 +- src/SMAPI.Web/SMAPI.Web.csproj | 2 + src/SMAPI.Web/Startup.cs | 48 ++++-- src/SMAPI.Web/ViewModels/ModListModel.cs | 19 ++- src/SMAPI.Web/Views/Mods/Index.cshtml | 172 +++++++++++---------- src/SMAPI.Web/appsettings.Development.json | 7 - src/SMAPI.Web/appsettings.json | 9 +- src/SMAPI.Web/wwwroot/Content/css/mods.css | 57 ++++--- 15 files changed, 317 insertions(+), 154 deletions(-) create mode 100644 src/SMAPI.Web/BackgroundService.cs create mode 100644 src/SMAPI.Web/Framework/ConfigModels/BackgroundServicesConfig.cs (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index ea988fe5..9c3e3d28 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -25,6 +25,8 @@ These changes have not been released yet. * Fixed outdoor tilesheets being seasonalised when added to an indoor location. * For the mod compatibility list: + * Now loads faster (since data is fetched in a background service). + * Now continues working with cached data when the wiki is offline. * Clicking a mod link now automatically adds it to the visible mods when the list is filtered. * Added metadata links and dev notes (if any) to advanced info. diff --git a/src/SMAPI.Web/BackgroundService.cs b/src/SMAPI.Web/BackgroundService.cs new file mode 100644 index 00000000..2ccfd5f7 --- /dev/null +++ b/src/SMAPI.Web/BackgroundService.cs @@ -0,0 +1,92 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Hangfire; +using Microsoft.Extensions.Hosting; +using StardewModdingAPI.Toolkit; +using StardewModdingAPI.Toolkit.Framework.Clients.Wiki; +using StardewModdingAPI.Web.Framework.Caching.Wiki; + +namespace StardewModdingAPI.Web +{ + /// A hosted service which runs background data updates. + /// Task methods need to be static, since otherwise Hangfire will try to serialise the entire instance. + internal class BackgroundService : IHostedService, IDisposable + { + /********* + ** Fields + *********/ + /// The background task server. + private static BackgroundJobServer JobServer; + + /// The cache in which to store mod metadata. + private static IWikiCacheRepository WikiCache; + + + /********* + ** Public methods + *********/ + /**** + ** Hosted service + ****/ + /// Construct an instance. + /// The cache in which to store mod metadata. + public BackgroundService(IWikiCacheRepository wikiCache) + { + BackgroundService.WikiCache = wikiCache; + } + + /// Start the service. + /// Tracks whether the start process has been aborted. + public Task StartAsync(CancellationToken cancellationToken) + { + this.TryInit(); + + // set startup tasks + BackgroundJob.Enqueue(() => BackgroundService.UpdateWikiAsync()); + + // set recurring tasks + RecurringJob.AddOrUpdate(() => BackgroundService.UpdateWikiAsync(), "*/10 * * * *"); + + return Task.CompletedTask; + } + + /// Triggered when the application host is performing a graceful shutdown. + /// Tracks whether the shutdown process should no longer be graceful. + public async Task StopAsync(CancellationToken cancellationToken) + { + if (BackgroundService.JobServer != null) + await BackgroundService.JobServer.WaitForShutdownAsync(cancellationToken); + } + + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + public void Dispose() + { + BackgroundService.JobServer?.Dispose(); + } + + /**** + ** Tasks + ****/ + /// Update the cached wiki metadata. + public static async Task UpdateWikiAsync() + { + WikiModList wikiCompatList = await new ModToolkit().GetWikiCompatibilityListAsync(); + BackgroundService.WikiCache.SaveWikiData(wikiCompatList.StableVersion, wikiCompatList.BetaVersion, wikiCompatList.Mods, out _, out _); + } + + + /********* + ** Private method + *********/ + /// Initialise the background service if it's not already initialised. + /// The background service is already initialised. + private void TryInit() + { + if (BackgroundService.JobServer != null) + throw new InvalidOperationException("The scheduler service is already started."); + + BackgroundService.JobServer = new BackgroundJobServer(); + } + } +} diff --git a/src/SMAPI.Web/Controllers/ModsController.cs b/src/SMAPI.Web/Controllers/ModsController.cs index b6040e06..b621ded0 100644 --- a/src/SMAPI.Web/Controllers/ModsController.cs +++ b/src/SMAPI.Web/Controllers/ModsController.cs @@ -1,9 +1,7 @@ using System.Linq; using System.Text.RegularExpressions; -using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; -using StardewModdingAPI.Toolkit; using StardewModdingAPI.Web.Framework.Caching.Wiki; using StardewModdingAPI.Web.Framework.ConfigModels; using StardewModdingAPI.Web.ViewModels; @@ -19,8 +17,8 @@ namespace StardewModdingAPI.Web.Controllers /// The cache in which to store mod metadata. private readonly IWikiCacheRepository Cache; - /// The number of minutes successful update checks should be cached before refetching them. - private readonly int CacheMinutes; + /// The number of minutes before which wiki data should be considered old. + private readonly int StaleMinutes; /********* @@ -34,15 +32,15 @@ namespace StardewModdingAPI.Web.Controllers ModCompatibilityListConfig config = configProvider.Value; this.Cache = cache; - this.CacheMinutes = config.CacheMinutes; + this.StaleMinutes = config.StaleMinutes; } /// Display information for all mods. [HttpGet] [Route("mods")] - public async Task Index() + public ViewResult Index() { - return this.View("Index", await this.FetchDataAsync()); + return this.View("Index", this.FetchData()); } @@ -50,25 +48,22 @@ namespace StardewModdingAPI.Web.Controllers ** Private methods *********/ /// Asynchronously fetch mod metadata from the wiki. - public async Task FetchDataAsync() + public ModListModel FetchData() { - // refresh cache - CachedWikiMod[] mods; - if (!this.Cache.TryGetWikiMetadata(out CachedWikiMetadata metadata) || this.Cache.IsStale(metadata.LastUpdated, this.CacheMinutes)) - { - var wikiCompatList = await new ModToolkit().GetWikiCompatibilityListAsync(); - this.Cache.SaveWikiData(wikiCompatList.StableVersion, wikiCompatList.BetaVersion, wikiCompatList.Mods, out metadata, out mods); - } - else - mods = this.Cache.GetWikiMods().ToArray(); + // fetch cached data + if (!this.Cache.TryGetWikiMetadata(out CachedWikiMetadata metadata)) + return new ModListModel(); // build model return new ModListModel( stableVersion: metadata.StableVersion, betaVersion: metadata.BetaVersion, - mods: mods + mods: this.Cache + .GetWikiMods() .Select(mod => new ModModel(mod.GetModel())) - .OrderBy(p => Regex.Replace(p.Name.ToLower(), "[^a-z0-9]", "")) // ignore case, spaces, and special characters when sorting + .OrderBy(p => Regex.Replace(p.Name.ToLower(), "[^a-z0-9]", "")), // ignore case, spaces, and special characters when sorting + lastUpdated: metadata.LastUpdated, + isStale: this.Cache.IsStale(metadata.LastUpdated, this.StaleMinutes) ); } } diff --git a/src/SMAPI.Web/Framework/Caching/BaseCacheRepository.cs b/src/SMAPI.Web/Framework/Caching/BaseCacheRepository.cs index 904455c5..f5354b93 100644 --- a/src/SMAPI.Web/Framework/Caching/BaseCacheRepository.cs +++ b/src/SMAPI.Web/Framework/Caching/BaseCacheRepository.cs @@ -10,10 +10,10 @@ namespace StardewModdingAPI.Web.Framework.Caching *********/ /// Whether cached data is stale. /// The date when the data was updated. - /// The age in minutes before data is considered stale. - public bool IsStale(DateTimeOffset lastUpdated, int cacheMinutes) + /// The age in minutes before data is considered stale. + public bool IsStale(DateTimeOffset lastUpdated, int staleMinutes) { - return lastUpdated < DateTimeOffset.UtcNow.AddMinutes(-cacheMinutes); + return lastUpdated < DateTimeOffset.UtcNow.AddMinutes(-staleMinutes); } } } diff --git a/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMetadata.cs b/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMetadata.cs index de1ea9db..4d6b4b10 100644 --- a/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMetadata.cs +++ b/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMetadata.cs @@ -37,7 +37,7 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki { this.StableVersion = stableVersion; this.BetaVersion = betaVersion; - this.LastUpdated = DateTimeOffset.UtcNow;; + this.LastUpdated = DateTimeOffset.UtcNow; } } } diff --git a/src/SMAPI.Web/Framework/Caching/Wiki/IWikiCacheRepository.cs b/src/SMAPI.Web/Framework/Caching/Wiki/IWikiCacheRepository.cs index d319db69..6031123d 100644 --- a/src/SMAPI.Web/Framework/Caching/Wiki/IWikiCacheRepository.cs +++ b/src/SMAPI.Web/Framework/Caching/Wiki/IWikiCacheRepository.cs @@ -17,8 +17,8 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki /// Whether cached data is stale. /// The date when the data was updated. - /// The age in minutes before data is considered stale. - bool IsStale(DateTimeOffset lastUpdated, int cacheMinutes); + /// The age in minutes before data is considered stale. + bool IsStale(DateTimeOffset lastUpdated, int staleMinutes); /// Get the cached wiki mods. /// A filter to apply, if any. diff --git a/src/SMAPI.Web/Framework/ConfigModels/BackgroundServicesConfig.cs b/src/SMAPI.Web/Framework/ConfigModels/BackgroundServicesConfig.cs new file mode 100644 index 00000000..de871c9a --- /dev/null +++ b/src/SMAPI.Web/Framework/ConfigModels/BackgroundServicesConfig.cs @@ -0,0 +1,12 @@ +namespace StardewModdingAPI.Web.Framework.ConfigModels +{ + /// The config settings for background services. + internal class BackgroundServicesConfig + { + /********* + ** Accessors + *********/ + /// Whether to enable background update services. + public bool Enabled { get; set; } + } +} diff --git a/src/SMAPI.Web/Framework/ConfigModels/ModCompatibilityListConfig.cs b/src/SMAPI.Web/Framework/ConfigModels/ModCompatibilityListConfig.cs index d9ac9f02..24b540cd 100644 --- a/src/SMAPI.Web/Framework/ConfigModels/ModCompatibilityListConfig.cs +++ b/src/SMAPI.Web/Framework/ConfigModels/ModCompatibilityListConfig.cs @@ -1,12 +1,12 @@ namespace StardewModdingAPI.Web.Framework.ConfigModels { - /// The config settings for mod compatibility list. + /// The config settings for the mod compatibility list. internal class ModCompatibilityListConfig { /********* ** Accessors *********/ - /// The number of minutes data from the wiki should be cached before refetching it. - public int CacheMinutes { get; set; } + /// The number of minutes before which wiki data should be considered old. + public int StaleMinutes { get; set; } } } diff --git a/src/SMAPI.Web/SMAPI.Web.csproj b/src/SMAPI.Web/SMAPI.Web.csproj index 2f90389b..d53914d5 100644 --- a/src/SMAPI.Web/SMAPI.Web.csproj +++ b/src/SMAPI.Web/SMAPI.Web.csproj @@ -16,6 +16,8 @@ + + diff --git a/src/SMAPI.Web/Startup.cs b/src/SMAPI.Web/Startup.cs index 7beb0bcc..bdfa5ed9 100644 --- a/src/SMAPI.Web/Startup.cs +++ b/src/SMAPI.Web/Startup.cs @@ -1,4 +1,6 @@ using System.Collections.Generic; +using Hangfire; +using Hangfire.Mongo; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Rewrite; @@ -49,12 +51,13 @@ namespace StardewModdingAPI.Web /// The service injection container. public void ConfigureServices(IServiceCollection services) { - // init configuration + // init basic services services + .Configure(this.Configuration.GetSection("BackgroundServices")) .Configure(this.Configuration.GetSection("ModCompatibilityList")) .Configure(this.Configuration.GetSection("ModUpdateCheck")) - .Configure(this.Configuration.GetSection("Site")) .Configure(this.Configuration.GetSection("MongoDB")) + .Configure(this.Configuration.GetSection("Site")) .Configure(options => options.ConstraintMap.Add("semanticVersion", typeof(VersionConstraint))) .AddLogging() .AddMemoryCache() @@ -69,6 +72,33 @@ namespace StardewModdingAPI.Web options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }); + // init background service + { + BackgroundServicesConfig config = this.Configuration.GetSection("BackgroundServices").Get(); + if (config.Enabled) + services.AddHostedService(); + } + + // init MongoDB + MongoDbConfig mongoConfig = this.Configuration.GetSection("MongoDB").Get(); + string mongoConnectionStr = mongoConfig.GetConnectionString(); + services.AddSingleton(serv => new MongoClient(mongoConnectionStr).GetDatabase(mongoConfig.Database)); + services.AddSingleton(serv => new WikiCacheRepository(serv.GetService())); + + // init Hangfire (needs MongoDB) + services + .AddHangfire(config => + { + config + .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) + .UseSimpleAssemblyNameTypeSerializer() + .UseRecommendedSerializerSettings() + .UseMongoStorage(mongoConnectionStr, $"{mongoConfig.Database}-hangfire", new MongoStorageOptions + { + MigrationOptions = new MongoMigrationOptions(MongoMigrationStrategy.Drop) + }); + }); + // init API clients { ApiClientsConfig api = this.Configuration.GetSection("ApiClients").Get(); @@ -111,15 +141,6 @@ namespace StardewModdingAPI.Web devKey: api.PastebinDevKey )); } - - // init MongoDB - { - MongoDbConfig mongoConfig = this.Configuration.GetSection("MongoDB").Get(); - string connectionString = mongoConfig.GetConnectionString(); - - services.AddSingleton(serv => new MongoClient(connectionString).GetDatabase(mongoConfig.Database)); - services.AddSingleton(serv => new WikiCacheRepository(serv.GetService())); - } } /// The method called by the runtime to configure the HTTP request pipeline. @@ -127,9 +148,9 @@ namespace StardewModdingAPI.Web /// The hosting environment. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { + // basic config if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); - app .UseCors(policy => policy .AllowAnyHeader() @@ -140,6 +161,9 @@ namespace StardewModdingAPI.Web .UseRewriter(this.GetRedirectRules()) .UseStaticFiles() // wwwroot folder .UseMvc(); + + // config Hangfire + app.UseHangfireDashboard("/tasks"); } diff --git a/src/SMAPI.Web/ViewModels/ModListModel.cs b/src/SMAPI.Web/ViewModels/ModListModel.cs index 3b87d393..ff7513bc 100644 --- a/src/SMAPI.Web/ViewModels/ModListModel.cs +++ b/src/SMAPI.Web/ViewModels/ModListModel.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; @@ -18,19 +19,35 @@ namespace StardewModdingAPI.Web.ViewModels /// The mods to display. public ModModel[] Mods { get; set; } + /// When the data was last updated. + public DateTimeOffset LastUpdated { get; set; } + + /// Whether the data hasn't been updated in a while. + public bool IsStale { get; set; } + + /// Whether the mod metadata is available. + public bool HasData => this.Mods != null; + /********* ** Public methods *********/ + /// Construct an empty instance. + public ModListModel() { } + /// Construct an instance. /// The current stable version of the game. /// The current beta version of the game (if any). /// The mods to display. - public ModListModel(string stableVersion, string betaVersion, IEnumerable mods) + /// When the data was last updated. + /// Whether the data hasn't been updated in a while. + public ModListModel(string stableVersion, string betaVersion, IEnumerable mods, DateTimeOffset lastUpdated, bool isStale) { this.StableVersion = stableVersion; this.BetaVersion = betaVersion; this.Mods = mods.ToArray(); + this.LastUpdated = lastUpdated; + this.IsStale = isStale; } } } diff --git a/src/SMAPI.Web/Views/Mods/Index.cshtml b/src/SMAPI.Web/Views/Mods/Index.cshtml index 2d45a64d..aa7c0678 100644 --- a/src/SMAPI.Web/Views/Mods/Index.cshtml +++ b/src/SMAPI.Web/Views/Mods/Index.cshtml @@ -18,92 +18,104 @@ } -
-
-

This page shows all known SMAPI mods and (incompatible) content packs, whether they work with the latest versions of Stardew Valley and SMAPI, and how to fix them if not. If a mod doesn't work after following the instructions below, check the troubleshooting guide or ask for help.

+@if (!Model.HasData) +{ +
↻ The mod data hasn't been fetched yet; please try again in a few minutes.
+} +else +{ + @if (Model.IsStale) + { +
Showing data from @(Math.Round((DateTimeOffset.UtcNow - Model.LastUpdated).TotalMinutes)) minutes ago. (Couldn't fetch newer data; the wiki API may be offline.)
+ } -

The list is updated every few days (you can help update it!). It doesn't include XNB mods (see using XNB mods on the wiki instead) or compatible content packs.

+
+
+

This page shows all known SMAPI mods and (incompatible) content packs, whether they work with the latest versions of Stardew Valley and SMAPI, and how to fix them if not. If a mod doesn't work after following the instructions below, check the troubleshooting guide or ask for help.

- @if (Model.BetaVersion != null) - { -

Note: "SDV @Model.BetaVersion only" lines are for an unreleased version of the game, not the stable version most players have. If a mod doesn't have that line, the info applies to both versions of the game.

- } -
+

The list is updated every few days (you can help update it!). It doesn't include XNB mods (see using XNB mods on the wiki instead) or compatible content packs.

-
-
- - + @if (Model.BetaVersion != null) + { +

Note: "SDV @Model.BetaVersion only" lines are for an unreleased version of the game, not the stable version most players have. If a mod doesn't have that line, the info applies to both versions of the game.

+ }
-
- - -
-
- {{filterGroup.label}}: + +
+
+ + +
+
+ + +
+
+ {{filterGroup.label}}: +
-
-
-
- {{visibleStats.total}} mods shown ({{Math.round((visibleStats.compatible + visibleStats.workaround) / visibleStats.total * 100)}}% compatible or have a workaround, {{Math.round((visibleStats.soon + visibleStats.broken) / visibleStats.total * 100)}}% broken, {{Math.round(visibleStats.abandoned / visibleStats.total * 100)}}% obsolete). +
+
+ {{visibleStats.total}} mods shown ({{Math.round((visibleStats.compatible + visibleStats.workaround) / visibleStats.total * 100)}}% compatible or have a workaround, {{Math.round((visibleStats.soon + visibleStats.broken) / visibleStats.total * 100)}}% broken, {{Math.round(visibleStats.abandoned / visibleStats.total * 100)}}% obsolete). +
+ No matching mods found.
- No matching mods found. -
- - - - - - - - - - - - - - - - - - - - - + + + + + + + +
mod namelinksauthorcompatibilitybroke incode 
- {{mod.Name}} - (aka {{mod.AlternateNames}}) - - {{mod.Author}} - (aka {{mod.AlternateAuthors}}) - -
-
- SDV @Model.BetaVersion only: - -
-
⚠ {{warning}}
-
- source - no source - - - # - - - - [dev note] + + + + + + + + + + + + + + + + - - -
mod namelinksauthorcompatibilitybroke incode 
+ {{mod.Name}} + (aka {{mod.AlternateNames}}) +
- +
+ {{mod.Author}} + (aka {{mod.AlternateAuthors}}) + +
+
+ SDV @Model.BetaVersion only: + +
+
⚠ {{warning}}
+
+ source + no source + + + # + + + + [dev note] + + +
+
+} diff --git a/src/SMAPI.Web/appsettings.Development.json b/src/SMAPI.Web/appsettings.Development.json index c50557b5..5856b96c 100644 --- a/src/SMAPI.Web/appsettings.Development.json +++ b/src/SMAPI.Web/appsettings.Development.json @@ -8,13 +8,6 @@ */ { - "Logging": { - "IncludeScopes": false, - "LogLevel": { - "Default": "Warning" - } - }, - "Site": { "RootUrl": "http://localhost:59482/", "ModListUrl": "http://localhost:59482/mods/", diff --git a/src/SMAPI.Web/appsettings.json b/src/SMAPI.Web/appsettings.json index 532ea017..ea7e9cd2 100644 --- a/src/SMAPI.Web/appsettings.json +++ b/src/SMAPI.Web/appsettings.json @@ -10,7 +10,8 @@ "Logging": { "IncludeScopes": false, "LogLevel": { - "Default": "Warning" + "Default": "Warning", + "Hangfire": "Information" } }, @@ -55,7 +56,11 @@ }, "ModCompatibilityList": { - "CacheMinutes": 10 + "StaleMinutes": 15 + }, + + "BackgroundServices": { + "Enabled": true }, "ModUpdateCheck": { diff --git a/src/SMAPI.Web/wwwroot/Content/css/mods.css b/src/SMAPI.Web/wwwroot/Content/css/mods.css index fc5fff47..1c2b8056 100644 --- a/src/SMAPI.Web/wwwroot/Content/css/mods.css +++ b/src/SMAPI.Web/wwwroot/Content/css/mods.css @@ -15,30 +15,6 @@ border: 3px solid darkgreen; } -table.wikitable { - background-color:#f8f9fa; - color:#222; - border:1px solid #a2a9b1; - border-collapse:collapse -} - -table.wikitable > tr > th, -table.wikitable > tr > td, -table.wikitable > * > tr > th, -table.wikitable > * > tr > td { - border:1px solid #a2a9b1; - padding:0.2em 0.4em -} - -table.wikitable > tr > th, -table.wikitable > * > tr > th { - background-color:#eaecf0; -} - -table.wikitable > caption { - font-weight:bold -} - #options { margin-bottom: 1em; } @@ -73,6 +49,39 @@ table.wikitable > caption { opacity: 0.5; } +div.error { + padding: 2em 0; + color: red; + font-weight: bold; +} + +/********* +** Mod list +*********/ +table.wikitable { + background-color:#f8f9fa; + color:#222; + border:1px solid #a2a9b1; + border-collapse:collapse +} + +table.wikitable > tr > th, +table.wikitable > tr > td, +table.wikitable > * > tr > th, +table.wikitable > * > tr > td { + border:1px solid #a2a9b1; + padding:0.2em 0.4em +} + +table.wikitable > tr > th, +table.wikitable > * > tr > th { + background-color:#eaecf0; +} + +table.wikitable > caption { + font-weight:bold +} + #mod-list { font-size: 0.9em; } -- cgit From 673ef91cc75e3b460acb8ab875d4d9d0be07042e Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 20 Jul 2019 14:54:56 -0400 Subject: show versions in duplicate-mod errors, make folder paths in trace logs clearer --- docs/release-notes.md | 4 +++- src/SMAPI.Tests/Core/ModResolverTests.cs | 14 ++++++++++---- src/SMAPI/Framework/IModMetadata.cs | 10 ++++++++-- src/SMAPI/Framework/ModLoading/ModMetadata.cs | 25 +++++++++++++++++++------ src/SMAPI/Framework/ModLoading/ModResolver.cs | 12 +++++++++--- src/SMAPI/Framework/SCore.cs | 10 +++++----- 6 files changed, 54 insertions(+), 21 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 9c3e3d28..d6076b0f 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -12,6 +12,7 @@ These changes have not been released yet. * Now ignores metadata files/folders like `__MACOSX` and `__folder_managed_by_vortex`. * Now ignores content files like `.txt` or `.png`, which avoids missing-manifest errors in some common cases. * Now detects XNB mods more accurately, and consolidates multi-folder XNB mods. + * Duplicate-mod errors now show the mod version in each folder. * Updated mod compatibility list. * Fixed mods needing to load custom `Map` assets before the game accesses them (SMAPI will now do so automatically). * Fixed Save Backup not pruning old backups if they're uncompressed. @@ -37,7 +38,8 @@ These changes have not been released yet. * Added separate `LogNetworkTraffic` option to make verbose logging less overwhelmingly verbose. * Added asset propagation for critter textures and `DayTimeMoneyBox` buttons. * The installer now recognises custom game paths stored in `stardewvalley.targets`, if any. - * When a mod is incompatible, the trace logs now list all detected issues instead of the first one. + * Trace logs for a broken mod now list all detected issues (instead of the first one). + * Trace logs when loading mods are now more clear. * Removed all deprecated APIs. * Removed the `Monitor.ExitGameImmediately` method. * Updated dependencies (including Json.NET 11.0.2 → 12.0.2, Mono.Cecil 0.10.1 → 0.10.4). diff --git a/src/SMAPI.Tests/Core/ModResolverTests.cs b/src/SMAPI.Tests/Core/ModResolverTests.cs index 4a1f04c6..ee1c0b99 100644 --- a/src/SMAPI.Tests/Core/ModResolverTests.cs +++ b/src/SMAPI.Tests/Core/ModResolverTests.cs @@ -27,7 +27,7 @@ namespace StardewModdingAPI.Tests.Core public void ReadBasicManifest_NoMods_ReturnsEmptyList() { // arrange - string rootFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + string rootFolder = this.GetTempFolderPath(); Directory.CreateDirectory(rootFolder); // act @@ -41,7 +41,7 @@ namespace StardewModdingAPI.Tests.Core public void ReadBasicManifest_EmptyModFolder_ReturnsFailedManifest() { // arrange - string rootFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + string rootFolder = this.GetTempFolderPath(); string modFolder = Path.Combine(rootFolder, Guid.NewGuid().ToString("N")); Directory.CreateDirectory(modFolder); @@ -78,7 +78,7 @@ namespace StardewModdingAPI.Tests.Core }; // write to filesystem - string rootFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + string rootFolder = this.GetTempFolderPath(); string modFolder = Path.Combine(rootFolder, Guid.NewGuid().ToString("N")); string filename = Path.Combine(modFolder, "manifest.json"); Directory.CreateDirectory(modFolder); @@ -209,7 +209,7 @@ namespace StardewModdingAPI.Tests.Core IManifest manifest = this.GetManifest(); // create DLL - string modFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + string modFolder = Path.Combine(this.GetTempFolderPath(), Guid.NewGuid().ToString("N")); Directory.CreateDirectory(modFolder); File.WriteAllText(Path.Combine(modFolder, manifest.EntryDll), ""); @@ -462,6 +462,12 @@ namespace StardewModdingAPI.Tests.Core /********* ** Private methods *********/ + /// Get a generated folder path in the temp folder. This folder isn't created automatically. + private string GetTempFolderPath() + { + return Path.Combine(Path.GetTempPath(), "smapi-unit-tests", Guid.NewGuid().ToString("N")); + } + /// Get a randomised basic manifest. /// The value, or null for a generated value. /// The value, or null for a generated value. diff --git a/src/SMAPI/Framework/IModMetadata.cs b/src/SMAPI/Framework/IModMetadata.cs index 32870c2a..6ee7df69 100644 --- a/src/SMAPI/Framework/IModMetadata.cs +++ b/src/SMAPI/Framework/IModMetadata.cs @@ -16,10 +16,13 @@ namespace StardewModdingAPI.Framework /// The mod's display name. string DisplayName { get; } - /// The mod's full directory path. + /// The root path containing mods. + string RootPath { get; } + + /// The mod's full directory path within the . string DirectoryPath { get; } - /// The relative to the game's Mods folder. + /// The relative to the . string RelativeDirectoryPath { get; } /// Metadata about the mod from SMAPI's internal data (if any). @@ -108,5 +111,8 @@ namespace StardewModdingAPI.Framework /// Get whether the mod has a given warning and it hasn't been suppressed in the . /// The warning to check. bool HasUnsuppressWarning(ModWarning warning); + + /// Get a relative path which includes the root folder name. + string GetRelativePathWithRoot(); } } diff --git a/src/SMAPI/Framework/ModLoading/ModMetadata.cs b/src/SMAPI/Framework/ModLoading/ModMetadata.cs index 39f2f482..7f788d17 100644 --- a/src/SMAPI/Framework/ModLoading/ModMetadata.cs +++ b/src/SMAPI/Framework/ModLoading/ModMetadata.cs @@ -1,10 +1,12 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using StardewModdingAPI.Framework.ModHelpers; using StardewModdingAPI.Toolkit.Framework.Clients.WebApi; using StardewModdingAPI.Toolkit.Framework.ModData; using StardewModdingAPI.Toolkit.Framework.UpdateData; +using StardewModdingAPI.Toolkit.Utilities; namespace StardewModdingAPI.Framework.ModLoading { @@ -17,10 +19,13 @@ namespace StardewModdingAPI.Framework.ModLoading /// The mod's display name. public string DisplayName { get; } - /// The mod's full directory path. + /// The root path containing mods. + public string RootPath { get; } + + /// The mod's full directory path within the . public string DirectoryPath { get; } - /// The relative to the game's Mods folder. + /// The relative to the . public string RelativeDirectoryPath { get; } /// The mod manifest. @@ -68,16 +73,17 @@ namespace StardewModdingAPI.Framework.ModLoading *********/ /// Construct an instance. /// The mod's display name. - /// The mod's full directory path. - /// The relative to the game's Mods folder. + /// The mod's full directory path within the . + /// The root path containing mods. /// The mod manifest. /// Metadata about the mod from SMAPI's internal data (if any). /// Whether the mod folder should be ignored. This should be true if it was found within a folder whose name starts with a dot. - public ModMetadata(string displayName, string directoryPath, string relativeDirectoryPath, IManifest manifest, ModDataRecordVersionedFields dataRecord, bool isIgnored) + public ModMetadata(string displayName, string directoryPath, string rootPath, IManifest manifest, ModDataRecordVersionedFields dataRecord, bool isIgnored) { this.DisplayName = displayName; this.DirectoryPath = directoryPath; - this.RelativeDirectoryPath = relativeDirectoryPath; + this.RootPath = rootPath; + this.RelativeDirectoryPath = PathUtilities.GetRelativePath(this.RootPath, this.DirectoryPath); this.Manifest = manifest; this.DataRecord = dataRecord; this.IsIgnored = isIgnored; @@ -196,5 +202,12 @@ namespace StardewModdingAPI.Framework.ModLoading this.Warnings.HasFlag(warning) && (this.DataRecord?.DataRecord == null || !this.DataRecord.DataRecord.SuppressWarnings.HasFlag(warning)); } + + /// Get a relative path which includes the root folder name. + public string GetRelativePathWithRoot() + { + string rootFolderName = Path.GetFileName(this.RootPath) ?? ""; + return Path.Combine(rootFolderName, this.RelativeDirectoryPath); + } } } diff --git a/src/SMAPI/Framework/ModLoading/ModResolver.cs b/src/SMAPI/Framework/ModLoading/ModResolver.cs index b6bdb357..20941a5f 100644 --- a/src/SMAPI/Framework/ModLoading/ModResolver.cs +++ b/src/SMAPI/Framework/ModLoading/ModResolver.cs @@ -42,9 +42,8 @@ namespace StardewModdingAPI.Framework.ModLoading ModMetadataStatus status = folder.ManifestParseError == ModParseError.None || shouldIgnore ? ModMetadataStatus.Found : ModMetadataStatus.Failed; - string relativePath = PathUtilities.GetRelativePath(rootPath, folder.Directory.FullName); - yield return new ModMetadata(folder.DisplayName, folder.Directory.FullName, relativePath, manifest, dataRecord, isIgnored: shouldIgnore) + yield return new ModMetadata(folder.DisplayName, folder.Directory.FullName, rootPath, manifest, dataRecord, isIgnored: shouldIgnore) .SetStatus(status, shouldIgnore ? "disabled by dot convention" : folder.ManifestParseErrorText); } } @@ -199,7 +198,14 @@ namespace StardewModdingAPI.Framework.ModLoading { if (mod.Status == ModMetadataStatus.Failed) continue; // don't replace metadata error - mod.SetStatus(ModMetadataStatus.Failed, $"you have multiple copies of this mod installed ({string.Join(", ", group.Select(p => p.RelativeDirectoryPath).OrderBy(p => p))})."); + + string folderList = string.Join(", ", + from entry in @group + let relativePath = entry.GetRelativePathWithRoot() + orderby relativePath + select $"{relativePath} ({entry.Manifest.Version})" + ); + mod.SetStatus(ModMetadataStatus.Failed, $"you have multiple copies of this mod installed. Found in folders: {folderList}."); } } } diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index 60deed70..0aae3b84 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -400,7 +400,7 @@ namespace StardewModdingAPI.Framework // filter out ignored mods foreach (IModMetadata mod in mods.Where(p => p.IsIgnored)) - this.Monitor.Log($" Skipped {mod.RelativeDirectoryPath} (folder name starts with a dot).", LogLevel.Trace); + this.Monitor.Log($" Skipped {mod.GetRelativePathWithRoot()} (folder name starts with a dot).", LogLevel.Trace); mods = mods.Where(p => !p.IsIgnored).ToArray(); // load mods @@ -902,13 +902,13 @@ namespace StardewModdingAPI.Framework // log entry { - string relativePath = PathUtilities.GetRelativePath(this.ModsPath, mod.DirectoryPath); + string relativePath = mod.GetRelativePathWithRoot(); if (mod.IsContentPack) - this.Monitor.Log($" {mod.DisplayName} ({relativePath}) [content pack]...", LogLevel.Trace); + this.Monitor.Log($" {mod.DisplayName} (from {relativePath}) [content pack]...", LogLevel.Trace); else if (mod.Manifest?.EntryDll != null) - this.Monitor.Log($" {mod.DisplayName} ({relativePath}{Path.DirectorySeparatorChar}{mod.Manifest.EntryDll})...", LogLevel.Trace); // don't use Path.Combine here, since EntryDLL might not be valid + this.Monitor.Log($" {mod.DisplayName} (from {relativePath}{Path.DirectorySeparatorChar}{mod.Manifest.EntryDll})...", LogLevel.Trace); // don't use Path.Combine here, since EntryDLL might not be valid else - this.Monitor.Log($" {mod.DisplayName} ({relativePath})...", LogLevel.Trace); + this.Monitor.Log($" {mod.DisplayName} (from {relativePath})...", LogLevel.Trace); } // add warning for missing update key -- cgit From dc1c9bf036ad61cbddd3390bbc2044b5f3ebd5aa Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 21 Jul 2019 22:01:23 -0400 Subject: normalise custom map's tilesheet paths for the OS --- docs/release-notes.md | 1 + .../Framework/ContentManagers/ModContentManager.cs | 53 ++++++++++++++-------- 2 files changed, 35 insertions(+), 19 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index d6076b0f..58114dde 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -40,6 +40,7 @@ These changes have not been released yet. * The installer now recognises custom game paths stored in `stardewvalley.targets`, if any. * Trace logs for a broken mod now list all detected issues (instead of the first one). * Trace logs when loading mods are now more clear. + * Fixed custom maps loaded from the mod folder with tilesheets in a subfolder not working crossplatform. All tilesheet paths are now normalised for the OS automatically. * Removed all deprecated APIs. * Removed the `Monitor.ExitGameImmediately` method. * Updated dependencies (including Json.NET 11.0.2 → 12.0.2, Mono.Cecil 0.10.1 → 0.10.4). diff --git a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs index 2c73e861..de05e92d 100644 --- a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs @@ -117,7 +117,9 @@ namespace StardewModdingAPI.Framework.ContentManagers { // XNB file case ".xnb": - return this.RawLoad(assetName, useCache: false); + { + return this.RawLoad(assetName, useCache: false); + } // unpacked data case ".json": @@ -129,29 +131,34 @@ namespace StardewModdingAPI.Framework.ContentManagers // unpacked image case ".png": - // validate - if (typeof(T) != typeof(Texture2D)) - throw GetContentError($"can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Texture2D)}'."); - - // fetch & cache - using (FileStream stream = File.OpenRead(file.FullName)) { - Texture2D texture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream); - texture = this.PremultiplyTransparency(texture); - return (T)(object)texture; + // validate + if (typeof(T) != typeof(Texture2D)) + throw GetContentError($"can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Texture2D)}'."); + + // fetch & cache + using (FileStream stream = File.OpenRead(file.FullName)) + { + Texture2D texture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream); + texture = this.PremultiplyTransparency(texture); + return (T)(object)texture; + } } // unpacked map case ".tbin": - // validate - if (typeof(T) != typeof(Map)) - throw GetContentError($"can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Map)}'."); - - // fetch & cache - FormatManager formatManager = FormatManager.Instance; - Map map = formatManager.LoadMap(file.FullName); - this.FixCustomTilesheetPaths(map, relativeMapPath: assetName); - return (T)(object)map; + { + // validate + if (typeof(T) != typeof(Map)) + throw GetContentError($"can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Map)}'."); + + // fetch & cache + FormatManager formatManager = FormatManager.Instance; + Map map = formatManager.LoadMap(file.FullName); + this.FixCustomTilesheetPaths(map, relativeMapPath: assetName); + this.NormaliseTilesheetPaths(map); + return (T)(object)map; + } default: throw GetContentError($"unknown file extension '{file.Extension}'; must be one of '.json', '.png', '.tbin', or '.xnb'."); @@ -232,6 +239,14 @@ namespace StardewModdingAPI.Framework.ContentManagers return texture; } + /// Normalise map tilesheet paths for the current platform. + /// The map whose tilesheets to fix. + private void NormaliseTilesheetPaths(Map map) + { + foreach (TileSheet tilesheet in map.TileSheets) + tilesheet.ImageSource = this.NormalisePathSeparators(tilesheet.ImageSource); + } + /// Fix custom map tilesheet paths so they can be found by the content manager. /// The map whose tilesheets to fix. /// The relative map path within the mod folder. -- cgit From 4b9ba35a194ac711d7c36943fc7277ce2a33b141 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 21 Jul 2019 22:05:47 -0400 Subject: apply tilesheet fixes to XNB map files too --- docs/release-notes.md | 1 + src/SMAPI/Framework/ContentManagers/ModContentManager.cs | 8 +++++++- 2 files changed, 8 insertions(+), 1 deletion(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 58114dde..abc08e16 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -40,6 +40,7 @@ These changes have not been released yet. * The installer now recognises custom game paths stored in `stardewvalley.targets`, if any. * Trace logs for a broken mod now list all detected issues (instead of the first one). * Trace logs when loading mods are now more clear. + * Fixed custom maps loaded from `.xnb` files not having their tilesheet paths automatically adjusted. * Fixed custom maps loaded from the mod folder with tilesheets in a subfolder not working crossplatform. All tilesheet paths are now normalised for the OS automatically. * Removed all deprecated APIs. * Removed the `Monitor.ExitGameImmediately` method. diff --git a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs index de05e92d..d6eb28c8 100644 --- a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs @@ -118,7 +118,13 @@ namespace StardewModdingAPI.Framework.ContentManagers // XNB file case ".xnb": { - return this.RawLoad(assetName, useCache: false); + T data = this.RawLoad(assetName, useCache: false); + if (data is Map map) + { + this.FixCustomTilesheetPaths(map, relativeMapPath: assetName); + this.NormaliseTilesheetPaths(map); + } + return data; } // unpacked data -- cgit From e856d5efebe12b3aa65d5868ea7baa59cc54863d Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 24 Jul 2019 18:29:50 -0400 Subject: add remote mod status to update check info (#651) --- docs/release-notes.md | 1 + src/SMAPI.Web/Controllers/ModsApiController.cs | 10 ++++----- .../Framework/Clients/ModDrop/ModDropMod.cs | 3 --- .../ModRepositories/ChucklefishRepository.cs | 6 ++--- .../Framework/ModRepositories/GitHubRepository.cs | 6 ++--- .../Framework/ModRepositories/ModDropRepository.cs | 8 +++---- .../Framework/ModRepositories/ModInfoModel.cs | 26 ++++++++++++---------- .../Framework/ModRepositories/NexusRepository.cs | 8 +++---- .../Framework/ModRepositories/RemoteModStatus.cs | 18 +++++++++++++++ 9 files changed, 51 insertions(+), 35 deletions(-) create mode 100644 src/SMAPI.Web/Framework/ModRepositories/RemoteModStatus.cs (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index abc08e16..4b380564 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -40,6 +40,7 @@ These changes have not been released yet. * The installer now recognises custom game paths stored in `stardewvalley.targets`, if any. * Trace logs for a broken mod now list all detected issues (instead of the first one). * Trace logs when loading mods are now more clear. + * Clarified update-check errors for mods with multiple update keys. * Fixed custom maps loaded from `.xnb` files not having their tilesheet paths automatically adjusted. * Fixed custom maps loaded from the mod folder with tilesheets in a subfolder not working crossplatform. All tilesheet paths are now normalised for the OS automatically. * Removed all deprecated APIs. diff --git a/src/SMAPI.Web/Controllers/ModsApiController.cs b/src/SMAPI.Web/Controllers/ModsApiController.cs index 9cffd3b3..a74d0d8a 100644 --- a/src/SMAPI.Web/Controllers/ModsApiController.cs +++ b/src/SMAPI.Web/Controllers/ModsApiController.cs @@ -245,11 +245,11 @@ namespace StardewModdingAPI.Web.Controllers // parse update key UpdateKey parsed = UpdateKey.Parse(updateKey); if (!parsed.LooksValid) - return new ModInfoModel($"The update key '{updateKey}' isn't in a valid format. It should contain the site key and mod ID like 'Nexus:541'."); + return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, $"The update key '{updateKey}' isn't in a valid format. It should contain the site key and mod ID like 'Nexus:541'."); // get matching repository if (!this.Repositories.TryGetValue(parsed.Repository, out IModRepository repository)) - return new ModInfoModel($"There's no mod site with key '{parsed.Repository}'. Expected one of [{string.Join(", ", this.Repositories.Keys)}]."); + return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, $"There's no mod site with key '{parsed.Repository}'. Expected one of [{string.Join(", ", this.Repositories.Keys)}]."); // fetch mod info return await this.Cache.GetOrCreateAsync($"{repository.VendorKey}:{parsed.ID}".ToLower(), async entry => @@ -258,11 +258,11 @@ namespace StardewModdingAPI.Web.Controllers if (result.Error == null) { if (result.Version == null) - result.Error = $"The update key '{updateKey}' matches a mod with no version number."; + result.WithError(RemoteModStatus.InvalidData, $"The update key '{updateKey}' matches a mod with no version number."); else if (!Regex.IsMatch(result.Version, this.VersionRegex, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)) - result.Error = $"The update key '{updateKey}' matches a mod with invalid semantic version '{result.Version}'."; + result.WithError(RemoteModStatus.InvalidData, $"The update key '{updateKey}' matches a mod with invalid semantic version '{result.Version}'."); } - entry.AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(result.Error == null ? this.SuccessCacheMinutes : this.ErrorCacheMinutes); + entry.AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(result.Status == RemoteModStatus.TemporaryError ? this.ErrorCacheMinutes : this.SuccessCacheMinutes); return result; }); } diff --git a/src/SMAPI.Web/Framework/Clients/ModDrop/ModDropMod.cs b/src/SMAPI.Web/Framework/Clients/ModDrop/ModDropMod.cs index 291fb353..def79106 100644 --- a/src/SMAPI.Web/Framework/Clients/ModDrop/ModDropMod.cs +++ b/src/SMAPI.Web/Framework/Clients/ModDrop/ModDropMod.cs @@ -17,8 +17,5 @@ namespace StardewModdingAPI.Web.Framework.Clients.ModDrop /// The mod's web URL. public string Url { get; set; } - - /// A user-friendly error which indicates why fetching the mod info failed (if applicable). - public string Error { get; set; } } } diff --git a/src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs index 87e29a2f..04c80dd2 100644 --- a/src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs +++ b/src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs @@ -32,21 +32,21 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories { // validate ID format if (!uint.TryParse(id, out uint realID)) - return new ModInfoModel($"The value '{id}' isn't a valid Chucklefish mod ID, must be an integer ID."); + return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid Chucklefish mod ID, must be an integer ID."); // fetch info try { var mod = await this.Client.GetModAsync(realID); if (mod == null) - return new ModInfoModel("Found no mod with this ID."); + return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, "Found no Chucklefish mod with this ID."); // create model return new ModInfoModel(name: mod.Name, version: this.NormaliseVersion(mod.Version), url: mod.Url); } catch (Exception ex) { - return new ModInfoModel(ex.ToString()); + return new ModInfoModel().WithError(RemoteModStatus.TemporaryError, ex.ToString()); } } diff --git a/src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs index 14f44dc0..614e00c2 100644 --- a/src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs +++ b/src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs @@ -32,7 +32,7 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories { // validate ID format if (!id.Contains("/") || id.IndexOf("/", StringComparison.InvariantCultureIgnoreCase) != id.LastIndexOf("/", StringComparison.InvariantCultureIgnoreCase)) - return new ModInfoModel($"The value '{id}' isn't a valid GitHub mod ID, must be a username and project name like 'Pathoschild/LookupAnything'."); + return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid GitHub mod ID, must be a username and project name like 'Pathoschild/LookupAnything'."); // fetch info try @@ -40,7 +40,7 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories // get latest release (whether preview or stable) GitRelease latest = await this.Client.GetLatestReleaseAsync(id, includePrerelease: true); if (latest == null) - return new ModInfoModel("Found no mod with this ID."); + return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, "Found no GitHub release for this ID."); // split stable/prerelease if applicable GitRelease preview = null; @@ -59,7 +59,7 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories } catch (Exception ex) { - return new ModInfoModel(ex.ToString()); + return new ModInfoModel().WithError(RemoteModStatus.TemporaryError, ex.ToString()); } } diff --git a/src/SMAPI.Web/Framework/ModRepositories/ModDropRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/ModDropRepository.cs index 1994f515..5703b34e 100644 --- a/src/SMAPI.Web/Framework/ModRepositories/ModDropRepository.cs +++ b/src/SMAPI.Web/Framework/ModRepositories/ModDropRepository.cs @@ -32,21 +32,19 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories { // validate ID format if (!long.TryParse(id, out long modDropID)) - return new ModInfoModel($"The value '{id}' isn't a valid ModDrop mod ID, must be an integer ID."); + return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid ModDrop mod ID, must be an integer ID."); // fetch info try { ModDropMod mod = await this.Client.GetModAsync(modDropID); if (mod == null) - return new ModInfoModel("Found no mod with this ID."); - if (mod.Error != null) - return new ModInfoModel(mod.Error); + return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, "Found no ModDrop mod with this ID."); return new ModInfoModel(name: mod.Name, version: mod.LatestDefaultVersion?.ToString(), previewVersion: mod.LatestOptionalVersion?.ToString(), url: mod.Url); } catch (Exception ex) { - return new ModInfoModel(ex.ToString()); + return new ModInfoModel().WithError(RemoteModStatus.TemporaryError, ex.ToString()); } } diff --git a/src/SMAPI.Web/Framework/ModRepositories/ModInfoModel.cs b/src/SMAPI.Web/Framework/ModRepositories/ModInfoModel.cs index 18252298..16885bfd 100644 --- a/src/SMAPI.Web/Framework/ModRepositories/ModInfoModel.cs +++ b/src/SMAPI.Web/Framework/ModRepositories/ModInfoModel.cs @@ -9,15 +9,18 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories /// The mod name. public string Name { get; set; } - /// The mod's latest release number. + /// The mod's latest version. public string Version { get; set; } - /// The mod's latest optional release, if newer than . + /// The mod's latest optional or prerelease version, if newer than . public string PreviewVersion { get; set; } /// The mod's web URL. public string Url { get; set; } + /// The mod availability status. + public RemoteModStatus Status { get; set; } = RemoteModStatus.Ok; + /// The error message indicating why the mod is invalid (if applicable). public string Error { get; set; } @@ -26,31 +29,30 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories ** Public methods *********/ /// Construct an empty instance. - public ModInfoModel() - { - // needed for JSON deserialising - } + public ModInfoModel() { } /// Construct an instance. /// The mod name. /// The semantic version for the mod's latest release. /// The semantic version for the mod's latest preview release, if available and different from . /// The mod's web URL. - /// The error message indicating why the mod is invalid (if applicable). - public ModInfoModel(string name, string version, string url, string previewVersion = null, string error = null) + public ModInfoModel(string name, string version, string url, string previewVersion = null) { this.Name = name; this.Version = version; this.PreviewVersion = previewVersion; this.Url = url; - this.Error = error; } - /// Construct an instance. - /// The error message indicating why the mod is invalid. - public ModInfoModel(string error) + /// Set a mod error. + /// The mod availability status. + /// The error message indicating why the mod is invalid (if applicable). + public ModInfoModel WithError(RemoteModStatus status, string error) { + this.Status = status; this.Error = error; + + return this; } } } diff --git a/src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs index 4c5fe9bf..9679f93e 100644 --- a/src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs +++ b/src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs @@ -32,21 +32,21 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories { // validate ID format if (!uint.TryParse(id, out uint nexusID)) - return new ModInfoModel($"The value '{id}' isn't a valid Nexus mod ID, must be an integer ID."); + return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid Nexus mod ID, must be an integer ID."); // fetch info try { NexusMod mod = await this.Client.GetModAsync(nexusID); if (mod == null) - return new ModInfoModel("Found no mod with this ID."); + return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, "Found no Nexus mod with this ID."); if (mod.Error != null) - return new ModInfoModel(mod.Error); + return new ModInfoModel().WithError(RemoteModStatus.TemporaryError, mod.Error); return new ModInfoModel(name: mod.Name, version: this.NormaliseVersion(mod.Version), previewVersion: mod.LatestFileVersion?.ToString(), url: mod.Url); } catch (Exception ex) { - return new ModInfoModel(ex.ToString()); + return new ModInfoModel().WithError(RemoteModStatus.TemporaryError, ex.ToString()); } } diff --git a/src/SMAPI.Web/Framework/ModRepositories/RemoteModStatus.cs b/src/SMAPI.Web/Framework/ModRepositories/RemoteModStatus.cs new file mode 100644 index 00000000..02876556 --- /dev/null +++ b/src/SMAPI.Web/Framework/ModRepositories/RemoteModStatus.cs @@ -0,0 +1,18 @@ +namespace StardewModdingAPI.Web.Framework.ModRepositories +{ + /// The mod availability status on a remote site. + internal enum RemoteModStatus + { + /// The mod is valid. + Ok, + + /// The mod data was fetched, but the data is not valid (e.g. version isn't semantic). + InvalidData, + + /// The mod does not exist. + DoesNotExist, + + /// The mod was temporarily unavailable (e.g. the site could not be reached or an unknown error occurred). + TemporaryError + } +} -- cgit From 95f261b1f30d8c5ad6c179cd75a220dcca3c6395 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 24 Jul 2019 22:11:51 -0400 Subject: fetch mod info from Nexus API if the web page is hidden due to adult content (#651) --- docs/release-notes.md | 1 + .../Framework/Clients/Nexus/NexusClient.cs | 133 ++++++++++++++++----- .../Framework/Clients/Nexus/NexusModStatus.cs | 3 + .../Framework/ConfigModels/ApiClientsConfig.cs | 3 + src/SMAPI.Web/SMAPI.Web.csproj | 1 + src/SMAPI.Web/Startup.cs | 10 +- src/SMAPI.Web/appsettings.Development.json | 2 + src/SMAPI.Web/appsettings.json | 1 + 8 files changed, 120 insertions(+), 34 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 4b380564..2b7d1545 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -24,6 +24,7 @@ These changes have not been released yet. * Fixed map reloads resetting tilesheet seasons. * Fixed map reloads not updating door warps. * Fixed outdoor tilesheets being seasonalised when added to an indoor location. + * Fixed update checks failing for Nexus mods marked as adult content. * For the mod compatibility list: * Now loads faster (since data is fetched in a background service). diff --git a/src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs b/src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs index 87393367..753d3b4f 100644 --- a/src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs +++ b/src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs @@ -4,8 +4,10 @@ using System.Linq; using System.Net; using System.Threading.Tasks; using HtmlAgilityPack; +using Pathoschild.FluentNexus.Models; using Pathoschild.Http.Client; using StardewModdingAPI.Toolkit; +using FluentNexusClient = Pathoschild.FluentNexus.NexusClient; namespace StardewModdingAPI.Web.Framework.Clients.Nexus { @@ -16,41 +18,73 @@ namespace StardewModdingAPI.Web.Framework.Clients.Nexus ** Fields *********/ /// The URL for a Nexus mod page for the user, excluding the base URL, where {0} is the mod ID. - private readonly string ModUrlFormat; + private readonly string WebModUrlFormat; /// The URL for a Nexus mod page to scrape for versions, excluding the base URL, where {0} is the mod ID. - public string ModScrapeUrlFormat { get; set; } + public string WebModScrapeUrlFormat { get; set; } - /// The underlying HTTP client. - private readonly IClient Client; + /// The underlying HTTP client for the Nexus Mods website. + private readonly IClient WebClient; + + /// The underlying HTTP client for the Nexus API. + private readonly FluentNexusClient ApiClient; /********* ** Public methods *********/ /// Construct an instance. - /// The user agent for the Nexus Mods API client. - /// The base URL for the Nexus Mods site. - /// The URL for a Nexus Mods mod page for the user, excluding the , where {0} is the mod ID. - /// The URL for a Nexus mod page to scrape for versions, excluding the base URL, where {0} is the mod ID. - public NexusClient(string userAgent, string baseUrl, string modUrlFormat, string modScrapeUrlFormat) + /// The user agent for the Nexus Mods web client. + /// The base URL for the Nexus Mods site. + /// The URL for a Nexus Mods mod page for the user, excluding the , where {0} is the mod ID. + /// The URL for a Nexus mod page to scrape for versions, excluding the base URL, where {0} is the mod ID. + /// The app version to show in API user agents. + /// The Nexus API authentication key. + public NexusClient(string webUserAgent, string webBaseUrl, string webModUrlFormat, string webModScrapeUrlFormat, string apiAppVersion, string apiKey) { - this.ModUrlFormat = modUrlFormat; - this.ModScrapeUrlFormat = modScrapeUrlFormat; - this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent); + this.WebModUrlFormat = webModUrlFormat; + this.WebModScrapeUrlFormat = webModScrapeUrlFormat; + this.WebClient = new FluentClient(webBaseUrl).SetUserAgent(webUserAgent); + this.ApiClient = new FluentNexusClient(apiKey, "SMAPI", apiAppVersion); } /// Get metadata about a mod. /// The Nexus mod ID. /// Returns the mod info if found, else null. public async Task GetModAsync(uint id) + { + // Fetch from the Nexus website when possible, since it has no rate limits. Mods with + // adult content are hidden for anonymous users, so fall back to the API in that case. + // Note that the API has very restrictive rate limits which means we can't just use it + // for all cases. + NexusMod mod = await this.GetModFromWebsiteAsync(id); + if (mod?.Status == NexusModStatus.AdultContentForbidden) + mod = await this.GetModFromApiAsync(id); + + return mod; + } + + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + public void Dispose() + { + this.WebClient?.Dispose(); + } + + + /********* + ** Private methods + *********/ + /// Get metadata about a mod by scraping the Nexus website. + /// The Nexus mod ID. + /// Returns the mod info if found, else null. + private async Task GetModFromWebsiteAsync(uint id) { // fetch HTML string html; try { - html = await this.Client - .GetAsync(string.Format(this.ModScrapeUrlFormat, id)) + html = await this.WebClient + .GetAsync(string.Format(this.WebModScrapeUrlFormat, id)) .AsString(); } catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound) @@ -74,14 +108,8 @@ namespace StardewModdingAPI.Web.Framework.Clients.Nexus case "not found": return null; - case "hidden mod": - return new NexusMod { Error = $"Nexus error: {errorCode} ({errorText}).", Status = NexusModStatus.Hidden }; - - case "not published": - return new NexusMod { Error = $"Nexus error: {errorCode} ({errorText}).", Status = NexusModStatus.NotPublished }; - default: - return new NexusMod { Error = $"Nexus error: {errorCode} ({errorText}).", Status = NexusModStatus.Other }; + return new NexusMod { Error = $"Nexus error: {errorCode} ({errorText}).", Status = this.GetWebStatus(errorCode) }; } } @@ -130,23 +158,68 @@ namespace StardewModdingAPI.Web.Framework.Clients.Nexus }; } - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - public void Dispose() + /// Get metadata about a mod from the Nexus API. + /// The Nexus mod ID. + /// Returns the mod info if found, else null. + private async Task GetModFromApiAsync(uint id) { - this.Client?.Dispose(); - } + // fetch mod + Mod mod = await this.ApiClient.Mods.GetMod("stardewvalley", (int)id); + ModFileList files = await this.ApiClient.ModFiles.GetModFiles("stardewvalley", (int)id, FileCategory.Main, FileCategory.Optional); + + // get versions + if (!SemanticVersion.TryParse(mod.Version, out ISemanticVersion mainVersion)) + mainVersion = null; + ISemanticVersion latestFileVersion = null; + foreach (string rawVersion in files.Files.Select(p => p.FileVersion)) + { + if (!SemanticVersion.TryParse(rawVersion, out ISemanticVersion cur)) + continue; + if (mainVersion != null && !cur.IsNewerThan(mainVersion)) + continue; + if (latestFileVersion != null && !cur.IsNewerThan(latestFileVersion)) + continue; + latestFileVersion = cur; + } + + // yield info + return new NexusMod + { + Name = mod.Name, + Version = SemanticVersion.TryParse(mod.Version, out ISemanticVersion version) ? version?.ToString() : mod.Version, + LatestFileVersion = latestFileVersion, + Url = this.GetModUrl(id) + }; + } - /********* - ** Private methods - *********/ /// Get the full mod page URL for a given ID. /// The mod ID. private string GetModUrl(uint id) { - UriBuilder builder = new UriBuilder(this.Client.BaseClient.BaseAddress); - builder.Path += string.Format(this.ModUrlFormat, id); + UriBuilder builder = new UriBuilder(this.WebClient.BaseClient.BaseAddress); + builder.Path += string.Format(this.WebModUrlFormat, id); return builder.Uri.ToString(); } + + /// Get the mod status for a web error code. + /// The Nexus error code. + private NexusModStatus GetWebStatus(string errorCode) + { + switch (errorCode.Trim().ToLower()) + { + case "adult content": + return NexusModStatus.AdultContentForbidden; + + case "hidden mod": + return NexusModStatus.Hidden; + + case "not published": + return NexusModStatus.NotPublished; + + default: + return NexusModStatus.Other; + } + } } } diff --git a/src/SMAPI.Web/Framework/Clients/Nexus/NexusModStatus.cs b/src/SMAPI.Web/Framework/Clients/Nexus/NexusModStatus.cs index c5723093..9ef314cd 100644 --- a/src/SMAPI.Web/Framework/Clients/Nexus/NexusModStatus.cs +++ b/src/SMAPI.Web/Framework/Clients/Nexus/NexusModStatus.cs @@ -12,6 +12,9 @@ namespace StardewModdingAPI.Web.Framework.Clients.Nexus /// The mod hasn't been published yet. NotPublished, + /// The mod contains adult content which is hidden for anonymous web users. + AdultContentForbidden, + /// The Nexus API returned an unhandled error. Other } diff --git a/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs b/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs index c27cadab..d2e9a2fe 100644 --- a/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs +++ b/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs @@ -65,6 +65,9 @@ namespace StardewModdingAPI.Web.Framework.ConfigModels /// The URL for a Nexus mod page to scrape for versions, excluding the , where {0} is the mod ID. public string NexusModScrapeUrlFormat { get; set; } + /// The Nexus API authentication key. + public string NexusApiKey { get; set; } + /**** ** Pastebin ****/ diff --git a/src/SMAPI.Web/SMAPI.Web.csproj b/src/SMAPI.Web/SMAPI.Web.csproj index f4e99e0c..26b29fce 100644 --- a/src/SMAPI.Web/SMAPI.Web.csproj +++ b/src/SMAPI.Web/SMAPI.Web.csproj @@ -26,6 +26,7 @@ + diff --git a/src/SMAPI.Web/Startup.cs b/src/SMAPI.Web/Startup.cs index 66e1f00d..4d23fe65 100644 --- a/src/SMAPI.Web/Startup.cs +++ b/src/SMAPI.Web/Startup.cs @@ -136,10 +136,12 @@ namespace StardewModdingAPI.Web )); services.AddSingleton(new NexusClient( - userAgent: userAgent, - baseUrl: api.NexusBaseUrl, - modUrlFormat: api.NexusModUrlFormat, - modScrapeUrlFormat: api.NexusModScrapeUrlFormat + webUserAgent: userAgent, + webBaseUrl: api.NexusBaseUrl, + webModUrlFormat: api.NexusModUrlFormat, + webModScrapeUrlFormat: api.NexusModScrapeUrlFormat, + apiAppVersion: version, + apiKey: api.NexusApiKey )); services.AddSingleton(new PastebinClient( diff --git a/src/SMAPI.Web/appsettings.Development.json b/src/SMAPI.Web/appsettings.Development.json index 5856b96c..e6b4a1b1 100644 --- a/src/SMAPI.Web/appsettings.Development.json +++ b/src/SMAPI.Web/appsettings.Development.json @@ -20,6 +20,8 @@ "GitHubUsername": null, "GitHubPassword": null, + "NexusApiKey": null, + "PastebinUserKey": null, "PastebinDevKey": null }, diff --git a/src/SMAPI.Web/appsettings.json b/src/SMAPI.Web/appsettings.json index 77d13924..3ea37dea 100644 --- a/src/SMAPI.Web/appsettings.json +++ b/src/SMAPI.Web/appsettings.json @@ -39,6 +39,7 @@ "ModDropApiUrl": "https://www.moddrop.com/api/mods/data", "ModDropModPageUrl": "https://www.moddrop.com/sdv/mod/{0}", + "NexusApiKey": null, // see top note "NexusBaseUrl": "https://www.nexusmods.com/stardewvalley/", "NexusModUrlFormat": "mods/{0}", "NexusModScrapeUrlFormat": "mods/{0}?tab=files", -- cgit From 2b4bc2c282e17ba431f9a6ec1892b87a37eb4bb7 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 29 Jul 2019 13:15:27 -0400 Subject: back up saves in a background thread --- docs/release-notes.md | 1 + src/SMAPI.Mods.SaveBackup/ModEntry.cs | 11 +++++++---- 2 files changed, 8 insertions(+), 4 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 2b7d1545..b425112d 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -12,6 +12,7 @@ These changes have not been released yet. * Now ignores metadata files/folders like `__MACOSX` and `__folder_managed_by_vortex`. * Now ignores content files like `.txt` or `.png`, which avoids missing-manifest errors in some common cases. * Now detects XNB mods more accurately, and consolidates multi-folder XNB mods. + * Save Backup now works in the background, to avoid affecting startup time for players with a large number of saves. * Duplicate-mod errors now show the mod version in each folder. * Updated mod compatibility list. * Fixed mods needing to load custom `Map` assets before the game accesses them (SMAPI will now do so automatically). diff --git a/src/SMAPI.Mods.SaveBackup/ModEntry.cs b/src/SMAPI.Mods.SaveBackup/ModEntry.cs index 33adf76d..845df453 100644 --- a/src/SMAPI.Mods.SaveBackup/ModEntry.cs +++ b/src/SMAPI.Mods.SaveBackup/ModEntry.cs @@ -4,6 +4,7 @@ using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; +using System.Threading.Tasks; using StardewValley; namespace StardewModdingAPI.Mods.SaveBackup @@ -40,9 +41,10 @@ namespace StardewModdingAPI.Mods.SaveBackup DirectoryInfo backupFolder = new DirectoryInfo(this.BackupFolder); backupFolder.Create(); - // back up saves - this.CreateBackup(backupFolder); - this.PruneBackups(backupFolder, this.BackupsToKeep); + // back up & prune saves + Task + .Run(() => this.CreateBackup(backupFolder)) + .ContinueWith(backupTask => this.PruneBackups(backupFolder, this.BackupsToKeep)); } catch (Exception ex) { @@ -68,7 +70,7 @@ namespace StardewModdingAPI.Mods.SaveBackup // create zip // due to limitations with the bundled Mono on Mac, we can't reference System.IO.Compression. - this.Monitor.Log($"Adding {targetFile.Name}...", LogLevel.Trace); + this.Monitor.Log($"Backing up saves to {targetFile.FullName}...", LogLevel.Trace); switch (Constants.TargetPlatform) { case GamePlatform.Linux: @@ -108,6 +110,7 @@ namespace StardewModdingAPI.Mods.SaveBackup } break; } + this.Monitor.Log("Backup done!", LogLevel.Trace); } catch (Exception ex) { -- cgit From 1d085df5b796e02b3e9e6874bd4e5684e840cb92 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 29 Jul 2019 16:43:25 -0400 Subject: track license info for mod GitHub repos (#651) --- docs/release-notes.md | 1 + .../Framework/Clients/Wiki/WikiModEntry.cs | 1 - .../Framework/UpdateData/UpdateKey.cs | 32 ++++++++++++- src/SMAPI.Web/BackgroundService.cs | 7 +-- src/SMAPI.Web/Controllers/ModsApiController.cs | 54 ++++++++++++++-------- src/SMAPI.Web/Framework/Caching/Mods/CachedMod.cs | 12 ++++- .../Framework/Clients/GitHub/GitHubClient.cs | 39 +++++++++------- .../Framework/Clients/GitHub/GitLicense.cs | 20 ++++++++ src/SMAPI.Web/Framework/Clients/GitHub/GitRepo.cs | 20 ++++++++ .../Framework/Clients/GitHub/IGitHubClient.cs | 5 ++ .../Framework/ConfigModels/ApiClientsConfig.cs | 6 --- .../ModRepositories/ChucklefishRepository.cs | 12 ++--- .../Framework/ModRepositories/GitHubRepository.cs | 24 +++++++--- .../Framework/ModRepositories/ModDropRepository.cs | 10 ++-- .../Framework/ModRepositories/ModInfoModel.cs | 42 ++++++++++++++++- .../Framework/ModRepositories/NexusRepository.cs | 8 ++-- src/SMAPI.Web/Startup.cs | 2 - src/SMAPI.Web/appsettings.json | 2 - 18 files changed, 220 insertions(+), 77 deletions(-) create mode 100644 src/SMAPI.Web/Framework/Clients/GitHub/GitLicense.cs create mode 100644 src/SMAPI.Web/Framework/Clients/GitHub/GitRepo.cs (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index b425112d..fd0cda51 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -26,6 +26,7 @@ These changes have not been released yet. * Fixed map reloads not updating door warps. * Fixed outdoor tilesheets being seasonalised when added to an indoor location. * Fixed update checks failing for Nexus mods marked as adult content. + * Fixed update checks not recognising releases on GitHub if they're not explicitly listed as update keys. * For the mod compatibility list: * Now loads faster (since data is fetched in a background service). diff --git a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs index fff86891..06c44308 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki { diff --git a/src/SMAPI.Toolkit/Framework/UpdateData/UpdateKey.cs b/src/SMAPI.Toolkit/Framework/UpdateData/UpdateKey.cs index 865ebcf7..3fc1759e 100644 --- a/src/SMAPI.Toolkit/Framework/UpdateData/UpdateKey.cs +++ b/src/SMAPI.Toolkit/Framework/UpdateData/UpdateKey.cs @@ -3,7 +3,7 @@ using System; namespace StardewModdingAPI.Toolkit.Framework.UpdateData { /// A namespaced mod ID which uniquely identifies a mod within a mod repository. - public class UpdateKey + public class UpdateKey : IEquatable { /********* ** Accessors @@ -38,6 +38,12 @@ namespace StardewModdingAPI.Toolkit.Framework.UpdateData && !string.IsNullOrWhiteSpace(id); } + /// Construct an instance. + /// The mod repository containing the mod. + /// The mod ID within the repository. + public UpdateKey(ModRepositoryKey repository, string id) + : this($"{repository}:{id}", repository, id) { } + /// Parse a raw update key. /// The raw update key to parse. public static UpdateKey Parse(string raw) @@ -69,5 +75,29 @@ namespace StardewModdingAPI.Toolkit.Framework.UpdateData ? $"{this.Repository}:{this.ID}" : this.RawText; } + + /// Indicates whether the current object is equal to another object of the same type. + /// An object to compare with this object. + public bool Equals(UpdateKey other) + { + return + other != null + && this.Repository == other.Repository + && string.Equals(this.ID, other.ID, StringComparison.InvariantCultureIgnoreCase); + } + + /// Determines whether the specified object is equal to the current object. + /// The object to compare with the current object. + public override bool Equals(object obj) + { + return obj is UpdateKey other && this.Equals(other); + } + + /// Serves as the default hash function. + /// A hash code for the current object. + public override int GetHashCode() + { + return $"{this.Repository}:{this.ID}".ToLower().GetHashCode(); + } } } diff --git a/src/SMAPI.Web/BackgroundService.cs b/src/SMAPI.Web/BackgroundService.cs index 2dd3b921..dfd2c1b9 100644 --- a/src/SMAPI.Web/BackgroundService.cs +++ b/src/SMAPI.Web/BackgroundService.cs @@ -50,11 +50,11 @@ namespace StardewModdingAPI.Web // set startup tasks BackgroundJob.Enqueue(() => BackgroundService.UpdateWikiAsync()); - BackgroundJob.Enqueue(() => BackgroundService.RemoveStaleMods()); + BackgroundJob.Enqueue(() => BackgroundService.RemoveStaleModsAsync()); // set recurring tasks RecurringJob.AddOrUpdate(() => BackgroundService.UpdateWikiAsync(), "*/10 * * * *"); // every 10 minutes - RecurringJob.AddOrUpdate(() => BackgroundService.RemoveStaleMods(), "0 * * * *"); // hourly + RecurringJob.AddOrUpdate(() => BackgroundService.RemoveStaleModsAsync(), "0 * * * *"); // hourly return Task.CompletedTask; } @@ -84,9 +84,10 @@ namespace StardewModdingAPI.Web } /// Remove mods which haven't been requested in over 48 hours. - public static async Task RemoveStaleMods() + public static Task RemoveStaleModsAsync() { BackgroundService.ModCache.RemoveStaleMods(TimeSpan.FromHours(48)); + return Task.CompletedTask; } diff --git a/src/SMAPI.Web/Controllers/ModsApiController.cs b/src/SMAPI.Web/Controllers/ModsApiController.cs index 195ee5bf..13dd5529 100644 --- a/src/SMAPI.Web/Controllers/ModsApiController.cs +++ b/src/SMAPI.Web/Controllers/ModsApiController.cs @@ -123,18 +123,33 @@ namespace StardewModdingAPI.Web.Controllers // crossreference data ModDataRecord record = this.ModDatabase.Get(search.ID); WikiModEntry wikiEntry = wikiData.FirstOrDefault(entry => entry.ID.Contains(search.ID.Trim(), StringComparer.InvariantCultureIgnoreCase)); - string[] updateKeys = this.GetUpdateKeys(search.UpdateKeys, record, wikiEntry).ToArray(); + UpdateKey[] updateKeys = this.GetUpdateKeys(search.UpdateKeys, record, wikiEntry).ToArray(); + + // add soft lookups (don't log errors if the target doesn't exist) + UpdateKey[] softUpdateKeys = updateKeys.All(key => key.Repository != ModRepositoryKey.GitHub) && !string.IsNullOrWhiteSpace(wikiEntry?.GitHubRepo) + ? new[] { new UpdateKey(ModRepositoryKey.GitHub, wikiEntry.GitHubRepo) } + : new UpdateKey[0]; // get latest versions ModEntryModel result = new ModEntryModel { ID = search.ID }; IList errors = new List(); - foreach (string updateKey in updateKeys) + foreach (UpdateKey updateKey in updateKeys.Concat(softUpdateKeys)) { + bool isSoftLookup = softUpdateKeys.Contains(updateKey); + + // validate update key + if (!updateKey.LooksValid) + { + errors.Add($"The update key '{updateKey}' isn't in a valid format. It should contain the site key and mod ID like 'Nexus:541'."); + continue; + } + // fetch data ModInfoModel data = await this.GetInfoForUpdateKeyAsync(updateKey); if (data.Error != null) { - errors.Add(data.Error); + if (!isSoftLookup || data.Status != RemoteModStatus.DoesNotExist) + errors.Add(data.Error); continue; } @@ -221,32 +236,27 @@ namespace StardewModdingAPI.Web.Controllers /// Get the mod info for an update key. /// The namespaced update key. - private async Task GetInfoForUpdateKeyAsync(string updateKey) + private async Task GetInfoForUpdateKeyAsync(UpdateKey updateKey) { - // parse update key - UpdateKey parsed = UpdateKey.Parse(updateKey); - if (!parsed.LooksValid) - return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, $"The update key '{updateKey}' isn't in a valid format. It should contain the site key and mod ID like 'Nexus:541'."); - // get mod - if (!this.ModCache.TryGetMod(parsed.Repository, parsed.ID, out CachedMod mod) || this.ModCache.IsStale(mod.LastUpdated, mod.FetchStatus == RemoteModStatus.TemporaryError ? this.ErrorCacheMinutes : this.SuccessCacheMinutes)) + if (!this.ModCache.TryGetMod(updateKey.Repository, updateKey.ID, out CachedMod mod) || this.ModCache.IsStale(mod.LastUpdated, mod.FetchStatus == RemoteModStatus.TemporaryError ? this.ErrorCacheMinutes : this.SuccessCacheMinutes)) { // get site - if (!this.Repositories.TryGetValue(parsed.Repository, out IModRepository repository)) - return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, $"There's no mod site with key '{parsed.Repository}'. Expected one of [{string.Join(", ", this.Repositories.Keys)}]."); + if (!this.Repositories.TryGetValue(updateKey.Repository, out IModRepository repository)) + return new ModInfoModel().SetError(RemoteModStatus.DoesNotExist, $"There's no mod site with key '{updateKey.Repository}'. Expected one of [{string.Join(", ", this.Repositories.Keys)}]."); // fetch mod - ModInfoModel result = await repository.GetModInfoAsync(parsed.ID); + ModInfoModel result = await repository.GetModInfoAsync(updateKey.ID); if (result.Error == null) { if (result.Version == null) - result.WithError(RemoteModStatus.InvalidData, $"The update key '{updateKey}' matches a mod with no version number."); + result.SetError(RemoteModStatus.InvalidData, $"The update key '{updateKey}' matches a mod with no version number."); else if (!SemanticVersion.TryParse(result.Version, out _)) - result.WithError(RemoteModStatus.InvalidData, $"The update key '{updateKey}' matches a mod with invalid semantic version '{result.Version}'."); + result.SetError(RemoteModStatus.InvalidData, $"The update key '{updateKey}' matches a mod with invalid semantic version '{result.Version}'."); } // cache mod - this.ModCache.SaveMod(repository.VendorKey, parsed.ID, result, out mod); + this.ModCache.SaveMod(repository.VendorKey, updateKey.ID, result, out mod); } return mod.GetModel(); } @@ -255,7 +265,7 @@ namespace StardewModdingAPI.Web.Controllers /// The specified update keys. /// The mod's entry in SMAPI's internal database. /// The mod's entry in the wiki list. - public IEnumerable GetUpdateKeys(string[] specifiedKeys, ModDataRecord record, WikiModEntry entry) + public IEnumerable GetUpdateKeys(string[] specifiedKeys, ModDataRecord record, WikiModEntry entry) { IEnumerable GetRaw() { @@ -283,10 +293,14 @@ namespace StardewModdingAPI.Web.Controllers } } - HashSet seen = new HashSet(StringComparer.InvariantCulture); - foreach (string key in GetRaw()) + HashSet seen = new HashSet(); + foreach (string rawKey in GetRaw()) { - if (!string.IsNullOrWhiteSpace(key) && seen.Add(key)) + if (string.IsNullOrWhiteSpace(rawKey)) + continue; + + UpdateKey key = UpdateKey.Parse(rawKey); + if (seen.Add(key)) yield return key; } } diff --git a/src/SMAPI.Web/Framework/Caching/Mods/CachedMod.cs b/src/SMAPI.Web/Framework/Caching/Mods/CachedMod.cs index fe8a7a1f..96eca847 100644 --- a/src/SMAPI.Web/Framework/Caching/Mods/CachedMod.cs +++ b/src/SMAPI.Web/Framework/Caching/Mods/CachedMod.cs @@ -58,6 +58,12 @@ namespace StardewModdingAPI.Web.Framework.Caching.Mods /// The URL for the mod page. public string Url { get; set; } + /// The license URL, if available. + public string LicenseUrl { get; set; } + + /// The license name, if available. + public string LicenseName { get; set; } + /********* ** Accessors @@ -86,12 +92,16 @@ namespace StardewModdingAPI.Web.Framework.Caching.Mods this.MainVersion = mod.Version; this.PreviewVersion = mod.PreviewVersion; this.Url = mod.Url; + this.LicenseUrl = mod.LicenseUrl; + this.LicenseName = mod.LicenseName; } /// Get the API model for the cached data. public ModInfoModel GetModel() { - return new ModInfoModel(name: this.Name, version: this.MainVersion, previewVersion: this.PreviewVersion, url: this.Url).WithError(this.FetchStatus, this.FetchError); + return new ModInfoModel(name: this.Name, version: this.MainVersion, url: this.Url, previewVersion: this.PreviewVersion) + .SetLicense(this.LicenseUrl, this.LicenseName) + .SetError(this.FetchStatus, this.FetchError); } } } diff --git a/src/SMAPI.Web/Framework/Clients/GitHub/GitHubClient.cs b/src/SMAPI.Web/Framework/Clients/GitHub/GitHubClient.cs index 22950db9..84c20957 100644 --- a/src/SMAPI.Web/Framework/Clients/GitHub/GitHubClient.cs +++ b/src/SMAPI.Web/Framework/Clients/GitHub/GitHubClient.cs @@ -12,12 +12,6 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub /********* ** Fields *********/ - /// The URL for a GitHub API query for the latest stable release, excluding the base URL, where {0} is the organisation and project name. - private readonly string StableReleaseUrlFormat; - - /// The URL for a GitHub API query for the latest release (including prerelease), excluding the base URL, where {0} is the organisation and project name. - private readonly string AnyReleaseUrlFormat; - /// The underlying HTTP client. private readonly IClient Client; @@ -27,17 +21,12 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub *********/ /// Construct an instance. /// The base URL for the GitHub API. - /// The URL for a GitHub API query for the latest stable release, excluding the , where {0} is the organisation and project name. - /// The URL for a GitHub API query for the latest release (including prerelease), excluding the , where {0} is the organisation and project name. /// The user agent for the API client. /// The Accept header value expected by the GitHub API. /// The username with which to authenticate to the GitHub API. /// The password with which to authenticate to the GitHub API. - public GitHubClient(string baseUrl, string stableReleaseUrlFormat, string anyReleaseUrlFormat, string userAgent, string acceptHeader, string username, string password) + public GitHubClient(string baseUrl, string userAgent, string acceptHeader, string username, string password) { - this.StableReleaseUrlFormat = stableReleaseUrlFormat; - this.AnyReleaseUrlFormat = anyReleaseUrlFormat; - this.Client = new FluentClient(baseUrl) .SetUserAgent(userAgent) .AddDefault(req => req.WithHeader("Accept", acceptHeader)); @@ -45,25 +34,43 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub this.Client = this.Client.SetBasicAuthentication(username, password); } + /// Get basic metadata for a GitHub repository, if available. + /// The repository key (like Pathoschild/SMAPI). + /// Returns the repository info if it exists, else null. + public async Task GetRepositoryAsync(string repo) + { + this.AssertKeyFormat(repo); + try + { + return await this.Client + .GetAsync($"repos/{repo}") + .As(); + } + catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound) + { + return null; + } + } + /// Get the latest release for a GitHub repository. /// The repository key (like Pathoschild/SMAPI). /// Whether to return a prerelease version if it's latest. /// Returns the release if found, else null. public async Task GetLatestReleaseAsync(string repo, bool includePrerelease = false) { - this.AssetKeyFormat(repo); + this.AssertKeyFormat(repo); try { if (includePrerelease) { GitRelease[] results = await this.Client - .GetAsync(string.Format(this.AnyReleaseUrlFormat, repo)) + .GetAsync($"repos/{repo}/releases?per_page=2") // allow for draft release (only visible if GitHub repo is owned by same account as the update check credentials) .AsArray(); return results.FirstOrDefault(p => !p.IsDraft); } return await this.Client - .GetAsync(string.Format(this.StableReleaseUrlFormat, repo)) + .GetAsync($"repos/{repo}/releases/latest") .As(); } catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound) @@ -85,7 +92,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub /// Assert that a repository key is formatted correctly. /// The repository key (like Pathoschild/SMAPI). /// The repository key is invalid. - private void AssetKeyFormat(string repo) + private void AssertKeyFormat(string repo) { if (repo == null || !repo.Contains("/") || repo.IndexOf("/", StringComparison.InvariantCultureIgnoreCase) != repo.LastIndexOf("/", StringComparison.InvariantCultureIgnoreCase)) throw new ArgumentException($"The value '{repo}' isn't a valid GitHub repository key, must be a username and project name like 'Pathoschild/SMAPI'.", nameof(repo)); diff --git a/src/SMAPI.Web/Framework/Clients/GitHub/GitLicense.cs b/src/SMAPI.Web/Framework/Clients/GitHub/GitLicense.cs new file mode 100644 index 00000000..736efbe6 --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/GitHub/GitLicense.cs @@ -0,0 +1,20 @@ +using Newtonsoft.Json; + +namespace StardewModdingAPI.Web.Framework.Clients.GitHub +{ + /// The license info for a GitHub project. + internal class GitLicense + { + /// The license display name. + [JsonProperty("name")] + public string Name { get; set; } + + /// The SPDX ID for the license. + [JsonProperty("spdx_id")] + public string SpdxId { get; set; } + + /// The URL for the license info. + [JsonProperty("url")] + public string Url { get; set; } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/GitHub/GitRepo.cs b/src/SMAPI.Web/Framework/Clients/GitHub/GitRepo.cs new file mode 100644 index 00000000..7d80576e --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/GitHub/GitRepo.cs @@ -0,0 +1,20 @@ +using Newtonsoft.Json; + +namespace StardewModdingAPI.Web.Framework.Clients.GitHub +{ + /// Basic metadata about a GitHub project. + internal class GitRepo + { + /// The full repository name, including the owner. + [JsonProperty("full_name")] + public string FullName { get; set; } + + /// The URL to the repository web page, if any. + [JsonProperty("html_url")] + public string WebUrl { get; set; } + + /// The code license, if any. + [JsonProperty("license")] + public GitLicense License { get; set; } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/GitHub/IGitHubClient.cs b/src/SMAPI.Web/Framework/Clients/GitHub/IGitHubClient.cs index 9519c26f..a34f03bd 100644 --- a/src/SMAPI.Web/Framework/Clients/GitHub/IGitHubClient.cs +++ b/src/SMAPI.Web/Framework/Clients/GitHub/IGitHubClient.cs @@ -9,6 +9,11 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub /********* ** Methods *********/ + /// Get basic metadata for a GitHub repository, if available. + /// The repository key (like Pathoschild/SMAPI). + /// Returns the repository info if it exists, else null. + Task GetRepositoryAsync(string repo); + /// Get the latest release for a GitHub repository. /// The repository key (like Pathoschild/SMAPI). /// Whether to return a prerelease version if it's latest. diff --git a/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs b/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs index d2e9a2fe..a0a1f42a 100644 --- a/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs +++ b/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs @@ -29,12 +29,6 @@ namespace StardewModdingAPI.Web.Framework.ConfigModels /// The base URL for the GitHub API. public string GitHubBaseUrl { get; set; } - /// The URL for a GitHub API query for the latest stable release, excluding the , where {0} is the organisation and project name. - public string GitHubStableReleaseUrlFormat { get; set; } - - /// The URL for a GitHub API query for the latest release (including prerelease), excluding the , where {0} is the organisation and project name. - public string GitHubAnyReleaseUrlFormat { get; set; } - /// The Accept header value expected by the GitHub API. public string GitHubAcceptHeader { get; set; } diff --git a/src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs index 04c80dd2..c14fb45d 100644 --- a/src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs +++ b/src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs @@ -32,21 +32,19 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories { // validate ID format if (!uint.TryParse(id, out uint realID)) - return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid Chucklefish mod ID, must be an integer ID."); + return new ModInfoModel().SetError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid Chucklefish mod ID, must be an integer ID."); // fetch info try { var mod = await this.Client.GetModAsync(realID); - if (mod == null) - return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, "Found no Chucklefish mod with this ID."); - - // create model - return new ModInfoModel(name: mod.Name, version: this.NormaliseVersion(mod.Version), url: mod.Url); + return mod != null + ? new ModInfoModel(name: mod.Name, version: this.NormaliseVersion(mod.Version), url: mod.Url) + : new ModInfoModel().SetError(RemoteModStatus.DoesNotExist, "Found no Chucklefish mod with this ID."); } catch (Exception ex) { - return new ModInfoModel().WithError(RemoteModStatus.TemporaryError, ex.ToString()); + return new ModInfoModel().SetError(RemoteModStatus.TemporaryError, ex.ToString()); } } diff --git a/src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs index 614e00c2..0e254b39 100644 --- a/src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs +++ b/src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs @@ -30,36 +30,46 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories /// The mod ID in this repository. public override async Task GetModInfoAsync(string id) { + ModInfoModel result = new ModInfoModel().SetBasicInfo(id, $"https://github.com/{id}/releases"); + // validate ID format if (!id.Contains("/") || id.IndexOf("/", StringComparison.InvariantCultureIgnoreCase) != id.LastIndexOf("/", StringComparison.InvariantCultureIgnoreCase)) - return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid GitHub mod ID, must be a username and project name like 'Pathoschild/LookupAnything'."); + return result.SetError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid GitHub mod ID, must be a username and project name like 'Pathoschild/LookupAnything'."); // fetch info try { + // fetch repo info + GitRepo repository = await this.Client.GetRepositoryAsync(id); + if (repository == null) + return result.SetError(RemoteModStatus.DoesNotExist, "Found no GitHub repository for this ID."); + result + .SetBasicInfo(repository.FullName, $"{repository.WebUrl}/releases") + .SetLicense(url: repository.License?.Url, name: repository.License?.Name); + // get latest release (whether preview or stable) GitRelease latest = await this.Client.GetLatestReleaseAsync(id, includePrerelease: true); if (latest == null) - return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, "Found no GitHub release for this ID."); + return result.SetError(RemoteModStatus.DoesNotExist, "Found no GitHub release for this ID."); // split stable/prerelease if applicable GitRelease preview = null; if (latest.IsPrerelease) { - GitRelease result = await this.Client.GetLatestReleaseAsync(id, includePrerelease: false); - if (result != null) + GitRelease release = await this.Client.GetLatestReleaseAsync(id, includePrerelease: false); + if (release != null) { preview = latest; - latest = result; + latest = release; } } // return data - return new ModInfoModel(name: id, version: this.NormaliseVersion(latest.Tag), previewVersion: this.NormaliseVersion(preview?.Tag), url: $"https://github.com/{id}/releases"); + return result.SetVersions(version: this.NormaliseVersion(latest.Tag), previewVersion: this.NormaliseVersion(preview?.Tag)); } catch (Exception ex) { - return new ModInfoModel().WithError(RemoteModStatus.TemporaryError, ex.ToString()); + return result.SetError(RemoteModStatus.TemporaryError, ex.ToString()); } } diff --git a/src/SMAPI.Web/Framework/ModRepositories/ModDropRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/ModDropRepository.cs index 5703b34e..62142668 100644 --- a/src/SMAPI.Web/Framework/ModRepositories/ModDropRepository.cs +++ b/src/SMAPI.Web/Framework/ModRepositories/ModDropRepository.cs @@ -32,19 +32,19 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories { // validate ID format if (!long.TryParse(id, out long modDropID)) - return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid ModDrop mod ID, must be an integer ID."); + return new ModInfoModel().SetError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid ModDrop mod ID, must be an integer ID."); // fetch info try { ModDropMod mod = await this.Client.GetModAsync(modDropID); - if (mod == null) - return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, "Found no ModDrop mod with this ID."); - return new ModInfoModel(name: mod.Name, version: mod.LatestDefaultVersion?.ToString(), previewVersion: mod.LatestOptionalVersion?.ToString(), url: mod.Url); + return mod != null + ? new ModInfoModel(name: mod.Name, version: mod.LatestDefaultVersion?.ToString(), previewVersion: mod.LatestOptionalVersion?.ToString(), url: mod.Url) + : new ModInfoModel().SetError(RemoteModStatus.DoesNotExist, "Found no ModDrop mod with this ID."); } catch (Exception ex) { - return new ModInfoModel().WithError(RemoteModStatus.TemporaryError, ex.ToString()); + return new ModInfoModel().SetError(RemoteModStatus.TemporaryError, ex.ToString()); } } diff --git a/src/SMAPI.Web/Framework/ModRepositories/ModInfoModel.cs b/src/SMAPI.Web/Framework/ModRepositories/ModInfoModel.cs index 15e6c213..46b98860 100644 --- a/src/SMAPI.Web/Framework/ModRepositories/ModInfoModel.cs +++ b/src/SMAPI.Web/Framework/ModRepositories/ModInfoModel.cs @@ -18,6 +18,12 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories /// The mod's web URL. public string Url { get; set; } + /// The license URL, if available. + public string LicenseUrl { get; set; } + + /// The license name, if available. + public string LicenseName { get; set; } + /// The mod availability status on the remote site. public RemoteModStatus Status { get; set; } = RemoteModStatus.Ok; @@ -37,17 +43,49 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories /// The semantic version for the mod's latest preview release, if available and different from . /// The mod's web URL. public ModInfoModel(string name, string version, string url, string previewVersion = null) + { + this + .SetBasicInfo(name, url) + .SetVersions(version, previewVersion); + } + + /// Set the basic mod info. + /// The mod name. + /// The mod's web URL. + public ModInfoModel SetBasicInfo(string name, string url) { this.Name = name; + this.Url = url; + + return this; + } + + /// Set the mod version info. + /// The semantic version for the mod's latest release. + /// The semantic version for the mod's latest preview release, if available and different from . + public ModInfoModel SetVersions(string version, string previewVersion = null) + { this.Version = version; this.PreviewVersion = previewVersion; - this.Url = url; + + return this; + } + + /// Set the license info, if available. + /// The license URL. + /// The license name. + public ModInfoModel SetLicense(string url, string name) + { + this.LicenseUrl = url; + this.LicenseName = name; + + return this; } /// Set a mod error. /// The mod availability status on the remote site. /// The error message indicating why the mod is invalid (if applicable). - public ModInfoModel WithError(RemoteModStatus status, string error) + public ModInfoModel SetError(RemoteModStatus status, string error) { this.Status = status; this.Error = error; diff --git a/src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs index a4ae61eb..b4791f56 100644 --- a/src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs +++ b/src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs @@ -32,27 +32,27 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories { // validate ID format if (!uint.TryParse(id, out uint nexusID)) - return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid Nexus mod ID, must be an integer ID."); + return new ModInfoModel().SetError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid Nexus mod ID, must be an integer ID."); // fetch info try { NexusMod mod = await this.Client.GetModAsync(nexusID); if (mod == null) - return new ModInfoModel().WithError(RemoteModStatus.DoesNotExist, "Found no Nexus mod with this ID."); + return new ModInfoModel().SetError(RemoteModStatus.DoesNotExist, "Found no Nexus mod with this ID."); if (mod.Error != null) { RemoteModStatus remoteStatus = mod.Status == NexusModStatus.Hidden || mod.Status == NexusModStatus.NotPublished ? RemoteModStatus.DoesNotExist : RemoteModStatus.TemporaryError; - return new ModInfoModel().WithError(remoteStatus, mod.Error); + return new ModInfoModel().SetError(remoteStatus, mod.Error); } return new ModInfoModel(name: mod.Name, version: this.NormaliseVersion(mod.Version), previewVersion: mod.LatestFileVersion?.ToString(), url: mod.Url); } catch (Exception ex) { - return new ModInfoModel().WithError(RemoteModStatus.TemporaryError, ex.ToString()); + return new ModInfoModel().SetError(RemoteModStatus.TemporaryError, ex.ToString()); } } diff --git a/src/SMAPI.Web/Startup.cs b/src/SMAPI.Web/Startup.cs index 4d23fe65..33737235 100644 --- a/src/SMAPI.Web/Startup.cs +++ b/src/SMAPI.Web/Startup.cs @@ -121,8 +121,6 @@ namespace StardewModdingAPI.Web services.AddSingleton(new GitHubClient( baseUrl: api.GitHubBaseUrl, - stableReleaseUrlFormat: api.GitHubStableReleaseUrlFormat, - anyReleaseUrlFormat: api.GitHubAnyReleaseUrlFormat, userAgent: userAgent, acceptHeader: api.GitHubAcceptHeader, username: api.GitHubUsername, diff --git a/src/SMAPI.Web/appsettings.json b/src/SMAPI.Web/appsettings.json index 3ea37dea..f9777f87 100644 --- a/src/SMAPI.Web/appsettings.json +++ b/src/SMAPI.Web/appsettings.json @@ -30,8 +30,6 @@ "ChucklefishModPageUrlFormat": "resources/{0}", "GitHubBaseUrl": "https://api.github.com", - "GitHubStableReleaseUrlFormat": "repos/{0}/releases/latest", - "GitHubAnyReleaseUrlFormat": "repos/{0}/releases?per_page=2", // allow for draft release (only visible if GitHub repo is owned by same account as the update check credentials) "GitHubAcceptHeader": "application/vnd.github.v3+json", "GitHubUsername": null, // see top note "GitHubPassword": null, // see top note -- cgit From 85715988f987a2bf1e7016e9ad82e76ec44d4f94 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 31 Jul 2019 14:49:54 -0400 Subject: fix error when Chucklefish page doesn't exist for update checks --- docs/release-notes.md | 6 ++++-- src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index fd0cda51..9ee8ae8f 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -15,6 +15,10 @@ These changes have not been released yet. * Save Backup now works in the background, to avoid affecting startup time for players with a large number of saves. * Duplicate-mod errors now show the mod version in each folder. * Updated mod compatibility list. + * Improved update checks: + * Update checks are now faster in some cases. + * Fixed error if a Nexus mod is marked as adult content. + * Fixed error if the Chucklefish page for an update key doesn't exist. * Fixed mods needing to load custom `Map` assets before the game accesses them (SMAPI will now do so automatically). * Fixed Save Backup not pruning old backups if they're uncompressed. * Fixed issues when a farmhand reconnects before the game notices they're disconnected. @@ -25,8 +29,6 @@ These changes have not been released yet. * Fixed map reloads resetting tilesheet seasons. * Fixed map reloads not updating door warps. * Fixed outdoor tilesheets being seasonalised when added to an indoor location. - * Fixed update checks failing for Nexus mods marked as adult content. - * Fixed update checks not recognising releases on GitHub if they're not explicitly listed as update keys. * For the mod compatibility list: * Now loads faster (since data is fetched in a background service). diff --git a/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs b/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs index 2753e33a..939c32c6 100644 --- a/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs +++ b/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs @@ -45,7 +45,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.Chucklefish .GetAsync(string.Format(this.ModPageUrlFormat, id)) .AsString(); } - catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound) + catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound || ex.Status == HttpStatusCode.Forbidden) { return null; } -- cgit From 5e8991bfcf7f287f595e858c34b8ac1a92c42b9b Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 4 Aug 2019 18:55:06 -0400 Subject: tweak button names, update release notes (#654) --- docs/release-notes.md | 4 ++++ src/SMAPI.Web/Views/JsonValidator/Index.cshtml | 2 +- src/SMAPI.Web/Views/LogParser/Index.cshtml | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 9ee8ae8f..9ec33000 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -36,6 +36,10 @@ These changes have not been released yet. * Clicking a mod link now automatically adds it to the visible mods when the list is filtered. * Added metadata links and dev notes (if any) to advanced info. +* For the JSON validator: + * Added JSON validator at [json.smapi.io](https://json.smapi.io), which lets you validate a JSON file against predefined mod formats. + * Added support for the `manifest.json` format. + * For modders: * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialised when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialised). * Added support for content pack translations. diff --git a/src/SMAPI.Web/Views/JsonValidator/Index.cshtml b/src/SMAPI.Web/Views/JsonValidator/Index.cshtml index 5c3168e5..1cf35e39 100644 --- a/src/SMAPI.Web/Views/JsonValidator/Index.cshtml +++ b/src/SMAPI.Web/Views/JsonValidator/Index.cshtml @@ -72,7 +72,7 @@ else if (Model.PasteID != null)
  • Click this button:
    - +
  • diff --git a/src/SMAPI.Web/Views/LogParser/Index.cshtml b/src/SMAPI.Web/Views/LogParser/Index.cshtml index 1b40cfa9..e974c308 100644 --- a/src/SMAPI.Web/Views/LogParser/Index.cshtml +++ b/src/SMAPI.Web/Views/LogParser/Index.cshtml @@ -118,7 +118,7 @@ else if (Model.ParsedLog?.IsValid == true)
  • Click this button:
    - +
  • On the new page, copy the URL and send it to the person helping you.
  • -- cgit From 3331beb17a7bda439b281e7507ae187c68b6359c Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 5 Aug 2019 23:30:11 -0400 Subject: integrate Content Patcher schema into validator, update docs (#654) --- docs/release-notes.md | 1 + docs/technical/web.md | 1 + .../Controllers/JsonValidatorController.cs | 3 +- src/SMAPI.Web/wwwroot/schemas/content-patcher.json | 33 +++++++++++----------- 4 files changed, 21 insertions(+), 17 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 9ec33000..9ce88db1 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -39,6 +39,7 @@ These changes have not been released yet. * For the JSON validator: * Added JSON validator at [json.smapi.io](https://json.smapi.io), which lets you validate a JSON file against predefined mod formats. * Added support for the `manifest.json` format. + * Added support for Content Patcher's `content.json` format (thanks to TehPers!). * For modders: * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialised when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialised). diff --git a/docs/technical/web.md b/docs/technical/web.md index 0d2039d8..a008fe72 100644 --- a/docs/technical/web.md +++ b/docs/technical/web.md @@ -60,6 +60,7 @@ Current schemas: format | schema URL ------ | ---------- [SMAPI `manifest.json`](https://stardewvalleywiki.com/Modding:Modder_Guide/APIs/Manifest) | https://smapi.io/schemas/manifest.json +[Content Patcher `content.json`](https://github.com/Pathoschild/StardewMods/tree/develop/ContentPatcher#readme) | https://smapi.io/schemas/content-patcher.json ### Web API SMAPI provides a web API at `api.smapi.io` for use by SMAPI and external tools. The URL includes a diff --git a/src/SMAPI.Web/Controllers/JsonValidatorController.cs b/src/SMAPI.Web/Controllers/JsonValidatorController.cs index 41c07cee..9ded9c0d 100644 --- a/src/SMAPI.Web/Controllers/JsonValidatorController.cs +++ b/src/SMAPI.Web/Controllers/JsonValidatorController.cs @@ -39,7 +39,8 @@ namespace StardewModdingAPI.Web.Controllers private readonly IDictionary SchemaFormats = new Dictionary { ["none"] = "None", - ["manifest"] = "Manifest" + ["manifest"] = "Manifest", + ["content-patcher"] = "Content Patcher" }; /// The schema ID to use if none was specified. diff --git a/src/SMAPI.Web/wwwroot/schemas/content-patcher.json b/src/SMAPI.Web/wwwroot/schemas/content-patcher.json index e5810871..8dae5a98 100644 --- a/src/SMAPI.Web/wwwroot/schemas/content-patcher.json +++ b/src/SMAPI.Web/wwwroot/schemas/content-patcher.json @@ -3,6 +3,7 @@ "$id": "https://smapi.io/schemas/content-patcher.json", "title": "Content Patcher content pack", "description": "Content Patcher content file for mods", + "@documentationUrl": "https://github.com/Pathoschild/StardewMods/tree/develop/ContentPatcher#readme", "type": "object", "definitions": { "Version": { @@ -15,7 +16,7 @@ "title": "Action", "description": "The kind of change to make.", "type": "string", - "enum": ["Load", "EditImage", "EditData", "EditMap"] + "enum": [ "Load", "EditImage", "EditData", "EditMap" ] }, "Target": { "title": "Target asset", @@ -33,7 +34,7 @@ "anyOf": [ { "type": "string", - "enum": ["true", "false"] + "enum": [ "true", "false" ] }, { "type": "string", @@ -47,7 +48,7 @@ "$ref": "#/definitions/Condition" } }, - "required": ["Action", "Target"], + "required": [ "Action", "Target" ], "allOf": [ { "if": { @@ -105,7 +106,7 @@ "$ref": "#/definitions/FromFile" } }, - "required": ["FromFile"] + "required": [ "FromFile" ] }, "EditImageChange": { "properties": { @@ -126,10 +127,10 @@ "title": "Patch mode", "description": "How to apply FromArea to ToArea. Defaults to Replace.", "type": "string", - "enum": ["Replace", "Overlay"] + "enum": [ "Replace", "Overlay" ] } }, - "required": ["FromFile"] + "required": [ "FromFile" ] }, "EditDataChange": { "properties": { @@ -166,7 +167,7 @@ "type": "string" } }, - "required": ["ID", "BeforeID"], + "required": [ "ID", "BeforeID" ], "additionalProperties": false }, { @@ -178,7 +179,7 @@ "type": "string" } }, - "required": ["ID", "AfterID"], + "required": [ "ID", "AfterID" ], "additionalProperties": false }, { @@ -187,14 +188,14 @@ "ToPosition": { "title": "To position", "description": "Move entry so it's right at this position", - "enum": ["Top", "Bottom"] + "enum": [ "Top", "Bottom" ] } }, - "required": ["ID", "ToPosition"], + "required": [ "ID", "ToPosition" ], "additionalProperties": false } ], - "required": ["ID"] + "required": [ "ID" ] } } } @@ -216,7 +217,7 @@ "$ref": "#/definitions/Rectangle" } }, - "required": ["FromFile", "ToArea"] + "required": [ "FromFile", "ToArea" ] }, "Config": { "type": "object", @@ -250,10 +251,10 @@ "const": false } }, - "required": ["AllowBlank"] + "required": [ "AllowBlank" ] }, "then": { - "required": ["Default"] + "required": [ "Default" ] } } }, @@ -282,7 +283,7 @@ "$ref": "#/definitions/Condition" } }, - "required": ["Name", "Value"] + "required": [ "Name", "Value" ] }, "FromFile": { "title": "Source file", @@ -354,5 +355,5 @@ "format": "uri" } }, - "required": ["Format", "Changes"] + "required": [ "Format", "Changes" ] } -- cgit From 674ceea74e74c5b0f432534dba981b5066ea7630 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Tue, 6 Aug 2019 03:19:38 -0400 Subject: add support for transparent schema errors (#654) --- docs/release-notes.md | 3 +- docs/technical/web.md | 101 +++++++++++++-------- .../Controllers/JsonValidatorController.cs | 89 +++++++++++------- 3 files changed, 124 insertions(+), 69 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 9ce88db1..e253c3c0 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -39,7 +39,8 @@ These changes have not been released yet. * For the JSON validator: * Added JSON validator at [json.smapi.io](https://json.smapi.io), which lets you validate a JSON file against predefined mod formats. * Added support for the `manifest.json` format. - * Added support for Content Patcher's `content.json` format (thanks to TehPers!). + * Added support for the Content Patcher format (thanks to TehPers!). + * Added support for referencing a schema in a JSON Schema-compatible text editor. * For modders: * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialised when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialised). diff --git a/docs/technical/web.md b/docs/technical/web.md index 108e3671..91af2f98 100644 --- a/docs/technical/web.md +++ b/docs/technical/web.md @@ -4,50 +4,77 @@ and update check API. ## Contents -* [Overview](#overview) - * [Log parser](#log-parser) - * [JSON validator](#json-validator) - * [Web API](#web-api) +* [Log parser](#log-parser) +* [JSON validator](#json-validator) +* [Web API](#web-api) * [For SMAPI developers](#for-smapi-developers) * [Local development](#local-development) * [Deploying to Amazon Beanstalk](#deploying-to-amazon-beanstalk) -## Overview -The `SMAPI.Web` project provides an API and web UI hosted at `*.smapi.io`. - -### Log parser +## Log parser The log parser provides a web UI for uploading, parsing, and sharing SMAPI logs. The logs are persisted in a compressed form to Pastebin. The log parser lives at https://log.smapi.io. -### JSON validator -The JSON validator provides a web UI for uploading and sharing JSON files, and validating them -as plain JSON or against a predefined format like `manifest.json` or Content Patcher's -`content.json`. The JSON validator lives at https://json.smapi.io. +## JSON validator +### Overview +The JSON validator provides a web UI for uploading and sharing JSON files, and validating them as +plain JSON or against a predefined format like `manifest.json` or Content Patcher's `content.json`. +The JSON validator lives at https://json.smapi.io. +### Schema file format Schema files are defined in `wwwroot/schemas` using the [JSON Schema](https://json-schema.org/) -format, with some special properties: -* The root schema may have a `@documentationURL` field, which is the URL to the user-facing - documentation for the format (if any). -* Any part of the schema can define an `@errorMessages` field, which specifies user-friendly errors - which override the auto-generated messages. These can be indexed by error type: - ```js - "pattern": "^[a-zA-Z0-9_.-]+\\.dll$", - "@errorMessages": { - "pattern": "Invalid value; must be a filename ending with .dll." - } - ``` - ...or by error type and a regular expression applied to the default message (not recommended - unless the previous form doesn't work, since it's more likely to break in future versions): - ```js - "@errorMessages": { - "oneOf:valid against no schemas": "Missing required field: EntryDll or ContentPackFor.", - "oneOf:valid against more than one schema": "Can't specify both EntryDll or ContentPackFor, they're mutually exclusive." - } - ``` - Error messages can optionally include a `@value` token, which will be replaced with the error's - value field (which is usually the original field value). - -You can also reference these schemas in your JSON file directly using the `$schema` field, for +format. The JSON validator UI recognises a superset of the standard fields to change output: + +
    +
    Documentation URL
    +
    + +The root schema may have a `@documentationURL` field, which is a web URL for the user +documentation: +```js +"@documentationUrl": "https://stardewvalleywiki.com/Modding:Modder_Guide/APIs/Manifest" +``` + +If present, this is shown in the JSON validator UI. + +
    +
    Error messages
    +
    + +Any part of the schema can define an `@errorMessages` field, which overrides matching schema +errors. You can override by error code (recommended), or by error type and a regex pattern matched +against the error message (more fragile): + +```js +// by error type +"pattern": "^[a-zA-Z0-9_.-]+\\.dll$", +"@errorMessages": { + "pattern": "Invalid value; must be a filename ending with .dll." +} +``` +```js +// by error type + message pattern +"@errorMessages": { + "oneOf:valid against no schemas": "Missing required field: EntryDll or ContentPackFor.", + "oneOf:valid against more than one schema": "Can't specify both EntryDll or ContentPackFor, they're mutually exclusive." +} +``` + +Error messages may contain special tokens: +* `@value` is replaced with the error's value field (which is usually the original field value, but + not always). +* If the validation error has exactly one sub-error and the message is set to `$transparent`, the + sub-error will be displayed instead. (The sub-error itself may be set to `$transparent`, etc.) + +Caveats: +* To override an error from a `then` block, the `@errorMessages` must be inside the `then` block + instead of adjacent. + +
    +
    + +### Using a schema file directly +You can reference the validator schemas in your JSON file directly using the `$schema` field, for text editors that support schema validation. For example: ```js { @@ -64,11 +91,13 @@ format | schema URL [SMAPI `manifest.json`](https://stardewvalleywiki.com/Modding:Modder_Guide/APIs/Manifest) | https://smapi.io/schemas/manifest.json [Content Patcher `content.json`](https://github.com/Pathoschild/StardewMods/tree/develop/ContentPatcher#readme) | https://smapi.io/schemas/content-patcher.json -### Web API +## Web API +### Overview SMAPI provides a web API at `api.smapi.io` for use by SMAPI and external tools. The URL includes a `{version}` token, which is the SMAPI version for backwards compatibility. This API is publicly accessible but not officially released; it may change at any time. +### `/mods` endpoint The API has one `/mods` endpoint. This provides mod info, including official versions and URLs (from Chucklefish, GitHub, or Nexus), unofficial versions from the wiki, and optional mod metadata from the wiki and SMAPI's internal data. This is used by SMAPI to perform update checks, and by diff --git a/src/SMAPI.Web/Controllers/JsonValidatorController.cs b/src/SMAPI.Web/Controllers/JsonValidatorController.cs index c23103dd..cd0a6439 100644 --- a/src/SMAPI.Web/Controllers/JsonValidatorController.cs +++ b/src/SMAPI.Web/Controllers/JsonValidatorController.cs @@ -124,7 +124,7 @@ namespace StardewModdingAPI.Web.Controllers // validate JSON parsed.IsValid(schema, out IList rawErrors); var errors = rawErrors - .Select(error => new JsonValidatorErrorModel(error.LineNumber, error.Path, this.GetFlattenedError(error), error.ErrorType)) + .Select(this.GetErrorModel) .ToArray(); return this.View("Index", result.AddErrors(errors)); } @@ -175,35 +175,6 @@ namespace StardewModdingAPI.Web.Controllers return response; } - /// Get a flattened, human-readable message representing a schema validation error. - /// The error to represent. - /// The indentation level to apply for inner errors. - private string GetFlattenedError(ValidationError error, int indent = 0) - { - // get override error - string message = this.GetOverrideError(error); - if (message != null) - return message; - - // get friendly representation of main error - message = error.Message; - switch (error.ErrorType) - { - case ErrorType.Enum: - message = $"Invalid value. Found '{error.Value}', but expected one of '{string.Join("', '", error.Schema.Enum)}'."; - break; - - case ErrorType.Required: - message = $"Missing required fields: {string.Join(", ", (List)error.Value)}."; - break; - } - - // add inner errors - foreach (ValidationError childError in error.ChildErrors) - message += "\n" + "".PadLeft(indent * 2, ' ') + $"==> {childError.Path}: " + this.GetFlattenedError(childError, indent + 1); - return message; - } - /// Get a normalised schema name, or the if blank. /// The raw schema name to normalise. private string NormaliseSchemaName(string schemaName) @@ -234,6 +205,60 @@ namespace StardewModdingAPI.Web.Controllers return null; } + /// Get a flattened representation representation of a schema validation error and any child errors. + /// The error to represent. + private JsonValidatorErrorModel GetErrorModel(ValidationError error) + { + // skip through transparent errors + while (this.GetOverrideError(error) == "$transparent" && error.ChildErrors.Count == 1) + error = error.ChildErrors[0]; + + // get message + string message = this.GetOverrideError(error); + if (message == null) + message = this.FlattenErrorMessage(error); + + // build model + return new JsonValidatorErrorModel(error.LineNumber, error.Path, message, error.ErrorType); + } + + /// Get a flattened, human-readable message for a schema validation error and any child errors. + /// The error to represent. + /// The indentation level to apply for inner errors. + private string FlattenErrorMessage(ValidationError error, int indent = 0) + { + // get override + string message = this.GetOverrideError(error); + if (message != null) + return message; + + // skip through transparent errors + while (this.GetOverrideError(error) == "$transparent" && error.ChildErrors.Count == 1) + error = error.ChildErrors[0]; + + // get friendly representation of main error + message = error.Message; + switch (error.ErrorType) + { + case ErrorType.Const: + message = $"Invalid value. Found '{error.Value}', but expected '{error.Schema.Const}'."; + break; + + case ErrorType.Enum: + message = $"Invalid value. Found '{error.Value}', but expected one of '{string.Join("', '", error.Schema.Enum)}'."; + break; + + case ErrorType.Required: + message = $"Missing required fields: {string.Join(", ", (List)error.Value)}."; + break; + } + + // add inner errors + foreach (ValidationError childError in error.ChildErrors) + message += "\n" + "".PadLeft(indent * 2, ' ') + $"==> {childError.Path}: " + this.FlattenErrorMessage(childError, indent + 1); + return message; + } + /// Get an override error from the JSON schema, if any. /// The schema validation error. private string GetOverrideError(ValidationError error) @@ -254,12 +279,12 @@ namespace StardewModdingAPI.Web.Controllers string[] parts = pair.Key.Split(':', 2); if (parts[0].Equals(error.ErrorType.ToString(), StringComparison.InvariantCultureIgnoreCase) && Regex.IsMatch(error.Message, parts[1])) - return pair.Value; + return pair.Value?.Trim(); } // match by type if (errors.TryGetValue(error.ErrorType.ToString(), out string message)) - return message; + return message?.Trim(); return null; } -- cgit From fd77ae93d59222d70c86aebfc044f3af11063372 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 9 Aug 2019 01:18:05 -0400 Subject: fix typos and inconsistent spelling --- .gitattributes | 2 +- docs/release-notes.md | 49 ++++---- src/SMAPI.Installer/InteractiveInstaller.cs | 12 +- src/SMAPI.Installer/Program.cs | 2 +- .../ConsoleWriting/ColorfulConsoleWriter.cs | 2 +- .../Mock/Netcode/NetFieldBase.cs | 2 +- .../NetFieldAnalyzer.cs | 8 +- .../ObsoleteFieldAnalyzer.cs | 2 +- .../Framework/ModFileManager.cs | 4 +- .../Framework/Commands/Player/AddCommand.cs | 2 +- .../Framework/Commands/Player/ListItemsCommand.cs | 4 +- .../Framework/Commands/World/SetTimeCommand.cs | 2 +- src/SMAPI.Tests/Core/ModResolverTests.cs | 12 +- src/SMAPI.Tests/Core/TranslationTests.cs | 2 +- src/SMAPI.Tests/Toolkit/PathUtilitiesTests.cs | 6 +- src/SMAPI.Tests/Utilities/SemanticVersionTests.cs | 8 +- .../ISemanticVersion.cs | 2 +- .../Clients/WebApi/ModExtendedMetadataModel.cs | 4 +- .../Framework/Clients/WebApi/ModSeachModel.cs | 2 +- .../Clients/WebApi/ModSearchEntryModel.cs | 2 +- .../Framework/Clients/WebApi/WebApiClient.cs | 2 +- .../Framework/GameScanning/GameScanner.cs | 2 +- .../Framework/ModData/ModDataModel.cs | 4 +- .../Framework/ModData/ModDataRecord.cs | 6 +- .../ModData/ModDataRecordVersionedFields.cs | 4 +- src/SMAPI.Toolkit/Framework/ModData/ModWarning.cs | 4 +- .../Framework/ModScanning/ModFolder.cs | 2 +- .../Framework/ModScanning/ModScanner.cs | 6 +- src/SMAPI.Toolkit/ModToolkit.cs | 2 +- src/SMAPI.Toolkit/SemanticVersion.cs | 24 ++-- .../Converters/ManifestContentPackForConverter.cs | 50 -------- .../Converters/ManifestDependencyArrayConverter.cs | 60 --------- .../Converters/SemanticVersionConverter.cs | 86 ------------- .../Converters/SimpleReadOnlyConverter.cs | 76 ------------ .../Serialisation/InternalExtensions.cs | 21 ---- src/SMAPI.Toolkit/Serialisation/JsonHelper.cs | 136 --------------------- src/SMAPI.Toolkit/Serialisation/Models/Manifest.cs | 74 ----------- .../Serialisation/Models/ManifestContentPackFor.cs | 15 --- .../Serialisation/Models/ManifestDependency.cs | 35 ------ src/SMAPI.Toolkit/Serialisation/SParseException.cs | 17 --- .../Converters/ManifestContentPackForConverter.cs | 50 ++++++++ .../Converters/ManifestDependencyArrayConverter.cs | 60 +++++++++ .../Converters/SemanticVersionConverter.cs | 86 +++++++++++++ .../Converters/SimpleReadOnlyConverter.cs | 76 ++++++++++++ .../Serialization/InternalExtensions.cs | 21 ++++ src/SMAPI.Toolkit/Serialization/JsonHelper.cs | 136 +++++++++++++++++++++ src/SMAPI.Toolkit/Serialization/Models/Manifest.cs | 74 +++++++++++ .../Serialization/Models/ManifestContentPackFor.cs | 15 +++ .../Serialization/Models/ManifestDependency.cs | 35 ++++++ src/SMAPI.Toolkit/Serialization/SParseException.cs | 17 +++ src/SMAPI.Toolkit/Utilities/PathUtilities.cs | 20 +-- src/SMAPI.Web/BackgroundService.cs | 6 +- .../Controllers/JsonValidatorController.cs | 14 +-- src/SMAPI.Web/Controllers/ModsApiController.cs | 2 +- .../Framework/AllowLargePostsAttribute.cs | 2 +- .../Framework/Caching/Mods/ModCacheRepository.cs | 10 +- .../Caching/UtcDateTimeOffsetSerializer.cs | 2 +- .../Framework/JobDashboardAuthorizationFilter.cs | 4 +- src/SMAPI.Web/Framework/LogParsing/LogParser.cs | 2 +- .../Framework/ModRepositories/BaseRepository.cs | 6 +- .../ModRepositories/ChucklefishRepository.cs | 2 +- .../Framework/ModRepositories/GitHubRepository.cs | 2 +- .../Framework/ModRepositories/NexusRepository.cs | 2 +- src/SMAPI.Web/Startup.cs | 2 +- src/SMAPI.Web/ViewModels/LogParserModel.cs | 2 +- src/SMAPI.Web/wwwroot/Content/js/json-validator.js | 2 +- src/SMAPI.Web/wwwroot/schemas/content-patcher.json | 6 +- src/SMAPI.sln.DotSettings | 42 +++++++ src/SMAPI/Context.cs | 4 +- src/SMAPI/Enums/LoadStage.cs | 10 +- src/SMAPI/Events/IGameLoopEvents.cs | 4 +- src/SMAPI/Events/IModEvents.cs | 4 +- src/SMAPI/Events/ISpecialisedEvents.cs | 4 +- src/SMAPI/Events/LoadStageChangedEventArgs.cs | 2 +- .../Events/UnvalidatedUpdateTickedEventArgs.cs | 2 +- .../Events/UnvalidatedUpdateTickingEventArgs.cs | 2 +- src/SMAPI/Framework/CommandManager.cs | 14 +-- src/SMAPI/Framework/Content/AssetData.cs | 10 +- .../Framework/Content/AssetDataForDictionary.cs | 10 +- src/SMAPI/Framework/Content/AssetDataForImage.cs | 10 +- src/SMAPI/Framework/Content/AssetDataForObject.cs | 20 +-- src/SMAPI/Framework/Content/AssetInfo.cs | 22 ++-- src/SMAPI/Framework/Content/ContentCache.cs | 30 ++--- src/SMAPI/Framework/ContentCoordinator.cs | 8 +- .../ContentManagers/BaseContentManager.cs | 34 +++--- .../ContentManagers/GameContentManager.cs | 58 ++++----- .../Framework/ContentManagers/IContentManager.cs | 10 +- .../Framework/ContentManagers/ModContentManager.cs | 28 ++--- src/SMAPI/Framework/ContentPack.cs | 10 +- src/SMAPI/Framework/Events/EventManager.cs | 18 +-- src/SMAPI/Framework/Events/ModEvents.cs | 6 +- src/SMAPI/Framework/Events/ModGameLoopEvents.cs | 2 +- src/SMAPI/Framework/Events/ModSpecialisedEvents.cs | 6 +- src/SMAPI/Framework/GameVersion.cs | 2 +- src/SMAPI/Framework/InternalExtensions.cs | 2 +- src/SMAPI/Framework/ModHelpers/ContentHelper.cs | 14 +-- .../Framework/ModHelpers/ContentPackHelper.cs | 4 +- src/SMAPI/Framework/ModHelpers/DataHelper.cs | 12 +- src/SMAPI/Framework/ModHelpers/ModHelper.cs | 4 +- .../Framework/ModHelpers/ModRegistryHelper.cs | 4 +- src/SMAPI/Framework/ModHelpers/ReflectionHelper.cs | 2 +- src/SMAPI/Framework/ModLoading/AssemblyLoader.cs | 10 +- .../Framework/ModLoading/Finders/TypeFinder.cs | 2 +- .../ModLoading/InstructionHandleResult.cs | 4 +- .../Framework/ModLoading/ModDependencyStatus.cs | 4 +- src/SMAPI/Framework/ModLoading/ModResolver.cs | 8 +- .../Framework/ModLoading/TypeReferenceComparer.cs | 2 +- src/SMAPI/Framework/ModRegistry.cs | 6 +- src/SMAPI/Framework/Monitor.cs | 2 +- src/SMAPI/Framework/Networking/MessageType.cs | 2 +- src/SMAPI/Framework/Reflection/Reflector.cs | 2 +- src/SMAPI/Framework/SCore.cs | 56 ++++----- src/SMAPI/Framework/SGame.cs | 50 ++++---- src/SMAPI/Framework/SGameConstructorHack.cs | 4 +- src/SMAPI/Framework/SMultiplayer.cs | 20 +-- .../Framework/Serialisation/ColorConverter.cs | 47 ------- .../Framework/Serialisation/PointConverter.cs | 43 ------- .../Framework/Serialisation/RectangleConverter.cs | 52 -------- .../Framework/Serialization/ColorConverter.cs | 47 +++++++ .../Framework/Serialization/PointConverter.cs | 43 +++++++ .../Framework/Serialization/RectangleConverter.cs | 52 ++++++++ .../FieldWatchers/ComparableListWatcher.cs | 2 +- src/SMAPI/IAssetInfo.cs | 6 +- src/SMAPI/IContentHelper.cs | 4 +- src/SMAPI/IContentPack.cs | 2 +- src/SMAPI/IContentPackHelper.cs | 2 +- src/SMAPI/IDataHelper.cs | 2 +- src/SMAPI/Metadata/CoreAssetPropagator.cs | 42 +++---- src/SMAPI/Metadata/InstructionMetadata.cs | 10 +- src/SMAPI/Mod.cs | 2 +- src/SMAPI/Program.cs | 4 +- src/SMAPI/SemanticVersion.cs | 4 +- src/SMAPI/Translation.cs | 4 +- src/SMAPI/Utilities/SDate.cs | 6 +- 134 files changed, 1207 insertions(+), 1164 deletions(-) delete mode 100644 src/SMAPI.Toolkit/Serialisation/Converters/ManifestContentPackForConverter.cs delete mode 100644 src/SMAPI.Toolkit/Serialisation/Converters/ManifestDependencyArrayConverter.cs delete mode 100644 src/SMAPI.Toolkit/Serialisation/Converters/SemanticVersionConverter.cs delete mode 100644 src/SMAPI.Toolkit/Serialisation/Converters/SimpleReadOnlyConverter.cs delete mode 100644 src/SMAPI.Toolkit/Serialisation/InternalExtensions.cs delete mode 100644 src/SMAPI.Toolkit/Serialisation/JsonHelper.cs delete mode 100644 src/SMAPI.Toolkit/Serialisation/Models/Manifest.cs delete mode 100644 src/SMAPI.Toolkit/Serialisation/Models/ManifestContentPackFor.cs delete mode 100644 src/SMAPI.Toolkit/Serialisation/Models/ManifestDependency.cs delete mode 100644 src/SMAPI.Toolkit/Serialisation/SParseException.cs create mode 100644 src/SMAPI.Toolkit/Serialization/Converters/ManifestContentPackForConverter.cs create mode 100644 src/SMAPI.Toolkit/Serialization/Converters/ManifestDependencyArrayConverter.cs create mode 100644 src/SMAPI.Toolkit/Serialization/Converters/SemanticVersionConverter.cs create mode 100644 src/SMAPI.Toolkit/Serialization/Converters/SimpleReadOnlyConverter.cs create mode 100644 src/SMAPI.Toolkit/Serialization/InternalExtensions.cs create mode 100644 src/SMAPI.Toolkit/Serialization/JsonHelper.cs create mode 100644 src/SMAPI.Toolkit/Serialization/Models/Manifest.cs create mode 100644 src/SMAPI.Toolkit/Serialization/Models/ManifestContentPackFor.cs create mode 100644 src/SMAPI.Toolkit/Serialization/Models/ManifestDependency.cs create mode 100644 src/SMAPI.Toolkit/Serialization/SParseException.cs delete mode 100644 src/SMAPI/Framework/Serialisation/ColorConverter.cs delete mode 100644 src/SMAPI/Framework/Serialisation/PointConverter.cs delete mode 100644 src/SMAPI/Framework/Serialisation/RectangleConverter.cs create mode 100644 src/SMAPI/Framework/Serialization/ColorConverter.cs create mode 100644 src/SMAPI/Framework/Serialization/PointConverter.cs create mode 100644 src/SMAPI/Framework/Serialization/RectangleConverter.cs (limited to 'docs/release-notes.md') diff --git a/.gitattributes b/.gitattributes index 67d0626d..1161a204 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,3 @@ -# normalise line endings +# normalize line endings * text=auto README.txt text=crlf diff --git a/docs/release-notes.md b/docs/release-notes.md index e253c3c0..5f964cfd 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -29,6 +29,7 @@ These changes have not been released yet. * Fixed map reloads resetting tilesheet seasons. * Fixed map reloads not updating door warps. * Fixed outdoor tilesheets being seasonalised when added to an indoor location. + * Fixed typos and inconsistent spelling. * For the mod compatibility list: * Now loads faster (since data is fetched in a background service). @@ -43,7 +44,7 @@ These changes have not been released yet. * Added support for referencing a schema in a JSON Schema-compatible text editor. * For modders: - * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialised when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialised). + * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialized when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialized). * Added support for content pack translations. * Added fields and methods: `IContentPack.HasFile`, `Context.IsGameLaunched`, and `SemanticVersion.TryParse`. * Added separate `LogNetworkTraffic` option to make verbose logging less overwhelmingly verbose. @@ -53,7 +54,7 @@ These changes have not been released yet. * Trace logs when loading mods are now more clear. * Clarified update-check errors for mods with multiple update keys. * Fixed custom maps loaded from `.xnb` files not having their tilesheet paths automatically adjusted. - * Fixed custom maps loaded from the mod folder with tilesheets in a subfolder not working crossplatform. All tilesheet paths are now normalised for the OS automatically. + * Fixed custom maps loaded from the mod folder with tilesheets in a subfolder not working crossplatform. All tilesheet paths are now normalized for the OS automatically. * Removed all deprecated APIs. * Removed the `Monitor.ExitGameImmediately` method. * Updated dependencies (including Json.NET 11.0.2 → 12.0.2, Mono.Cecil 0.10.1 → 0.10.4). @@ -73,7 +74,7 @@ Released 13 September 2019 for Stardew Valley 1.3.36. * For the web UI: * When filtering the mod list, clicking a mod link now automatically adds it to the visible mods. * Added log parser instructions for Android. - * Fixed log parser failing in some cases due to time format localisation. + * Fixed log parser failing in some cases due to time format localization. * For modders: * `this.Monitor.Log` now defaults to the `Trace` log level instead of `Debug`. The change will only take effect when you recompile the mod. @@ -141,12 +142,12 @@ Released 09 January 2019 for Stardew Valley 1.3.32–33. * Added locale to context trace logs. * Fixed error loading custom map tilesheets in some cases. * Fixed error when swapping maps mid-session for a location with interior doors. - * Fixed `Constants.SaveFolderName` and `CurrentSavePath` not available during early load stages when using `Specialised.LoadStageChanged` event. + * Fixed `Constants.SaveFolderName` and `CurrentSavePath` not available during early load stages when using `Specialized.LoadStageChanged` event. * Fixed `LoadStage.SaveParsed` raised before the parsed save data is available. * Fixed 'unknown mod' deprecation warnings showing the wrong stack trace. * Fixed `e.Cursor` in input events showing wrong grab tile when player using a controller moves without moving the viewpoint. - * Fixed incorrect 'bypassed safety checks' warning for mods using the new `Specialised.LoadStageChanged` event in 2.10. - * Deprecated `EntryDll` values whose capitalisation don't match the actual file. (This works on Windows, but causes errors for Linux/Mac players.) + * Fixed incorrect 'bypassed safety checks' warning for mods using the new `Specialized.LoadStageChanged` event in 2.10. + * Deprecated `EntryDll` values whose capitalization don't match the actual file. (This works on Windows, but causes errors for Linux/Mac players.) ## 2.10.1 Released 30 December 2018 for Stardew Valley 1.3.32–33. @@ -163,9 +164,9 @@ Released 29 December 2018 for Stardew Valley 1.3.32–33. * Tweaked installer to reduce antivirus false positives. * For modders: - * Added [events](https://stardewvalleywiki.com/Modding:Modder_Guide/APIs/Events): `GameLoop.OneSecondUpdateTicking`, `GameLoop.OneSecondUpdateTicked`, and `Specialised.LoadStageChanged`. + * Added [events](https://stardewvalleywiki.com/Modding:Modder_Guide/APIs/Events): `GameLoop.OneSecondUpdateTicking`, `GameLoop.OneSecondUpdateTicked`, and `Specialized.LoadStageChanged`. * Added `e.IsCurrentLocation` event arg to `World` events. - * You can now use `helper.Data.Read/WriteSaveData` as soon as the save is loaded (instead of once the world is initialised). + * You can now use `helper.Data.Read/WriteSaveData` as soon as the save is loaded (instead of once the world is initialized). * Increased deprecation levels to _info_ for the upcoming SMAPI 3.0. * For the web UI: @@ -338,7 +339,7 @@ Released 14 August 2018 for Stardew Valley 1.3.28. * dialogue; * map tilesheets. * Added `--mods-path` CLI command-line argument to switch between mod folders. - * All enums are now JSON-serialised by name instead of numeric value. (Previously only a few enums were serialised that way. JSON files which already have numeric enum values will still be parsed fine.) + * All enums are now JSON-serialized by name instead of numeric value. (Previously only a few enums were serialized that way. JSON files which already have numeric enum values will still be parsed fine.) * Fixed false compatibility error when constructing multidimensional arrays. * Fixed `.ToSButton()` methods not being public. @@ -365,7 +366,7 @@ Released 01 August 2018 for Stardew Valley 1.3.27. * Improved the Console Commands mod: * Added `player_add name`, which adds items to your inventory by name instead of ID. * Fixed `world_setseason` not running season-change logic. - * Fixed `world_setseason` not normalising the season value. + * Fixed `world_setseason` not normalizing the season value. * Fixed `world_settime` sometimes breaking NPC schedules (e.g. so they stay in bed). * Removed the `player_setlevel` and `player_setspeed` commands, which weren't implemented in a useful way. Use a mod like CJB Cheats Menu if you need those. * Fixed `SEHException` errors for some players. @@ -456,7 +457,7 @@ Released 11 April 2018 for Stardew Valley 1.2.30–1.2.33. * Fixed mod update alerts not shown if one mod has an invalid remote version. * Fixed SMAPI update alerts linking to the GitHub repository instead of [smapi.io](https://smapi.io). * Fixed SMAPI update alerts for draft releases. - * Fixed error when two content packs use different capitalisation for the same required mod ID. + * Fixed error when two content packs use different capitalization for the same required mod ID. * Fixed rare crash if the game duplicates an item. * For the [log parser](https://log.smapi.io): @@ -531,8 +532,8 @@ Released 24 February 2018 for Stardew Valley 1.2.30–1.2.33. * For modders: * Added support for content packs and new APIs to read them. * Added support for `ISemanticVersion` in JSON models. - * Added `SpecialisedEvents.UnvalidatedUpdateTick` event for specialised use cases. - * Added path normalising to `ReadJsonFile` and `WriteJsonFile` helpers (so no longer need `Path.Combine` with those). + * Added `SpecializedEvents.UnvalidatedUpdateTick` event for specialized use cases. + * Added path normalizing to `ReadJsonFile` and `WriteJsonFile` helpers (so no longer need `Path.Combine` with those). * Fixed deadlock in rare cases with asset loaders. * Fixed unhelpful error when a mod exposes a non-public API. * Fixed unhelpful error when a translation file has duplicate keys due to case-insensitivity. @@ -585,11 +586,11 @@ Released 26 December 2017 for Stardew Valley 1.2.30–1.2.33. * For modders: * **Added mod-provided APIs** to allow simple integrations between mods, even without direct assembly references. - * Added `GameEvents.FirstUpdateTick` event (called once after all mods are initialised). + * Added `GameEvents.FirstUpdateTick` event (called once after all mods are initialized). * Added `IsSuppressed` to input events so mods can optionally avoid handling keys another mod has already handled. * Added trace message for mods with no update keys. * Adjusted reflection API to match actual usage (e.g. renamed `GetPrivate*` to `Get*`), and deprecated previous methods. - * Fixed `GraphicsEvents.OnPostRenderEvent` not being raised in some specialised cases. + * Fixed `GraphicsEvents.OnPostRenderEvent` not being raised in some specialized cases. * Fixed reflection API error for properties missing a `get` and `set`. * Fixed issue where a mod could change the cursor position reported to other mods. * Updated compatibility list. @@ -614,7 +615,7 @@ Released 02 December 2017 for Stardew Valley 1.2.30–1.2.33. * Slightly improved the UI. * For modders: - * Added `helper.Content.NormaliseAssetName` method. + * Added `helper.Content.NormalizeAssetName` method. * Added `SDate.DaysSinceStart` property. * Fixed input events' `e.SuppressButton(button)` method ignoring specified button. * Fixed input events' `e.SuppressButton()` method not working with mouse buttons. @@ -769,7 +770,7 @@ For mod developers: * Added content helper properties for the game's current language. * Fixed `Context.IsPlayerFree` being false if the player is performing an action. * Fixed `GraphicsEvents.Resize` being raised before the game updates its window data. -* Fixed `SemanticVersion` not being deserialisable through Json.NET. +* Fixed `SemanticVersion` not being deserializable through Json.NET. * Fixed terminal not launching on Xfce Linux. For SMAPI developers: @@ -840,7 +841,7 @@ For modders: * SMAPI now automatically fixes tilesheet references for maps loaded from the mod folder. _When loading a map from the mod folder, SMAPI will automatically use tilesheets relative to the map file if they exists. Otherwise it will default to tilesheets in the game content._ * Added `Context.IsPlayerFree` for mods that need to check if the player can act (i.e. save is loaded, no menu is displayed, no cutscene is in progress, etc). -* Added `Context.IsInDrawLoop` for specialised mods. +* Added `Context.IsInDrawLoop` for specialized mods. * Fixed `smapi-crash.txt` being copied from the default log even if a different path is specified with `--log-path`. * Fixed the content API not matching XNB filenames with two dots (like `a.b.xnb`) if you don't specify the `.xnb` extension. * Fixed `debug` command output not printed to console. @@ -867,7 +868,7 @@ For players: For mod developers: * Added a `Context.IsWorldReady` flag for mods to use. - _This indicates whether a save is loaded and the world is finished initialising, which starts at the same point that `SaveEvents.AfterLoad` and `TimeEvents.AfterDayStarted` are raised. This is mainly useful for events which can be raised before the world is loaded (like update tick)._ + _This indicates whether a save is loaded and the world is finished initializing, which starts at the same point that `SaveEvents.AfterLoad` and `TimeEvents.AfterDayStarted` are raised. This is mainly useful for events which can be raised before the world is loaded (like update tick)._ * Added a `debug` console command which lets you run the game's debug commands (e.g. `debug warp FarmHouse 1 1` warps you to the farmhouse). * Added basic context info to logs to simplify troubleshooting. * Added a `Mod.Dispose` method which can be overriden to clean up before exit. This method isn't guaranteed to be called on every exit. @@ -905,8 +906,8 @@ For players: For mod developers: * Added a content API which loads custom textures/maps/data from the mod's folder (`.xnb` or `.png` format) or game content. * `Console.Out` messages are now written to the log file. -* `Monitor.ExitGameImmediately` now aborts SMAPI initialisation and events more quickly. -* Fixed value-changed events being raised when the player loads a save due to values being initialised. +* `Monitor.ExitGameImmediately` now aborts SMAPI initialization and events more quickly. +* Fixed value-changed events being raised when the player loads a save due to values being initialized. ## 1.10 Released 24 April 2017 for Stardew Valley 1.2.26. @@ -922,7 +923,7 @@ For players: * Replaced `player_addmelee` with `player_addweapon` with support for non-melee weapons. For mod developers: -* Mods are now initialised after the `Initialize`/`LoadContent` phase, which means the `GameEvents.Initialize` and `GameEvents.LoadContent` events are deprecated. You can move any logic in those methods to your mod's `Entry` method. +* Mods are now initialized after the `Initialize`/`LoadContent` phase, which means the `GameEvents.Initialize` and `GameEvents.LoadContent` events are deprecated. You can move any logic in those methods to your mod's `Entry` method. * Added `IsBetween` and string overloads to the `ISemanticVersion` methods. * Fixed mouse-changed event never updating prior mouse position. * Fixed `monitor.ExitGameImmediately` not working correctly. @@ -961,7 +962,7 @@ For mod developers: * The SMAPI log now has a simpler filename. * The SMAPI log now shows the OS caption (like "Windows 10") instead of its internal version when available. * The SMAPI log now always uses `\r\n` line endings to simplify crossplatform viewing. -* Fixed `SaveEvents.AfterLoad` being raised during the new-game intro before the player is initialised. +* Fixed `SaveEvents.AfterLoad` being raised during the new-game intro before the player is initialized. * Fixed SMAPI not recognising `Mod` instances that don't subclass `Mod` directly. * Several obsolete APIs have been removed (see [migration guides](https://stardewvalleywiki.com/Modding:Index#Migration_guides)), and all _notice_-level deprecations have been increased to _info_. @@ -1006,7 +1007,7 @@ For mod developers: * Added a mod registry which provides metadata about loaded mods. * The `Entry(…)` method is now deferred until all mods are loaded. * Fixed `SaveEvents.BeforeSave` and `.AfterSave` not triggering on days when the player shipped something. -* Fixed `PlayerEvents.LoadedGame` and `SaveEvents.AfterLoad` being fired before the world finishes initialising. +* Fixed `PlayerEvents.LoadedGame` and `SaveEvents.AfterLoad` being fired before the world finishes initializing. * Fixed some `LocationEvents`, `PlayerEvents`, and `TimeEvents` being fired during game startup. * Increased deprecation levels for `SObject`, `LogWriter` (not `Log`), and `Mod.Entry(ModHelper)` (not `Mod.Entry(IModHelper)`) to _pending removal_. Increased deprecation levels for `Mod.PerSaveConfigFolder`, `Mod.PerSaveConfigPath`, and `Version.VersionString` to _info_. diff --git a/src/SMAPI.Installer/InteractiveInstaller.cs b/src/SMAPI.Installer/InteractiveInstaller.cs index 41400617..4d313a3b 100644 --- a/src/SMAPI.Installer/InteractiveInstaller.cs +++ b/src/SMAPI.Installer/InteractiveInstaller.cs @@ -106,7 +106,7 @@ namespace StardewModdingApi.Installer /// Run the install or uninstall script. /// The command line arguments. /// - /// Initialisation flow: + /// Initialization flow: /// 1. Collect information (mainly OS and install path) and validate it. /// 2. Ask the user whether to install or uninstall. /// @@ -218,7 +218,7 @@ namespace StardewModdingApi.Installer ****/ // get theme writers var lightBackgroundWriter = new ColorfulConsoleWriter(EnvironmentUtility.DetectPlatform(), MonitorColorScheme.LightBackground); - var darkDarkgroundWriter = new ColorfulConsoleWriter(EnvironmentUtility.DetectPlatform(), MonitorColorScheme.DarkBackground); + var darkBackgroundWriter = new ColorfulConsoleWriter(EnvironmentUtility.DetectPlatform(), MonitorColorScheme.DarkBackground); // print question this.PrintPlain("Which text looks more readable?"); @@ -226,7 +226,7 @@ namespace StardewModdingApi.Installer Console.Write(" [1] "); lightBackgroundWriter.WriteLine("Dark text on light background", ConsoleLogLevel.Info); Console.Write(" [2] "); - darkDarkgroundWriter.WriteLine("Light text on dark background", ConsoleLogLevel.Info); + darkBackgroundWriter.WriteLine("Light text on dark background", ConsoleLogLevel.Info); Console.WriteLine(); // handle choice @@ -239,7 +239,7 @@ namespace StardewModdingApi.Installer break; case "2": scheme = MonitorColorScheme.DarkBackground; - this.ConsoleWriter = darkDarkgroundWriter; + this.ConsoleWriter = darkBackgroundWriter; break; default: throw new InvalidOperationException($"Unexpected action key '{choice}'."); @@ -646,7 +646,7 @@ namespace StardewModdingApi.Installer /// Delete a file or folder regardless of file permissions, and block until deletion completes. /// The file or folder to reset. - /// This method is mirred from FileUtilities.ForceDelete in the toolkit. + /// This method is mirrored from FileUtilities.ForceDelete in the toolkit. private void ForceDelete(FileSystemInfo entry) { // ignore if already deleted @@ -762,7 +762,7 @@ namespace StardewModdingApi.Installer continue; } - // normalise path + // normalize path if (platform == Platform.Windows) path = path.Replace("\"", ""); // in Windows, quotes are used to escape spaces and aren't part of the file path if (platform == Platform.Linux || platform == Platform.Mac) diff --git a/src/SMAPI.Installer/Program.cs b/src/SMAPI.Installer/Program.cs index 3c4d8593..b7fa45f5 100644 --- a/src/SMAPI.Installer/Program.cs +++ b/src/SMAPI.Installer/Program.cs @@ -36,7 +36,7 @@ namespace StardewModdingApi.Installer FileInfo zipFile = new FileInfo(Path.Combine(Program.InstallerPath, $"{(platform == PlatformID.Win32NT ? "windows" : "unix")}-install.dat")); if (!zipFile.Exists) { - Console.WriteLine($"Oops! Some of the installer files are missing; try redownloading the installer. (Missing file: {zipFile.FullName})"); + Console.WriteLine($"Oops! Some of the installer files are missing; try re-downloading the installer. (Missing file: {zipFile.FullName})"); Console.ReadLine(); return; } diff --git a/src/SMAPI.Internal/ConsoleWriting/ColorfulConsoleWriter.cs b/src/SMAPI.Internal/ConsoleWriting/ColorfulConsoleWriter.cs index 40c2d986..db016bae 100644 --- a/src/SMAPI.Internal/ConsoleWriting/ColorfulConsoleWriter.cs +++ b/src/SMAPI.Internal/ConsoleWriting/ColorfulConsoleWriter.cs @@ -126,7 +126,7 @@ namespace StardewModdingAPI.Internal.ConsoleWriting case ConsoleColor.Black: case ConsoleColor.Blue: case ConsoleColor.DarkBlue: - case ConsoleColor.DarkMagenta: // Powershell + case ConsoleColor.DarkMagenta: // PowerShell case ConsoleColor.DarkRed: case ConsoleColor.Red: return true; diff --git a/src/SMAPI.ModBuildConfig.Analyzer.Tests/Mock/Netcode/NetFieldBase.cs b/src/SMAPI.ModBuildConfig.Analyzer.Tests/Mock/Netcode/NetFieldBase.cs index 1684229a..140c6f59 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer.Tests/Mock/Netcode/NetFieldBase.cs +++ b/src/SMAPI.ModBuildConfig.Analyzer.Tests/Mock/Netcode/NetFieldBase.cs @@ -2,7 +2,7 @@ namespace Netcode { /// A simplified version of Stardew Valley's Netcode.NetFieldBase for unit testing. - /// The type of the synchronised value. + /// The type of the synchronized value. /// The type of the current instance. public class NetFieldBase where TSelf : NetFieldBase { diff --git a/src/SMAPI.ModBuildConfig.Analyzer/NetFieldAnalyzer.cs b/src/SMAPI.ModBuildConfig.Analyzer/NetFieldAnalyzer.cs index 70c01418..a9b981bd 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer/NetFieldAnalyzer.cs +++ b/src/SMAPI.ModBuildConfig.Analyzer/NetFieldAnalyzer.cs @@ -199,7 +199,7 @@ namespace StardewModdingAPI.ModBuildConfig.Analyzer /********* ** Private methods *********/ - /// Analyse a member access syntax node and add a diagnostic message if applicable. + /// Analyze a member access syntax node and add a diagnostic message if applicable. /// The analysis context. /// Returns whether any warnings were added. private void AnalyzeMemberAccess(SyntaxNodeAnalysisContext context) @@ -231,7 +231,7 @@ namespace StardewModdingAPI.ModBuildConfig.Analyzer }); } - /// Analyse an explicit cast or 'x as y' node and add a diagnostic message if applicable. + /// Analyze an explicit cast or 'x as y' node and add a diagnostic message if applicable. /// The analysis context. /// Returns whether any warnings were added. private void AnalyzeCast(SyntaxNodeAnalysisContext context) @@ -248,7 +248,7 @@ namespace StardewModdingAPI.ModBuildConfig.Analyzer }); } - /// Analyse a binary comparison syntax node and add a diagnostic message if applicable. + /// Analyze a binary comparison syntax node and add a diagnostic message if applicable. /// The analysis context. /// Returns whether any warnings were added. private void AnalyzeBinaryComparison(SyntaxNodeAnalysisContext context) @@ -288,7 +288,7 @@ namespace StardewModdingAPI.ModBuildConfig.Analyzer } /// Handle exceptions raised while analyzing a node. - /// The node being analysed. + /// The node being analyzed. /// The callback to invoke. private void HandleErrors(SyntaxNode node, Action action) { diff --git a/src/SMAPI.ModBuildConfig.Analyzer/ObsoleteFieldAnalyzer.cs b/src/SMAPI.ModBuildConfig.Analyzer/ObsoleteFieldAnalyzer.cs index 6b935caa..d071f0c1 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer/ObsoleteFieldAnalyzer.cs +++ b/src/SMAPI.ModBuildConfig.Analyzer/ObsoleteFieldAnalyzer.cs @@ -67,7 +67,7 @@ namespace StardewModdingAPI.ModBuildConfig.Analyzer /********* ** Private methods *********/ - /// Analyse a syntax node and add a diagnostic message if it references an obsolete field. + /// Analyze a syntax node and add a diagnostic message if it references an obsolete field. /// The analysis context. private void AnalyzeObsoleteFields(SyntaxNodeAnalysisContext context) { diff --git a/src/SMAPI.ModBuildConfig/Framework/ModFileManager.cs b/src/SMAPI.ModBuildConfig/Framework/ModFileManager.cs index e67a18c1..a852f133 100644 --- a/src/SMAPI.ModBuildConfig/Framework/ModFileManager.cs +++ b/src/SMAPI.ModBuildConfig/Framework/ModFileManager.cs @@ -3,8 +3,8 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; -using StardewModdingAPI.Toolkit.Serialisation; -using StardewModdingAPI.Toolkit.Serialisation.Models; +using StardewModdingAPI.Toolkit.Serialization; +using StardewModdingAPI.Toolkit.Serialization.Models; using StardewModdingAPI.Toolkit.Utilities; namespace StardewModdingAPI.ModBuildConfig.Framework diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/AddCommand.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/AddCommand.cs index 263e126c..6cb2b624 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/AddCommand.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/AddCommand.cs @@ -15,7 +15,7 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.Player /// Provides methods for searching and constructing items. private readonly ItemRepository Items = new ItemRepository(); - /// The type names recognised by this command. + /// The type names recognized by this command. private readonly string[] ValidTypes = Enum.GetNames(typeof(ItemType)).Concat(new[] { "Name" }).ToArray(); diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/ListItemsCommand.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/ListItemsCommand.cs index 5b52e9a2..4232ce16 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/ListItemsCommand.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/ListItemsCommand.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using StardewModdingAPI.Mods.ConsoleCommands.Framework.ItemData; @@ -58,7 +58,7 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.Player /// The search string to find. private IEnumerable GetItems(string[] searchWords) { - // normalise search term + // normalize search term searchWords = searchWords?.Where(word => !string.IsNullOrWhiteSpace(word)).ToArray(); if (searchWords?.Any() == false) searchWords = null; diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/World/SetTimeCommand.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/World/SetTimeCommand.cs index a6075013..9eae6741 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/World/SetTimeCommand.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/World/SetTimeCommand.cs @@ -60,7 +60,7 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.World { for (int i = 0; i > intervals; i--) { - Game1.timeOfDay = FromTimeSpan(ToTimeSpan(Game1.timeOfDay).Subtract(TimeSpan.FromMinutes(20))); // offset 20 mins so game updates to next interval + Game1.timeOfDay = FromTimeSpan(ToTimeSpan(Game1.timeOfDay).Subtract(TimeSpan.FromMinutes(20))); // offset 20 minutes so game updates to next interval Game1.performTenMinuteClockUpdate(); } } diff --git a/src/SMAPI.Tests/Core/ModResolverTests.cs b/src/SMAPI.Tests/Core/ModResolverTests.cs index ee1c0b99..c1aa0212 100644 --- a/src/SMAPI.Tests/Core/ModResolverTests.cs +++ b/src/SMAPI.Tests/Core/ModResolverTests.cs @@ -9,7 +9,7 @@ using StardewModdingAPI.Framework; using StardewModdingAPI.Framework.ModLoading; using StardewModdingAPI.Toolkit; using StardewModdingAPI.Toolkit.Framework.ModData; -using StardewModdingAPI.Toolkit.Serialisation.Models; +using StardewModdingAPI.Toolkit.Serialization.Models; namespace StardewModdingAPI.Tests.Core { @@ -55,7 +55,7 @@ namespace StardewModdingAPI.Tests.Core Assert.IsNotNull(mod.Error, "The mod metadata did not have an error message set."); } - [Test(Description = "Assert that the resolver correctly reads manifest data from a randomised file.")] + [Test(Description = "Assert that the resolver correctly reads manifest data from a randomized file.")] public void ReadBasicManifest_CanReadFile() { // create manifest data @@ -468,7 +468,7 @@ namespace StardewModdingAPI.Tests.Core return Path.Combine(Path.GetTempPath(), "smapi-unit-tests", Guid.NewGuid().ToString("N")); } - /// Get a randomised basic manifest. + /// Get a randomized basic manifest. /// The value, or null for a generated value. /// The value, or null for a generated value. /// The value, or null for a generated value. @@ -492,14 +492,14 @@ namespace StardewModdingAPI.Tests.Core }; } - /// Get a randomised basic manifest. + /// Get a randomized basic manifest. /// The mod's name and unique ID. private Mock GetMetadata(string uniqueID) { return this.GetMetadata(this.GetManifest(uniqueID, "1.0")); } - /// Get a randomised basic manifest. + /// Get a randomized basic manifest. /// The mod's name and unique ID. /// The dependencies this mod requires. /// Whether the code being tested is allowed to change the mod status. @@ -509,7 +509,7 @@ namespace StardewModdingAPI.Tests.Core return this.GetMetadata(manifest, allowStatusChange); } - /// Get a randomised basic manifest. + /// Get a randomized basic manifest. /// The mod manifest. /// Whether the code being tested is allowed to change the mod status. private Mock GetMetadata(IManifest manifest, bool allowStatusChange = false) diff --git a/src/SMAPI.Tests/Core/TranslationTests.cs b/src/SMAPI.Tests/Core/TranslationTests.cs index 63404a41..eea301ae 100644 --- a/src/SMAPI.Tests/Core/TranslationTests.cs +++ b/src/SMAPI.Tests/Core/TranslationTests.cs @@ -245,7 +245,7 @@ namespace StardewModdingAPI.Tests.Core [TestCase("{{value}}", "value")] [TestCase("{{VaLuE}}", "vAlUe")] [TestCase("{{VaLuE }}", " vAlUe")] - public void Translation_Tokens_KeysAreNormalised(string text, string key) + public void Translation_Tokens_KeysAreNormalized(string text, string key) { // arrange string value = Guid.NewGuid().ToString("N"); diff --git a/src/SMAPI.Tests/Toolkit/PathUtilitiesTests.cs b/src/SMAPI.Tests/Toolkit/PathUtilitiesTests.cs index 229b9a14..3dc65ed5 100644 --- a/src/SMAPI.Tests/Toolkit/PathUtilitiesTests.cs +++ b/src/SMAPI.Tests/Toolkit/PathUtilitiesTests.cs @@ -25,7 +25,7 @@ namespace StardewModdingAPI.Tests.Toolkit return string.Join("|", PathUtilities.GetSegments(path)); } - [Test(Description = "Assert that NormalisePathSeparators returns the expected values.")] + [Test(Description = "Assert that NormalizePathSeparators returns the expected values.")] #if SMAPI_FOR_WINDOWS [TestCase("", ExpectedResult = "")] [TestCase("/", ExpectedResult = "")] @@ -47,9 +47,9 @@ namespace StardewModdingAPI.Tests.Toolkit [TestCase("C:/boop", ExpectedResult = "C:/boop")] [TestCase(@"C:\usr\bin//.././boop.exe", ExpectedResult = "C:/usr/bin/.././boop.exe")] #endif - public string NormalisePathSeparators(string path) + public string NormalizePathSeparators(string path) { - return PathUtilities.NormalisePathSeparators(path); + return PathUtilities.NormalizePathSeparators(path); } [Test(Description = "Assert that GetRelativePath returns the expected values.")] diff --git a/src/SMAPI.Tests/Utilities/SemanticVersionTests.cs b/src/SMAPI.Tests/Utilities/SemanticVersionTests.cs index 2e7719eb..8f64a5fb 100644 --- a/src/SMAPI.Tests/Utilities/SemanticVersionTests.cs +++ b/src/SMAPI.Tests/Utilities/SemanticVersionTests.cs @@ -243,19 +243,19 @@ namespace StardewModdingAPI.Tests.Utilities } /**** - ** Serialisable + ** Serializable ****/ [Test(Description = "Assert that SemanticVersion can be round-tripped through JSON with no special configuration.")] [TestCase("1.0")] - public void Serialisable(string versionStr) + public void Serializable(string versionStr) { // act string json = JsonConvert.SerializeObject(new SemanticVersion(versionStr)); SemanticVersion after = JsonConvert.DeserializeObject(json); // assert - Assert.IsNotNull(after, "The semantic version after deserialisation is unexpectedly null."); - Assert.AreEqual(versionStr, after.ToString(), "The semantic version after deserialisation doesn't match the input version."); + Assert.IsNotNull(after, "The semantic version after deserialization is unexpectedly null."); + Assert.AreEqual(versionStr, after.ToString(), "The semantic version after deserialization doesn't match the input version."); } /**** diff --git a/src/SMAPI.Toolkit.CoreInterfaces/ISemanticVersion.cs b/src/SMAPI.Toolkit.CoreInterfaces/ISemanticVersion.cs index 4a61f9ae..4ec87d7c 100644 --- a/src/SMAPI.Toolkit.CoreInterfaces/ISemanticVersion.cs +++ b/src/SMAPI.Toolkit.CoreInterfaces/ISemanticVersion.cs @@ -24,7 +24,7 @@ namespace StardewModdingAPI /********* ** Accessors *********/ - /// Whether this is a pre-release version. + /// Whether this is a prerelease version. bool IsPrerelease(); /// Get whether this version is older than the specified version. diff --git a/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModExtendedMetadataModel.cs b/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModExtendedMetadataModel.cs index 989c18b0..bd5f71a9 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModExtendedMetadataModel.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModExtendedMetadataModel.cs @@ -48,7 +48,7 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi [JsonConverter(typeof(StringEnumConverter))] public WikiCompatibilityStatus? CompatibilityStatus { get; set; } - /// The human-readable summary of the compatibility status or workaround, without HTML formatitng. + /// The human-readable summary of the compatibility status or workaround, without HTML formatting. public string CompatibilitySummary { get; set; } /// The game or SMAPI version which broke this mod, if applicable. @@ -62,7 +62,7 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi [JsonConverter(typeof(StringEnumConverter))] public WikiCompatibilityStatus? BetaCompatibilityStatus { get; set; } - /// The human-readable summary of the compatibility status or workaround for the Stardew Valley beta (if any), without HTML formatitng. + /// The human-readable summary of the compatibility status or workaround for the Stardew Valley beta (if any), without HTML formatting. public string BetaCompatibilitySummary { get; set; } /// The beta game or SMAPI version which broke this mod, if applicable. diff --git a/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSeachModel.cs b/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSeachModel.cs index e352e1cc..a2eaad16 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSeachModel.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSeachModel.cs @@ -21,7 +21,7 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi /// Construct an empty instance. public ModSearchModel() { - // needed for JSON deserialising + // needed for JSON deserializing } /// Construct an instance. diff --git a/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSearchEntryModel.cs b/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSearchEntryModel.cs index bca47647..886cd5a1 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSearchEntryModel.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSearchEntryModel.cs @@ -19,7 +19,7 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi /// Construct an empty instance. public ModSearchEntryModel() { - // needed for JSON deserialising + // needed for JSON deserializing } /// Construct an instance. diff --git a/src/SMAPI.Toolkit/Framework/Clients/WebApi/WebApiClient.cs b/src/SMAPI.Toolkit/Framework/Clients/WebApi/WebApiClient.cs index 7c3df384..80c8f62b 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/WebApi/WebApiClient.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/WebApi/WebApiClient.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Net; using Newtonsoft.Json; -using StardewModdingAPI.Toolkit.Serialisation; +using StardewModdingAPI.Toolkit.Serialization; namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi { diff --git a/src/SMAPI.Toolkit/Framework/GameScanning/GameScanner.cs b/src/SMAPI.Toolkit/Framework/GameScanning/GameScanner.cs index 60c7a682..212c70ef 100644 --- a/src/SMAPI.Toolkit/Framework/GameScanning/GameScanner.cs +++ b/src/SMAPI.Toolkit/Framework/GameScanning/GameScanner.cs @@ -29,7 +29,7 @@ namespace StardewModdingAPI.Toolkit.Framework.GameScanning IEnumerable paths = this .GetCustomInstallPaths(platform) .Concat(this.GetDefaultInstallPaths(platform)) - .Select(PathUtilities.NormalisePathSeparators) + .Select(PathUtilities.NormalizePathSeparators) .Distinct(StringComparer.InvariantCultureIgnoreCase); // yield valid folders diff --git a/src/SMAPI.Toolkit/Framework/ModData/ModDataModel.cs b/src/SMAPI.Toolkit/Framework/ModData/ModDataModel.cs index 18039762..dd0bd07b 100644 --- a/src/SMAPI.Toolkit/Framework/ModData/ModDataModel.cs +++ b/src/SMAPI.Toolkit/Framework/ModData/ModDataModel.cs @@ -112,8 +112,8 @@ namespace StardewModdingAPI.Toolkit.Framework.ModData /********* ** Private methods *********/ - /// The method invoked after JSON deserialisation. - /// The deserialisation context. + /// The method invoked after JSON deserialization. + /// The deserialization context. [OnDeserialized] private void OnDeserialized(StreamingContext context) { diff --git a/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs b/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs index 794ad2e4..f01ada7c 100644 --- a/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs +++ b/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs @@ -68,7 +68,7 @@ namespace StardewModdingAPI.Toolkit.Framework.ModData } /// Get a semantic local version for update checks. - /// The remote version to normalise. + /// The remote version to normalize. public ISemanticVersion GetLocalVersionForUpdateChecks(ISemanticVersion version) { return this.MapLocalVersions != null && this.MapLocalVersions.TryGetValue(version.ToString(), out string newVersion) @@ -77,10 +77,10 @@ namespace StardewModdingAPI.Toolkit.Framework.ModData } /// Get a semantic remote version for update checks. - /// The remote version to normalise. + /// The remote version to normalize. public string GetRemoteVersionForUpdateChecks(string version) { - // normalise version if possible + // normalize version if possible if (SemanticVersion.TryParse(version, out ISemanticVersion parsed)) version = parsed.ToString(); diff --git a/src/SMAPI.Toolkit/Framework/ModData/ModDataRecordVersionedFields.cs b/src/SMAPI.Toolkit/Framework/ModData/ModDataRecordVersionedFields.cs index 237f2c66..9e22990d 100644 --- a/src/SMAPI.Toolkit/Framework/ModData/ModDataRecordVersionedFields.cs +++ b/src/SMAPI.Toolkit/Framework/ModData/ModDataRecordVersionedFields.cs @@ -32,14 +32,14 @@ namespace StardewModdingAPI.Toolkit.Framework.ModData ** Public methods *********/ /// Get a semantic local version for update checks. - /// The remote version to normalise. + /// The remote version to normalize. public ISemanticVersion GetLocalVersionForUpdateChecks(ISemanticVersion version) { return this.DataRecord.GetLocalVersionForUpdateChecks(version); } /// Get a semantic remote version for update checks. - /// The remote version to normalise. + /// The remote version to normalize. public ISemanticVersion GetRemoteVersionForUpdateChecks(ISemanticVersion version) { if (version == null) diff --git a/src/SMAPI.Toolkit/Framework/ModData/ModWarning.cs b/src/SMAPI.Toolkit/Framework/ModData/ModWarning.cs index d61c427f..e67616d0 100644 --- a/src/SMAPI.Toolkit/Framework/ModData/ModWarning.cs +++ b/src/SMAPI.Toolkit/Framework/ModData/ModWarning.cs @@ -13,7 +13,7 @@ namespace StardewModdingAPI.Toolkit.Framework.ModData BrokenCodeLoaded = 1, /// The mod affects the save serializer in a way that may make saves unloadable without the mod. - ChangesSaveSerialiser = 2, + ChangesSaveSerializer = 2, /// The mod patches the game in a way that may impact stability. PatchesGame = 4, @@ -21,7 +21,7 @@ namespace StardewModdingAPI.Toolkit.Framework.ModData /// The mod uses the dynamic keyword which won't work on Linux/Mac. UsesDynamic = 8, - /// The mod references specialised 'unvalided update tick' events which may impact stability. + /// The mod references specialized 'unvalidated update tick' events which may impact stability. UsesUnvalidatedUpdateTick = 16, /// The mod has no update keys set. diff --git a/src/SMAPI.Toolkit/Framework/ModScanning/ModFolder.cs b/src/SMAPI.Toolkit/Framework/ModScanning/ModFolder.cs index 4ce17c66..d0df09a1 100644 --- a/src/SMAPI.Toolkit/Framework/ModScanning/ModFolder.cs +++ b/src/SMAPI.Toolkit/Framework/ModScanning/ModFolder.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using StardewModdingAPI.Toolkit.Serialisation.Models; +using StardewModdingAPI.Toolkit.Serialization.Models; using StardewModdingAPI.Toolkit.Utilities; namespace StardewModdingAPI.Toolkit.Framework.ModScanning diff --git a/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs b/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs index 54cb2b8b..f11cc1a7 100644 --- a/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs +++ b/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs @@ -3,8 +3,8 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; -using StardewModdingAPI.Toolkit.Serialisation; -using StardewModdingAPI.Toolkit.Serialisation.Models; +using StardewModdingAPI.Toolkit.Serialization; +using StardewModdingAPI.Toolkit.Serialization.Models; namespace StardewModdingAPI.Toolkit.Framework.ModScanning { @@ -118,7 +118,7 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning } } - // normalise display fields + // normalize display fields if (manifest != null) { manifest.Name = this.StripNewlines(manifest.Name); diff --git a/src/SMAPI.Toolkit/ModToolkit.cs b/src/SMAPI.Toolkit/ModToolkit.cs index 4b026b7a..08fe0fed 100644 --- a/src/SMAPI.Toolkit/ModToolkit.cs +++ b/src/SMAPI.Toolkit/ModToolkit.cs @@ -8,7 +8,7 @@ using StardewModdingAPI.Toolkit.Framework.Clients.Wiki; using StardewModdingAPI.Toolkit.Framework.GameScanning; using StardewModdingAPI.Toolkit.Framework.ModData; using StardewModdingAPI.Toolkit.Framework.ModScanning; -using StardewModdingAPI.Toolkit.Serialisation; +using StardewModdingAPI.Toolkit.Serialization; namespace StardewModdingAPI.Toolkit { diff --git a/src/SMAPI.Toolkit/SemanticVersion.cs b/src/SMAPI.Toolkit/SemanticVersion.cs index 78b4c007..6d5d65ac 100644 --- a/src/SMAPI.Toolkit/SemanticVersion.cs +++ b/src/SMAPI.Toolkit/SemanticVersion.cs @@ -56,7 +56,7 @@ namespace StardewModdingAPI.Toolkit this.MajorVersion = major; this.MinorVersion = minor; this.PatchVersion = patch; - this.PrereleaseTag = this.GetNormalisedTag(prereleaseTag); + this.PrereleaseTag = this.GetNormalizedTag(prereleaseTag); this.AssertValid(); } @@ -89,16 +89,16 @@ namespace StardewModdingAPI.Toolkit if (!match.Success) throw new FormatException($"The input '{version}' isn't a valid semantic version."); - // initialise + // initialize this.MajorVersion = int.Parse(match.Groups["major"].Value); this.MinorVersion = match.Groups["minor"].Success ? int.Parse(match.Groups["minor"].Value) : 0; this.PatchVersion = match.Groups["patch"].Success ? int.Parse(match.Groups["patch"].Value) : 0; - this.PrereleaseTag = match.Groups["prerelease"].Success ? this.GetNormalisedTag(match.Groups["prerelease"].Value) : null; + this.PrereleaseTag = match.Groups["prerelease"].Success ? this.GetNormalizedTag(match.Groups["prerelease"].Value) : null; this.AssertValid(); } - /// Get an integer indicating whether this version precedes (less than 0), supercedes (more than 0), or is equivalent to (0) the specified version. + /// Get an integer indicating whether this version precedes (less than 0), supersedes (more than 0), or is equivalent to (0) the specified version. /// The version to compare with this instance. /// The value is null. public int CompareTo(ISemanticVersion other) @@ -116,7 +116,7 @@ namespace StardewModdingAPI.Toolkit return other != null && this.CompareTo(other) == 0; } - /// Whether this is a pre-release version. + /// Whether this is a prerelease version. public bool IsPrerelease() { return !string.IsNullOrWhiteSpace(this.PrereleaseTag); @@ -206,15 +206,15 @@ namespace StardewModdingAPI.Toolkit /********* ** Private methods *********/ - /// Get a normalised build tag. - /// The tag to normalise. - private string GetNormalisedTag(string tag) + /// Get a normalized build tag. + /// The tag to normalize. + private string GetNormalizedTag(string tag) { tag = tag?.Trim(); return !string.IsNullOrWhiteSpace(tag) ? tag : null; } - /// Get an integer indicating whether this version precedes (less than 0), supercedes (more than 0), or is equivalent to (0) the specified version. + /// Get an integer indicating whether this version precedes (less than 0), supersedes (more than 0), or is equivalent to (0) the specified version. /// The major version to compare with this instance. /// The minor version to compare with this instance. /// The patch version to compare with this instance. @@ -235,7 +235,7 @@ namespace StardewModdingAPI.Toolkit if (this.PrereleaseTag == otherTag) return same; - // stable supercedes pre-release + // stable supersedes prerelease bool curIsStable = string.IsNullOrWhiteSpace(this.PrereleaseTag); bool otherIsStable = string.IsNullOrWhiteSpace(otherTag); if (curIsStable) @@ -243,12 +243,12 @@ namespace StardewModdingAPI.Toolkit if (otherIsStable) return curOlder; - // compare two pre-release tag values + // compare two prerelease tag values string[] curParts = this.PrereleaseTag.Split('.', '-'); string[] otherParts = otherTag.Split('.', '-'); for (int i = 0; i < curParts.Length; i++) { - // longer prerelease tag supercedes if otherwise equal + // longer prerelease tag supersedes if otherwise equal if (otherParts.Length <= i) return curNewer; diff --git a/src/SMAPI.Toolkit/Serialisation/Converters/ManifestContentPackForConverter.cs b/src/SMAPI.Toolkit/Serialisation/Converters/ManifestContentPackForConverter.cs deleted file mode 100644 index 232c22a7..00000000 --- a/src/SMAPI.Toolkit/Serialisation/Converters/ManifestContentPackForConverter.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using Newtonsoft.Json; -using StardewModdingAPI.Toolkit.Serialisation.Models; - -namespace StardewModdingAPI.Toolkit.Serialisation.Converters -{ - /// Handles deserialisation of arrays. - public class ManifestContentPackForConverter : JsonConverter - { - /********* - ** Accessors - *********/ - /// Whether this converter can write JSON. - public override bool CanWrite => false; - - - /********* - ** Public methods - *********/ - /// Get whether this instance can convert the specified object type. - /// The object type. - public override bool CanConvert(Type objectType) - { - return objectType == typeof(ManifestContentPackFor[]); - } - - - /********* - ** Protected methods - *********/ - /// Read the JSON representation of the object. - /// The JSON reader. - /// The object type. - /// The object being read. - /// The calling serializer. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - return serializer.Deserialize(reader); - } - - /// Writes the JSON representation of the object. - /// The JSON writer. - /// The value. - /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - throw new InvalidOperationException("This converter does not write JSON."); - } - } -} diff --git a/src/SMAPI.Toolkit/Serialisation/Converters/ManifestDependencyArrayConverter.cs b/src/SMAPI.Toolkit/Serialisation/Converters/ManifestDependencyArrayConverter.cs deleted file mode 100644 index 0a304ee3..00000000 --- a/src/SMAPI.Toolkit/Serialisation/Converters/ManifestDependencyArrayConverter.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using System.Collections.Generic; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using StardewModdingAPI.Toolkit.Serialisation.Models; - -namespace StardewModdingAPI.Toolkit.Serialisation.Converters -{ - /// Handles deserialisation of arrays. - internal class ManifestDependencyArrayConverter : JsonConverter - { - /********* - ** Accessors - *********/ - /// Whether this converter can write JSON. - public override bool CanWrite => false; - - - /********* - ** Public methods - *********/ - /// Get whether this instance can convert the specified object type. - /// The object type. - public override bool CanConvert(Type objectType) - { - return objectType == typeof(ManifestDependency[]); - } - - - /********* - ** Protected methods - *********/ - /// Read the JSON representation of the object. - /// The JSON reader. - /// The object type. - /// The object being read. - /// The calling serializer. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - List result = new List(); - foreach (JObject obj in JArray.Load(reader).Children()) - { - string uniqueID = obj.ValueIgnoreCase(nameof(ManifestDependency.UniqueID)); - string minVersion = obj.ValueIgnoreCase(nameof(ManifestDependency.MinimumVersion)); - bool required = obj.ValueIgnoreCase(nameof(ManifestDependency.IsRequired)) ?? true; - result.Add(new ManifestDependency(uniqueID, minVersion, required)); - } - return result.ToArray(); - } - - /// Writes the JSON representation of the object. - /// The JSON writer. - /// The value. - /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - throw new InvalidOperationException("This converter does not write JSON."); - } - } -} diff --git a/src/SMAPI.Toolkit/Serialisation/Converters/SemanticVersionConverter.cs b/src/SMAPI.Toolkit/Serialisation/Converters/SemanticVersionConverter.cs deleted file mode 100644 index c50de4db..00000000 --- a/src/SMAPI.Toolkit/Serialisation/Converters/SemanticVersionConverter.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace StardewModdingAPI.Toolkit.Serialisation.Converters -{ - /// Handles deserialisation of . - internal class SemanticVersionConverter : JsonConverter - { - /********* - ** Accessors - *********/ - /// Get whether this converter can read JSON. - public override bool CanRead => true; - - /// Get whether this converter can write JSON. - public override bool CanWrite => true; - - - /********* - ** Public methods - *********/ - /// Get whether this instance can convert the specified object type. - /// The object type. - public override bool CanConvert(Type objectType) - { - return typeof(ISemanticVersion).IsAssignableFrom(objectType); - } - - /// Reads the JSON representation of the object. - /// The JSON reader. - /// The object type. - /// The object being read. - /// The calling serializer. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - string path = reader.Path; - switch (reader.TokenType) - { - case JsonToken.StartObject: - return this.ReadObject(JObject.Load(reader)); - case JsonToken.String: - return this.ReadString(JToken.Load(reader).Value(), path); - default: - throw new SParseException($"Can't parse {nameof(ISemanticVersion)} from {reader.TokenType} node (path: {reader.Path})."); - } - } - - /// Writes the JSON representation of the object. - /// The JSON writer. - /// The value. - /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - writer.WriteValue(value?.ToString()); - } - - - /********* - ** Private methods - *********/ - /// Read a JSON object. - /// The JSON object to read. - private ISemanticVersion ReadObject(JObject obj) - { - int major = obj.ValueIgnoreCase(nameof(ISemanticVersion.MajorVersion)); - int minor = obj.ValueIgnoreCase(nameof(ISemanticVersion.MinorVersion)); - int patch = obj.ValueIgnoreCase(nameof(ISemanticVersion.PatchVersion)); - string prereleaseTag = obj.ValueIgnoreCase(nameof(ISemanticVersion.PrereleaseTag)); - - return new SemanticVersion(major, minor, patch, prereleaseTag); - } - - /// Read a JSON string. - /// The JSON string value. - /// The path to the current JSON node. - private ISemanticVersion ReadString(string str, string path) - { - if (string.IsNullOrWhiteSpace(str)) - return null; - if (!SemanticVersion.TryParse(str, out ISemanticVersion version)) - throw new SParseException($"Can't parse semantic version from invalid value '{str}', should be formatted like 1.2, 1.2.30, or 1.2.30-beta (path: {path})."); - return version; - } - } -} diff --git a/src/SMAPI.Toolkit/Serialisation/Converters/SimpleReadOnlyConverter.cs b/src/SMAPI.Toolkit/Serialisation/Converters/SimpleReadOnlyConverter.cs deleted file mode 100644 index 5e0b0f4a..00000000 --- a/src/SMAPI.Toolkit/Serialisation/Converters/SimpleReadOnlyConverter.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace StardewModdingAPI.Toolkit.Serialisation.Converters -{ - /// The base implementation for simplified converters which deserialise without overriding serialisation. - /// The type to deserialise. - internal abstract class SimpleReadOnlyConverter : JsonConverter - { - /********* - ** Accessors - *********/ - /// Whether this converter can write JSON. - public override bool CanWrite => false; - - - /********* - ** Public methods - *********/ - /// Get whether this instance can convert the specified object type. - /// The object type. - public override bool CanConvert(Type objectType) - { - return objectType == typeof(T); - } - - /// Writes the JSON representation of the object. - /// The JSON writer. - /// The value. - /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - throw new InvalidOperationException("This converter does not write JSON."); - } - - /// Reads the JSON representation of the object. - /// The JSON reader. - /// The object type. - /// The object being read. - /// The calling serializer. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - string path = reader.Path; - switch (reader.TokenType) - { - case JsonToken.StartObject: - return this.ReadObject(JObject.Load(reader), path); - case JsonToken.String: - return this.ReadString(JToken.Load(reader).Value(), path); - default: - throw new SParseException($"Can't parse {typeof(T).Name} from {reader.TokenType} node (path: {reader.Path})."); - } - } - - - /********* - ** Protected methods - *********/ - /// Read a JSON object. - /// The JSON object to read. - /// The path to the current JSON node. - protected virtual T ReadObject(JObject obj, string path) - { - throw new SParseException($"Can't parse {typeof(T).Name} from object node (path: {path})."); - } - - /// Read a JSON string. - /// The JSON string value. - /// The path to the current JSON node. - protected virtual T ReadString(string str, string path) - { - throw new SParseException($"Can't parse {typeof(T).Name} from string node (path: {path})."); - } - } -} diff --git a/src/SMAPI.Toolkit/Serialisation/InternalExtensions.cs b/src/SMAPI.Toolkit/Serialisation/InternalExtensions.cs deleted file mode 100644 index 12b2c933..00000000 --- a/src/SMAPI.Toolkit/Serialisation/InternalExtensions.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using Newtonsoft.Json.Linq; - -namespace StardewModdingAPI.Toolkit.Serialisation -{ - /// Provides extension methods for parsing JSON. - public static class JsonExtensions - { - /// Get a JSON field value from a case-insensitive field name. This will check for an exact match first, then search without case sensitivity. - /// The value type. - /// The JSON object to search. - /// The field name. - public static T ValueIgnoreCase(this JObject obj, string fieldName) - { - JToken token = obj.GetValue(fieldName, StringComparison.InvariantCultureIgnoreCase); - return token != null - ? token.Value() - : default(T); - } - } -} diff --git a/src/SMAPI.Toolkit/Serialisation/JsonHelper.cs b/src/SMAPI.Toolkit/Serialisation/JsonHelper.cs deleted file mode 100644 index cf2ce0d1..00000000 --- a/src/SMAPI.Toolkit/Serialisation/JsonHelper.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using StardewModdingAPI.Toolkit.Serialisation.Converters; - -namespace StardewModdingAPI.Toolkit.Serialisation -{ - /// Encapsulates SMAPI's JSON file parsing. - public class JsonHelper - { - /********* - ** Accessors - *********/ - /// The JSON settings to use when serialising and deserialising files. - public JsonSerializerSettings JsonSettings { get; } = new JsonSerializerSettings - { - Formatting = Formatting.Indented, - ObjectCreationHandling = ObjectCreationHandling.Replace, // avoid issue where default ICollection values are duplicated each time the config is loaded - Converters = new List - { - new SemanticVersionConverter(), - new StringEnumConverter() - } - }; - - - /********* - ** Public methods - *********/ - /// Read a JSON file. - /// The model type. - /// The absolete file path. - /// The parsed content model. - /// Returns false if the file doesn't exist, else true. - /// The given is empty or invalid. - /// The file contains invalid JSON. - public bool ReadJsonFileIfExists(string fullPath, out TModel result) - { - // validate - if (string.IsNullOrWhiteSpace(fullPath)) - throw new ArgumentException("The file path is empty or invalid.", nameof(fullPath)); - - // read file - string json; - try - { - json = File.ReadAllText(fullPath); - } - catch (Exception ex) when (ex is DirectoryNotFoundException || ex is FileNotFoundException) - { - result = default(TModel); - return false; - } - - // deserialise model - try - { - result = this.Deserialise(json); - return true; - } - catch (Exception ex) - { - string error = $"Can't parse JSON file at {fullPath}."; - - if (ex is JsonReaderException) - { - error += " This doesn't seem to be valid JSON."; - if (json.Contains("“") || json.Contains("”")) - error += " Found curly quotes in the text; note that only straight quotes are allowed in JSON."; - } - error += $"\nTechnical details: {ex.Message}"; - throw new JsonReaderException(error); - } - } - - /// Save to a JSON file. - /// The model type. - /// The absolete file path. - /// The model to save. - /// The given path is empty or invalid. - public void WriteJsonFile(string fullPath, TModel model) - where TModel : class - { - // validate - if (string.IsNullOrWhiteSpace(fullPath)) - throw new ArgumentException("The file path is empty or invalid.", nameof(fullPath)); - - // create directory if needed - string dir = Path.GetDirectoryName(fullPath); - if (dir == null) - throw new ArgumentException("The file path is invalid.", nameof(fullPath)); - if (!Directory.Exists(dir)) - Directory.CreateDirectory(dir); - - // write file - string json = this.Serialise(model); - File.WriteAllText(fullPath, json); - } - - /// Deserialize JSON text if possible. - /// The model type. - /// The raw JSON text. - public TModel Deserialise(string json) - { - try - { - return JsonConvert.DeserializeObject(json, this.JsonSettings); - } - catch (JsonReaderException) - { - // try replacing curly quotes - if (json.Contains("“") || json.Contains("”")) - { - try - { - return JsonConvert.DeserializeObject(json.Replace('“', '"').Replace('”', '"'), this.JsonSettings); - } - catch { /* rethrow original error */ } - } - - throw; - } - } - - /// Serialize a model to JSON text. - /// The model type. - /// The model to serialise. - /// The formatting to apply. - public string Serialise(TModel model, Formatting formatting = Formatting.Indented) - { - return JsonConvert.SerializeObject(model, formatting, this.JsonSettings); - } - } -} diff --git a/src/SMAPI.Toolkit/Serialisation/Models/Manifest.cs b/src/SMAPI.Toolkit/Serialisation/Models/Manifest.cs deleted file mode 100644 index 6cb9496b..00000000 --- a/src/SMAPI.Toolkit/Serialisation/Models/Manifest.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System.Collections.Generic; -using Newtonsoft.Json; -using StardewModdingAPI.Toolkit.Serialisation.Converters; - -namespace StardewModdingAPI.Toolkit.Serialisation.Models -{ - /// A manifest which describes a mod for SMAPI. - public class Manifest : IManifest - { - /********* - ** Accessors - *********/ - /// The mod name. - public string Name { get; set; } - - /// A brief description of the mod. - public string Description { get; set; } - - /// The mod author's name. - public string Author { get; set; } - - /// The mod version. - public ISemanticVersion Version { get; set; } - - /// The minimum SMAPI version required by this mod, if any. - public ISemanticVersion MinimumApiVersion { get; set; } - - /// The name of the DLL in the directory that has the Entry method. Mutually exclusive with . - public string EntryDll { get; set; } - - /// The mod which will read this as a content pack. Mutually exclusive with . - [JsonConverter(typeof(ManifestContentPackForConverter))] - public IManifestContentPackFor ContentPackFor { get; set; } - - /// The other mods that must be loaded before this mod. - [JsonConverter(typeof(ManifestDependencyArrayConverter))] - public IManifestDependency[] Dependencies { get; set; } - - /// The namespaced mod IDs to query for updates (like Nexus:541). - public string[] UpdateKeys { get; set; } - - /// The unique mod ID. - public string UniqueID { get; set; } - - /// Any manifest fields which didn't match a valid field. - [JsonExtensionData] - public IDictionary ExtraFields { get; set; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - public Manifest() { } - - /// Construct an instance for a transitional content pack. - /// The unique mod ID. - /// The mod name. - /// The mod author's name. - /// A brief description of the mod. - /// The mod version. - /// The modID which will read this as a content pack. - public Manifest(string uniqueID, string name, string author, string description, ISemanticVersion version, string contentPackFor = null) - { - this.Name = name; - this.Author = author; - this.Description = description; - this.Version = version; - this.UniqueID = uniqueID; - this.UpdateKeys = new string[0]; - this.ContentPackFor = new ManifestContentPackFor { UniqueID = contentPackFor }; - } - } -} diff --git a/src/SMAPI.Toolkit/Serialisation/Models/ManifestContentPackFor.cs b/src/SMAPI.Toolkit/Serialisation/Models/ManifestContentPackFor.cs deleted file mode 100644 index d0e42216..00000000 --- a/src/SMAPI.Toolkit/Serialisation/Models/ManifestContentPackFor.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace StardewModdingAPI.Toolkit.Serialisation.Models -{ - /// Indicates which mod can read the content pack represented by the containing manifest. - public class ManifestContentPackFor : IManifestContentPackFor - { - /********* - ** Accessors - *********/ - /// The unique ID of the mod which can read this content pack. - public string UniqueID { get; set; } - - /// The minimum required version (if any). - public ISemanticVersion MinimumVersion { get; set; } - } -} diff --git a/src/SMAPI.Toolkit/Serialisation/Models/ManifestDependency.cs b/src/SMAPI.Toolkit/Serialisation/Models/ManifestDependency.cs deleted file mode 100644 index 8db58d5d..00000000 --- a/src/SMAPI.Toolkit/Serialisation/Models/ManifestDependency.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace StardewModdingAPI.Toolkit.Serialisation.Models -{ - /// A mod dependency listed in a mod manifest. - public class ManifestDependency : IManifestDependency - { - /********* - ** Accessors - *********/ - /// The unique mod ID to require. - public string UniqueID { get; set; } - - /// The minimum required version (if any). - public ISemanticVersion MinimumVersion { get; set; } - - /// Whether the dependency must be installed to use the mod. - public bool IsRequired { get; set; } - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The unique mod ID to require. - /// The minimum required version (if any). - /// Whether the dependency must be installed to use the mod. - public ManifestDependency(string uniqueID, string minimumVersion, bool required = true) - { - this.UniqueID = uniqueID; - this.MinimumVersion = !string.IsNullOrWhiteSpace(minimumVersion) - ? new SemanticVersion(minimumVersion) - : null; - this.IsRequired = required; - } - } -} diff --git a/src/SMAPI.Toolkit/Serialisation/SParseException.cs b/src/SMAPI.Toolkit/Serialisation/SParseException.cs deleted file mode 100644 index 61a7b305..00000000 --- a/src/SMAPI.Toolkit/Serialisation/SParseException.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; - -namespace StardewModdingAPI.Toolkit.Serialisation -{ - /// A format exception which provides a user-facing error message. - internal class SParseException : FormatException - { - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The error message. - /// The underlying exception, if any. - public SParseException(string message, Exception ex = null) - : base(message, ex) { } - } -} diff --git a/src/SMAPI.Toolkit/Serialization/Converters/ManifestContentPackForConverter.cs b/src/SMAPI.Toolkit/Serialization/Converters/ManifestContentPackForConverter.cs new file mode 100644 index 00000000..5cabe9d8 --- /dev/null +++ b/src/SMAPI.Toolkit/Serialization/Converters/ManifestContentPackForConverter.cs @@ -0,0 +1,50 @@ +using System; +using Newtonsoft.Json; +using StardewModdingAPI.Toolkit.Serialization.Models; + +namespace StardewModdingAPI.Toolkit.Serialization.Converters +{ + /// Handles deserialization of arrays. + public class ManifestContentPackForConverter : JsonConverter + { + /********* + ** Accessors + *********/ + /// Whether this converter can write JSON. + public override bool CanWrite => false; + + + /********* + ** Public methods + *********/ + /// Get whether this instance can convert the specified object type. + /// The object type. + public override bool CanConvert(Type objectType) + { + return objectType == typeof(ManifestContentPackFor[]); + } + + + /********* + ** Protected methods + *********/ + /// Read the JSON representation of the object. + /// The JSON reader. + /// The object type. + /// The object being read. + /// The calling serializer. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + return serializer.Deserialize(reader); + } + + /// Writes the JSON representation of the object. + /// The JSON writer. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + throw new InvalidOperationException("This converter does not write JSON."); + } + } +} diff --git a/src/SMAPI.Toolkit/Serialization/Converters/ManifestDependencyArrayConverter.cs b/src/SMAPI.Toolkit/Serialization/Converters/ManifestDependencyArrayConverter.cs new file mode 100644 index 00000000..7b88d6b7 --- /dev/null +++ b/src/SMAPI.Toolkit/Serialization/Converters/ManifestDependencyArrayConverter.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using StardewModdingAPI.Toolkit.Serialization.Models; + +namespace StardewModdingAPI.Toolkit.Serialization.Converters +{ + /// Handles deserialization of arrays. + internal class ManifestDependencyArrayConverter : JsonConverter + { + /********* + ** Accessors + *********/ + /// Whether this converter can write JSON. + public override bool CanWrite => false; + + + /********* + ** Public methods + *********/ + /// Get whether this instance can convert the specified object type. + /// The object type. + public override bool CanConvert(Type objectType) + { + return objectType == typeof(ManifestDependency[]); + } + + + /********* + ** Protected methods + *********/ + /// Read the JSON representation of the object. + /// The JSON reader. + /// The object type. + /// The object being read. + /// The calling serializer. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + List result = new List(); + foreach (JObject obj in JArray.Load(reader).Children()) + { + string uniqueID = obj.ValueIgnoreCase(nameof(ManifestDependency.UniqueID)); + string minVersion = obj.ValueIgnoreCase(nameof(ManifestDependency.MinimumVersion)); + bool required = obj.ValueIgnoreCase(nameof(ManifestDependency.IsRequired)) ?? true; + result.Add(new ManifestDependency(uniqueID, minVersion, required)); + } + return result.ToArray(); + } + + /// Writes the JSON representation of the object. + /// The JSON writer. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + throw new InvalidOperationException("This converter does not write JSON."); + } + } +} diff --git a/src/SMAPI.Toolkit/Serialization/Converters/SemanticVersionConverter.cs b/src/SMAPI.Toolkit/Serialization/Converters/SemanticVersionConverter.cs new file mode 100644 index 00000000..ece4a72e --- /dev/null +++ b/src/SMAPI.Toolkit/Serialization/Converters/SemanticVersionConverter.cs @@ -0,0 +1,86 @@ +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace StardewModdingAPI.Toolkit.Serialization.Converters +{ + /// Handles deserialization of . + internal class SemanticVersionConverter : JsonConverter + { + /********* + ** Accessors + *********/ + /// Get whether this converter can read JSON. + public override bool CanRead => true; + + /// Get whether this converter can write JSON. + public override bool CanWrite => true; + + + /********* + ** Public methods + *********/ + /// Get whether this instance can convert the specified object type. + /// The object type. + public override bool CanConvert(Type objectType) + { + return typeof(ISemanticVersion).IsAssignableFrom(objectType); + } + + /// Reads the JSON representation of the object. + /// The JSON reader. + /// The object type. + /// The object being read. + /// The calling serializer. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + string path = reader.Path; + switch (reader.TokenType) + { + case JsonToken.StartObject: + return this.ReadObject(JObject.Load(reader)); + case JsonToken.String: + return this.ReadString(JToken.Load(reader).Value(), path); + default: + throw new SParseException($"Can't parse {nameof(ISemanticVersion)} from {reader.TokenType} node (path: {reader.Path})."); + } + } + + /// Writes the JSON representation of the object. + /// The JSON writer. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteValue(value?.ToString()); + } + + + /********* + ** Private methods + *********/ + /// Read a JSON object. + /// The JSON object to read. + private ISemanticVersion ReadObject(JObject obj) + { + int major = obj.ValueIgnoreCase(nameof(ISemanticVersion.MajorVersion)); + int minor = obj.ValueIgnoreCase(nameof(ISemanticVersion.MinorVersion)); + int patch = obj.ValueIgnoreCase(nameof(ISemanticVersion.PatchVersion)); + string prereleaseTag = obj.ValueIgnoreCase(nameof(ISemanticVersion.PrereleaseTag)); + + return new SemanticVersion(major, minor, patch, prereleaseTag); + } + + /// Read a JSON string. + /// The JSON string value. + /// The path to the current JSON node. + private ISemanticVersion ReadString(string str, string path) + { + if (string.IsNullOrWhiteSpace(str)) + return null; + if (!SemanticVersion.TryParse(str, out ISemanticVersion version)) + throw new SParseException($"Can't parse semantic version from invalid value '{str}', should be formatted like 1.2, 1.2.30, or 1.2.30-beta (path: {path})."); + return version; + } + } +} diff --git a/src/SMAPI.Toolkit/Serialization/Converters/SimpleReadOnlyConverter.cs b/src/SMAPI.Toolkit/Serialization/Converters/SimpleReadOnlyConverter.cs new file mode 100644 index 00000000..549f0c18 --- /dev/null +++ b/src/SMAPI.Toolkit/Serialization/Converters/SimpleReadOnlyConverter.cs @@ -0,0 +1,76 @@ +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace StardewModdingAPI.Toolkit.Serialization.Converters +{ + /// The base implementation for simplified converters which deserialize without overriding serialization. + /// The type to deserialize. + internal abstract class SimpleReadOnlyConverter : JsonConverter + { + /********* + ** Accessors + *********/ + /// Whether this converter can write JSON. + public override bool CanWrite => false; + + + /********* + ** Public methods + *********/ + /// Get whether this instance can convert the specified object type. + /// The object type. + public override bool CanConvert(Type objectType) + { + return objectType == typeof(T); + } + + /// Writes the JSON representation of the object. + /// The JSON writer. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + throw new InvalidOperationException("This converter does not write JSON."); + } + + /// Reads the JSON representation of the object. + /// The JSON reader. + /// The object type. + /// The object being read. + /// The calling serializer. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + string path = reader.Path; + switch (reader.TokenType) + { + case JsonToken.StartObject: + return this.ReadObject(JObject.Load(reader), path); + case JsonToken.String: + return this.ReadString(JToken.Load(reader).Value(), path); + default: + throw new SParseException($"Can't parse {typeof(T).Name} from {reader.TokenType} node (path: {reader.Path})."); + } + } + + + /********* + ** Protected methods + *********/ + /// Read a JSON object. + /// The JSON object to read. + /// The path to the current JSON node. + protected virtual T ReadObject(JObject obj, string path) + { + throw new SParseException($"Can't parse {typeof(T).Name} from object node (path: {path})."); + } + + /// Read a JSON string. + /// The JSON string value. + /// The path to the current JSON node. + protected virtual T ReadString(string str, string path) + { + throw new SParseException($"Can't parse {typeof(T).Name} from string node (path: {path})."); + } + } +} diff --git a/src/SMAPI.Toolkit/Serialization/InternalExtensions.cs b/src/SMAPI.Toolkit/Serialization/InternalExtensions.cs new file mode 100644 index 00000000..9aba53bf --- /dev/null +++ b/src/SMAPI.Toolkit/Serialization/InternalExtensions.cs @@ -0,0 +1,21 @@ +using System; +using Newtonsoft.Json.Linq; + +namespace StardewModdingAPI.Toolkit.Serialization +{ + /// Provides extension methods for parsing JSON. + public static class JsonExtensions + { + /// Get a JSON field value from a case-insensitive field name. This will check for an exact match first, then search without case sensitivity. + /// The value type. + /// The JSON object to search. + /// The field name. + public static T ValueIgnoreCase(this JObject obj, string fieldName) + { + JToken token = obj.GetValue(fieldName, StringComparison.InvariantCultureIgnoreCase); + return token != null + ? token.Value() + : default(T); + } + } +} diff --git a/src/SMAPI.Toolkit/Serialization/JsonHelper.cs b/src/SMAPI.Toolkit/Serialization/JsonHelper.cs new file mode 100644 index 00000000..031afbb0 --- /dev/null +++ b/src/SMAPI.Toolkit/Serialization/JsonHelper.cs @@ -0,0 +1,136 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using StardewModdingAPI.Toolkit.Serialization.Converters; + +namespace StardewModdingAPI.Toolkit.Serialization +{ + /// Encapsulates SMAPI's JSON file parsing. + public class JsonHelper + { + /********* + ** Accessors + *********/ + /// The JSON settings to use when serializing and deserializing files. + public JsonSerializerSettings JsonSettings { get; } = new JsonSerializerSettings + { + Formatting = Formatting.Indented, + ObjectCreationHandling = ObjectCreationHandling.Replace, // avoid issue where default ICollection values are duplicated each time the config is loaded + Converters = new List + { + new SemanticVersionConverter(), + new StringEnumConverter() + } + }; + + + /********* + ** Public methods + *********/ + /// Read a JSON file. + /// The model type. + /// The absolute file path. + /// The parsed content model. + /// Returns false if the file doesn't exist, else true. + /// The given is empty or invalid. + /// The file contains invalid JSON. + public bool ReadJsonFileIfExists(string fullPath, out TModel result) + { + // validate + if (string.IsNullOrWhiteSpace(fullPath)) + throw new ArgumentException("The file path is empty or invalid.", nameof(fullPath)); + + // read file + string json; + try + { + json = File.ReadAllText(fullPath); + } + catch (Exception ex) when (ex is DirectoryNotFoundException || ex is FileNotFoundException) + { + result = default(TModel); + return false; + } + + // deserialize model + try + { + result = this.Deserialize(json); + return true; + } + catch (Exception ex) + { + string error = $"Can't parse JSON file at {fullPath}."; + + if (ex is JsonReaderException) + { + error += " This doesn't seem to be valid JSON."; + if (json.Contains("“") || json.Contains("”")) + error += " Found curly quotes in the text; note that only straight quotes are allowed in JSON."; + } + error += $"\nTechnical details: {ex.Message}"; + throw new JsonReaderException(error); + } + } + + /// Save to a JSON file. + /// The model type. + /// The absolute file path. + /// The model to save. + /// The given path is empty or invalid. + public void WriteJsonFile(string fullPath, TModel model) + where TModel : class + { + // validate + if (string.IsNullOrWhiteSpace(fullPath)) + throw new ArgumentException("The file path is empty or invalid.", nameof(fullPath)); + + // create directory if needed + string dir = Path.GetDirectoryName(fullPath); + if (dir == null) + throw new ArgumentException("The file path is invalid.", nameof(fullPath)); + if (!Directory.Exists(dir)) + Directory.CreateDirectory(dir); + + // write file + string json = this.Serialize(model); + File.WriteAllText(fullPath, json); + } + + /// Deserialize JSON text if possible. + /// The model type. + /// The raw JSON text. + public TModel Deserialize(string json) + { + try + { + return JsonConvert.DeserializeObject(json, this.JsonSettings); + } + catch (JsonReaderException) + { + // try replacing curly quotes + if (json.Contains("“") || json.Contains("”")) + { + try + { + return JsonConvert.DeserializeObject(json.Replace('“', '"').Replace('”', '"'), this.JsonSettings); + } + catch { /* rethrow original error */ } + } + + throw; + } + } + + /// Serialize a model to JSON text. + /// The model type. + /// The model to serialize. + /// The formatting to apply. + public string Serialize(TModel model, Formatting formatting = Formatting.Indented) + { + return JsonConvert.SerializeObject(model, formatting, this.JsonSettings); + } + } +} diff --git a/src/SMAPI.Toolkit/Serialization/Models/Manifest.cs b/src/SMAPI.Toolkit/Serialization/Models/Manifest.cs new file mode 100644 index 00000000..99e85cbd --- /dev/null +++ b/src/SMAPI.Toolkit/Serialization/Models/Manifest.cs @@ -0,0 +1,74 @@ +using System.Collections.Generic; +using Newtonsoft.Json; +using StardewModdingAPI.Toolkit.Serialization.Converters; + +namespace StardewModdingAPI.Toolkit.Serialization.Models +{ + /// A manifest which describes a mod for SMAPI. + public class Manifest : IManifest + { + /********* + ** Accessors + *********/ + /// The mod name. + public string Name { get; set; } + + /// A brief description of the mod. + public string Description { get; set; } + + /// The mod author's name. + public string Author { get; set; } + + /// The mod version. + public ISemanticVersion Version { get; set; } + + /// The minimum SMAPI version required by this mod, if any. + public ISemanticVersion MinimumApiVersion { get; set; } + + /// The name of the DLL in the directory that has the Entry method. Mutually exclusive with . + public string EntryDll { get; set; } + + /// The mod which will read this as a content pack. Mutually exclusive with . + [JsonConverter(typeof(ManifestContentPackForConverter))] + public IManifestContentPackFor ContentPackFor { get; set; } + + /// The other mods that must be loaded before this mod. + [JsonConverter(typeof(ManifestDependencyArrayConverter))] + public IManifestDependency[] Dependencies { get; set; } + + /// The namespaced mod IDs to query for updates (like Nexus:541). + public string[] UpdateKeys { get; set; } + + /// The unique mod ID. + public string UniqueID { get; set; } + + /// Any manifest fields which didn't match a valid field. + [JsonExtensionData] + public IDictionary ExtraFields { get; set; } + + + /********* + ** Public methods + *********/ + /// Construct an instance. + public Manifest() { } + + /// Construct an instance for a transitional content pack. + /// The unique mod ID. + /// The mod name. + /// The mod author's name. + /// A brief description of the mod. + /// The mod version. + /// The modID which will read this as a content pack. + public Manifest(string uniqueID, string name, string author, string description, ISemanticVersion version, string contentPackFor = null) + { + this.Name = name; + this.Author = author; + this.Description = description; + this.Version = version; + this.UniqueID = uniqueID; + this.UpdateKeys = new string[0]; + this.ContentPackFor = new ManifestContentPackFor { UniqueID = contentPackFor }; + } + } +} diff --git a/src/SMAPI.Toolkit/Serialization/Models/ManifestContentPackFor.cs b/src/SMAPI.Toolkit/Serialization/Models/ManifestContentPackFor.cs new file mode 100644 index 00000000..1eb80889 --- /dev/null +++ b/src/SMAPI.Toolkit/Serialization/Models/ManifestContentPackFor.cs @@ -0,0 +1,15 @@ +namespace StardewModdingAPI.Toolkit.Serialization.Models +{ + /// Indicates which mod can read the content pack represented by the containing manifest. + public class ManifestContentPackFor : IManifestContentPackFor + { + /********* + ** Accessors + *********/ + /// The unique ID of the mod which can read this content pack. + public string UniqueID { get; set; } + + /// The minimum required version (if any). + public ISemanticVersion MinimumVersion { get; set; } + } +} diff --git a/src/SMAPI.Toolkit/Serialization/Models/ManifestDependency.cs b/src/SMAPI.Toolkit/Serialization/Models/ManifestDependency.cs new file mode 100644 index 00000000..00f168f4 --- /dev/null +++ b/src/SMAPI.Toolkit/Serialization/Models/ManifestDependency.cs @@ -0,0 +1,35 @@ +namespace StardewModdingAPI.Toolkit.Serialization.Models +{ + /// A mod dependency listed in a mod manifest. + public class ManifestDependency : IManifestDependency + { + /********* + ** Accessors + *********/ + /// The unique mod ID to require. + public string UniqueID { get; set; } + + /// The minimum required version (if any). + public ISemanticVersion MinimumVersion { get; set; } + + /// Whether the dependency must be installed to use the mod. + public bool IsRequired { get; set; } + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The unique mod ID to require. + /// The minimum required version (if any). + /// Whether the dependency must be installed to use the mod. + public ManifestDependency(string uniqueID, string minimumVersion, bool required = true) + { + this.UniqueID = uniqueID; + this.MinimumVersion = !string.IsNullOrWhiteSpace(minimumVersion) + ? new SemanticVersion(minimumVersion) + : null; + this.IsRequired = required; + } + } +} diff --git a/src/SMAPI.Toolkit/Serialization/SParseException.cs b/src/SMAPI.Toolkit/Serialization/SParseException.cs new file mode 100644 index 00000000..5f58b5b8 --- /dev/null +++ b/src/SMAPI.Toolkit/Serialization/SParseException.cs @@ -0,0 +1,17 @@ +using System; + +namespace StardewModdingAPI.Toolkit.Serialization +{ + /// A format exception which provides a user-facing error message. + internal class SParseException : FormatException + { + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The error message. + /// The underlying exception, if any. + public SParseException(string message, Exception ex = null) + : base(message, ex) { } + } +} diff --git a/src/SMAPI.Toolkit/Utilities/PathUtilities.cs b/src/SMAPI.Toolkit/Utilities/PathUtilities.cs index 8a3c2b03..40a59d87 100644 --- a/src/SMAPI.Toolkit/Utilities/PathUtilities.cs +++ b/src/SMAPI.Toolkit/Utilities/PathUtilities.cs @@ -6,7 +6,7 @@ using System.Text.RegularExpressions; namespace StardewModdingAPI.Toolkit.Utilities { - /// Provides utilities for normalising file paths. + /// Provides utilities for normalizing file paths. public static class PathUtilities { /********* @@ -15,14 +15,14 @@ namespace StardewModdingAPI.Toolkit.Utilities /// The possible directory separator characters in a file path. private static readonly char[] PossiblePathSeparators = new[] { '/', '\\', Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }.Distinct().ToArray(); - /// The preferred directory separator chaeacter in an asset key. + /// The preferred directory separator character in an asset key. private static readonly string PreferredPathSeparator = Path.DirectorySeparatorChar.ToString(); /********* ** Public methods *********/ - /// Get the segments from a path (e.g. /usr/bin/boop => usr, bin, and boop). + /// Get the segments from a path (e.g. /usr/bin/example => usr, bin, and example). /// The path to split. /// The number of segments to match. Any additional segments will be merged into the last returned part. public static string[] GetSegments(string path, int? limit = null) @@ -32,16 +32,16 @@ namespace StardewModdingAPI.Toolkit.Utilities : path.Split(PathUtilities.PossiblePathSeparators, StringSplitOptions.RemoveEmptyEntries); } - /// Normalise path separators in a file path. - /// The file path to normalise. + /// Normalize path separators in a file path. + /// The file path to normalize. [Pure] - public static string NormalisePathSeparators(string path) + public static string NormalizePathSeparators(string path) { string[] parts = PathUtilities.GetSegments(path); - string normalised = string.Join(PathUtilities.PreferredPathSeparator, parts); + string normalized = string.Join(PathUtilities.PreferredPathSeparator, parts); if (path.StartsWith(PathUtilities.PreferredPathSeparator)) - normalised = PathUtilities.PreferredPathSeparator + normalised; // keep root slash - return normalised; + normalized = PathUtilities.PreferredPathSeparator + normalized; // keep root slash + return normalized; } /// Get a directory or file path relative to a given source path. @@ -57,7 +57,7 @@ namespace StardewModdingAPI.Toolkit.Utilities throw new InvalidOperationException($"Can't get path for '{targetPath}' relative to '{sourceDir}'."); // get relative path - string relative = PathUtilities.NormalisePathSeparators(Uri.UnescapeDataString(from.MakeRelativeUri(to).ToString())); + string relative = PathUtilities.NormalizePathSeparators(Uri.UnescapeDataString(from.MakeRelativeUri(to).ToString())); if (relative == "") relative = "./"; return relative; diff --git a/src/SMAPI.Web/BackgroundService.cs b/src/SMAPI.Web/BackgroundService.cs index dfd2c1b9..cb400fbe 100644 --- a/src/SMAPI.Web/BackgroundService.cs +++ b/src/SMAPI.Web/BackgroundService.cs @@ -11,7 +11,7 @@ using StardewModdingAPI.Web.Framework.Caching.Wiki; namespace StardewModdingAPI.Web { /// A hosted service which runs background data updates. - /// Task methods need to be static, since otherwise Hangfire will try to serialise the entire instance. + /// Task methods need to be static, since otherwise Hangfire will try to serialize the entire instance. internal class BackgroundService : IHostedService, IDisposable { /********* @@ -94,8 +94,8 @@ namespace StardewModdingAPI.Web /********* ** Private method *********/ - /// Initialise the background service if it's not already initialised. - /// The background service is already initialised. + /// Initialize the background service if it's not already initialized. + /// The background service is already initialized. private void TryInit() { if (BackgroundService.JobServer != null) diff --git a/src/SMAPI.Web/Controllers/JsonValidatorController.cs b/src/SMAPI.Web/Controllers/JsonValidatorController.cs index d82765e7..31471141 100644 --- a/src/SMAPI.Web/Controllers/JsonValidatorController.cs +++ b/src/SMAPI.Web/Controllers/JsonValidatorController.cs @@ -79,7 +79,7 @@ namespace StardewModdingAPI.Web.Controllers [Route("json/{schemaName}/{id}")] public async Task Index(string schemaName = null, string id = null) { - schemaName = this.NormaliseSchemaName(schemaName); + schemaName = this.NormalizeSchemaName(schemaName); var result = new JsonValidatorModel(this.SectionUrl, id, schemaName, this.SchemaFormats); if (string.IsNullOrWhiteSpace(id)) @@ -143,8 +143,8 @@ namespace StardewModdingAPI.Web.Controllers if (request == null) return this.View("Index", new JsonValidatorModel(this.SectionUrl, null, null, this.SchemaFormats).SetUploadError("The request seems to be invalid.")); - // normalise schema name - string schemaName = this.NormaliseSchemaName(request.SchemaName); + // normalize schema name + string schemaName = this.NormalizeSchemaName(request.SchemaName); // get raw log text string input = request.Content; @@ -178,9 +178,9 @@ namespace StardewModdingAPI.Web.Controllers return response; } - /// Get a normalised schema name, or the if blank. - /// The raw schema name to normalise. - private string NormaliseSchemaName(string schemaName) + /// Get a normalized schema name, or the if blank. + /// The raw schema name to normalize. + private string NormalizeSchemaName(string schemaName) { schemaName = schemaName?.Trim().ToLower(); return !string.IsNullOrWhiteSpace(schemaName) @@ -192,7 +192,7 @@ namespace StardewModdingAPI.Web.Controllers /// The schema ID. private FileInfo FindSchemaFile(string id) { - // normalise ID + // normalize ID id = id?.Trim().ToLower(); if (string.IsNullOrWhiteSpace(id)) return null; diff --git a/src/SMAPI.Web/Controllers/ModsApiController.cs b/src/SMAPI.Web/Controllers/ModsApiController.cs index a7398eee..8419b220 100644 --- a/src/SMAPI.Web/Controllers/ModsApiController.cs +++ b/src/SMAPI.Web/Controllers/ModsApiController.cs @@ -120,7 +120,7 @@ namespace StardewModdingAPI.Web.Controllers /// Returns the mod data if found, else null. private async Task GetModData(ModSearchEntryModel search, WikiModEntry[] wikiData, bool includeExtendedMetadata) { - // crossreference data + // cross-reference data ModDataRecord record = this.ModDatabase.Get(search.ID); WikiModEntry wikiEntry = wikiData.FirstOrDefault(entry => entry.ID.Contains(search.ID.Trim(), StringComparer.InvariantCultureIgnoreCase)); UpdateKey[] updateKeys = this.GetUpdateKeys(search.UpdateKeys, record, wikiEntry).ToArray(); diff --git a/src/SMAPI.Web/Framework/AllowLargePostsAttribute.cs b/src/SMAPI.Web/Framework/AllowLargePostsAttribute.cs index 5dc0feb6..864aa215 100644 --- a/src/SMAPI.Web/Framework/AllowLargePostsAttribute.cs +++ b/src/SMAPI.Web/Framework/AllowLargePostsAttribute.cs @@ -36,7 +36,7 @@ namespace StardewModdingAPI.Web.Framework } /// Called early in the filter pipeline to confirm request is authorized. - /// The authorisation filter context. + /// The authorization filter context. public void OnAuthorization(AuthorizationFilterContext context) { IFeatureCollection features = context.HttpContext.Features; diff --git a/src/SMAPI.Web/Framework/Caching/Mods/ModCacheRepository.cs b/src/SMAPI.Web/Framework/Caching/Mods/ModCacheRepository.cs index 4258cc85..2e7804a7 100644 --- a/src/SMAPI.Web/Framework/Caching/Mods/ModCacheRepository.cs +++ b/src/SMAPI.Web/Framework/Caching/Mods/ModCacheRepository.cs @@ -40,7 +40,7 @@ namespace StardewModdingAPI.Web.Framework.Caching.Mods public bool TryGetMod(ModRepositoryKey site, string id, out CachedMod mod, bool markRequested = true) { // get mod - id = this.NormaliseId(id); + id = this.NormalizeId(id); mod = this.Mods.Find(entry => entry.ID == id && entry.Site == site).FirstOrDefault(); if (mod == null) return false; @@ -62,7 +62,7 @@ namespace StardewModdingAPI.Web.Framework.Caching.Mods /// The stored mod record. public void SaveMod(ModRepositoryKey site, string id, ModInfoModel mod, out CachedMod cachedMod) { - id = this.NormaliseId(id); + id = this.NormalizeId(id); cachedMod = this.SaveMod(new CachedMod(site, id, mod)); } @@ -83,7 +83,7 @@ namespace StardewModdingAPI.Web.Framework.Caching.Mods /// The mod data. public CachedMod SaveMod(CachedMod mod) { - string id = this.NormaliseId(mod.ID); + string id = this.NormalizeId(mod.ID); this.Mods.ReplaceOne( entry => entry.ID == id && entry.Site == mod.Site, @@ -94,9 +94,9 @@ namespace StardewModdingAPI.Web.Framework.Caching.Mods return mod; } - /// Normalise a mod ID for case-insensitive search. + /// Normalize a mod ID for case-insensitive search. /// The mod ID. - public string NormaliseId(string id) + public string NormalizeId(string id) { return id.Trim().ToLower(); } diff --git a/src/SMAPI.Web/Framework/Caching/UtcDateTimeOffsetSerializer.cs b/src/SMAPI.Web/Framework/Caching/UtcDateTimeOffsetSerializer.cs index ad95a975..6a103e37 100644 --- a/src/SMAPI.Web/Framework/Caching/UtcDateTimeOffsetSerializer.cs +++ b/src/SMAPI.Web/Framework/Caching/UtcDateTimeOffsetSerializer.cs @@ -5,7 +5,7 @@ using MongoDB.Bson.Serialization.Serializers; namespace StardewModdingAPI.Web.Framework.Caching { - /// Serialises to a UTC date field instead of the default array. + /// Serializes to a UTC date field instead of the default array. public class UtcDateTimeOffsetSerializer : StructSerializerBase { /********* diff --git a/src/SMAPI.Web/Framework/JobDashboardAuthorizationFilter.cs b/src/SMAPI.Web/Framework/JobDashboardAuthorizationFilter.cs index 9471d5fe..385c0c91 100644 --- a/src/SMAPI.Web/Framework/JobDashboardAuthorizationFilter.cs +++ b/src/SMAPI.Web/Framework/JobDashboardAuthorizationFilter.cs @@ -2,7 +2,7 @@ using Hangfire.Dashboard; namespace StardewModdingAPI.Web.Framework { - /// Authorises requests to access the Hangfire job dashboard. + /// Authorizes requests to access the Hangfire job dashboard. internal class JobDashboardAuthorizationFilter : IDashboardAuthorizationFilter { /********* @@ -15,7 +15,7 @@ namespace StardewModdingAPI.Web.Framework /********* ** Public methods *********/ - /// Authorise a request. + /// Authorize a request. /// The dashboard context. public bool Authorize(DashboardContext context) { diff --git a/src/SMAPI.Web/Framework/LogParsing/LogParser.cs b/src/SMAPI.Web/Framework/LogParsing/LogParser.cs index 595e6b49..66a3687f 100644 --- a/src/SMAPI.Web/Framework/LogParsing/LogParser.cs +++ b/src/SMAPI.Web/Framework/LogParsing/LogParser.cs @@ -221,7 +221,7 @@ namespace StardewModdingAPI.Web.Framework.LogParsing } } - // finalise log + // finalize log gameMod.Version = log.GameVersion; log.Mods = new[] { gameMod, smapiMod }.Concat(mods.Values.OrderBy(p => p.Name)).ToArray(); return log; diff --git a/src/SMAPI.Web/Framework/ModRepositories/BaseRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/BaseRepository.cs index 94256005..f9f9f47d 100644 --- a/src/SMAPI.Web/Framework/ModRepositories/BaseRepository.cs +++ b/src/SMAPI.Web/Framework/ModRepositories/BaseRepository.cs @@ -34,9 +34,9 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories this.VendorKey = vendorKey; } - /// Normalise a version string. - /// The version to normalise. - protected string NormaliseVersion(string version) + /// Normalize a version string. + /// The version to normalize. + protected string NormalizeVersion(string version) { if (string.IsNullOrWhiteSpace(version)) return null; diff --git a/src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs index c14fb45d..0945735a 100644 --- a/src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs +++ b/src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs @@ -39,7 +39,7 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories { var mod = await this.Client.GetModAsync(realID); return mod != null - ? new ModInfoModel(name: mod.Name, version: this.NormaliseVersion(mod.Version), url: mod.Url) + ? new ModInfoModel(name: mod.Name, version: this.NormalizeVersion(mod.Version), url: mod.Url) : new ModInfoModel().SetError(RemoteModStatus.DoesNotExist, "Found no Chucklefish mod with this ID."); } catch (Exception ex) diff --git a/src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs index e06a2497..c62cb73f 100644 --- a/src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs +++ b/src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs @@ -65,7 +65,7 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories } // return data - return result.SetVersions(version: this.NormaliseVersion(latest.Tag), previewVersion: this.NormaliseVersion(preview?.Tag)); + return result.SetVersions(version: this.NormalizeVersion(latest.Tag), previewVersion: this.NormalizeVersion(preview?.Tag)); } catch (Exception ex) { diff --git a/src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs index b4791f56..9551258c 100644 --- a/src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs +++ b/src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs @@ -48,7 +48,7 @@ namespace StardewModdingAPI.Web.Framework.ModRepositories return new ModInfoModel().SetError(remoteStatus, mod.Error); } - return new ModInfoModel(name: mod.Name, version: this.NormaliseVersion(mod.Version), previewVersion: mod.LatestFileVersion?.ToString(), url: mod.Url); + return new ModInfoModel(name: mod.Name, version: this.NormalizeVersion(mod.Version), previewVersion: mod.LatestFileVersion?.ToString(), url: mod.Url); } catch (Exception ex) { diff --git a/src/SMAPI.Web/Startup.cs b/src/SMAPI.Web/Startup.cs index de45b8a4..da5c1f1b 100644 --- a/src/SMAPI.Web/Startup.cs +++ b/src/SMAPI.Web/Startup.cs @@ -10,7 +10,7 @@ using Microsoft.Extensions.DependencyInjection; using MongoDB.Bson.Serialization; using MongoDB.Driver; using Newtonsoft.Json; -using StardewModdingAPI.Toolkit.Serialisation; +using StardewModdingAPI.Toolkit.Serialization; using StardewModdingAPI.Web.Framework; using StardewModdingAPI.Web.Framework.Caching; using StardewModdingAPI.Web.Framework.Caching.Mods; diff --git a/src/SMAPI.Web/ViewModels/LogParserModel.cs b/src/SMAPI.Web/ViewModels/LogParserModel.cs index 41864c99..25493a29 100644 --- a/src/SMAPI.Web/ViewModels/LogParserModel.cs +++ b/src/SMAPI.Web/ViewModels/LogParserModel.cs @@ -81,7 +81,7 @@ namespace StardewModdingAPI.Web.ViewModels .ToDictionary(group => group.Key, group => group.ToArray()); } - /// Get a sanitised mod name that's safe to use in anchors, attributes, and URLs. + /// Get a sanitized mod name that's safe to use in anchors, attributes, and URLs. /// The mod name. public string GetSlug(string modName) { diff --git a/src/SMAPI.Web/wwwroot/Content/js/json-validator.js b/src/SMAPI.Web/wwwroot/Content/js/json-validator.js index 265e0c5e..5499cef6 100644 --- a/src/SMAPI.Web/wwwroot/Content/js/json-validator.js +++ b/src/SMAPI.Web/wwwroot/Content/js/json-validator.js @@ -120,7 +120,7 @@ smapi.jsonValidator = function (sectionUrl, pasteID) { }; /** - * Initialise the JSON validator page. + * Initialize the JSON validator page. */ var init = function () { // set initial code formatting diff --git a/src/SMAPI.Web/wwwroot/schemas/content-patcher.json b/src/SMAPI.Web/wwwroot/schemas/content-patcher.json index 315a1fb2..e12be408 100644 --- a/src/SMAPI.Web/wwwroot/schemas/content-patcher.json +++ b/src/SMAPI.Web/wwwroot/schemas/content-patcher.json @@ -107,7 +107,7 @@ }, "Target": { "title": "Target asset", - "description": "The game asset you want to patch (or multiple comma-delimited assets). This is the file path inside your game's Content folder, without the file extension or language (like Animals/Dinosaur to edit Content/Animals/Dinosaur.xnb). This field supports tokens and capitalisation doesn't matter. Your changes are applied in all languages unless you specify a language condition.", + "description": "The game asset you want to patch (or multiple comma-delimited assets). This is the file path inside your game's Content folder, without the file extension or language (like Animals/Dinosaur to edit Content/Animals/Dinosaur.xnb). This field supports tokens and capitalization doesn't matter. Your changes are applied in all languages unless you specify a language condition.", "type": "string", "not": { "pattern": "^ *[cC][oO][nN][tT][eE][nN][tT]/|\\.[xX][nN][bB] *$|\\.[a-zA-Z][a-zA-Z]-[a-zA-Z][a-zA-Z](?:.xnb)? *$" @@ -140,7 +140,7 @@ }, "FromFile": { "title": "Source file", - "description": "The relative file path in your content pack folder to load instead (like 'assets/dinosaur.png'). This can be a .json (data), .png (image), .tbin (map), or .xnb file. This field supports tokens and capitalisation doesn't matter.", + "description": "The relative file path in your content pack folder to load instead (like 'assets/dinosaur.png'). This can be a .json (data), .png (image), .tbin (map), or .xnb file. This field supports tokens and capitalization doesn't matter.", "type": "string", "allOf": [ { @@ -310,7 +310,7 @@ "then": { "properties": { "FromFile": { - "description": "The relative path to the map in your content pack folder from which to copy (like assets/town.tbin). This can be a .tbin or .xnb file. This field supports tokens and capitalisation doesn't matter.\nContent Patcher will handle tilesheets referenced by the FromFile map for you if it's a .tbin file:\n - If a tilesheet isn't referenced by the target map, Content Patcher will add it for you (with a z_ ID prefix to avoid conflicts with hardcoded game logic). If the source map has a custom version of a tilesheet that's already referenced, it'll be added as a separate tilesheet only used by your tiles.\n - If you include the tilesheet file in your mod folder, Content Patcher will use that one automatically; otherwise it will be loaded from the game's Content/Maps folder." + "description": "The relative path to the map in your content pack folder from which to copy (like assets/town.tbin). This can be a .tbin or .xnb file. This field supports tokens and capitalization doesn't matter.\nContent Patcher will handle tilesheets referenced by the FromFile map for you if it's a .tbin file:\n - If a tilesheet isn't referenced by the target map, Content Patcher will add it for you (with a z_ ID prefix to avoid conflicts with hardcoded game logic). If the source map has a custom version of a tilesheet that's already referenced, it'll be added as a separate tilesheet only used by your tiles.\n - If you include the tilesheet file in your mod folder, Content Patcher will use that one automatically; otherwise it will be loaded from the game's Content/Maps folder." }, "FromArea": { "description": "The part of the source map to copy. Defaults to the whole source map." diff --git a/src/SMAPI.sln.DotSettings b/src/SMAPI.sln.DotSettings index 5f67fd9e..556f1ec0 100644 --- a/src/SMAPI.sln.DotSettings +++ b/src/SMAPI.sln.DotSettings @@ -23,4 +23,46 @@ True True True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True \ No newline at end of file diff --git a/src/SMAPI/Context.cs b/src/SMAPI/Context.cs index a933752d..a7238b32 100644 --- a/src/SMAPI/Context.cs +++ b/src/SMAPI/Context.cs @@ -14,10 +14,10 @@ namespace StardewModdingAPI /**** ** Public ****/ - /// Whether the game has performed core initialisation. This becomes true right before the first update tick.. + /// Whether the game has performed core initialization. This becomes true right before the first update tick. public static bool IsGameLaunched { get; internal set; } - /// Whether the player has loaded a save and the world has finished initialising. + /// Whether the player has loaded a save and the world has finished initializing. public static bool IsWorldReady { get; internal set; } /// Whether is true and the player is free to act in the world (no menu is displayed, no cutscene is in progress, etc). diff --git a/src/SMAPI/Enums/LoadStage.cs b/src/SMAPI/Enums/LoadStage.cs index 6ff7de4f..5c2b0412 100644 --- a/src/SMAPI/Enums/LoadStage.cs +++ b/src/SMAPI/Enums/LoadStage.cs @@ -6,10 +6,10 @@ namespace StardewModdingAPI.Enums /// A save is not loaded or loading. None, - /// The game is creating a new save slot, and has initialised the basic save info. + /// The game is creating a new save slot, and has initialized the basic save info. CreatedBasicInfo, - /// The game is creating a new save slot, and has initialised the in-game locations. + /// The game is creating a new save slot, and has initialized the in-game locations. CreatedLocations, /// The game is creating a new save slot, and has created the physical save files. @@ -18,7 +18,7 @@ namespace StardewModdingAPI.Enums /// The game is loading a save slot, and has read the raw save data into . Not applicable when connecting to a multiplayer host. This is equivalent to value 20. SaveParsed, - /// The game is loading a save slot, and has applied the basic save info (including player data). Not applicable when connecting to a multiplayer host. Note that some basic info (like daily luck) is not initialised at this point. This is equivalent to value 36. + /// The game is loading a save slot, and has applied the basic save info (including player data). Not applicable when connecting to a multiplayer host. Note that some basic info (like daily luck) is not initialized at this point. This is equivalent to value 36. SaveLoadedBasicInfo, /// The game is loading a save slot, and has applied the in-game location data. Not applicable when connecting to a multiplayer host. This is equivalent to value 50. @@ -27,10 +27,10 @@ namespace StardewModdingAPI.Enums /// The final metadata has been loaded from the save file. This happens before the game applies problem fixes, checks for achievements, starts music, etc. Not applicable when connecting to a multiplayer host. Preloaded, - /// The save is fully loaded, but the world may not be fully initialised yet. + /// The save is fully loaded, but the world may not be fully initialized yet. Loaded, - /// The save is fully loaded, the world has been initialised, and is now true. + /// The save is fully loaded, the world has been initialized, and is now true. Ready } } diff --git a/src/SMAPI/Events/IGameLoopEvents.cs b/src/SMAPI/Events/IGameLoopEvents.cs index 6fb56c8b..a576895b 100644 --- a/src/SMAPI/Events/IGameLoopEvents.cs +++ b/src/SMAPI/Events/IGameLoopEvents.cs @@ -5,7 +5,7 @@ namespace StardewModdingAPI.Events /// Events linked to the game's update loop. The update loop runs roughly ≈60 times/second to run game logic like state changes, action handling, etc. These can be useful, but you should consider more semantic events like if possible. public interface IGameLoopEvents { - /// Raised after the game is launched, right before the first update tick. This happens once per game session (unrelated to loading saves). All mods are loaded and initialised at this point, so this is a good time to set up mod integrations. + /// Raised after the game is launched, right before the first update tick. This happens once per game session (unrelated to loading saves). All mods are loaded and initialized at this point, so this is a good time to set up mod integrations. event EventHandler GameLaunched; /// Raised before the game state is updated (≈60 times per second). @@ -32,7 +32,7 @@ namespace StardewModdingAPI.Events /// Raised after the game finishes writing data to the save file (except the initial save creation). event EventHandler Saved; - /// Raised after the player loads a save slot and the world is initialised. + /// Raised after the player loads a save slot and the world is initialized. event EventHandler SaveLoaded; /// Raised after the game begins a new day (including when the player loads a save). diff --git a/src/SMAPI/Events/IModEvents.cs b/src/SMAPI/Events/IModEvents.cs index bd7ab880..1f892b31 100644 --- a/src/SMAPI/Events/IModEvents.cs +++ b/src/SMAPI/Events/IModEvents.cs @@ -21,7 +21,7 @@ namespace StardewModdingAPI.Events /// Events raised when something changes in the world. IWorldEvents World { get; } - /// Events serving specialised edge cases that shouldn't be used by most mods. - ISpecialisedEvents Specialised { get; } + /// Events serving specialized edge cases that shouldn't be used by most mods. + ISpecializedEvents Specialized { get; } } } diff --git a/src/SMAPI/Events/ISpecialisedEvents.cs b/src/SMAPI/Events/ISpecialisedEvents.cs index ecb109e6..bf70956d 100644 --- a/src/SMAPI/Events/ISpecialisedEvents.cs +++ b/src/SMAPI/Events/ISpecialisedEvents.cs @@ -2,8 +2,8 @@ using System; namespace StardewModdingAPI.Events { - /// Events serving specialised edge cases that shouldn't be used by most mods. - public interface ISpecialisedEvents + /// Events serving specialized edge cases that shouldn't be used by most mods. + public interface ISpecializedEvents { /// Raised when the low-level stage in the game's loading process has changed. This is an advanced event for mods which need to run code at specific points in the loading process. The available stages or when they happen might change without warning in future versions (e.g. due to changes in the game's load process), so mods using this event are more likely to break or have bugs. Most mods should use instead. event EventHandler LoadStageChanged; diff --git a/src/SMAPI/Events/LoadStageChangedEventArgs.cs b/src/SMAPI/Events/LoadStageChangedEventArgs.cs index e837a5f1..3529dcf3 100644 --- a/src/SMAPI/Events/LoadStageChangedEventArgs.cs +++ b/src/SMAPI/Events/LoadStageChangedEventArgs.cs @@ -3,7 +3,7 @@ using StardewModdingAPI.Enums; namespace StardewModdingAPI.Events { - /// Event arguments for an event. + /// Event arguments for an event. public class LoadStageChangedEventArgs : EventArgs { /********* diff --git a/src/SMAPI/Events/UnvalidatedUpdateTickedEventArgs.cs b/src/SMAPI/Events/UnvalidatedUpdateTickedEventArgs.cs index 13c367a0..258e2f99 100644 --- a/src/SMAPI/Events/UnvalidatedUpdateTickedEventArgs.cs +++ b/src/SMAPI/Events/UnvalidatedUpdateTickedEventArgs.cs @@ -3,7 +3,7 @@ using StardewModdingAPI.Framework; namespace StardewModdingAPI.Events { - /// Event arguments for an event. + /// Event arguments for an event. public class UnvalidatedUpdateTickedEventArgs : EventArgs { /********* diff --git a/src/SMAPI/Events/UnvalidatedUpdateTickingEventArgs.cs b/src/SMAPI/Events/UnvalidatedUpdateTickingEventArgs.cs index c2e60f25..e3c8b3ee 100644 --- a/src/SMAPI/Events/UnvalidatedUpdateTickingEventArgs.cs +++ b/src/SMAPI/Events/UnvalidatedUpdateTickingEventArgs.cs @@ -3,7 +3,7 @@ using StardewModdingAPI.Framework; namespace StardewModdingAPI.Events { - /// Event arguments for an event. + /// Event arguments for an event. public class UnvalidatedUpdateTickingEventArgs : EventArgs { /********* diff --git a/src/SMAPI/Framework/CommandManager.cs b/src/SMAPI/Framework/CommandManager.cs index fdaafff1..ceeb6f93 100644 --- a/src/SMAPI/Framework/CommandManager.cs +++ b/src/SMAPI/Framework/CommandManager.cs @@ -29,7 +29,7 @@ namespace StardewModdingAPI.Framework /// There's already a command with that name. public void Add(IModMetadata mod, string name, string documentation, Action callback, bool allowNullCallback = false) { - name = this.GetNormalisedName(name); + name = this.GetNormalizedName(name); // validate format if (string.IsNullOrWhiteSpace(name)) @@ -52,7 +52,7 @@ namespace StardewModdingAPI.Framework /// Returns the matching command, or null if not found. public Command Get(string name) { - name = this.GetNormalisedName(name); + name = this.GetNormalizedName(name); this.Commands.TryGetValue(name, out Command command); return command; } @@ -84,7 +84,7 @@ namespace StardewModdingAPI.Framework // parse input args = this.ParseArgs(input); - name = this.GetNormalisedName(args[0]); + name = this.GetNormalizedName(args[0]); args = args.Skip(1).ToArray(); // get command @@ -97,8 +97,8 @@ namespace StardewModdingAPI.Framework /// Returns whether a matching command was triggered. public bool Trigger(string name, string[] arguments) { - // get normalised name - name = this.GetNormalisedName(name); + // get normalized name + name = this.GetNormalizedName(name); if (name == null) return false; @@ -140,9 +140,9 @@ namespace StardewModdingAPI.Framework return args.Where(item => !string.IsNullOrWhiteSpace(item)).ToArray(); } - /// Get a normalised command name. + /// Get a normalized command name. /// The command name. - private string GetNormalisedName(string name) + private string GetNormalizedName(string name) { name = name?.Trim().ToLower(); return !string.IsNullOrWhiteSpace(name) diff --git a/src/SMAPI/Framework/Content/AssetData.cs b/src/SMAPI/Framework/Content/AssetData.cs index 553404d3..cacc6078 100644 --- a/src/SMAPI/Framework/Content/AssetData.cs +++ b/src/SMAPI/Framework/Content/AssetData.cs @@ -24,13 +24,13 @@ namespace StardewModdingAPI.Framework.Content ** Public methods *********/ /// Construct an instance. - /// The content's locale code, if the content is localised. - /// The normalised asset name being read. + /// The content's locale code, if the content is localized. + /// The normalized asset name being read. /// The content data being read. - /// Normalises an asset key to match the cache key. + /// Normalizes an asset key to match the cache key. /// A callback to invoke when the data is replaced (if any). - public AssetData(string locale, string assetName, TValue data, Func getNormalisedPath, Action onDataReplaced) - : base(locale, assetName, data.GetType(), getNormalisedPath) + public AssetData(string locale, string assetName, TValue data, Func getNormalizedPath, Action onDataReplaced) + : base(locale, assetName, data.GetType(), getNormalizedPath) { this.Data = data; this.OnDataReplaced = onDataReplaced; diff --git a/src/SMAPI/Framework/Content/AssetDataForDictionary.cs b/src/SMAPI/Framework/Content/AssetDataForDictionary.cs index a331f38a..26cbff5a 100644 --- a/src/SMAPI/Framework/Content/AssetDataForDictionary.cs +++ b/src/SMAPI/Framework/Content/AssetDataForDictionary.cs @@ -10,12 +10,12 @@ namespace StardewModdingAPI.Framework.Content ** Public methods *********/ /// Construct an instance. - /// The content's locale code, if the content is localised. - /// The normalised asset name being read. + /// The content's locale code, if the content is localized. + /// The normalized asset name being read. /// The content data being read. - /// Normalises an asset key to match the cache key. + /// Normalizes an asset key to match the cache key. /// A callback to invoke when the data is replaced (if any). - public AssetDataForDictionary(string locale, string assetName, IDictionary data, Func getNormalisedPath, Action> onDataReplaced) - : base(locale, assetName, data, getNormalisedPath, onDataReplaced) { } + public AssetDataForDictionary(string locale, string assetName, IDictionary data, Func getNormalizedPath, Action> onDataReplaced) + : base(locale, assetName, data, getNormalizedPath, onDataReplaced) { } } } diff --git a/src/SMAPI/Framework/Content/AssetDataForImage.cs b/src/SMAPI/Framework/Content/AssetDataForImage.cs index f2d21b5e..4ae2ad68 100644 --- a/src/SMAPI/Framework/Content/AssetDataForImage.cs +++ b/src/SMAPI/Framework/Content/AssetDataForImage.cs @@ -19,13 +19,13 @@ namespace StardewModdingAPI.Framework.Content ** Public methods *********/ /// Construct an instance. - /// The content's locale code, if the content is localised. - /// The normalised asset name being read. + /// The content's locale code, if the content is localized. + /// The normalized asset name being read. /// The content data being read. - /// Normalises an asset key to match the cache key. + /// Normalizes an asset key to match the cache key. /// A callback to invoke when the data is replaced (if any). - public AssetDataForImage(string locale, string assetName, Texture2D data, Func getNormalisedPath, Action onDataReplaced) - : base(locale, assetName, data, getNormalisedPath, onDataReplaced) { } + public AssetDataForImage(string locale, string assetName, Texture2D data, Func getNormalizedPath, Action onDataReplaced) + : base(locale, assetName, data, getNormalizedPath, onDataReplaced) { } /// Overwrite part of the image. /// The image to patch into the content. diff --git a/src/SMAPI/Framework/Content/AssetDataForObject.cs b/src/SMAPI/Framework/Content/AssetDataForObject.cs index 90f9e2d4..4dbc988c 100644 --- a/src/SMAPI/Framework/Content/AssetDataForObject.cs +++ b/src/SMAPI/Framework/Content/AssetDataForObject.cs @@ -11,19 +11,19 @@ namespace StardewModdingAPI.Framework.Content ** Public methods *********/ /// Construct an instance. - /// The content's locale code, if the content is localised. - /// The normalised asset name being read. + /// The content's locale code, if the content is localized. + /// The normalized asset name being read. /// The content data being read. - /// Normalises an asset key to match the cache key. - public AssetDataForObject(string locale, string assetName, object data, Func getNormalisedPath) - : base(locale, assetName, data, getNormalisedPath, onDataReplaced: null) { } + /// Normalizes an asset key to match the cache key. + public AssetDataForObject(string locale, string assetName, object data, Func getNormalizedPath) + : base(locale, assetName, data, getNormalizedPath, onDataReplaced: null) { } /// Construct an instance. /// The asset metadata. /// The content data being read. - /// Normalises an asset key to match the cache key. - public AssetDataForObject(IAssetInfo info, object data, Func getNormalisedPath) - : this(info.Locale, info.AssetName, data, getNormalisedPath) { } + /// Normalizes an asset key to match the cache key. + public AssetDataForObject(IAssetInfo info, object data, Func getNormalizedPath) + : this(info.Locale, info.AssetName, data, getNormalizedPath) { } /// Get a helper to manipulate the data as a dictionary. /// The expected dictionary key. @@ -31,14 +31,14 @@ namespace StardewModdingAPI.Framework.Content /// The content being read isn't a dictionary. public IAssetDataForDictionary AsDictionary() { - return new AssetDataForDictionary(this.Locale, this.AssetName, this.GetData>(), this.GetNormalisedPath, this.ReplaceWith); + return new AssetDataForDictionary(this.Locale, this.AssetName, this.GetData>(), this.GetNormalizedPath, this.ReplaceWith); } /// Get a helper to manipulate the data as an image. /// The content being read isn't an image. public IAssetDataForImage AsImage() { - return new AssetDataForImage(this.Locale, this.AssetName, this.GetData(), this.GetNormalisedPath, this.ReplaceWith); + return new AssetDataForImage(this.Locale, this.AssetName, this.GetData(), this.GetNormalizedPath, this.ReplaceWith); } /// Get the data as a given type. diff --git a/src/SMAPI/Framework/Content/AssetInfo.cs b/src/SMAPI/Framework/Content/AssetInfo.cs index e5211290..9b685e72 100644 --- a/src/SMAPI/Framework/Content/AssetInfo.cs +++ b/src/SMAPI/Framework/Content/AssetInfo.cs @@ -9,17 +9,17 @@ namespace StardewModdingAPI.Framework.Content /********* ** Fields *********/ - /// Normalises an asset key to match the cache key. - protected readonly Func GetNormalisedPath; + /// Normalizes an asset key to match the cache key. + protected readonly Func GetNormalizedPath; /********* ** Accessors *********/ - /// The content's locale code, if the content is localised. + /// The content's locale code, if the content is localized. public string Locale { get; } - /// The normalised asset name being read. The format may change between platforms; see to compare with a known path. + /// The normalized asset name being read. The format may change between platforms; see to compare with a known path. public string AssetName { get; } /// The content data type. @@ -30,23 +30,23 @@ namespace StardewModdingAPI.Framework.Content ** Public methods *********/ /// Construct an instance. - /// The content's locale code, if the content is localised. - /// The normalised asset name being read. + /// The content's locale code, if the content is localized. + /// The normalized asset name being read. /// The content type being read. - /// Normalises an asset key to match the cache key. - public AssetInfo(string locale, string assetName, Type type, Func getNormalisedPath) + /// Normalizes an asset key to match the cache key. + public AssetInfo(string locale, string assetName, Type type, Func getNormalizedPath) { this.Locale = locale; this.AssetName = assetName; this.DataType = type; - this.GetNormalisedPath = getNormalisedPath; + this.GetNormalizedPath = getNormalizedPath; } - /// Get whether the asset name being loaded matches a given name after normalisation. + /// Get whether the asset name being loaded matches a given name after normalization. /// The expected asset path, relative to the game's content folder and without the .xnb extension or locale suffix (like 'Data\ObjectInformation'). public bool AssetNameEquals(string path) { - path = this.GetNormalisedPath(path); + path = this.GetNormalizedPath(path); return this.AssetName.Equals(path, StringComparison.InvariantCultureIgnoreCase); } diff --git a/src/SMAPI/Framework/Content/ContentCache.cs b/src/SMAPI/Framework/Content/ContentCache.cs index 55a96ed2..4178b663 100644 --- a/src/SMAPI/Framework/Content/ContentCache.cs +++ b/src/SMAPI/Framework/Content/ContentCache.cs @@ -10,7 +10,7 @@ using StardewValley; namespace StardewModdingAPI.Framework.Content { - /// A low-level wrapper around the content cache which handles reading, writing, and invalidating entries in the cache. This doesn't handle any higher-level logic like localisation, loading content, etc. It assumes all keys passed in are already normalised. + /// A low-level wrapper around the content cache which handles reading, writing, and invalidating entries in the cache. This doesn't handle any higher-level logic like localization, loading content, etc. It assumes all keys passed in are already normalized. internal class ContentCache { /********* @@ -19,8 +19,8 @@ namespace StardewModdingAPI.Framework.Content /// The underlying asset cache. private readonly IDictionary Cache; - /// Applies platform-specific asset key normalisation so it's consistent with the underlying cache. - private readonly Func NormaliseAssetNameForPlatform; + /// Applies platform-specific asset key normalization so it's consistent with the underlying cache. + private readonly Func NormalizeAssetNameForPlatform; /********* @@ -52,14 +52,14 @@ namespace StardewModdingAPI.Framework.Content // init this.Cache = reflection.GetField>(contentManager, "loadedAssets").GetValue(); - // get key normalisation logic + // get key normalization logic if (Constants.Platform == Platform.Windows) { IReflectedMethod method = reflection.GetMethod(typeof(TitleContainer), "GetCleanPath"); - this.NormaliseAssetNameForPlatform = path => method.Invoke(path); + this.NormalizeAssetNameForPlatform = path => method.Invoke(path); } else - this.NormaliseAssetNameForPlatform = key => key.Replace('\\', '/'); // based on MonoGame's ContentManager.Load logic + this.NormalizeAssetNameForPlatform = key => key.Replace('\\', '/'); // based on MonoGame's ContentManager.Load logic } /**** @@ -74,25 +74,25 @@ namespace StardewModdingAPI.Framework.Content /**** - ** Normalise + ** Normalize ****/ - /// Normalise path separators in a file path. For asset keys, see instead. - /// The file path to normalise. + /// Normalize path separators in a file path. For asset keys, see instead. + /// The file path to normalize. [Pure] - public string NormalisePathSeparators(string path) + public string NormalizePathSeparators(string path) { - return PathUtilities.NormalisePathSeparators(path); + return PathUtilities.NormalizePathSeparators(path); } - /// Normalise a cache key so it's consistent with the underlying cache. + /// Normalize a cache key so it's consistent with the underlying cache. /// The asset key. [Pure] - public string NormaliseKey(string key) + public string NormalizeKey(string key) { - key = this.NormalisePathSeparators(key); + key = this.NormalizePathSeparators(key); return key.EndsWith(".xnb", StringComparison.InvariantCultureIgnoreCase) ? key.Substring(0, key.Length - 4) - : this.NormaliseAssetNameForPlatform(key); + : this.NormalizeAssetNameForPlatform(key); } /**** diff --git a/src/SMAPI/Framework/ContentCoordinator.cs b/src/SMAPI/Framework/ContentCoordinator.cs index 39bebdd1..08ebe6a5 100644 --- a/src/SMAPI/Framework/ContentCoordinator.cs +++ b/src/SMAPI/Framework/ContentCoordinator.cs @@ -9,7 +9,7 @@ using StardewModdingAPI.Framework.Content; using StardewModdingAPI.Framework.ContentManagers; using StardewModdingAPI.Framework.Reflection; using StardewModdingAPI.Metadata; -using StardewModdingAPI.Toolkit.Serialisation; +using StardewModdingAPI.Toolkit.Serialization; using StardewModdingAPI.Toolkit.Utilities; using StardewValley; @@ -74,7 +74,7 @@ namespace StardewModdingAPI.Framework /// Construct an instance. /// The service provider to use to locate services. /// The root directory to search for content. - /// The current culture for which to localise content. + /// The current culture for which to localize content. /// Encapsulates monitoring and logging. /// Simplifies access to private code. /// Encapsulates SMAPI's JSON file parsing. @@ -89,7 +89,7 @@ namespace StardewModdingAPI.Framework this.ContentManagers.Add( this.MainContentManager = new GameContentManager("Game1.content", serviceProvider, rootDirectory, currentCulture, this, monitor, reflection, this.OnDisposing, onLoadingFirstAsset) ); - this.CoreAssets = new CoreAssetPropagator(this.MainContentManager.AssertAndNormaliseAssetName, reflection, monitor); + this.CoreAssets = new CoreAssetPropagator(this.MainContentManager.AssertAndNormalizeAssetName, reflection, monitor); } /// Get a new content manager which handles reading files from the game content folder with support for interception. @@ -250,7 +250,7 @@ namespace StardewModdingAPI.Framework string locale = this.GetLocale(); return this.InvalidateCache((assetName, type) => { - IAssetInfo info = new AssetInfo(locale, assetName, type, this.MainContentManager.AssertAndNormaliseAssetName); + IAssetInfo info = new AssetInfo(locale, assetName, type, this.MainContentManager.AssertAndNormalizeAssetName); return predicate(info); }, dispose); } diff --git a/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs b/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs index fc558eb9..de39dbae 100644 --- a/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs @@ -64,7 +64,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// A name for the mod manager. Not guaranteed to be unique. /// The service provider to use to locate services. /// The root directory to search for content. - /// The current culture for which to localise content. + /// The current culture for which to localize content. /// The central coordinator which manages content managers. /// Encapsulates monitoring and logging. /// Simplifies access to private code. @@ -109,7 +109,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Whether to read/write the loaded asset to the asset cache. public abstract T Load(string assetName, LocalizedContentManager.LanguageCode language, bool useCache); - /// Load the base asset without localisation. + /// Load the base asset without localization. /// The type of asset to load. /// The asset path relative to the loader root directory, not including the .xnb extension. [Obsolete("This method is implemented for the base game and should not be used directly. To load an asset from the underlying content manager directly, use " + nameof(BaseContentManager.RawLoad) + " instead.")] @@ -121,19 +121,19 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Perform any cleanup needed when the locale changes. public virtual void OnLocaleChanged() { } - /// Normalise path separators in a file path. For asset keys, see instead. - /// The file path to normalise. + /// Normalize path separators in a file path. For asset keys, see instead. + /// The file path to normalize. [Pure] - public string NormalisePathSeparators(string path) + public string NormalizePathSeparators(string path) { - return this.Cache.NormalisePathSeparators(path); + return this.Cache.NormalizePathSeparators(path); } - /// Assert that the given key has a valid format and return a normalised form consistent with the underlying cache. + /// Assert that the given key has a valid format and return a normalized form consistent with the underlying cache. /// The asset key to check. /// The asset key is empty or contains invalid characters. [SuppressMessage("ReSharper", "ParameterOnlyUsedForPreconditionCheck.Local", Justification = "Parameter is only used for assertion checks by design.")] - public string AssertAndNormaliseAssetName(string assetName) + public string AssertAndNormalizeAssetName(string assetName) { // NOTE: the game checks for ContentLoadException to handle invalid keys, so avoid // throwing other types like ArgumentException here. @@ -142,7 +142,7 @@ namespace StardewModdingAPI.Framework.ContentManagers if (assetName.Intersect(Path.GetInvalidPathChars()).Any()) throw new SContentLoadException("The asset key or local path contains invalid characters."); - return this.Cache.NormaliseKey(assetName); + return this.Cache.NormalizeKey(assetName); } /**** @@ -165,8 +165,8 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The asset path relative to the loader root directory, not including the .xnb extension. public bool IsLoaded(string assetName) { - assetName = this.Cache.NormaliseKey(assetName); - return this.IsNormalisedKeyLoaded(assetName); + assetName = this.Cache.NormalizeKey(assetName); + return this.IsNormalizedKeyLoaded(assetName); } /// Get the cached asset keys. @@ -248,7 +248,7 @@ namespace StardewModdingAPI.Framework.ContentManagers *********/ /// Load an asset file directly from the underlying content manager. /// The type of asset to load. - /// The normalised asset key. + /// The normalized asset key. /// Whether to read/write the loaded asset to the asset cache. protected virtual T RawLoad(string assetName, bool useCache) { @@ -264,17 +264,17 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The language code for which to inject the asset. protected virtual void Inject(string assetName, T value, LanguageCode language) { - assetName = this.AssertAndNormaliseAssetName(assetName); + assetName = this.AssertAndNormalizeAssetName(assetName); this.Cache[assetName] = value; } /// Parse a cache key into its component parts. /// The input cache key. /// The original asset name. - /// The asset locale code (or null if not localised). + /// The asset locale code (or null if not localized). protected void ParseCacheKey(string cacheKey, out string assetName, out string localeCode) { - // handle localised key + // handle localized key if (!string.IsNullOrWhiteSpace(cacheKey)) { int lastSepIndex = cacheKey.LastIndexOf(".", StringComparison.InvariantCulture); @@ -296,8 +296,8 @@ namespace StardewModdingAPI.Framework.ContentManagers } /// Get whether an asset has already been loaded. - /// The normalised asset name. - protected abstract bool IsNormalisedKeyLoaded(string normalisedAssetName); + /// The normalized asset name. + protected abstract bool IsNormalizedKeyLoaded(string normalizedAssetName); /// Get the locale codes (like ja-JP) used in asset keys. private IDictionary GetKeyLocales() diff --git a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs index 488ec245..c64e9ba9 100644 --- a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs @@ -26,8 +26,8 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Interceptors which edit matching assets after they're loaded. private IDictionary> Editors => this.Coordinator.Editors; - /// A lookup which indicates whether the asset is localisable (i.e. the filename contains the locale), if previously loaded. - private readonly IDictionary IsLocalisableLookup; + /// A lookup which indicates whether the asset is localizable (i.e. the filename contains the locale), if previously loaded. + private readonly IDictionary IsLocalizableLookup; /// Whether the next load is the first for any game content manager. private static bool IsFirstLoad = true; @@ -43,7 +43,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// A name for the mod manager. Not guaranteed to be unique. /// The service provider to use to locate services. /// The root directory to search for content. - /// The current culture for which to localise content. + /// The current culture for which to localize content. /// The central coordinator which manages content managers. /// Encapsulates monitoring and logging. /// Simplifies access to private code. @@ -52,7 +52,7 @@ namespace StardewModdingAPI.Framework.ContentManagers public GameContentManager(string name, IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, Action onDisposing, Action onLoadingFirstAsset) : base(name, serviceProvider, rootDirectory, currentCulture, coordinator, monitor, reflection, onDisposing, isNamespaced: false) { - this.IsLocalisableLookup = reflection.GetField>(this, "_localizedAsset").GetValue(); + this.IsLocalizableLookup = reflection.GetField>(this, "_localizedAsset").GetValue(); this.OnLoadingFirstAsset = onLoadingFirstAsset; } @@ -70,8 +70,8 @@ namespace StardewModdingAPI.Framework.ContentManagers this.OnLoadingFirstAsset(); } - // normalise asset name - assetName = this.AssertAndNormaliseAssetName(assetName); + // normalize asset name + assetName = this.AssertAndNormalizeAssetName(assetName); if (this.TryParseExplicitLanguageAssetKey(assetName, out string newAssetName, out LanguageCode newLanguage)) return this.Load(newAssetName, newLanguage, useCache); @@ -101,10 +101,10 @@ namespace StardewModdingAPI.Framework.ContentManagers data = this.AssetsBeingLoaded.Track(assetName, () => { string locale = this.GetLocale(language); - IAssetInfo info = new AssetInfo(locale, assetName, typeof(T), this.AssertAndNormaliseAssetName); + IAssetInfo info = new AssetInfo(locale, assetName, typeof(T), this.AssertAndNormalizeAssetName); IAssetData asset = this.ApplyLoader(info) - ?? new AssetDataForObject(info, this.RawLoad(assetName, language, useCache), this.AssertAndNormaliseAssetName); + ?? new AssetDataForObject(info, this.RawLoad(assetName, language, useCache), this.AssertAndNormalizeAssetName); asset = this.ApplyEditors(info, asset); return (T)asset.Data; }); @@ -122,7 +122,7 @@ namespace StardewModdingAPI.Framework.ContentManagers // find assets for which a translatable version was loaded HashSet removeAssetNames = new HashSet(StringComparer.InvariantCultureIgnoreCase); - foreach (string key in this.IsLocalisableLookup.Where(p => p.Value).Select(p => p.Key)) + foreach (string key in this.IsLocalizableLookup.Where(p => p.Value).Select(p => p.Key)) removeAssetNames.Add(this.TryParseExplicitLanguageAssetKey(key, out string assetName, out _) ? assetName : key); // invalidate translatable assets @@ -149,20 +149,20 @@ namespace StardewModdingAPI.Framework.ContentManagers ** Private methods *********/ /// Get whether an asset has already been loaded. - /// The normalised asset name. - protected override bool IsNormalisedKeyLoaded(string normalisedAssetName) + /// The normalized asset name. + protected override bool IsNormalizedKeyLoaded(string normalizedAssetName) { // default English - if (this.Language == LocalizedContentManager.LanguageCode.en || this.Coordinator.IsManagedAssetKey(normalisedAssetName)) - return this.Cache.ContainsKey(normalisedAssetName); + if (this.Language == LocalizedContentManager.LanguageCode.en || this.Coordinator.IsManagedAssetKey(normalizedAssetName)) + return this.Cache.ContainsKey(normalizedAssetName); // translated - string keyWithLocale = $"{normalisedAssetName}.{this.GetLocale(this.GetCurrentLanguage())}"; - if (this.IsLocalisableLookup.TryGetValue(keyWithLocale, out bool localisable)) + string keyWithLocale = $"{normalizedAssetName}.{this.GetLocale(this.GetCurrentLanguage())}"; + if (this.IsLocalizableLookup.TryGetValue(keyWithLocale, out bool localizable)) { - return localisable + return localizable ? this.Cache.ContainsKey(keyWithLocale) - : this.Cache.ContainsKey(normalisedAssetName); + : this.Cache.ContainsKey(normalizedAssetName); } // not loaded yet @@ -190,13 +190,13 @@ namespace StardewModdingAPI.Framework.ContentManagers string keyWithLocale = $"{assetName}.{this.GetLocale(language)}"; if (this.Cache.ContainsKey(keyWithLocale)) { - this.IsLocalisableLookup[assetName] = true; - this.IsLocalisableLookup[keyWithLocale] = true; + this.IsLocalizableLookup[assetName] = true; + this.IsLocalizableLookup[keyWithLocale] = true; } else if (this.Cache.ContainsKey(assetName)) { - this.IsLocalisableLookup[assetName] = false; - this.IsLocalisableLookup[keyWithLocale] = false; + this.IsLocalizableLookup[assetName] = false; + this.IsLocalizableLookup[keyWithLocale] = false; } else this.Monitor.Log($"Asset '{assetName}' could not be found in the cache immediately after injection.", LogLevel.Error); @@ -204,7 +204,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Load an asset file directly from the underlying content manager. /// The type of asset to load. - /// The normalised asset key. + /// The normalized asset key. /// The language code for which to load content. /// Whether to read/write the loaded asset to the asset cache. /// Derived from . @@ -214,19 +214,19 @@ namespace StardewModdingAPI.Framework.ContentManagers if (language != LocalizedContentManager.LanguageCode.en) { string translatedKey = $"{assetName}.{this.GetLocale(language)}"; - if (!this.IsLocalisableLookup.TryGetValue(translatedKey, out bool isTranslatable) || isTranslatable) + if (!this.IsLocalizableLookup.TryGetValue(translatedKey, out bool isTranslatable) || isTranslatable) { try { T obj = base.RawLoad(translatedKey, useCache); - this.IsLocalisableLookup[assetName] = true; - this.IsLocalisableLookup[translatedKey] = true; + this.IsLocalizableLookup[assetName] = true; + this.IsLocalizableLookup[translatedKey] = true; return obj; } catch (ContentLoadException) { - this.IsLocalisableLookup[assetName] = false; - this.IsLocalisableLookup[translatedKey] = false; + this.IsLocalizableLookup[assetName] = false; + this.IsLocalizableLookup[translatedKey] = false; } } } @@ -313,7 +313,7 @@ namespace StardewModdingAPI.Framework.ContentManagers } // return matched asset - return new AssetDataForObject(info, data, this.AssertAndNormaliseAssetName); + return new AssetDataForObject(info, data, this.AssertAndNormalizeAssetName); } /// Apply any to a loaded asset. @@ -322,7 +322,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The loaded asset. private IAssetData ApplyEditors(IAssetInfo info, IAssetData asset) { - IAssetData GetNewData(object data) => new AssetDataForObject(info, data, this.AssertAndNormaliseAssetName); + IAssetData GetNewData(object data) => new AssetDataForObject(info, data, this.AssertAndNormalizeAssetName); // edit asset foreach (var entry in this.GetInterceptors(this.Editors)) diff --git a/src/SMAPI/Framework/ContentManagers/IContentManager.cs b/src/SMAPI/Framework/ContentManagers/IContentManager.cs index 78211821..12c01352 100644 --- a/src/SMAPI/Framework/ContentManagers/IContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/IContentManager.cs @@ -39,15 +39,15 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Perform any cleanup needed when the locale changes. void OnLocaleChanged(); - /// Normalise path separators in a file path. For asset keys, see instead. - /// The file path to normalise. + /// Normalize path separators in a file path. For asset keys, see instead. + /// The file path to normalize. [Pure] - string NormalisePathSeparators(string path); + string NormalizePathSeparators(string path); - /// Assert that the given key has a valid format and return a normalised form consistent with the underlying cache. + /// Assert that the given key has a valid format and return a normalized form consistent with the underlying cache. /// The asset key to check. /// The asset key is empty or contains invalid characters. - string AssertAndNormaliseAssetName(string assetName); + string AssertAndNormalizeAssetName(string assetName); /// Get the current content locale. string GetLocale(); diff --git a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs index 34cabefc..b88bd71e 100644 --- a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs @@ -7,7 +7,7 @@ using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.Framework.Exceptions; using StardewModdingAPI.Framework.Reflection; -using StardewModdingAPI.Toolkit.Serialisation; +using StardewModdingAPI.Toolkit.Serialization; using StardewModdingAPI.Toolkit.Utilities; using StardewValley; using xTile; @@ -41,7 +41,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The game content manager used for map tilesheets not provided by the mod. /// The service provider to use to locate services. /// The root directory to search for content. - /// The current culture for which to localise content. + /// The current culture for which to localize content. /// The central coordinator which manages content managers. /// Encapsulates monitoring and logging. /// Simplifies access to private code. @@ -78,7 +78,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Whether to read/write the loaded asset to the asset cache. public override T Load(string assetName, LanguageCode language, bool useCache) { - assetName = this.AssertAndNormaliseAssetName(assetName); + assetName = this.AssertAndNormalizeAssetName(assetName); // disable caching // This is necessary to avoid assets being shared between content managers, which can @@ -91,7 +91,7 @@ namespace StardewModdingAPI.Framework.ContentManagers // disable language handling // Mod files don't support automatic translation logic, so this should never happen. if (language != this.DefaultLanguage) - throw new InvalidOperationException("Localised assets aren't supported by the mod content manager."); + throw new InvalidOperationException("Localized assets aren't supported by the mod content manager."); // resolve managed asset key { @@ -121,7 +121,7 @@ namespace StardewModdingAPI.Framework.ContentManagers T data = this.RawLoad(assetName, useCache: false); if (data is Map map) { - this.NormaliseTilesheetPaths(map); + this.NormalizeTilesheetPaths(map); this.FixCustomTilesheetPaths(map, relativeMapPath: assetName); } return data; @@ -161,7 +161,7 @@ namespace StardewModdingAPI.Framework.ContentManagers // fetch & cache FormatManager formatManager = FormatManager.Instance; Map map = formatManager.LoadMap(file.FullName); - this.NormaliseTilesheetPaths(map); + this.NormalizeTilesheetPaths(map); this.FixCustomTilesheetPaths(map, relativeMapPath: assetName); return (T)(object)map; } @@ -199,10 +199,10 @@ namespace StardewModdingAPI.Framework.ContentManagers ** Private methods *********/ /// Get whether an asset has already been loaded. - /// The normalised asset name. - protected override bool IsNormalisedKeyLoaded(string normalisedAssetName) + /// The normalized asset name. + protected override bool IsNormalizedKeyLoaded(string normalizedAssetName) { - return this.Cache.ContainsKey(normalisedAssetName); + return this.Cache.ContainsKey(normalizedAssetName); } /// Get a file from the mod folder. @@ -245,12 +245,12 @@ namespace StardewModdingAPI.Framework.ContentManagers return texture; } - /// Normalise map tilesheet paths for the current platform. + /// Normalize map tilesheet paths for the current platform. /// The map whose tilesheets to fix. - private void NormaliseTilesheetPaths(Map map) + private void NormalizeTilesheetPaths(Map map) { foreach (TileSheet tilesheet in map.TileSheets) - tilesheet.ImageSource = this.NormalisePathSeparators(tilesheet.ImageSource); + tilesheet.ImageSource = this.NormalizePathSeparators(tilesheet.ImageSource); } /// Fix custom map tilesheet paths so they can be found by the content manager. @@ -258,7 +258,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The relative map path within the mod folder. /// A map tilesheet couldn't be resolved. /// - /// The game's logic for tilesheets in is a bit specialised. It boils + /// The game's logic for tilesheets in is a bit specialized. It boils /// down to this: /// * If the location is indoors or the desert, or the image source contains 'path' or 'object', it's loaded /// as-is relative to the Content folder. @@ -276,7 +276,7 @@ namespace StardewModdingAPI.Framework.ContentManagers // get map info if (!map.TileSheets.Any()) return; - relativeMapPath = this.AssertAndNormaliseAssetName(relativeMapPath); // Mono's Path.GetDirectoryName doesn't handle Windows dir separators + relativeMapPath = this.AssertAndNormalizeAssetName(relativeMapPath); // Mono's Path.GetDirectoryName doesn't handle Windows dir separators string relativeMapFolder = Path.GetDirectoryName(relativeMapPath) ?? ""; // folder path containing the map, relative to the mod folder bool isOutdoors = map.Properties.TryGetValue("Outdoors", out PropertyValue outdoorsProperty) && outdoorsProperty != null; diff --git a/src/SMAPI/Framework/ContentPack.cs b/src/SMAPI/Framework/ContentPack.cs index 829a7dc1..9c0bb9d1 100644 --- a/src/SMAPI/Framework/ContentPack.cs +++ b/src/SMAPI/Framework/ContentPack.cs @@ -2,7 +2,7 @@ using System; using System.IO; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; -using StardewModdingAPI.Toolkit.Serialisation; +using StardewModdingAPI.Toolkit.Serialization; using StardewModdingAPI.Toolkit.Utilities; using xTile; @@ -63,14 +63,14 @@ namespace StardewModdingAPI.Framework /// Read a JSON file from the content pack folder. /// The model type. - /// The file path relative to the contnet directory. - /// Returns the deserialised model, or null if the file doesn't exist or is empty. + /// The file path relative to the content directory. + /// Returns the deserialized model, or null if the file doesn't exist or is empty. /// The is not relative or contains directory climbing (../). public TModel ReadJsonFile(string path) where TModel : class { this.AssertRelativePath(path, nameof(this.ReadJsonFile)); - path = Path.Combine(this.DirectoryPath, PathUtilities.NormalisePathSeparators(path)); + path = Path.Combine(this.DirectoryPath, PathUtilities.NormalizePathSeparators(path)); return this.JsonHelper.ReadJsonFileIfExists(path, out TModel model) ? model : null; @@ -85,7 +85,7 @@ namespace StardewModdingAPI.Framework { this.AssertRelativePath(path, nameof(this.WriteJsonFile)); - path = Path.Combine(this.DirectoryPath, PathUtilities.NormalisePathSeparators(path)); + path = Path.Combine(this.DirectoryPath, PathUtilities.NormalizePathSeparators(path)); this.JsonHelper.WriteJsonFile(path, data); } diff --git a/src/SMAPI/Framework/Events/EventManager.cs b/src/SMAPI/Framework/Events/EventManager.cs index 23879f1d..18b00f69 100644 --- a/src/SMAPI/Framework/Events/EventManager.cs +++ b/src/SMAPI/Framework/Events/EventManager.cs @@ -73,7 +73,7 @@ namespace StardewModdingAPI.Framework.Events /// Raised after the game finishes writing data to the save file (except the initial save creation). public readonly ManagedEvent Saved; - /// Raised after the player loads a save slot and the world is initialised. + /// Raised after the player loads a save slot and the world is initialized. public readonly ManagedEvent SaveLoaded; /// Raised after the game begins a new day, including when loading a save. @@ -152,15 +152,15 @@ namespace StardewModdingAPI.Framework.Events public readonly ManagedEvent TerrainFeatureListChanged; /**** - ** Specialised + ** Specialized ****/ - /// Raised when the low-level stage in the game's loading process has changed. See notes on . + /// Raised when the low-level stage in the game's loading process has changed. See notes on . public readonly ManagedEvent LoadStageChanged; - /// Raised before the game performs its overall update tick (≈60 times per second). See notes on . + /// Raised before the game performs its overall update tick (≈60 times per second). See notes on . public readonly ManagedEvent UnvalidatedUpdateTicking; - /// Raised after the game performs its overall update tick (≈60 times per second). See notes on . + /// Raised after the game performs its overall update tick (≈60 times per second). See notes on . public readonly ManagedEvent UnvalidatedUpdateTicked; @@ -172,7 +172,7 @@ namespace StardewModdingAPI.Framework.Events /// The mod registry with which to identify mods. public EventManager(IMonitor monitor, ModRegistry modRegistry) { - // create shortcut initialisers + // create shortcut initializers ManagedEvent ManageEventOf(string typeName, string eventName) => new ManagedEvent($"{typeName}.{eventName}", monitor, modRegistry); // init events (new) @@ -223,9 +223,9 @@ namespace StardewModdingAPI.Framework.Events this.ObjectListChanged = ManageEventOf(nameof(IModEvents.World), nameof(IWorldEvents.ObjectListChanged)); this.TerrainFeatureListChanged = ManageEventOf(nameof(IModEvents.World), nameof(IWorldEvents.TerrainFeatureListChanged)); - this.LoadStageChanged = ManageEventOf(nameof(IModEvents.Specialised), nameof(ISpecialisedEvents.LoadStageChanged)); - this.UnvalidatedUpdateTicking = ManageEventOf(nameof(IModEvents.Specialised), nameof(ISpecialisedEvents.UnvalidatedUpdateTicking)); - this.UnvalidatedUpdateTicked = ManageEventOf(nameof(IModEvents.Specialised), nameof(ISpecialisedEvents.UnvalidatedUpdateTicked)); + this.LoadStageChanged = ManageEventOf(nameof(IModEvents.Specialized), nameof(ISpecializedEvents.LoadStageChanged)); + this.UnvalidatedUpdateTicking = ManageEventOf(nameof(IModEvents.Specialized), nameof(ISpecializedEvents.UnvalidatedUpdateTicking)); + this.UnvalidatedUpdateTicked = ManageEventOf(nameof(IModEvents.Specialized), nameof(ISpecializedEvents.UnvalidatedUpdateTicked)); } } } diff --git a/src/SMAPI/Framework/Events/ModEvents.cs b/src/SMAPI/Framework/Events/ModEvents.cs index 8ad3936c..1d1c92c6 100644 --- a/src/SMAPI/Framework/Events/ModEvents.cs +++ b/src/SMAPI/Framework/Events/ModEvents.cs @@ -26,8 +26,8 @@ namespace StardewModdingAPI.Framework.Events /// Events raised when something changes in the world. public IWorldEvents World { get; } - /// Events serving specialised edge cases that shouldn't be used by most mods. - public ISpecialisedEvents Specialised { get; } + /// Events serving specialized edge cases that shouldn't be used by most mods. + public ISpecializedEvents Specialized { get; } /********* @@ -44,7 +44,7 @@ namespace StardewModdingAPI.Framework.Events this.Multiplayer = new ModMultiplayerEvents(mod, eventManager); this.Player = new ModPlayerEvents(mod, eventManager); this.World = new ModWorldEvents(mod, eventManager); - this.Specialised = new ModSpecialisedEvents(mod, eventManager); + this.Specialized = new ModSpecializedEvents(mod, eventManager); } } } diff --git a/src/SMAPI/Framework/Events/ModGameLoopEvents.cs b/src/SMAPI/Framework/Events/ModGameLoopEvents.cs index 0177c22e..c15460fa 100644 --- a/src/SMAPI/Framework/Events/ModGameLoopEvents.cs +++ b/src/SMAPI/Framework/Events/ModGameLoopEvents.cs @@ -72,7 +72,7 @@ namespace StardewModdingAPI.Framework.Events remove => this.EventManager.Saved.Remove(value); } - /// Raised after the player loads a save slot and the world is initialised. + /// Raised after the player loads a save slot and the world is initialized. public event EventHandler SaveLoaded { add => this.EventManager.SaveLoaded.Add(value); diff --git a/src/SMAPI/Framework/Events/ModSpecialisedEvents.cs b/src/SMAPI/Framework/Events/ModSpecialisedEvents.cs index 7c3e9dee..9388bdb2 100644 --- a/src/SMAPI/Framework/Events/ModSpecialisedEvents.cs +++ b/src/SMAPI/Framework/Events/ModSpecialisedEvents.cs @@ -3,8 +3,8 @@ using StardewModdingAPI.Events; namespace StardewModdingAPI.Framework.Events { - /// Events serving specialised edge cases that shouldn't be used by most mods. - internal class ModSpecialisedEvents : ModEventsBase, ISpecialisedEvents + /// Events serving specialized edge cases that shouldn't be used by most mods. + internal class ModSpecializedEvents : ModEventsBase, ISpecializedEvents { /********* ** Accessors @@ -37,7 +37,7 @@ namespace StardewModdingAPI.Framework.Events /// Construct an instance. /// The mod which uses this instance. /// The underlying event manager. - internal ModSpecialisedEvents(IModMetadata mod, EventManager eventManager) + internal ModSpecializedEvents(IModMetadata mod, EventManager eventManager) : base(mod, eventManager) { } } } diff --git a/src/SMAPI/Framework/GameVersion.cs b/src/SMAPI/Framework/GameVersion.cs index 261de374..b9ef12c8 100644 --- a/src/SMAPI/Framework/GameVersion.cs +++ b/src/SMAPI/Framework/GameVersion.cs @@ -18,7 +18,7 @@ namespace StardewModdingAPI.Framework ["1.04"] = "1.0.4", ["1.05"] = "1.0.5", ["1.051"] = "1.0.6-prerelease1", // not a very good mapping, but good enough for SMAPI's purposes. - ["1.051b"] = "1.0.6-prelease2", + ["1.051b"] = "1.0.6-prerelease2", ["1.06"] = "1.0.6", ["1.07"] = "1.0.7", ["1.07a"] = "1.0.8-prerelease1", diff --git a/src/SMAPI/Framework/InternalExtensions.cs b/src/SMAPI/Framework/InternalExtensions.cs index f52bfe2b..c3155b1c 100644 --- a/src/SMAPI/Framework/InternalExtensions.cs +++ b/src/SMAPI/Framework/InternalExtensions.cs @@ -55,7 +55,7 @@ namespace StardewModdingAPI.Framework ** Exceptions ****/ /// Get a string representation of an exception suitable for writing to the error log. - /// The error to summarise. + /// The error to summarize. public static string GetLogSummary(this Exception exception) { switch (exception) diff --git a/src/SMAPI/Framework/ModHelpers/ContentHelper.cs b/src/SMAPI/Framework/ModHelpers/ContentHelper.cs index 15b164b1..043ae376 100644 --- a/src/SMAPI/Framework/ModHelpers/ContentHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ContentHelper.cs @@ -87,7 +87,7 @@ namespace StardewModdingAPI.Framework.ModHelpers { try { - this.AssertAndNormaliseAssetName(key); + this.AssertAndNormalizeAssetName(key); switch (source) { case ContentSource.GameContent: @@ -106,12 +106,12 @@ namespace StardewModdingAPI.Framework.ModHelpers } } - /// Normalise an asset name so it's consistent with those generated by the game. This is mainly useful for string comparisons like on generated asset names, and isn't necessary when passing asset names into other content helper methods. + /// Normalize an asset name so it's consistent with those generated by the game. This is mainly useful for string comparisons like on generated asset names, and isn't necessary when passing asset names into other content helper methods. /// The asset key. [Pure] - public string NormaliseAssetName(string assetName) + public string NormalizeAssetName(string assetName) { - return this.ModContentManager.AssertAndNormaliseAssetName(assetName); + return this.ModContentManager.AssertAndNormalizeAssetName(assetName); } /// Get the underlying key in the game's content cache for an asset. This can be used to load custom map tilesheets, but should be avoided when you can use the content API instead. This does not validate whether the asset exists. @@ -123,7 +123,7 @@ namespace StardewModdingAPI.Framework.ModHelpers switch (source) { case ContentSource.GameContent: - return this.GameContentManager.AssertAndNormaliseAssetName(key); + return this.GameContentManager.AssertAndNormalizeAssetName(key); case ContentSource.ModFolder: return this.ModContentManager.GetInternalAssetKey(key); @@ -170,9 +170,9 @@ namespace StardewModdingAPI.Framework.ModHelpers /// The asset key to check. /// The asset key is empty or contains invalid characters. [SuppressMessage("ReSharper", "ParameterOnlyUsedForPreconditionCheck.Local", Justification = "Parameter is only used for assertion checks by design.")] - private void AssertAndNormaliseAssetName(string key) + private void AssertAndNormalizeAssetName(string key) { - this.ModContentManager.AssertAndNormaliseAssetName(key); + this.ModContentManager.AssertAndNormalizeAssetName(key); if (Path.IsPathRooted(key)) throw new ArgumentException("The asset key must not be an absolute path."); } diff --git a/src/SMAPI/Framework/ModHelpers/ContentPackHelper.cs b/src/SMAPI/Framework/ModHelpers/ContentPackHelper.cs index 34f24d65..acdd82a0 100644 --- a/src/SMAPI/Framework/ModHelpers/ContentPackHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ContentPackHelper.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.IO; -using StardewModdingAPI.Toolkit.Serialisation.Models; +using StardewModdingAPI.Toolkit.Serialization.Models; namespace StardewModdingAPI.Framework.ModHelpers { @@ -38,7 +38,7 @@ namespace StardewModdingAPI.Framework.ModHelpers return this.ContentPacks.Value; } - /// Create a temporary content pack to read files from a directory, using randomised manifest fields. This will generate fake manifest data; any manifest.json in the directory will be ignored. Temporary content packs will not appear in the SMAPI log and update checks will not be performed. + /// Create a temporary content pack to read files from a directory, using randomized manifest fields. This will generate fake manifest data; any manifest.json in the directory will be ignored. Temporary content packs will not appear in the SMAPI log and update checks will not be performed. /// The absolute directory path containing the content pack files. public IContentPack CreateFake(string directoryPath) { diff --git a/src/SMAPI/Framework/ModHelpers/DataHelper.cs b/src/SMAPI/Framework/ModHelpers/DataHelper.cs index 3b5c1752..cc08c42b 100644 --- a/src/SMAPI/Framework/ModHelpers/DataHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/DataHelper.cs @@ -1,7 +1,7 @@ using System; using System.IO; using Newtonsoft.Json; -using StardewModdingAPI.Toolkit.Serialisation; +using StardewModdingAPI.Toolkit.Serialization; using StardewModdingAPI.Toolkit.Utilities; using StardewValley; @@ -40,14 +40,14 @@ namespace StardewModdingAPI.Framework.ModHelpers /// Read data from a JSON file in the mod's folder. /// The model type. This should be a plain class that has public properties for the data you want. The properties can be complex types. /// The file path relative to the mod folder. - /// Returns the deserialised model, or null if the file doesn't exist or is empty. + /// Returns the deserialized model, or null if the file doesn't exist or is empty. /// The is not relative or contains directory climbing (../). public TModel ReadJsonFile(string path) where TModel : class { if (!PathUtilities.IsSafeRelativePath(path)) throw new InvalidOperationException($"You must call {nameof(IModHelper.Data)}.{nameof(this.ReadJsonFile)} with a relative path."); - path = Path.Combine(this.ModFolderPath, PathUtilities.NormalisePathSeparators(path)); + path = Path.Combine(this.ModFolderPath, PathUtilities.NormalizePathSeparators(path)); return this.JsonHelper.ReadJsonFileIfExists(path, out TModel data) ? data : null; @@ -63,7 +63,7 @@ namespace StardewModdingAPI.Framework.ModHelpers if (!PathUtilities.IsSafeRelativePath(path)) throw new InvalidOperationException($"You must call {nameof(IMod.Helper)}.{nameof(IModHelper.Data)}.{nameof(this.WriteJsonFile)} with a relative path (without directory climbing)."); - path = Path.Combine(this.ModFolderPath, PathUtilities.NormalisePathSeparators(path)); + path = Path.Combine(this.ModFolderPath, PathUtilities.NormalizePathSeparators(path)); this.JsonHelper.WriteJsonFile(path, data); } @@ -83,7 +83,7 @@ namespace StardewModdingAPI.Framework.ModHelpers throw new InvalidOperationException($"Can't use {nameof(IMod.Helper)}.{nameof(IModHelper.Data)}.{nameof(this.ReadSaveData)} because this isn't the main player. (Save files are stored on the main player's computer.)"); return Game1.CustomData.TryGetValue(this.GetSaveFileKey(key), out string value) - ? this.JsonHelper.Deserialise(value) + ? this.JsonHelper.Deserialize(value) : null; } @@ -101,7 +101,7 @@ namespace StardewModdingAPI.Framework.ModHelpers string internalKey = this.GetSaveFileKey(key); if (data != null) - Game1.CustomData[internalKey] = this.JsonHelper.Serialise(data, Formatting.None); + Game1.CustomData[internalKey] = this.JsonHelper.Serialize(data, Formatting.None); else Game1.CustomData.Remove(internalKey); } diff --git a/src/SMAPI/Framework/ModHelpers/ModHelper.cs b/src/SMAPI/Framework/ModHelpers/ModHelper.cs index 86e8eb28..25401e23 100644 --- a/src/SMAPI/Framework/ModHelpers/ModHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ModHelper.cs @@ -2,7 +2,7 @@ using System; using System.IO; using StardewModdingAPI.Events; using StardewModdingAPI.Framework.Input; -using StardewModdingAPI.Toolkit.Serialisation; +using StardewModdingAPI.Toolkit.Serialization; namespace StardewModdingAPI.Framework.ModHelpers { @@ -73,7 +73,7 @@ namespace StardewModdingAPI.Framework.ModHelpers if (!Directory.Exists(modDirectory)) throw new InvalidOperationException("The specified mod directory does not exist."); - // initialise + // initialize this.DirectoryPath = modDirectory; this.Content = contentHelper ?? throw new ArgumentNullException(nameof(contentHelper)); this.ContentPacks = contentPackHelper ?? throw new ArgumentNullException(nameof(contentPackHelper)); diff --git a/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs b/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs index 8330e078..24bed3bb 100644 --- a/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs @@ -75,9 +75,9 @@ namespace StardewModdingAPI.Framework.ModHelpers public TInterface GetApi(string uniqueID) where TInterface : class { // validate - if (!this.Registry.AreAllModsInitialised) + if (!this.Registry.AreAllModsInitialized) { - this.Monitor.Log("Tried to access a mod-provided API before all mods were initialised.", LogLevel.Error); + this.Monitor.Log("Tried to access a mod-provided API before all mods were initialized.", LogLevel.Error); return null; } if (!typeof(TInterface).IsInterface) diff --git a/src/SMAPI/Framework/ModHelpers/ReflectionHelper.cs b/src/SMAPI/Framework/ModHelpers/ReflectionHelper.cs index 0ce72a9e..86c327ed 100644 --- a/src/SMAPI/Framework/ModHelpers/ReflectionHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ReflectionHelper.cs @@ -5,7 +5,7 @@ using StardewModdingAPI.Framework.Reflection; namespace StardewModdingAPI.Framework.ModHelpers { /// Provides helper methods for accessing private game code. - /// This implementation searches up the type hierarchy, and caches the reflected fields and methods with a sliding expiry (to optimise performance without unnecessary memory usage). + /// This implementation searches up the type hierarchy, and caches the reflected fields and methods with a sliding expiry (to optimize performance without unnecessary memory usage). internal class ReflectionHelper : BaseHelper, IReflectionHelper { /********* diff --git a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs index 8dfacc33..7670eb3a 100644 --- a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs +++ b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs @@ -317,7 +317,7 @@ namespace StardewModdingAPI.Framework.ModLoading } /// Process the result from an instruction handler. - /// The mod being analysed. + /// The mod being analyzed. /// The instruction handler. /// The result returned by the handler. /// The messages already logged for the current mod. @@ -341,9 +341,9 @@ namespace StardewModdingAPI.Framework.ModLoading mod.SetWarning(ModWarning.PatchesGame); break; - case InstructionHandleResult.DetectedSaveSerialiser: - this.Monitor.LogOnce(loggedMessages, $"{logPrefix}Detected possible save serialiser change ({handler.NounPhrase}) in assembly {filename}."); - mod.SetWarning(ModWarning.ChangesSaveSerialiser); + case InstructionHandleResult.DetectedSaveSerializer: + this.Monitor.LogOnce(loggedMessages, $"{logPrefix}Detected possible save serializer change ({handler.NounPhrase}) in assembly {filename}."); + mod.SetWarning(ModWarning.ChangesSaveSerializer); break; case InstructionHandleResult.DetectedUnvalidatedUpdateTick: @@ -370,7 +370,7 @@ namespace StardewModdingAPI.Framework.ModLoading break; default: - throw new NotSupportedException($"Unrecognised instruction handler result '{result}'."); + throw new NotSupportedException($"Unrecognized instruction handler result '{result}'."); } } diff --git a/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs index 79045241..701b15f2 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs @@ -73,7 +73,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders ** Protected methods *********/ /// Get whether a CIL instruction matches. - /// The method deifnition. + /// The method definition. protected bool IsMatch(MethodDefinition method) { if (this.IsMatch(method.ReturnType)) diff --git a/src/SMAPI/Framework/ModLoading/InstructionHandleResult.cs b/src/SMAPI/Framework/ModLoading/InstructionHandleResult.cs index 6592760e..d93b603d 100644 --- a/src/SMAPI/Framework/ModLoading/InstructionHandleResult.cs +++ b/src/SMAPI/Framework/ModLoading/InstructionHandleResult.cs @@ -18,12 +18,12 @@ namespace StardewModdingAPI.Framework.ModLoading DetectedGamePatch, /// The instruction is compatible, but affects the save serializer in a way that may make saves unloadable without the mod. - DetectedSaveSerialiser, + DetectedSaveSerializer, /// The instruction is compatible, but uses the dynamic keyword which won't work on Linux/Mac. DetectedDynamic, - /// The instruction is compatible, but references or which may impact stability. + /// The instruction is compatible, but references or which may impact stability. DetectedUnvalidatedUpdateTick, /// The instruction accesses the filesystem directly. diff --git a/src/SMAPI/Framework/ModLoading/ModDependencyStatus.cs b/src/SMAPI/Framework/ModLoading/ModDependencyStatus.cs index 0774b487..dd855d2f 100644 --- a/src/SMAPI/Framework/ModLoading/ModDependencyStatus.cs +++ b/src/SMAPI/Framework/ModLoading/ModDependencyStatus.cs @@ -1,4 +1,4 @@ -namespace StardewModdingAPI.Framework.ModLoading +namespace StardewModdingAPI.Framework.ModLoading { /// The status of a given mod in the dependency-sorting algorithm. internal enum ModDependencyStatus @@ -6,7 +6,7 @@ /// The mod hasn't been visited yet. Queued, - /// The mod is currently being analysed as part of a dependency chain. + /// The mod is currently being analyzed as part of a dependency chain. Checking, /// The mod has already been sorted. diff --git a/src/SMAPI/Framework/ModLoading/ModResolver.cs b/src/SMAPI/Framework/ModLoading/ModResolver.cs index 20941a5f..5ea21710 100644 --- a/src/SMAPI/Framework/ModLoading/ModResolver.cs +++ b/src/SMAPI/Framework/ModLoading/ModResolver.cs @@ -5,7 +5,7 @@ using System.Linq; using StardewModdingAPI.Toolkit; using StardewModdingAPI.Toolkit.Framework.ModData; using StardewModdingAPI.Toolkit.Framework.ModScanning; -using StardewModdingAPI.Toolkit.Serialisation.Models; +using StardewModdingAPI.Toolkit.Serialization.Models; using StardewModdingAPI.Toolkit.Utilities; namespace StardewModdingAPI.Framework.ModLoading @@ -143,11 +143,11 @@ namespace StardewModdingAPI.Framework.ModLoading continue; } - // invalid capitalisation + // invalid capitalization string actualFilename = new DirectoryInfo(mod.DirectoryPath).GetFiles(mod.Manifest.EntryDll).FirstOrDefault()?.Name; if (actualFilename != mod.Manifest.EntryDll) { - mod.SetStatus(ModMetadataStatus.Failed, $"its {nameof(IManifest.EntryDll)} value '{mod.Manifest.EntryDll}' doesn't match the actual file capitalisation '{actualFilename}'. The capitalisation must match for crossplatform compatibility."); + mod.SetStatus(ModMetadataStatus.Failed, $"its {nameof(IManifest.EntryDll)} value '{mod.Manifest.EntryDll}' doesn't match the actual file capitalization '{actualFilename}'. The capitalization must match for crossplatform compatibility."); continue; } } @@ -216,7 +216,7 @@ namespace StardewModdingAPI.Framework.ModLoading /// Handles access to SMAPI's internal mod metadata list. public IEnumerable ProcessDependencies(IEnumerable mods, ModDatabase modDatabase) { - // initialise metadata + // initialize metadata mods = mods.ToArray(); var sortedMods = new Stack(); var states = mods.ToDictionary(mod => mod, mod => ModDependencyStatus.Queued); diff --git a/src/SMAPI/Framework/ModLoading/TypeReferenceComparer.cs b/src/SMAPI/Framework/ModLoading/TypeReferenceComparer.cs index f7497789..a4ac54e2 100644 --- a/src/SMAPI/Framework/ModLoading/TypeReferenceComparer.cs +++ b/src/SMAPI/Framework/ModLoading/TypeReferenceComparer.cs @@ -54,7 +54,7 @@ namespace StardewModdingAPI.Framework.ModLoading { bool HeuristicallyEquals(string typeNameA, string typeNameB, IDictionary tokenMap) { - // analyse type names + // analyze type names bool hasTokensA = typeNameA.Contains("!"); bool hasTokensB = typeNameB.Contains("!"); bool isTokenA = hasTokensA && typeNameA[0] == '!'; diff --git a/src/SMAPI/Framework/ModRegistry.cs b/src/SMAPI/Framework/ModRegistry.cs index 5be33cb4..ef389337 100644 --- a/src/SMAPI/Framework/ModRegistry.cs +++ b/src/SMAPI/Framework/ModRegistry.cs @@ -21,8 +21,8 @@ namespace StardewModdingAPI.Framework /// Whether all mod assemblies have been loaded. public bool AreAllModsLoaded { get; set; } - /// Whether all mods have been initialised and their method called. - public bool AreAllModsInitialised { get; set; } + /// Whether all mods have been initialized and their method called. + public bool AreAllModsInitialized { get; set; } /********* @@ -62,7 +62,7 @@ namespace StardewModdingAPI.Framework /// Returns the matching mod's metadata, or null if not found. public IModMetadata Get(string uniqueID) { - // normalise search ID + // normalize search ID if (string.IsNullOrWhiteSpace(uniqueID)) return null; uniqueID = uniqueID.Trim(); diff --git a/src/SMAPI/Framework/Monitor.cs b/src/SMAPI/Framework/Monitor.cs index 3771f114..1fa55a9e 100644 --- a/src/SMAPI/Framework/Monitor.cs +++ b/src/SMAPI/Framework/Monitor.cs @@ -58,7 +58,7 @@ namespace StardewModdingAPI.Framework if (string.IsNullOrWhiteSpace(source)) throw new ArgumentException("The log source cannot be empty."); - // initialise + // initialize this.Source = source; this.LogFile = logFile ?? throw new ArgumentNullException(nameof(logFile), "The log file manager cannot be null."); this.ConsoleWriter = new ColorfulConsoleWriter(Constants.Platform, colorScheme); diff --git a/src/SMAPI/Framework/Networking/MessageType.cs b/src/SMAPI/Framework/Networking/MessageType.cs index bd9acfa9..4e1388ca 100644 --- a/src/SMAPI/Framework/Networking/MessageType.cs +++ b/src/SMAPI/Framework/Networking/MessageType.cs @@ -2,7 +2,7 @@ using StardewValley; namespace StardewModdingAPI.Framework.Networking { - /// Network message types recognised by SMAPI and Stardew Valley. + /// Network message types recognized by SMAPI and Stardew Valley. internal enum MessageType : byte { /********* diff --git a/src/SMAPI/Framework/Reflection/Reflector.cs b/src/SMAPI/Framework/Reflection/Reflector.cs index ed1a4381..d4904878 100644 --- a/src/SMAPI/Framework/Reflection/Reflector.cs +++ b/src/SMAPI/Framework/Reflection/Reflector.cs @@ -6,7 +6,7 @@ using System.Runtime.Caching; namespace StardewModdingAPI.Framework.Reflection { /// Provides helper methods for accessing inaccessible code. - /// This implementation searches up the type hierarchy, and caches the reflected fields and methods with a sliding expiry (to optimise performance without unnecessary memory usage). + /// This implementation searches up the type hierarchy, and caches the reflected fields and methods with a sliding expiry (to optimize performance without unnecessary memory usage). internal class Reflector { /********* diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index 0aae3b84..c5dede01 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -24,13 +24,13 @@ using StardewModdingAPI.Framework.ModHelpers; using StardewModdingAPI.Framework.ModLoading; using StardewModdingAPI.Framework.Patching; using StardewModdingAPI.Framework.Reflection; -using StardewModdingAPI.Framework.Serialisation; +using StardewModdingAPI.Framework.Serialization; using StardewModdingAPI.Internal; using StardewModdingAPI.Patches; using StardewModdingAPI.Toolkit; using StardewModdingAPI.Toolkit.Framework.Clients.WebApi; using StardewModdingAPI.Toolkit.Framework.ModData; -using StardewModdingAPI.Toolkit.Serialisation; +using StardewModdingAPI.Toolkit.Serialization; using StardewModdingAPI.Toolkit.Utilities; using StardewValley; using Object = StardewValley.Object; @@ -38,7 +38,7 @@ using ThreadState = System.Threading.ThreadState; namespace StardewModdingAPI.Framework { - /// The core class which initialises and manages SMAPI. + /// The core class which initializes and manages SMAPI. internal class SCore : IDisposable { /********* @@ -56,7 +56,7 @@ namespace StardewModdingAPI.Framework /// The core logger and monitor on behalf of the game. private readonly Monitor MonitorForGame; - /// Tracks whether the game should exit immediately and any pending initialisation should be cancelled. + /// Tracks whether the game should exit immediately and any pending initialization should be cancelled. private readonly CancellationTokenSource CancellationToken = new CancellationTokenSource(); /// Simplifies access to private game code. @@ -72,7 +72,7 @@ namespace StardewModdingAPI.Framework private ContentCoordinator ContentCore => this.GameInstance.ContentCore; /// Tracks the installed mods. - /// This is initialised after the game starts. + /// This is initialized after the game starts. private readonly ModRegistry ModRegistry = new ModRegistry(); /// Manages SMAPI events for mods. @@ -120,7 +120,7 @@ namespace StardewModdingAPI.Framework ** Accessors *********/ /// Manages deprecation warnings. - /// This is initialised after the game starts. This is accessed directly because it's not part of the normal class model. + /// This is initialized after the game starts. This is accessed directly because it's not part of the normal class model. internal static DeprecationManager DeprecationManager { get; private set; } @@ -187,7 +187,7 @@ namespace StardewModdingAPI.Framework [HandleProcessCorruptedStateExceptions, SecurityCritical] // let try..catch handle corrupted state exceptions public void RunInteractively() { - // initialise SMAPI + // initialize SMAPI try { JsonConverter[] converters = { @@ -205,14 +205,14 @@ namespace StardewModdingAPI.Framework #endif AppDomain.CurrentDomain.UnhandledException += (sender, e) => this.Monitor.Log($"Critical app domain exception: {e.ExceptionObject}", LogLevel.Error); - // add more leniant assembly resolvers + // add more lenient assembly resolvers AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => AssemblyLoader.ResolveAssembly(e.Name); // hook locale event LocalizedContentManager.OnLanguageChange += locale => this.OnLocaleChanged(); // override game - SGame.ConstructorHack = new SGameConstructorHack(this.Monitor, this.Reflection, this.Toolkit.JsonHelper, this.InitialiseBeforeFirstAssetLoaded); + SGame.ConstructorHack = new SGameConstructorHack(this.Monitor, this.Reflection, this.Toolkit.JsonHelper, this.InitializeBeforeFirstAssetLoaded); this.GameInstance = new SGame( monitor: this.Monitor, monitorForGame: this.MonitorForGame, @@ -221,7 +221,7 @@ namespace StardewModdingAPI.Framework jsonHelper: this.Toolkit.JsonHelper, modRegistry: this.ModRegistry, deprecationManager: SCore.DeprecationManager, - onGameInitialised: this.InitialiseAfterGameStart, + onGameInitialized: this.InitializeAfterGameStart, onGameExiting: this.Dispose, cancellationToken: this.CancellationToken, logNetworkTraffic: this.Settings.LogNetworkTraffic @@ -262,7 +262,7 @@ namespace StardewModdingAPI.Framework } catch (Exception ex) { - this.Monitor.Log($"SMAPI failed to initialise: {ex.GetLogSummary()}", LogLevel.Error); + this.Monitor.Log($"SMAPI failed to initialize: {ex.GetLogSummary()}", LogLevel.Error); this.PressAnyKeyToExit(); return; } @@ -377,12 +377,12 @@ namespace StardewModdingAPI.Framework /********* ** Private methods *********/ - /// Initialise mods before the first game asset is loaded. At this point the core content managers are loaded (so mods can load their own assets), but the game is mostly uninitialised. - private void InitialiseBeforeFirstAssetLoaded() + /// Initialize mods before the first game asset is loaded. At this point the core content managers are loaded (so mods can load their own assets), but the game is mostly uninitialized. + private void InitializeBeforeFirstAssetLoaded() { if (this.CancellationToken.IsCancellationRequested) { - this.Monitor.Log("SMAPI shutting down: aborting initialisation.", LogLevel.Warn); + this.Monitor.Log("SMAPI shutting down: aborting initialization.", LogLevel.Warn); return; } @@ -432,8 +432,8 @@ namespace StardewModdingAPI.Framework Console.Title = $"SMAPI {Constants.ApiVersion} - running Stardew Valley {Constants.GameVersion} with {modsLoaded} mods"; } - /// Initialise SMAPI and mods after the game starts. - private void InitialiseAfterGameStart() + /// Initialize SMAPI and mods after the game starts. + private void InitializeAfterGameStart() { // validate XNB integrity if (!this.ValidateContentIntegrity()) @@ -696,7 +696,7 @@ namespace StardewModdingAPI.Framework /// Get whether a given version should be offered to the user as an update. /// The current semantic version. /// The target semantic version. - /// Whether the user enabled the beta channel and should be offered pre-release updates. + /// Whether the user enabled the beta channel and should be offered prerelease updates. private bool IsValidUpdate(ISemanticVersion currentVersion, ISemanticVersion newVersion, bool useBetaChannel) { return @@ -716,7 +716,7 @@ namespace StardewModdingAPI.Framework } catch (Exception ex) { - // note: this happens before this.Monitor is initialised + // note: this happens before this.Monitor is initialized Console.WriteLine($"Couldn't create a path: {path}\n\n{ex.GetLogSummary()}"); } } @@ -795,10 +795,10 @@ namespace StardewModdingAPI.Framework // log mod warnings this.LogModWarnings(loaded, skippedMods); - // initialise translations + // initialize translations this.ReloadTranslations(loaded); - // initialise loaded non-content-pack mods + // initialize loaded non-content-pack mods foreach (IModMetadata metadata in loadedMods) { // add interceptors @@ -847,7 +847,7 @@ namespace StardewModdingAPI.Framework } // invalidate cache entries when needed - // (These listeners are registered after Entry to avoid repeatedly reloading assets as mods initialise.) + // (These listeners are registered after Entry to avoid repeatedly reloading assets as mods initialize.) foreach (IModMetadata metadata in loadedMods) { if (metadata.Mod.Helper.Content is ContentHelper helper) @@ -881,7 +881,7 @@ namespace StardewModdingAPI.Framework } // unlock mod integrations - this.ModRegistry.AreAllModsInitialised = true; + this.ModRegistry.AreAllModsInitialized = true; } /// Load a given mod. @@ -924,7 +924,7 @@ namespace StardewModdingAPI.Framework } // validate dependencies - // Although dependences are validated before mods are loaded, a dependency may have failed to load. + // Although dependencies are validated before mods are loaded, a dependency may have failed to load. if (mod.Manifest.Dependencies?.Any() == true) { foreach (IManifestDependency dependency in mod.Manifest.Dependencies.Where(p => p.IsRequired)) @@ -988,7 +988,7 @@ namespace StardewModdingAPI.Framework return false; } - // initialise mod + // initialize mod try { // get mod instance @@ -1045,7 +1045,7 @@ namespace StardewModdingAPI.Framework } catch (Exception ex) { - errorReasonPhrase = $"initialisation failed:\n{ex.GetLogSummary()}"; + errorReasonPhrase = $"initialization failed:\n{ex.GetLogSummary()}"; return false; } } @@ -1120,8 +1120,8 @@ namespace StardewModdingAPI.Framework "These mods have broken code, but you configured SMAPI to load them anyway. This may cause bugs,", "errors, or crashes in-game." ); - LogWarningGroup(ModWarning.ChangesSaveSerialiser, LogLevel.Warn, "Changed save serialiser", - "These mods change the save serialiser. They may corrupt your save files, or make them unusable if", + LogWarningGroup(ModWarning.ChangesSaveSerializer, LogLevel.Warn, "Changed save serializer", + "These mods change the save serializer. They may corrupt your save files, or make them unusable if", "you uninstall these mods." ); if (this.Settings.ParanoidWarnings) @@ -1285,7 +1285,7 @@ namespace StardewModdingAPI.Framework break; default: - throw new NotSupportedException($"Unrecognise core SMAPI command '{name}'."); + throw new NotSupportedException($"Unrecognized core SMAPI command '{name}'."); } } diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index 376368d6..e6d91fc3 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -18,7 +18,7 @@ using StardewModdingAPI.Framework.Networking; using StardewModdingAPI.Framework.Reflection; using StardewModdingAPI.Framework.StateTracking.Snapshots; using StardewModdingAPI.Framework.Utilities; -using StardewModdingAPI.Toolkit.Serialisation; +using StardewModdingAPI.Toolkit.Serialization; using StardewValley; using StardewValley.BellsAndWhistles; using StardewValley.Events; @@ -60,7 +60,7 @@ namespace StardewModdingAPI.Framework private readonly Countdown UpdateCrashTimer = new Countdown(60); // 60 ticks = roughly one second /// The number of ticks until SMAPI should notify mods that the game has loaded. - /// Skipping a few frames ensures the game finishes initialising the world before mods try to change it. + /// Skipping a few frames ensures the game finishes initializing the world before mods try to change it. private readonly Countdown AfterLoadTimer = new Countdown(5); /// Whether the game is saving and SMAPI has already raised . @@ -72,8 +72,8 @@ namespace StardewModdingAPI.Framework /// A callback to invoke the first time *any* game content manager loads an asset. private readonly Action OnLoadingFirstAsset; - /// A callback to invoke after the game finishes initialising. - private readonly Action OnGameInitialised; + /// A callback to invoke after the game finishes initializing. + private readonly Action OnGameInitialized; /// A callback to invoke when the game exits. private readonly Action OnGameExiting; @@ -93,8 +93,8 @@ namespace StardewModdingAPI.Framework /// A snapshot of the current state. private WatcherSnapshot WatcherSnapshot = new WatcherSnapshot(); - /// Whether post-game-startup initialisation has been performed. - private bool IsInitialised; + /// Whether post-game-startup initialization has been performed. + private bool IsInitialized; /// Whether the next content manager requested by the game will be for . private bool NextContentManagerIsMain; @@ -103,7 +103,7 @@ namespace StardewModdingAPI.Framework /********* ** Accessors *********/ - /// Static state to use while is initialising, which happens before the constructor runs. + /// Static state to use while is initializing, which happens before the constructor runs. internal static SGameConstructorHack ConstructorHack { get; set; } /// The number of update ticks which have already executed. This is similar to , but incremented more consistently for every tick. @@ -137,18 +137,18 @@ namespace StardewModdingAPI.Framework /// Encapsulates SMAPI's JSON file parsing. /// Tracks the installed mods. /// Manages deprecation warnings. - /// A callback to invoke after the game finishes initialising. + /// A callback to invoke after the game finishes initializing. /// A callback to invoke when the game exits. /// Propagates notification that SMAPI should exit. /// Whether to log network traffic. - internal SGame(Monitor monitor, IMonitor monitorForGame, Reflector reflection, EventManager eventManager, JsonHelper jsonHelper, ModRegistry modRegistry, DeprecationManager deprecationManager, Action onGameInitialised, Action onGameExiting, CancellationTokenSource cancellationToken, bool logNetworkTraffic) + internal SGame(Monitor monitor, IMonitor monitorForGame, Reflector reflection, EventManager eventManager, JsonHelper jsonHelper, ModRegistry modRegistry, DeprecationManager deprecationManager, Action onGameInitialized, Action onGameExiting, CancellationTokenSource cancellationToken, bool logNetworkTraffic) { this.OnLoadingFirstAsset = SGame.ConstructorHack.OnLoadingFirstAsset; SGame.ConstructorHack = null; // check expectations if (this.ContentCore == null) - throw new InvalidOperationException($"The game didn't initialise its first content manager before SMAPI's {nameof(SGame)} constructor. This indicates an incompatible lifecycle change."); + throw new InvalidOperationException($"The game didn't initialize its first content manager before SMAPI's {nameof(SGame)} constructor. This indicates an incompatible lifecycle change."); // init XNA Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef; @@ -160,7 +160,7 @@ namespace StardewModdingAPI.Framework this.ModRegistry = modRegistry; this.Reflection = reflection; this.DeprecationManager = deprecationManager; - this.OnGameInitialised = onGameInitialised; + this.OnGameInitialized = onGameInitialized; this.OnGameExiting = onGameExiting; Game1.input = new SInputState(); Game1.multiplayer = new SMultiplayer(monitor, eventManager, jsonHelper, modRegistry, reflection, this.OnModMessageReceived, logNetworkTraffic); @@ -171,8 +171,8 @@ namespace StardewModdingAPI.Framework Game1.locations = new ObservableCollection(); } - /// Initialise just before the game's first update tick. - private void InitialiseAfterGameStarted() + /// Initialize just before the game's first update tick. + private void InitializeAfterGameStarted() { // set initial state this.Input.TrueUpdate(); @@ -181,7 +181,7 @@ namespace StardewModdingAPI.Framework this.Watchers = new WatcherCore(this.Input); // raise callback - this.OnGameInitialised(); + this.OnGameInitialized(); } /// Perform cleanup logic when the game exits. @@ -238,8 +238,8 @@ namespace StardewModdingAPI.Framework /// The root directory to search for content. protected override LocalizedContentManager CreateContentManager(IServiceProvider serviceProvider, string rootDirectory) { - // Game1._temporaryContent initialising from SGame constructor - // NOTE: this method is called before the SGame constructor runs. Don't depend on anything being initialised at this point. + // Game1._temporaryContent initializing from SGame constructor + // NOTE: this method is called before the SGame constructor runs. Don't depend on anything being initialized at this point. if (this.ContentCore == null) { this.ContentCore = new ContentCoordinator(serviceProvider, rootDirectory, Thread.CurrentThread.CurrentUICulture, SGame.ConstructorHack.Monitor, SGame.ConstructorHack.Reflection, SGame.ConstructorHack.JsonHelper, this.OnLoadingFirstAsset ?? SGame.ConstructorHack?.OnLoadingFirstAsset); @@ -247,7 +247,7 @@ namespace StardewModdingAPI.Framework return this.ContentCore.CreateGameContentManager("Game1._temporaryContent"); } - // Game1.content initialising from LoadContent + // Game1.content initializing from LoadContent if (this.NextContentManagerIsMain) { this.NextContentManagerIsMain = false; @@ -269,12 +269,12 @@ namespace StardewModdingAPI.Framework this.DeprecationManager.PrintQueued(); /********* - ** First-tick initialisation + ** First-tick initialization *********/ - if (!this.IsInitialised) + if (!this.IsInitialized) { - this.IsInitialised = true; - this.InitialiseAfterGameStarted(); + this.IsInitialized = true; + this.InitializeAfterGameStarted(); } /********* @@ -302,7 +302,7 @@ namespace StardewModdingAPI.Framework bool saveParsed = false; if (Game1.currentLoader != null) { - this.Monitor.Log("Game loader synchronising...", LogLevel.Trace); + this.Monitor.Log("Game loader synchronizing...", LogLevel.Trace); while (Game1.currentLoader?.MoveNext() == true) { // raise load stage changed @@ -333,7 +333,7 @@ namespace StardewModdingAPI.Framework } if (Game1._newDayTask?.Status == TaskStatus.Created) { - this.Monitor.Log("New day task synchronising...", LogLevel.Trace); + this.Monitor.Log("New day task synchronizing...", LogLevel.Trace); Game1._newDayTask.RunSynchronously(); this.Monitor.Log("New day task done.", LogLevel.Trace); } @@ -346,7 +346,7 @@ namespace StardewModdingAPI.Framework // Therefore we can just run Game1.Update here without raising any SMAPI events. There's // a small chance that the task will finish after we defer but before the game checks, // which means technically events should be raised, but the effects of missing one - // update tick are neglible and not worth the complications of bypassing Game1.Update. + // update tick are negligible and not worth the complications of bypassing Game1.Update. if (Game1._newDayTask != null || Game1.gameMode == Game1.loadingMode) { events.UnvalidatedUpdateTicking.RaiseEmpty(); @@ -436,7 +436,7 @@ namespace StardewModdingAPI.Framework } else if (Context.IsSaveLoaded && this.AfterLoadTimer.Current > 0 && Game1.currentLocation != null) { - if (Game1.dayOfMonth != 0) // wait until new-game intro finishes (world not fully initialised yet) + if (Game1.dayOfMonth != 0) // wait until new-game intro finishes (world not fully initialized yet) this.AfterLoadTimer.Decrement(); Context.IsWorldReady = this.AfterLoadTimer.Current == 0; } diff --git a/src/SMAPI/Framework/SGameConstructorHack.cs b/src/SMAPI/Framework/SGameConstructorHack.cs index c3d22197..f70dec03 100644 --- a/src/SMAPI/Framework/SGameConstructorHack.cs +++ b/src/SMAPI/Framework/SGameConstructorHack.cs @@ -1,11 +1,11 @@ using System; using StardewModdingAPI.Framework.Reflection; -using StardewModdingAPI.Toolkit.Serialisation; +using StardewModdingAPI.Toolkit.Serialization; using StardewValley; namespace StardewModdingAPI.Framework { - /// The static state to use while is initialising, which happens before the constructor runs. + /// The static state to use while is initializing, which happens before the constructor runs. internal class SGameConstructorHack { /********* diff --git a/src/SMAPI/Framework/SMultiplayer.cs b/src/SMAPI/Framework/SMultiplayer.cs index 531c229e..e04205c8 100644 --- a/src/SMAPI/Framework/SMultiplayer.cs +++ b/src/SMAPI/Framework/SMultiplayer.cs @@ -9,7 +9,7 @@ using StardewModdingAPI.Events; using StardewModdingAPI.Framework.Events; using StardewModdingAPI.Framework.Networking; using StardewModdingAPI.Framework.Reflection; -using StardewModdingAPI.Toolkit.Serialisation; +using StardewModdingAPI.Toolkit.Serialization; using StardewValley; using StardewValley.Network; using StardewValley.SDKs; @@ -94,8 +94,8 @@ namespace StardewModdingAPI.Framework this.HostPeer = null; } - /// Initialise a client before the game connects to a remote server. - /// The client to initialise. + /// Initialize a client before the game connects to a remote server. + /// The client to initialize. public override Client InitClient(Client client) { switch (client) @@ -118,8 +118,8 @@ namespace StardewModdingAPI.Framework } } - /// Initialise a server before the game connects to an incoming player. - /// The server to initialise. + /// Initialize a server before the game connects to an incoming player. + /// The server to initialize. public override Server InitServer(Server server) { switch (server) @@ -423,7 +423,7 @@ namespace StardewModdingAPI.Framework private RemoteContextModel ReadContext(BinaryReader reader) { string data = reader.ReadString(); - RemoteContextModel model = this.JsonHelper.Deserialise(data); + RemoteContextModel model = this.JsonHelper.Deserialize(data); return model.ApiVersion != null ? model : null; // no data available for unmodded players @@ -435,7 +435,7 @@ namespace StardewModdingAPI.Framework { // parse message string json = message.Reader.ReadString(); - ModMessageModel model = this.JsonHelper.Deserialise(json); + ModMessageModel model = this.JsonHelper.Deserialize(json); HashSet playerIDs = new HashSet(model.ToPlayerIDs ?? this.GetKnownPlayerIDs()); if (this.LogNetworkTraffic) this.Monitor.Log($"Received message: {json}.", LogLevel.Trace); @@ -454,7 +454,7 @@ namespace StardewModdingAPI.Framework { newModel.ToPlayerIDs = new[] { peer.PlayerID }; this.Monitor.VerboseLog($" Forwarding message to player {peer.PlayerID}."); - peer.SendMessage(new OutgoingMessage((byte)MessageType.ModMessage, peer.PlayerID, this.JsonHelper.Serialise(newModel, Formatting.None))); + peer.SendMessage(new OutgoingMessage((byte)MessageType.ModMessage, peer.PlayerID, this.JsonHelper.Serialize(newModel, Formatting.None))); } } } @@ -488,7 +488,7 @@ namespace StardewModdingAPI.Framework .ToArray() }; - return new object[] { this.JsonHelper.Serialise(model, Formatting.None) }; + return new object[] { this.JsonHelper.Serialize(model, Formatting.None) }; } /// Get the fields to include in a context sync message sent to other players. @@ -514,7 +514,7 @@ namespace StardewModdingAPI.Framework .ToArray() }; - return new object[] { this.JsonHelper.Serialise(model, Formatting.None) }; + return new object[] { this.JsonHelper.Serialize(model, Formatting.None) }; } } } diff --git a/src/SMAPI/Framework/Serialisation/ColorConverter.cs b/src/SMAPI/Framework/Serialisation/ColorConverter.cs deleted file mode 100644 index c27065bf..00000000 --- a/src/SMAPI/Framework/Serialisation/ColorConverter.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using Microsoft.Xna.Framework; -using Newtonsoft.Json.Linq; -using StardewModdingAPI.Toolkit.Serialisation; -using StardewModdingAPI.Toolkit.Serialisation.Converters; - -namespace StardewModdingAPI.Framework.Serialisation -{ - /// Handles deserialisation of for crossplatform compatibility. - /// - /// - Linux/Mac format: { "B": 76, "G": 51, "R": 25, "A": 102 } - /// - Windows format: "26, 51, 76, 102" - /// - internal class ColorConverter : SimpleReadOnlyConverter - { - /********* - ** Protected methods - *********/ - /// Read a JSON object. - /// The JSON object to read. - /// The path to the current JSON node. - protected override Color ReadObject(JObject obj, string path) - { - int r = obj.ValueIgnoreCase(nameof(Color.R)); - int g = obj.ValueIgnoreCase(nameof(Color.G)); - int b = obj.ValueIgnoreCase(nameof(Color.B)); - int a = obj.ValueIgnoreCase(nameof(Color.A)); - return new Color(r, g, b, a); - } - - /// Read a JSON string. - /// The JSON string value. - /// The path to the current JSON node. - protected override Color ReadString(string str, string path) - { - string[] parts = str.Split(','); - if (parts.Length != 4) - throw new SParseException($"Can't parse {typeof(Color).Name} from invalid value '{str}' (path: {path})."); - - int r = Convert.ToInt32(parts[0]); - int g = Convert.ToInt32(parts[1]); - int b = Convert.ToInt32(parts[2]); - int a = Convert.ToInt32(parts[3]); - return new Color(r, g, b, a); - } - } -} diff --git a/src/SMAPI/Framework/Serialisation/PointConverter.cs b/src/SMAPI/Framework/Serialisation/PointConverter.cs deleted file mode 100644 index fbc857d2..00000000 --- a/src/SMAPI/Framework/Serialisation/PointConverter.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using Microsoft.Xna.Framework; -using Newtonsoft.Json.Linq; -using StardewModdingAPI.Toolkit.Serialisation; -using StardewModdingAPI.Toolkit.Serialisation.Converters; - -namespace StardewModdingAPI.Framework.Serialisation -{ - /// Handles deserialisation of for crossplatform compatibility. - /// - /// - Linux/Mac format: { "X": 1, "Y": 2 } - /// - Windows format: "1, 2" - /// - internal class PointConverter : SimpleReadOnlyConverter - { - /********* - ** Protected methods - *********/ - /// Read a JSON object. - /// The JSON object to read. - /// The path to the current JSON node. - protected override Point ReadObject(JObject obj, string path) - { - int x = obj.ValueIgnoreCase(nameof(Point.X)); - int y = obj.ValueIgnoreCase(nameof(Point.Y)); - return new Point(x, y); - } - - /// Read a JSON string. - /// The JSON string value. - /// The path to the current JSON node. - protected override Point ReadString(string str, string path) - { - string[] parts = str.Split(','); - if (parts.Length != 2) - throw new SParseException($"Can't parse {typeof(Point).Name} from invalid value '{str}' (path: {path})."); - - int x = Convert.ToInt32(parts[0]); - int y = Convert.ToInt32(parts[1]); - return new Point(x, y); - } - } -} diff --git a/src/SMAPI/Framework/Serialisation/RectangleConverter.cs b/src/SMAPI/Framework/Serialisation/RectangleConverter.cs deleted file mode 100644 index 4f55cc32..00000000 --- a/src/SMAPI/Framework/Serialisation/RectangleConverter.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Text.RegularExpressions; -using Microsoft.Xna.Framework; -using Newtonsoft.Json.Linq; -using StardewModdingAPI.Toolkit.Serialisation; -using StardewModdingAPI.Toolkit.Serialisation.Converters; - -namespace StardewModdingAPI.Framework.Serialisation -{ - /// Handles deserialisation of for crossplatform compatibility. - /// - /// - Linux/Mac format: { "X": 1, "Y": 2, "Width": 3, "Height": 4 } - /// - Windows format: "{X:1 Y:2 Width:3 Height:4}" - /// - internal class RectangleConverter : SimpleReadOnlyConverter - { - /********* - ** Protected methods - *********/ - /// Read a JSON object. - /// The JSON object to read. - /// The path to the current JSON node. - protected override Rectangle ReadObject(JObject obj, string path) - { - int x = obj.ValueIgnoreCase(nameof(Rectangle.X)); - int y = obj.ValueIgnoreCase(nameof(Rectangle.Y)); - int width = obj.ValueIgnoreCase(nameof(Rectangle.Width)); - int height = obj.ValueIgnoreCase(nameof(Rectangle.Height)); - return new Rectangle(x, y, width, height); - } - - /// Read a JSON string. - /// The JSON string value. - /// The path to the current JSON node. - protected override Rectangle ReadString(string str, string path) - { - if (string.IsNullOrWhiteSpace(str)) - return Rectangle.Empty; - - var match = Regex.Match(str, @"^\{X:(?\d+) Y:(?\d+) Width:(?\d+) Height:(?\d+)\}$", RegexOptions.IgnoreCase); - if (!match.Success) - throw new SParseException($"Can't parse {typeof(Rectangle).Name} from invalid value '{str}' (path: {path})."); - - int x = Convert.ToInt32(match.Groups["x"].Value); - int y = Convert.ToInt32(match.Groups["y"].Value); - int width = Convert.ToInt32(match.Groups["width"].Value); - int height = Convert.ToInt32(match.Groups["height"].Value); - - return new Rectangle(x, y, width, height); - } - } -} diff --git a/src/SMAPI/Framework/Serialization/ColorConverter.cs b/src/SMAPI/Framework/Serialization/ColorConverter.cs new file mode 100644 index 00000000..19979981 --- /dev/null +++ b/src/SMAPI/Framework/Serialization/ColorConverter.cs @@ -0,0 +1,47 @@ +using System; +using Microsoft.Xna.Framework; +using Newtonsoft.Json.Linq; +using StardewModdingAPI.Toolkit.Serialization; +using StardewModdingAPI.Toolkit.Serialization.Converters; + +namespace StardewModdingAPI.Framework.Serialization +{ + /// Handles deserialization of for crossplatform compatibility. + /// + /// - Linux/Mac format: { "B": 76, "G": 51, "R": 25, "A": 102 } + /// - Windows format: "26, 51, 76, 102" + /// + internal class ColorConverter : SimpleReadOnlyConverter + { + /********* + ** Protected methods + *********/ + /// Read a JSON object. + /// The JSON object to read. + /// The path to the current JSON node. + protected override Color ReadObject(JObject obj, string path) + { + int r = obj.ValueIgnoreCase(nameof(Color.R)); + int g = obj.ValueIgnoreCase(nameof(Color.G)); + int b = obj.ValueIgnoreCase(nameof(Color.B)); + int a = obj.ValueIgnoreCase(nameof(Color.A)); + return new Color(r, g, b, a); + } + + /// Read a JSON string. + /// The JSON string value. + /// The path to the current JSON node. + protected override Color ReadString(string str, string path) + { + string[] parts = str.Split(','); + if (parts.Length != 4) + throw new SParseException($"Can't parse {typeof(Color).Name} from invalid value '{str}' (path: {path})."); + + int r = Convert.ToInt32(parts[0]); + int g = Convert.ToInt32(parts[1]); + int b = Convert.ToInt32(parts[2]); + int a = Convert.ToInt32(parts[3]); + return new Color(r, g, b, a); + } + } +} diff --git a/src/SMAPI/Framework/Serialization/PointConverter.cs b/src/SMAPI/Framework/Serialization/PointConverter.cs new file mode 100644 index 00000000..8c2f3396 --- /dev/null +++ b/src/SMAPI/Framework/Serialization/PointConverter.cs @@ -0,0 +1,43 @@ +using System; +using Microsoft.Xna.Framework; +using Newtonsoft.Json.Linq; +using StardewModdingAPI.Toolkit.Serialization; +using StardewModdingAPI.Toolkit.Serialization.Converters; + +namespace StardewModdingAPI.Framework.Serialization +{ + /// Handles deserialization of for crossplatform compatibility. + /// + /// - Linux/Mac format: { "X": 1, "Y": 2 } + /// - Windows format: "1, 2" + /// + internal class PointConverter : SimpleReadOnlyConverter + { + /********* + ** Protected methods + *********/ + /// Read a JSON object. + /// The JSON object to read. + /// The path to the current JSON node. + protected override Point ReadObject(JObject obj, string path) + { + int x = obj.ValueIgnoreCase(nameof(Point.X)); + int y = obj.ValueIgnoreCase(nameof(Point.Y)); + return new Point(x, y); + } + + /// Read a JSON string. + /// The JSON string value. + /// The path to the current JSON node. + protected override Point ReadString(string str, string path) + { + string[] parts = str.Split(','); + if (parts.Length != 2) + throw new SParseException($"Can't parse {typeof(Point).Name} from invalid value '{str}' (path: {path})."); + + int x = Convert.ToInt32(parts[0]); + int y = Convert.ToInt32(parts[1]); + return new Point(x, y); + } + } +} diff --git a/src/SMAPI/Framework/Serialization/RectangleConverter.cs b/src/SMAPI/Framework/Serialization/RectangleConverter.cs new file mode 100644 index 00000000..fbb2e253 --- /dev/null +++ b/src/SMAPI/Framework/Serialization/RectangleConverter.cs @@ -0,0 +1,52 @@ +using System; +using System.Text.RegularExpressions; +using Microsoft.Xna.Framework; +using Newtonsoft.Json.Linq; +using StardewModdingAPI.Toolkit.Serialization; +using StardewModdingAPI.Toolkit.Serialization.Converters; + +namespace StardewModdingAPI.Framework.Serialization +{ + /// Handles deserialization of for crossplatform compatibility. + /// + /// - Linux/Mac format: { "X": 1, "Y": 2, "Width": 3, "Height": 4 } + /// - Windows format: "{X:1 Y:2 Width:3 Height:4}" + /// + internal class RectangleConverter : SimpleReadOnlyConverter + { + /********* + ** Protected methods + *********/ + /// Read a JSON object. + /// The JSON object to read. + /// The path to the current JSON node. + protected override Rectangle ReadObject(JObject obj, string path) + { + int x = obj.ValueIgnoreCase(nameof(Rectangle.X)); + int y = obj.ValueIgnoreCase(nameof(Rectangle.Y)); + int width = obj.ValueIgnoreCase(nameof(Rectangle.Width)); + int height = obj.ValueIgnoreCase(nameof(Rectangle.Height)); + return new Rectangle(x, y, width, height); + } + + /// Read a JSON string. + /// The JSON string value. + /// The path to the current JSON node. + protected override Rectangle ReadString(string str, string path) + { + if (string.IsNullOrWhiteSpace(str)) + return Rectangle.Empty; + + var match = Regex.Match(str, @"^\{X:(?\d+) Y:(?\d+) Width:(?\d+) Height:(?\d+)\}$", RegexOptions.IgnoreCase); + if (!match.Success) + throw new SParseException($"Can't parse {typeof(Rectangle).Name} from invalid value '{str}' (path: {path})."); + + int x = Convert.ToInt32(match.Groups["x"].Value); + int y = Convert.ToInt32(match.Groups["y"].Value); + int width = Convert.ToInt32(match.Groups["width"].Value); + int height = Convert.ToInt32(match.Groups["height"].Value); + + return new Rectangle(x, y, width, height); + } + } +} diff --git a/src/SMAPI/Framework/StateTracking/FieldWatchers/ComparableListWatcher.cs b/src/SMAPI/Framework/StateTracking/FieldWatchers/ComparableListWatcher.cs index 6550f950..32ec8c7e 100644 --- a/src/SMAPI/Framework/StateTracking/FieldWatchers/ComparableListWatcher.cs +++ b/src/SMAPI/Framework/StateTracking/FieldWatchers/ComparableListWatcher.cs @@ -53,7 +53,7 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers { this.AssertNotDisposed(); - // optimise for zero items + // optimize for zero items if (this.CurrentValues.Count == 0) { if (this.LastValues.Count > 0) diff --git a/src/SMAPI/IAssetInfo.cs b/src/SMAPI/IAssetInfo.cs index 5dd58e2e..6cdf01ee 100644 --- a/src/SMAPI/IAssetInfo.cs +++ b/src/SMAPI/IAssetInfo.cs @@ -8,10 +8,10 @@ namespace StardewModdingAPI /********* ** Accessors *********/ - /// The content's locale code, if the content is localised. + /// The content's locale code, if the content is localized. string Locale { get; } - /// The normalised asset name being read. The format may change between platforms; see to compare with a known path. + /// The normalized asset name being read. The format may change between platforms; see to compare with a known path. string AssetName { get; } /// The content data type. @@ -21,7 +21,7 @@ namespace StardewModdingAPI /********* ** Public methods *********/ - /// Get whether the asset name being loaded matches a given name after normalisation. + /// Get whether the asset name being loaded matches a given name after normalization. /// The expected asset path, relative to the game's content folder and without the .xnb extension or locale suffix (like 'Data\ObjectInformation'). bool AssetNameEquals(string path); } diff --git a/src/SMAPI/IContentHelper.cs b/src/SMAPI/IContentHelper.cs index 1b87183d..dd7eb758 100644 --- a/src/SMAPI/IContentHelper.cs +++ b/src/SMAPI/IContentHelper.cs @@ -38,10 +38,10 @@ namespace StardewModdingAPI /// The content asset couldn't be loaded (e.g. because it doesn't exist). T Load(string key, ContentSource source = ContentSource.ModFolder); - /// Normalise an asset name so it's consistent with those generated by the game. This is mainly useful for string comparisons like on generated asset names, and isn't necessary when passing asset names into other content helper methods. + /// Normalize an asset name so it's consistent with those generated by the game. This is mainly useful for string comparisons like on generated asset names, and isn't necessary when passing asset names into other content helper methods. /// The asset key. [Pure] - string NormaliseAssetName(string assetName); + string NormalizeAssetName(string assetName); /// Get the underlying key in the game's content cache for an asset. This can be used to load custom map tilesheets, but should be avoided when you can use the content API instead. This does not validate whether the asset exists. /// The asset key to fetch (if the is ), or the local path to a content file relative to the mod folder. diff --git a/src/SMAPI/IContentPack.cs b/src/SMAPI/IContentPack.cs index 7085c538..c0479eae 100644 --- a/src/SMAPI/IContentPack.cs +++ b/src/SMAPI/IContentPack.cs @@ -31,7 +31,7 @@ namespace StardewModdingAPI /// Read a JSON file from the content pack folder. /// The model type. This should be a plain class that has public properties for the data you want. The properties can be complex types. /// The file path relative to the content pack directory. - /// Returns the deserialised model, or null if the file doesn't exist or is empty. + /// Returns the deserialized model, or null if the file doesn't exist or is empty. /// The is not relative or contains directory climbing (../). TModel ReadJsonFile(string path) where TModel : class; diff --git a/src/SMAPI/IContentPackHelper.cs b/src/SMAPI/IContentPackHelper.cs index e4949f58..c48a4f86 100644 --- a/src/SMAPI/IContentPackHelper.cs +++ b/src/SMAPI/IContentPackHelper.cs @@ -11,7 +11,7 @@ namespace StardewModdingAPI /// Get all content packs loaded for this mod. IEnumerable GetOwned(); - /// Create a temporary content pack to read files from a directory, using randomised manifest fields. Temporary content packs will not appear in the SMAPI log and update checks will not be performed. + /// Create a temporary content pack to read files from a directory, using randomized manifest fields. Temporary content packs will not appear in the SMAPI log and update checks will not be performed. /// The absolute directory path containing the content pack files. IContentPack CreateFake(string directoryPath); diff --git a/src/SMAPI/IDataHelper.cs b/src/SMAPI/IDataHelper.cs index 6afdc529..252030bd 100644 --- a/src/SMAPI/IDataHelper.cs +++ b/src/SMAPI/IDataHelper.cs @@ -14,7 +14,7 @@ namespace StardewModdingAPI /// Read data from a JSON file in the mod's folder. /// The model type. This should be a plain class that has public properties for the data you want. The properties can be complex types. /// The file path relative to the mod folder. - /// Returns the deserialised model, or null if the file doesn't exist or is empty. + /// Returns the deserialized model, or null if the file doesn't exist or is empty. /// The is not relative or contains directory climbing (../). TModel ReadJsonFile(string path) where TModel : class; diff --git a/src/SMAPI/Metadata/CoreAssetPropagator.cs b/src/SMAPI/Metadata/CoreAssetPropagator.cs index 3fbca04a..b72590fd 100644 --- a/src/SMAPI/Metadata/CoreAssetPropagator.cs +++ b/src/SMAPI/Metadata/CoreAssetPropagator.cs @@ -24,8 +24,8 @@ namespace StardewModdingAPI.Metadata /********* ** Fields *********/ - /// Normalises an asset key to match the cache key. - private readonly Func GetNormalisedPath; + /// Normalizes an asset key to match the cache key. + private readonly Func GetNormalizedPath; /// Simplifies access to private game code. private readonly Reflector Reflection; @@ -33,7 +33,7 @@ namespace StardewModdingAPI.Metadata /// Encapsulates monitoring and logging. private readonly IMonitor Monitor; - /// Optimised bucket categories for batch reloading assets. + /// Optimized bucket categories for batch reloading assets. private enum AssetBucket { /// NPC overworld sprites. @@ -50,13 +50,13 @@ namespace StardewModdingAPI.Metadata /********* ** Public methods *********/ - /// Initialise the core asset data. - /// Normalises an asset key to match the cache key. + /// Initialize the core asset data. + /// Normalizes an asset key to match the cache key. /// Simplifies access to private code. /// Encapsulates monitoring and logging. - public CoreAssetPropagator(Func getNormalisedPath, Reflector reflection, IMonitor monitor) + public CoreAssetPropagator(Func getNormalizedPath, Reflector reflection, IMonitor monitor) { - this.GetNormalisedPath = getNormalisedPath; + this.GetNormalizedPath = getNormalizedPath; this.Reflection = reflection; this.Monitor = monitor; } @@ -67,7 +67,7 @@ namespace StardewModdingAPI.Metadata /// Returns the number of reloaded assets. public int Propagate(LocalizedContentManager content, IDictionary assets) { - // group into optimised lists + // group into optimized lists var buckets = assets.GroupBy(p => { if (this.IsInFolder(p.Key, "Characters") || this.IsInFolder(p.Key, "Characters\\Monsters")) @@ -112,7 +112,7 @@ namespace StardewModdingAPI.Metadata /// Returns whether an asset was loaded. The return value may be true or false, or a non-null value for true. private bool PropagateOther(LocalizedContentManager content, string key, Type type) { - key = this.GetNormalisedPath(key); + key = this.GetNormalizedPath(key); /**** ** Special case: current map tilesheet @@ -123,7 +123,7 @@ namespace StardewModdingAPI.Metadata { foreach (TileSheet tilesheet in Game1.currentLocation.map.TileSheets) { - if (this.GetNormalisedPath(tilesheet.ImageSource) == key) + if (this.GetNormalizedPath(tilesheet.ImageSource) == key) Game1.mapDisplayDevice.LoadTileSheet(tilesheet); } } @@ -136,7 +136,7 @@ namespace StardewModdingAPI.Metadata bool anyChanged = false; foreach (GameLocation location in this.GetLocations()) { - if (!string.IsNullOrWhiteSpace(location.mapPath.Value) && this.GetNormalisedPath(location.mapPath.Value) == key) + if (!string.IsNullOrWhiteSpace(location.mapPath.Value) && this.GetNormalizedPath(location.mapPath.Value) == key) { // general updates location.reloadMap(); @@ -162,7 +162,7 @@ namespace StardewModdingAPI.Metadata ** Propagate by key ****/ Reflector reflection = this.Reflection; - switch (key.ToLower().Replace("/", "\\")) // normalised key so we can compare statically + switch (key.ToLower().Replace("/", "\\")) // normalized key so we can compare statically { /**** ** Animals @@ -584,7 +584,7 @@ namespace StardewModdingAPI.Metadata let locCritters = this.Reflection.GetField>(location, "critters").GetValue() where locCritters != null from Critter critter in locCritters - where this.GetNormalisedPath(critter.sprite.textureName) == key + where this.GetNormalizedPath(critter.sprite.textureName) == key select critter ) .ToArray(); @@ -664,7 +664,7 @@ namespace StardewModdingAPI.Metadata // get NPCs HashSet lookup = new HashSet(keys, StringComparer.InvariantCultureIgnoreCase); NPC[] characters = this.GetCharacters() - .Where(npc => npc.Sprite != null && lookup.Contains(this.GetNormalisedPath(npc.Sprite.textureName.Value))) + .Where(npc => npc.Sprite != null && lookup.Contains(this.GetNormalizedPath(npc.Sprite.textureName.Value))) .ToArray(); if (!characters.Any()) return 0; @@ -692,7 +692,7 @@ namespace StardewModdingAPI.Metadata ( from npc in this.GetCharacters() where npc.isVillager() - let textureKey = this.GetNormalisedPath($"Portraits\\{this.getTextureName(npc)}") + let textureKey = this.GetNormalizedPath($"Portraits\\{this.getTextureName(npc)}") where lookup.Contains(textureKey) select new { npc, textureKey } ) @@ -852,17 +852,17 @@ namespace StardewModdingAPI.Metadata } } - /// Get whether a key starts with a substring after the substring is normalised. + /// Get whether a key starts with a substring after the substring is normalized. /// The key to check. - /// The substring to normalise and find. + /// The substring to normalize and find. private bool KeyStartsWith(string key, string rawSubstring) { - return key.StartsWith(this.GetNormalisedPath(rawSubstring), StringComparison.InvariantCultureIgnoreCase); + return key.StartsWith(this.GetNormalizedPath(rawSubstring), StringComparison.InvariantCultureIgnoreCase); } - /// Get whether a normalised asset key is in the given folder. - /// The normalised asset key (like Animals/cat). - /// The key folder (like Animals); doesn't need to be normalised. + /// Get whether a normalized asset key is in the given folder. + /// The normalized asset key (like Animals/cat). + /// The key folder (like Animals); doesn't need to be normalized. /// Whether to return true if the key is inside a subfolder of the . private bool IsInFolder(string key, string folder, bool allowSubfolders = false) { diff --git a/src/SMAPI/Metadata/InstructionMetadata.cs b/src/SMAPI/Metadata/InstructionMetadata.cs index 72410d41..95482708 100644 --- a/src/SMAPI/Metadata/InstructionMetadata.cs +++ b/src/SMAPI/Metadata/InstructionMetadata.cs @@ -48,11 +48,11 @@ namespace StardewModdingAPI.Metadata ****/ yield return new TypeFinder("Harmony.HarmonyInstance", InstructionHandleResult.DetectedGamePatch); yield return new TypeFinder("System.Runtime.CompilerServices.CallSite", InstructionHandleResult.DetectedDynamic); - yield return new FieldFinder(typeof(SaveGame).FullName, nameof(SaveGame.serializer), InstructionHandleResult.DetectedSaveSerialiser); - yield return new FieldFinder(typeof(SaveGame).FullName, nameof(SaveGame.farmerSerializer), InstructionHandleResult.DetectedSaveSerialiser); - yield return new FieldFinder(typeof(SaveGame).FullName, nameof(SaveGame.locationSerializer), InstructionHandleResult.DetectedSaveSerialiser); - yield return new EventFinder(typeof(ISpecialisedEvents).FullName, nameof(ISpecialisedEvents.UnvalidatedUpdateTicked), InstructionHandleResult.DetectedUnvalidatedUpdateTick); - yield return new EventFinder(typeof(ISpecialisedEvents).FullName, nameof(ISpecialisedEvents.UnvalidatedUpdateTicking), InstructionHandleResult.DetectedUnvalidatedUpdateTick); + yield return new FieldFinder(typeof(SaveGame).FullName, nameof(SaveGame.serializer), InstructionHandleResult.DetectedSaveSerializer); + yield return new FieldFinder(typeof(SaveGame).FullName, nameof(SaveGame.farmerSerializer), InstructionHandleResult.DetectedSaveSerializer); + yield return new FieldFinder(typeof(SaveGame).FullName, nameof(SaveGame.locationSerializer), InstructionHandleResult.DetectedSaveSerializer); + yield return new EventFinder(typeof(ISpecializedEvents).FullName, nameof(ISpecializedEvents.UnvalidatedUpdateTicked), InstructionHandleResult.DetectedUnvalidatedUpdateTick); + yield return new EventFinder(typeof(ISpecializedEvents).FullName, nameof(ISpecializedEvents.UnvalidatedUpdateTicking), InstructionHandleResult.DetectedUnvalidatedUpdateTick); /**** ** detect paranoid issues diff --git a/src/SMAPI/Mod.cs b/src/SMAPI/Mod.cs index 3a753afc..0e5be1c1 100644 --- a/src/SMAPI/Mod.cs +++ b/src/SMAPI/Mod.cs @@ -41,7 +41,7 @@ namespace StardewModdingAPI ** Private methods *********/ /// Release or reset unmanaged resources when the game exits. There's no guarantee this will be called on every exit. - /// Whether the instance is being disposed explicitly rather than finalised. If this is false, the instance shouldn't dispose other objects since they may already be finalised. + /// Whether the instance is being disposed explicitly rather than finalized. If this is false, the instance shouldn't dispose other objects since they may already be finalized. protected virtual void Dispose(bool disposing) { } /// Destruct the instance. diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index df7654cd..6c94a2af 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -39,7 +39,7 @@ namespace StardewModdingAPI } catch (Exception ex) { - Console.WriteLine($"SMAPI failed to initialise: {ex}"); + Console.WriteLine($"SMAPI failed to initialize: {ex}"); Program.PressAnyKeyToExit(true); } } @@ -108,7 +108,7 @@ namespace StardewModdingAPI } - /// Initialise SMAPI and launch the game. + /// Initialize SMAPI and launch the game. /// The command-line arguments. /// This method is separate from because that can't contain any references to assemblies loaded by (e.g. via ), or Mono will incorrectly show an assembly resolution error before assembly resolution is set up. private static void Start(string[] args) diff --git a/src/SMAPI/SemanticVersion.cs b/src/SMAPI/SemanticVersion.cs index b346cfdd..0db41673 100644 --- a/src/SMAPI/SemanticVersion.cs +++ b/src/SMAPI/SemanticVersion.cs @@ -61,13 +61,13 @@ namespace StardewModdingAPI this.Version = version; } - /// Whether this is a pre-release version. + /// Whether this is a prerelease version. public bool IsPrerelease() { return this.Version.IsPrerelease(); } - /// Get an integer indicating whether this version precedes (less than 0), supercedes (more than 0), or is equivalent to (0) the specified version. + /// Get an integer indicating whether this version precedes (less than 0), supersedes (more than 0), or is equivalent to (0) the specified version. /// The version to compare with this instance. /// The value is null. /// The implementation is defined by Semantic Version 2.0 (https://semver.org/). diff --git a/src/SMAPI/Translation.cs b/src/SMAPI/Translation.cs index abcdb336..e8698e2c 100644 --- a/src/SMAPI/Translation.cs +++ b/src/SMAPI/Translation.cs @@ -38,7 +38,7 @@ namespace StardewModdingAPI /********* ** Public methods *********/ - /// Construct an isntance. + /// Construct an instance. /// The name of the relevant mod for error messages. /// The locale for which the translation was fetched. /// The translation key. @@ -46,7 +46,7 @@ namespace StardewModdingAPI internal Translation(string modName, string locale, string key, string text) : this(modName, locale, key, text, string.Format(Translation.PlaceholderText, key)) { } - /// Construct an isntance. + /// Construct an instance. /// The name of the relevant mod for error messages. /// The locale for which the translation was fetched. /// The translation key. diff --git a/src/SMAPI/Utilities/SDate.cs b/src/SMAPI/Utilities/SDate.cs index 9ea4f370..0ab37aa0 100644 --- a/src/SMAPI/Utilities/SDate.cs +++ b/src/SMAPI/Utilities/SDate.cs @@ -197,7 +197,7 @@ namespace StardewModdingAPI.Utilities if (year < 1) throw new ArgumentException($"Invalid year '{year}', must be at least 1."); - // initialise + // initialize this.Day = day; this.Season = season; this.Year = year; @@ -256,12 +256,12 @@ namespace StardewModdingAPI.Utilities /// Get a season index. /// The season name. - /// The current season wasn't recognised. + /// The current season wasn't recognized. private int GetSeasonIndex(string season) { int index = Array.IndexOf(this.Seasons, season); if (index == -1) - throw new InvalidOperationException($"The season '{season}' wasn't recognised."); + throw new InvalidOperationException($"The season '{season}' wasn't recognized."); return index; } } -- cgit From 1003116f7f95d149b350642db8da2464d9ed9954 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 18 Aug 2019 01:00:11 -0400 Subject: fix asset changes not affecting cached asset loads in a specific case --- docs/release-notes.md | 1 + src/SMAPI/Framework/ContentManagers/GameContentManager.cs | 12 +++++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 5f964cfd..01b48998 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -59,6 +59,7 @@ These changes have not been released yet. * Removed the `Monitor.ExitGameImmediately` method. * Updated dependencies (including Json.NET 11.0.2 → 12.0.2, Mono.Cecil 0.10.1 → 0.10.4). * Fixed issue where mod changes weren't tracked correctly for raising events in some cases. Events now reflect a frozen snapshot of the game state, and any mod changes are reflected in the next event tick. + * Fixed issue where, when a mod's `IAssetEditor` uses `asset.ReplaceWith` on a texture asset while playing in non-English, any changes from that point won't affect subsequent cached asset loads. * Fixed `LoadStageChanged` event not raising correct flags in some cases when creating a new save. ## 2.11.3 diff --git a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs index c64e9ba9..0b563555 100644 --- a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs @@ -184,10 +184,20 @@ namespace StardewModdingAPI.Framework.ContentManagers return; } } + + // save to cache + // Note: even if the asset was loaded and cached right before this method was called, + // we need to fully re-inject it here for two reasons: + // 1. So we can look up an asset by its base or localized key (the game/XNA logic + // only caches by the most specific key). + // 2. Because a mod asset loader/editor may have changed the asset in a way that + // doesn't change the instance stored in the cache, e.g. using `asset.ReplaceWith`. + string keyWithLocale = $"{assetName}.{this.GetLocale(language)}"; base.Inject(assetName, value, language); + if (this.Cache.ContainsKey(keyWithLocale)) + base.Inject(keyWithLocale, value, language); // track whether the injected asset is translatable for is-loaded lookups - string keyWithLocale = $"{assetName}.{this.GetLocale(language)}"; if (this.Cache.ContainsKey(keyWithLocale)) { this.IsLocalizableLookup[assetName] = true; -- cgit From 15fd868f59e84629b66e0cb8fcfdda86b1ffd813 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 23 Aug 2019 16:18:51 -0400 Subject: fix 'unknown file extension' error not listing .json as a valid extension --- docs/release-notes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 01b48998..352198e0 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -29,7 +29,7 @@ These changes have not been released yet. * Fixed map reloads resetting tilesheet seasons. * Fixed map reloads not updating door warps. * Fixed outdoor tilesheets being seasonalised when added to an indoor location. - * Fixed typos and inconsistent spelling. + * Fixed various error messages and inconsistent spelling. * For the mod compatibility list: * Now loads faster (since data is fetched in a background service). -- cgit From 7ca168269fc8cc76d900fba6c6d04d2b02287956 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Thu, 29 Aug 2019 13:45:21 -0400 Subject: log skipped loose files --- docs/release-notes.md | 6 +++--- src/SMAPI/Framework/SCore.cs | 8 +++++++- 2 files changed, 10 insertions(+), 4 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 352198e0..500f2427 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -9,9 +9,9 @@ These changes have not been released yet. * Improved performance. * Rewrote launch script on Linux to improve compatibility (thanks to kurumushi and toastal!). * Improved mod scanning: - * Now ignores metadata files/folders like `__MACOSX` and `__folder_managed_by_vortex`. - * Now ignores content files like `.txt` or `.png`, which avoids missing-manifest errors in some common cases. - * Now detects XNB mods more accurately, and consolidates multi-folder XNB mods. + * Now ignores metadata files and folders (like `__MACOSX` and `__folder_managed_by_vortex`) and content files (like `.txt` or `.png`), which avoids missing-manifest errors in some common cases. + * Now detects XNB mods more accurately, and consolidates multi-folder XNB mods in logged messages. + * Added trace logs for skipped loose files so it's easier to troubleshoot player logs. * Save Backup now works in the background, to avoid affecting startup time for players with a large number of saves. * Duplicate-mod errors now show the mod version in each folder. * Updated mod compatibility list. diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index c5dede01..fde28852 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -25,7 +25,6 @@ using StardewModdingAPI.Framework.ModLoading; using StardewModdingAPI.Framework.Patching; using StardewModdingAPI.Framework.Reflection; using StardewModdingAPI.Framework.Serialization; -using StardewModdingAPI.Internal; using StardewModdingAPI.Patches; using StardewModdingAPI.Toolkit; using StardewModdingAPI.Toolkit.Framework.Clients.WebApi; @@ -395,6 +394,13 @@ namespace StardewModdingAPI.Framework this.Monitor.Log("Loading mod metadata...", LogLevel.Trace); ModResolver resolver = new ModResolver(); + // log loose files + { + string[] looseFiles = new DirectoryInfo(this.ModsPath).GetFiles().Select(p => p.Name).ToArray(); + if (looseFiles.Any()) + this.Monitor.Log($" Ignored loose files: {string.Join(", ", looseFiles.OrderBy(p => p, StringComparer.InvariantCultureIgnoreCase))}", LogLevel.Trace); + } + // load manifests IModMetadata[] mods = resolver.ReadManifests(toolkit, this.ModsPath, modDatabase).ToArray(); -- cgit From 98a56169e76432bd9efc43caddc59717278d758e Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 31 Aug 2019 16:33:57 -0400 Subject: update release notes --- docs/release-notes.md | 3 +++ 1 file changed, 3 insertions(+) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 352198e0..65fd71d4 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -43,6 +43,9 @@ These changes have not been released yet. * Added support for the Content Patcher format (thanks to TehPers!). * Added support for referencing a schema in a JSON Schema-compatible text editor. +* For the log parser: + * The page now detects your OS and preselects the right instructions (thanks to danvolchek!). + * For modders: * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialized when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialized). * Added support for content pack translations. -- cgit From 8cb190de080aad56372b1c63d8b4f977f3c81d01 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 31 Aug 2019 17:46:47 -0400 Subject: add Android detection --- docs/release-notes.md | 1 + src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs | 68 +++++++++++++++++++---- src/SMAPI/GamePlatform.cs | 3 + 3 files changed, 60 insertions(+), 12 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index a52b3e7f..7740cb1c 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -52,6 +52,7 @@ These changes have not been released yet. * Added fields and methods: `IContentPack.HasFile`, `Context.IsGameLaunched`, and `SemanticVersion.TryParse`. * Added separate `LogNetworkTraffic` option to make verbose logging less overwhelmingly verbose. * Added asset propagation for critter textures and `DayTimeMoneyBox` buttons. + * `Constants.TargetPlatform` now returns `Android` when playing on an Android device. * The installer now recognises custom game paths stored in `stardewvalley.targets`, if any. * Trace logs for a broken mod now list all detected issues (instead of the first one). * Trace logs when loading mods are now more clear. diff --git a/src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs b/src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs index 4f67c00e..6dce5da5 100644 --- a/src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs +++ b/src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; #if SMAPI_FOR_WINDOWS @@ -14,6 +15,9 @@ namespace StardewModdingAPI.Toolkit.Utilities /********* ** Fields *********/ + /// The cached platform. + private static Platform? CachedPlatform; + /// Get the OS name from the system uname command. /// The buffer to fill with the resulting string. [DllImport("libc")] @@ -26,19 +30,10 @@ namespace StardewModdingAPI.Toolkit.Utilities /// Detect the current OS. public static Platform DetectPlatform() { - switch (Environment.OSVersion.Platform) - { - case PlatformID.MacOSX: - return Platform.Mac; + if (EnvironmentUtility.CachedPlatform == null) + EnvironmentUtility.CachedPlatform = EnvironmentUtility.DetectPlatformImpl(); - case PlatformID.Unix: - return EnvironmentUtility.IsRunningMac() - ? Platform.Mac - : Platform.Linux; - - default: - return Platform.Windows; - } + return EnvironmentUtility.CachedPlatform.Value; } @@ -81,6 +76,55 @@ namespace StardewModdingAPI.Toolkit.Utilities /********* ** Private methods *********/ + /// Detect the current OS. + private static Platform DetectPlatformImpl() + { + switch (Environment.OSVersion.Platform) + { + case PlatformID.MacOSX: + return Platform.Mac; + + case PlatformID.Unix when EnvironmentUtility.IsRunningAndroid(): + return Platform.Android; + + case PlatformID.Unix when EnvironmentUtility.IsRunningMac(): + return Platform.Mac; + + case PlatformID.Unix: + return Platform.Linux; + + default: + return Platform.Windows; + } + } + + /// Detect whether the code is running on Android. + /// + /// This code is derived from https://stackoverflow.com/a/47521647/262123. It detects Android by calling the + /// getprop system command to check for an Android-specific property. + /// + private static bool IsRunningAndroid() + { + using (Process process = new Process()) + { + process.StartInfo.FileName = "getprop"; + process.StartInfo.Arguments = "ro.build.user"; + process.StartInfo.RedirectStandardOutput = true; + process.StartInfo.UseShellExecute = false; + process.StartInfo.CreateNoWindow = true; + try + { + process.Start(); + string output = process.StandardOutput.ReadToEnd(); + return !string.IsNullOrEmpty(output); + } + catch + { + return false; + } + } + } + /// Detect whether the code is running on Mac. /// /// This code is derived from the Mono project (see System.Windows.Forms/System.Windows.Forms/XplatUI.cs). It detects Mac by calling the diff --git a/src/SMAPI/GamePlatform.cs b/src/SMAPI/GamePlatform.cs index 174239e0..b64595e4 100644 --- a/src/SMAPI/GamePlatform.cs +++ b/src/SMAPI/GamePlatform.cs @@ -5,6 +5,9 @@ namespace StardewModdingAPI /// The game's platform version. public enum GamePlatform { + /// The Android version of the game. + Android = Platform.Android, + /// The Linux version of the game. Linux = Platform.Linux, -- cgit From 1db1a8fa2346c3aa77547c22b4d069fbc8b8ea60 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 31 Aug 2019 17:48:48 -0400 Subject: update SMAPI/game version map --- docs/release-notes.md | 3 ++- src/SMAPI/Constants.cs | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 7740cb1c..0202015b 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -14,11 +14,12 @@ These changes have not been released yet. * Added trace logs for skipped loose files so it's easier to troubleshoot player logs. * Save Backup now works in the background, to avoid affecting startup time for players with a large number of saves. * Duplicate-mod errors now show the mod version in each folder. - * Updated mod compatibility list. * Improved update checks: * Update checks are now faster in some cases. * Fixed error if a Nexus mod is marked as adult content. * Fixed error if the Chucklefish page for an update key doesn't exist. + * Updated mod compatibility list. + * Updated SMAPI/game version map. * Fixed mods needing to load custom `Map` assets before the game accesses them (SMAPI will now do so automatically). * Fixed Save Backup not pruning old backups if they're uncompressed. * Fixed issues when a farmhand reconnects before the game notices they're disconnected. diff --git a/src/SMAPI/Constants.cs b/src/SMAPI/Constants.cs index 4e24477b..e3a6e6d5 100644 --- a/src/SMAPI/Constants.cs +++ b/src/SMAPI/Constants.cs @@ -111,6 +111,13 @@ namespace StardewModdingAPI { switch (version.ToString()) { + case "1.3.36": + return new SemanticVersion(2, 11, 2); + + case "1.3.32": + case "1.3.33": + return new SemanticVersion(2, 10, 2); + case "1.3.28": return new SemanticVersion(2, 7, 0); -- cgit From 2f9884c47be16d476d5acbecd053b0754fa2bd59 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Thu, 5 Sep 2019 02:09:24 -0400 Subject: update packages --- docs/release-notes.md | 2 +- .../SMAPI.ModBuildConfig.Analyzer.Tests.csproj | 2 +- src/SMAPI.Tests/SMAPI.Tests.csproj | 2 +- src/SMAPI.Toolkit/SMAPI.Toolkit.csproj | 2 +- src/SMAPI.Web/SMAPI.Web.csproj | 8 ++++---- src/SMAPI/SMAPI.csproj | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 0202015b..4009d234 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -62,7 +62,7 @@ These changes have not been released yet. * Fixed custom maps loaded from the mod folder with tilesheets in a subfolder not working crossplatform. All tilesheet paths are now normalized for the OS automatically. * Removed all deprecated APIs. * Removed the `Monitor.ExitGameImmediately` method. - * Updated dependencies (including Json.NET 11.0.2 → 12.0.2, Mono.Cecil 0.10.1 → 0.10.4). + * Updated dependencies (including Json.NET 11.0.2 → 12.0.2 and Mono.Cecil 0.10.1 → 0.11). * Fixed issue where mod changes weren't tracked correctly for raising events in some cases. Events now reflect a frozen snapshot of the game state, and any mod changes are reflected in the next event tick. * Fixed issue where, when a mod's `IAssetEditor` uses `asset.ReplaceWith` on a texture asset while playing in non-English, any changes from that point won't affect subsequent cached asset loads. * Fixed `LoadStageChanged` event not raising correct flags in some cases when creating a new save. diff --git a/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj b/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj index 681eb5c2..e7c3e3dc 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj +++ b/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj @@ -9,7 +9,7 @@ - +
    diff --git a/src/SMAPI.Tests/SMAPI.Tests.csproj b/src/SMAPI.Tests/SMAPI.Tests.csproj index a627b3c3..84a05aee 100644 --- a/src/SMAPI.Tests/SMAPI.Tests.csproj +++ b/src/SMAPI.Tests/SMAPI.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/src/SMAPI.Toolkit/SMAPI.Toolkit.csproj b/src/SMAPI.Toolkit/SMAPI.Toolkit.csproj index 71b8fc55..a932c41b 100644 --- a/src/SMAPI.Toolkit/SMAPI.Toolkit.csproj +++ b/src/SMAPI.Toolkit/SMAPI.Toolkit.csproj @@ -13,7 +13,7 @@ - + diff --git a/src/SMAPI.Web/SMAPI.Web.csproj b/src/SMAPI.Web/SMAPI.Web.csproj index f7b2dc24..c6ee7594 100644 --- a/src/SMAPI.Web/SMAPI.Web.csproj +++ b/src/SMAPI.Web/SMAPI.Web.csproj @@ -12,9 +12,9 @@ - - - + + + @@ -22,7 +22,7 @@ - + diff --git a/src/SMAPI/SMAPI.csproj b/src/SMAPI/SMAPI.csproj index f41ede29..7c7bfc71 100644 --- a/src/SMAPI/SMAPI.csproj +++ b/src/SMAPI/SMAPI.csproj @@ -18,7 +18,7 @@ - + -- cgit From f5b46e8f3da3bb55ef1a116a8c24afa7fe2ec85b Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 7 Sep 2019 06:11:27 -0400 Subject: add asset propagation for Data\FarmAnimals (#618) --- docs/release-notes.md | 2 +- src/SMAPI/Metadata/CoreAssetPropagator.cs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 4009d234..aab2edb3 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -52,7 +52,7 @@ These changes have not been released yet. * Added support for content pack translations. * Added fields and methods: `IContentPack.HasFile`, `Context.IsGameLaunched`, and `SemanticVersion.TryParse`. * Added separate `LogNetworkTraffic` option to make verbose logging less overwhelmingly verbose. - * Added asset propagation for critter textures and `DayTimeMoneyBox` buttons. + * Added asset propagation for `Data\FarmAnimals`, critter textures, and `DayTimeMoneyBox` buttons. * `Constants.TargetPlatform` now returns `Android` when playing on an Android device. * The installer now recognises custom game paths stored in `stardewvalley.targets`, if any. * Trace logs for a broken mod now list all detected issues (instead of the first one). diff --git a/src/SMAPI/Metadata/CoreAssetPropagator.cs b/src/SMAPI/Metadata/CoreAssetPropagator.cs index 5911ba2c..66e6ed14 100644 --- a/src/SMAPI/Metadata/CoreAssetPropagator.cs +++ b/src/SMAPI/Metadata/CoreAssetPropagator.cs @@ -231,6 +231,9 @@ namespace StardewModdingAPI.Metadata CraftingRecipe.craftingRecipes = content.Load>(key); return true; + case "data\\farmanimals": // FarmAnimal constructor + return this.ReloadFarmAnimalData(); + case "data\\npcdispositions": // NPC constructor return this.ReloadNpcDispositions(content, key); @@ -599,6 +602,21 @@ namespace StardewModdingAPI.Metadata return critters.Length; } + /// Reload the data for matching farm animals. + /// Returns whether any farm animals were affected. + /// Derived from the constructor. + private bool ReloadFarmAnimalData() + { + bool changed = false; + foreach (FarmAnimal animal in this.GetFarmAnimals()) + { + animal.reloadData(); + changed = true; + } + + return changed; + } + /// Reload the sprites for a fence type. /// The asset key to reload. /// Returns whether any textures were reloaded. -- cgit From 449d793979ade4445b3c7b22f24131dbdae41780 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 7 Sep 2019 16:21:26 -0400 Subject: reorganise 3.0 release notes, add release highlights --- docs/release-notes.md | 62 ++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 49 insertions(+), 13 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index aab2edb3..fbd5df75 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -4,7 +4,39 @@ ## 3.0 (upcoming release) These changes have not been released yet. -* For players: +### Release highlights +For players: +* **Updated for Stardew Valley 1.4.** + SMAPI 3.0 adds compatibility with the latest game version, and improves mod APIs using changes in the game code. +* **Improved performance.** + SMAPI should have less impact on game performance and startup time for some players. +* **Added more error recovery.** + SMAPI now detects and prevents more crashes due to game or mod bugs. +* **Improved mod scanning.** + SMAPI now supports some non-standard mod structures automatically, improves compatibility with the Vortex mod manager, and improves various error/skip messages related to mod loading. +* **Fixed many bugs and edge cases.** + +For modders: +* **New event system.** + SMAPI 3.0 removes the deprecated static events in favor of the new `helper.Events` API. The event engine has been rewritten to make events more efficient, add events that weren't possible before, make existing events more useful, and make event usage and behavior more consistent. + +* **Improved mod build package.** + The [mod build package](https://www.nuget.org/packages/Pathoschild.Stardew.ModBuildConfig) has been improved to include the `assets` folder by default if present, support the new `.csproj` project format, enable mod `.pdb` files automatically (to provide line numbers in error messages), add optional Harmony support, and fix some bugs and edge cases. This also adds compatibility with SMAPI 3.0 and Stardew Valley 1.4, and drops support for older versions. + +* **Mods now loaded earlier.** + SMAPI now loads mods much earlier, before the game is initialised. That lets mods do things that were difficult before, like intercepting some core assets. + +* **Added initial Android support.** + SMAPI now automatically detects when it's running on Android, and updates the `Constants.TargetPlatform` for mods to use. + +* **Improved asset propagation.** + SMAPI now automatically propagates content changes for farm animal data, critter textures, and `DayTimeMoneyBox` buttons. + +* **Breaking changes:** + See _[migrate to SMAPI 3.0](https://stardewvalleywiki.com/Modding:Migrate_to_SMAPI_3.0)_ for more info. + +### For players +* Changes: * Updated for Stardew Valley 1.4. * Improved performance. * Rewrote launch script on Linux to improve compatibility (thanks to kurumushi and toastal!). @@ -13,13 +45,12 @@ These changes have not been released yet. * Now detects XNB mods more accurately, and consolidates multi-folder XNB mods in logged messages. * Added trace logs for skipped loose files so it's easier to troubleshoot player logs. * Save Backup now works in the background, to avoid affecting startup time for players with a large number of saves. + * The installer now recognises custom game paths stored in `stardewvalley.targets`. * Duplicate-mod errors now show the mod version in each folder. - * Improved update checks: - * Update checks are now faster in some cases. - * Fixed error if a Nexus mod is marked as adult content. - * Fixed error if the Chucklefish page for an update key doesn't exist. + * Update checks are now faster in some cases. * Updated mod compatibility list. * Updated SMAPI/game version map. +* Fixes: * Fixed mods needing to load custom `Map` assets before the game accesses them (SMAPI will now do so automatically). * Fixed Save Backup not pruning old backups if they're uncompressed. * Fixed issues when a farmhand reconnects before the game notices they're disconnected. @@ -31,38 +62,43 @@ These changes have not been released yet. * Fixed map reloads not updating door warps. * Fixed outdoor tilesheets being seasonalised when added to an indoor location. * Fixed various error messages and inconsistent spelling. + * Fixed update-check error if a Nexus mod is marked as adult content. + * Fixed update-check error if the Chucklefish page for an update key doesn't exist. -* For the mod compatibility list: +### For the web UI +* Mod compatibility list: * Now loads faster (since data is fetched in a background service). * Now continues working with cached data when the wiki is offline. * Clicking a mod link now automatically adds it to the visible mods when the list is filtered. * Added metadata links and dev notes (if any) to advanced info. - -* For the JSON validator: +* JSON validator: * Added JSON validator at [json.smapi.io](https://json.smapi.io), which lets you validate a JSON file against predefined mod formats. * Added support for the `manifest.json` format. * Added support for the Content Patcher format (thanks to TehPers!). * Added support for referencing a schema in a JSON Schema-compatible text editor. * For the log parser: + * Added instructions for Android. * The page now detects your OS and preselects the right instructions (thanks to danvolchek!). -* For modders: +### For modders +* Breaking changes: * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialized when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialized). + * Removed all deprecated APIs. + * Removed `Monitor.ExitGameImmediately`. +* Changes: * Added support for content pack translations. - * Added fields and methods: `IContentPack.HasFile`, `Context.IsGameLaunched`, and `SemanticVersion.TryParse`. + * Added `IContentPack.HasFile`, `Context.IsGameLaunched`, and `SemanticVersion.TryParse`. * Added separate `LogNetworkTraffic` option to make verbose logging less overwhelmingly verbose. * Added asset propagation for `Data\FarmAnimals`, critter textures, and `DayTimeMoneyBox` buttons. * `Constants.TargetPlatform` now returns `Android` when playing on an Android device. - * The installer now recognises custom game paths stored in `stardewvalley.targets`, if any. * Trace logs for a broken mod now list all detected issues (instead of the first one). * Trace logs when loading mods are now more clear. * Clarified update-check errors for mods with multiple update keys. * Fixed custom maps loaded from `.xnb` files not having their tilesheet paths automatically adjusted. * Fixed custom maps loaded from the mod folder with tilesheets in a subfolder not working crossplatform. All tilesheet paths are now normalized for the OS automatically. - * Removed all deprecated APIs. - * Removed the `Monitor.ExitGameImmediately` method. * Updated dependencies (including Json.NET 11.0.2 → 12.0.2 and Mono.Cecil 0.10.1 → 0.11). +* Fixes: * Fixed issue where mod changes weren't tracked correctly for raising events in some cases. Events now reflect a frozen snapshot of the game state, and any mod changes are reflected in the next event tick. * Fixed issue where, when a mod's `IAssetEditor` uses `asset.ReplaceWith` on a texture asset while playing in non-English, any changes from that point won't affect subsequent cached asset loads. * Fixed `LoadStageChanged` event not raising correct flags in some cases when creating a new save. -- cgit From 4b3a593941bf9880404171c4bef9a3b3f60b6dca Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 7 Sep 2019 16:38:17 -0400 Subject: track texture asset keys, fix NPC portrait propagation --- docs/release-notes.md | 10 ++++---- .../ContentManagers/BaseContentManager.cs | 6 +++++ src/SMAPI/Metadata/CoreAssetPropagator.cs | 28 +++++++--------------- 3 files changed, 20 insertions(+), 24 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index fbd5df75..0f5547ff 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -18,7 +18,7 @@ For players: For modders: * **New event system.** - SMAPI 3.0 removes the deprecated static events in favor of the new `helper.Events` API. The event engine has been rewritten to make events more efficient, add events that weren't possible before, make existing events more useful, and make event usage and behavior more consistent. + SMAPI 3.0 removes the deprecated static events in favor of the new `helper.Events` API. The event engine has been rewritten to make events more efficient, add events that weren't possible before, make existing events more useful, and make event usage and behavior more consistent. When a mod makes changes in an event handler, those changes are now also reflected in the next event raise. * **Improved mod build package.** The [mod build package](https://www.nuget.org/packages/Pathoschild.Stardew.ModBuildConfig) has been improved to include the `assets` folder by default if present, support the new `.csproj` project format, enable mod `.pdb` files automatically (to provide line numbers in error messages), add optional Harmony support, and fix some bugs and edge cases. This also adds compatibility with SMAPI 3.0 and Stardew Valley 1.4, and drops support for older versions. @@ -30,7 +30,7 @@ For modders: SMAPI now automatically detects when it's running on Android, and updates the `Constants.TargetPlatform` for mods to use. * **Improved asset propagation.** - SMAPI now automatically propagates content changes for farm animal data, critter textures, and `DayTimeMoneyBox` buttons. + SMAPI now automatically propagates content changes for farm animal data, critter textures, and `DayTimeMoneyBox` buttons. It also sets the `Texture2D.Name` field to the loaded asset key for all image assets, so mods can check which asset a texture was loaded for. * **Breaking changes:** See _[migrate to SMAPI 3.0](https://stardewvalleywiki.com/Modding:Migrate_to_SMAPI_3.0)_ for more info. @@ -91,16 +91,18 @@ For modders: * Added `IContentPack.HasFile`, `Context.IsGameLaunched`, and `SemanticVersion.TryParse`. * Added separate `LogNetworkTraffic` option to make verbose logging less overwhelmingly verbose. * Added asset propagation for `Data\FarmAnimals`, critter textures, and `DayTimeMoneyBox` buttons. + * Added `Texture2D.Name` values set to the asset key. * `Constants.TargetPlatform` now returns `Android` when playing on an Android device. * Trace logs for a broken mod now list all detected issues (instead of the first one). * Trace logs when loading mods are now more clear. * Clarified update-check errors for mods with multiple update keys. - * Fixed custom maps loaded from `.xnb` files not having their tilesheet paths automatically adjusted. - * Fixed custom maps loaded from the mod folder with tilesheets in a subfolder not working crossplatform. All tilesheet paths are now normalized for the OS automatically. * Updated dependencies (including Json.NET 11.0.2 → 12.0.2 and Mono.Cecil 0.10.1 → 0.11). * Fixes: + * Fixed custom maps loaded from `.xnb` files not having their tilesheet paths automatically adjusted. + * Fixed custom maps loaded from the mod folder with tilesheets in a subfolder not working crossplatform. All tilesheet paths are now normalized for the OS automatically. * Fixed issue where mod changes weren't tracked correctly for raising events in some cases. Events now reflect a frozen snapshot of the game state, and any mod changes are reflected in the next event tick. * Fixed issue where, when a mod's `IAssetEditor` uses `asset.ReplaceWith` on a texture asset while playing in non-English, any changes from that point won't affect subsequent cached asset loads. + * Fixed asset propagation for NPC portraits resetting any unique portraits (e.g. Maru's hospital portrait) to the default. * Fixed `LoadStageChanged` event not raising correct flags in some cases when creating a new save. ## 2.11.3 diff --git a/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs b/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs index de39dbae..5283340e 100644 --- a/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs @@ -6,6 +6,7 @@ using System.Globalization; using System.IO; using System.Linq; using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.Framework.Content; using StardewModdingAPI.Framework.Exceptions; using StardewModdingAPI.Framework.Reflection; @@ -264,6 +265,11 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The language code for which to inject the asset. protected virtual void Inject(string assetName, T value, LanguageCode language) { + // track asset key + if (value is Texture2D texture) + texture.Name = assetName; + + // cache asset assetName = this.AssertAndNormalizeAssetName(assetName); this.Cache[assetName] = value; } diff --git a/src/SMAPI/Metadata/CoreAssetPropagator.cs b/src/SMAPI/Metadata/CoreAssetPropagator.cs index 66e6ed14..c0d57f4b 100644 --- a/src/SMAPI/Metadata/CoreAssetPropagator.cs +++ b/src/SMAPI/Metadata/CoreAssetPropagator.cs @@ -507,6 +507,7 @@ namespace StardewModdingAPI.Metadata // find matches TAnimal[] animals = this.GetCharacters() .OfType() + .Where(p => key == this.GetNormalizedPath(p.Sprite?.Texture?.Name)) .ToArray(); if (!animals.Any()) return false; @@ -587,7 +588,7 @@ namespace StardewModdingAPI.Metadata let locCritters = this.Reflection.GetField>(location, "critters").GetValue() where locCritters != null from Critter critter in locCritters - where this.GetNormalizedPath(critter.sprite.textureName) == key + where this.GetNormalizedPath(critter.sprite?.Texture?.Name) == key select critter ) .ToArray(); @@ -673,7 +674,7 @@ namespace StardewModdingAPI.Metadata // get NPCs HashSet lookup = new HashSet(keys, StringComparer.InvariantCultureIgnoreCase); NPC[] characters = this.GetCharacters() - .Where(npc => npc.Sprite != null && lookup.Contains(this.GetNormalizedPath(npc.Sprite.textureName.Value))) + .Where(npc => npc.Sprite != null && lookup.Contains(this.GetNormalizedPath(npc.Sprite?.Texture?.Name))) .ToArray(); if (!characters.Any()) return 0; @@ -697,36 +698,23 @@ namespace StardewModdingAPI.Metadata { // get NPCs HashSet lookup = new HashSet(keys, StringComparer.InvariantCultureIgnoreCase); - var villagers = - ( - from npc in this.GetCharacters() - where npc.isVillager() - let textureKey = this.GetNormalizedPath($"Portraits\\{this.getTextureName(npc)}") - where lookup.Contains(textureKey) - select new { npc, textureKey } - ) + var villagers = this + .GetCharacters() + .Where(npc => npc.isVillager() && lookup.Contains(this.GetNormalizedPath(npc.Portrait?.Name))) .ToArray(); if (!villagers.Any()) return 0; // update portrait int reloaded = 0; - foreach (var entry in villagers) + foreach (NPC npc in villagers) { - entry.npc.resetPortrait(); - entry.npc.Portrait = content.Load(entry.textureKey); + npc.Portrait = content.Load(npc.Portrait.Name); reloaded++; } return reloaded; } - private string getTextureName(NPC npc) - { - string name = npc.Name; - string str = name == "Old Mariner" ? "Mariner" : (name == "Dwarf King" ? "DwarfKing" : (name == "Mister Qi" ? "MrQi" : (name == "???" ? "Monsters\\Shadow Guy" : name))); - return str; - } - /// Reload tree textures. /// The content manager through which to reload the asset. /// The asset key to reload. -- cgit From 8271c15d6a5ba9548fa605c5e0c543e12c9495f6 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Tue, 10 Sep 2019 19:49:24 -0400 Subject: update release notes for asset changes --- docs/release-notes.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 0f5547ff..45d65f7d 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -30,7 +30,7 @@ For modders: SMAPI now automatically detects when it's running on Android, and updates the `Constants.TargetPlatform` for mods to use. * **Improved asset propagation.** - SMAPI now automatically propagates content changes for farm animal data, critter textures, and `DayTimeMoneyBox` buttons. It also sets the `Texture2D.Name` field to the loaded asset key for all image assets, so mods can check which asset a texture was loaded for. + SMAPI now automatically propagates asset changes for farm animal data, NPC default location data, critter textures, and `DayTimeMoneyBox` buttons. Every loaded texture now also has a `Name` field so mods can check which asset a texture was loaded for. * **Breaking changes:** See _[migrate to SMAPI 3.0](https://stardewvalleywiki.com/Modding:Migrate_to_SMAPI_3.0)_ for more info. @@ -103,6 +103,7 @@ For modders: * Fixed issue where mod changes weren't tracked correctly for raising events in some cases. Events now reflect a frozen snapshot of the game state, and any mod changes are reflected in the next event tick. * Fixed issue where, when a mod's `IAssetEditor` uses `asset.ReplaceWith` on a texture asset while playing in non-English, any changes from that point won't affect subsequent cached asset loads. * Fixed asset propagation for NPC portraits resetting any unique portraits (e.g. Maru's hospital portrait) to the default. + * Fixed changes to `Data\NPCDispositions` not always propagated correctly to existing NPCs. * Fixed `LoadStageChanged` event not raising correct flags in some cases when creating a new save. ## 2.11.3 -- cgit From 3cf3df8ffb21afc7698427e51787324c5d237800 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 14 Sep 2019 23:18:03 -0400 Subject: fix ICursorPosition.AbsolutePixels not adjusted for zoom --- docs/release-notes.md | 1 + src/SMAPI/Framework/CursorPosition.cs | 8 ++++---- src/SMAPI/Framework/Input/SInputState.cs | 14 ++++++++------ 3 files changed, 13 insertions(+), 10 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 45d65f7d..af8b1d5b 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -86,6 +86,7 @@ For modders: * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialized when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialized). * Removed all deprecated APIs. * Removed `Monitor.ExitGameImmediately`. + * Fixed `ICursorPosition.AbsolutePixels` not adjusted for zoom. * Changes: * Added support for content pack translations. * Added `IContentPack.HasFile`, `Context.IsGameLaunched`, and `SemanticVersion.TryParse`. diff --git a/src/SMAPI/Framework/CursorPosition.cs b/src/SMAPI/Framework/CursorPosition.cs index 079917f2..2008ccce 100644 --- a/src/SMAPI/Framework/CursorPosition.cs +++ b/src/SMAPI/Framework/CursorPosition.cs @@ -8,10 +8,10 @@ namespace StardewModdingAPI.Framework /********* ** Accessors *********/ - /// The pixel position relative to the top-left corner of the in-game map. + /// The pixel position relative to the top-left corner of the in-game map, adjusted for pixel zoom. public Vector2 AbsolutePixels { get; } - /// The pixel position relative to the top-left corner of the visible screen. + /// The pixel position relative to the top-left corner of the visible screen, adjusted for pixel zoom. public Vector2 ScreenPixels { get; } /// The tile position under the cursor relative to the top-left corner of the map. @@ -25,8 +25,8 @@ namespace StardewModdingAPI.Framework ** Public methods *********/ /// Construct an instance. - /// The pixel position relative to the top-left corner of the in-game map. - /// The pixel position relative to the top-left corner of the visible screen. + /// The pixel position relative to the top-left corner of the in-game map, adjusted for pixel zoom. + /// The pixel position relative to the top-left corner of the visible screen, adjusted for pixel zoom. /// The tile position relative to the top-left corner of the map. /// The tile position that the game considers under the cursor for purposes of clicking actions. public CursorPosition(Vector2 absolutePixels, Vector2 screenPixels, Vector2 tile, Vector2 grabTile) diff --git a/src/SMAPI/Framework/Input/SInputState.cs b/src/SMAPI/Framework/Input/SInputState.cs index a15272d5..d69e5604 100644 --- a/src/SMAPI/Framework/Input/SInputState.cs +++ b/src/SMAPI/Framework/Input/SInputState.cs @@ -80,12 +80,14 @@ namespace StardewModdingAPI.Framework.Input { try { + float zoomMultiplier = (1f / Game1.options.zoomLevel); + // get new states GamePadState realController = GamePad.GetState(PlayerIndex.One); KeyboardState realKeyboard = Keyboard.GetState(); MouseState realMouse = Mouse.GetState(); var activeButtons = this.DeriveStatuses(this.ActiveButtons, realKeyboard, realMouse, realController); - Vector2 cursorAbsolutePos = new Vector2(realMouse.X + Game1.viewport.X, realMouse.Y + Game1.viewport.Y); + Vector2 cursorAbsolutePos = new Vector2((realMouse.X * zoomMultiplier) + Game1.viewport.X, (realMouse.Y * zoomMultiplier) + Game1.viewport.Y); Vector2? playerTilePos = Context.IsPlayerFree ? Game1.player.getTileLocation() : (Vector2?)null; // update real states @@ -96,7 +98,7 @@ namespace StardewModdingAPI.Framework.Input if (cursorAbsolutePos != this.CursorPositionImpl?.AbsolutePixels || playerTilePos != this.LastPlayerTile) { this.LastPlayerTile = playerTilePos; - this.CursorPositionImpl = this.GetCursorPosition(realMouse, cursorAbsolutePos); + this.CursorPositionImpl = this.GetCursorPosition(realMouse, cursorAbsolutePos, zoomMultiplier); } // update suppressed states @@ -170,11 +172,11 @@ namespace StardewModdingAPI.Framework.Input *********/ /// Get the current cursor position. /// The current mouse state. - /// The absolute pixel position relative to the map. - private CursorPosition GetCursorPosition(MouseState mouseState, Vector2 absolutePixels) + /// The absolute pixel position relative to the map, adjusted for pixel zoom. + /// The multiplier applied to pixel coordinates to adjust them for pixel zoom. + private CursorPosition GetCursorPosition(MouseState mouseState, Vector2 absolutePixels, float zoomMultiplier) { - Vector2 rawPixels = new Vector2(mouseState.X, mouseState.Y); - Vector2 screenPixels = rawPixels * new Vector2((float)1.0 / Game1.options.zoomLevel); // derived from Game1::getMouseX + Vector2 screenPixels = new Vector2(mouseState.X * zoomMultiplier, mouseState.Y * zoomMultiplier); Vector2 tile = new Vector2((int)((Game1.viewport.X + screenPixels.X) / Game1.tileSize), (int)((Game1.viewport.Y + screenPixels.Y) / Game1.tileSize)); Vector2 grabTile = (Game1.mouseCursorTransparency > 0 && Utility.tileWithinRadiusOfPlayer((int)tile.X, (int)tile.Y, 1, Game1.player)) // derived from Game1.pressActionButton ? tile -- cgit From 4e7a67bc6d616950fed03ba8c26f9dec2cc273ff Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 16 Sep 2019 16:28:12 -0400 Subject: log custom SMAPI settings to simplify troubleshooting --- docs/release-notes.md | 2 +- src/SMAPI/Framework/Models/SConfig.cs | 64 +++++++++++++++++++++++++++++++---- src/SMAPI/Framework/SCore.cs | 7 ++++ src/SMAPI/SMAPI.config.json | 1 + 4 files changed, 66 insertions(+), 8 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index af8b1d5b..ba64db0d 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -43,7 +43,6 @@ For modders: * Improved mod scanning: * Now ignores metadata files and folders (like `__MACOSX` and `__folder_managed_by_vortex`) and content files (like `.txt` or `.png`), which avoids missing-manifest errors in some common cases. * Now detects XNB mods more accurately, and consolidates multi-folder XNB mods in logged messages. - * Added trace logs for skipped loose files so it's easier to troubleshoot player logs. * Save Backup now works in the background, to avoid affecting startup time for players with a large number of saves. * The installer now recognises custom game paths stored in `stardewvalley.targets`. * Duplicate-mod errors now show the mod version in each folder. @@ -93,6 +92,7 @@ For modders: * Added separate `LogNetworkTraffic` option to make verbose logging less overwhelmingly verbose. * Added asset propagation for `Data\FarmAnimals`, critter textures, and `DayTimeMoneyBox` buttons. * Added `Texture2D.Name` values set to the asset key. + * Added trace logs for skipped loose files in the `Mods` folder and custom SMAPI settings so it's easier to troubleshoot player logs. * `Constants.TargetPlatform` now returns `Android` when playing on an Android device. * Trace logs for a broken mod now list all detected issues (instead of the first one). * Trace logs when loading mods are now more clear. diff --git a/src/SMAPI/Framework/Models/SConfig.cs b/src/SMAPI/Framework/Models/SConfig.cs index 2bc71adf..40ed9512 100644 --- a/src/SMAPI/Framework/Models/SConfig.cs +++ b/src/SMAPI/Framework/Models/SConfig.cs @@ -1,3 +1,6 @@ +using System; +using System.Collections.Generic; +using System.Linq; using StardewModdingAPI.Internal.ConsoleWriting; namespace StardewModdingAPI.Framework.Models @@ -5,6 +8,35 @@ namespace StardewModdingAPI.Framework.Models /// The SMAPI configuration settings. internal class SConfig { + /******** + ** Fields + ********/ + /// The default config values, for fields that should be logged if different. + private static readonly IDictionary DefaultValues = new Dictionary + { + [nameof(CheckForUpdates)] = true, + [nameof(ParanoidWarnings)] = +#if DEBUG + true, +#else + false, +#endif + [nameof(UseBetaChannel)] = Constants.ApiVersion.IsPrerelease(), + [nameof(GitHubProjectName)] = "Pathoschild/SMAPI", + [nameof(WebApiBaseUrl)] = "https://api.smapi.io", + [nameof(VerboseLogging)] = false, + [nameof(LogNetworkTraffic)] = false, + [nameof(DumpMetadata)] = false + }; + + /// The default values for , to log changes if different. + private static readonly HashSet DefaultSuppressUpdateChecks = new HashSet(StringComparer.InvariantCultureIgnoreCase) + { + "SMAPI.ConsoleCommands", + "SMAPI.SaveBackup" + }; + + /******** ** Accessors ********/ @@ -15,15 +47,10 @@ namespace StardewModdingAPI.Framework.Models public bool CheckForUpdates { get; set; } /// Whether to add a section to the 'mod issues' list for mods which which directly use potentially sensitive .NET APIs like file or shell access. - public bool ParanoidWarnings { get; set; } = -#if DEBUG - true; -#else - false; -#endif + public bool ParanoidWarnings { get; set; } = (bool)SConfig.DefaultValues[nameof(SConfig.ParanoidWarnings)]; /// Whether to show beta versions as valid updates. - public bool UseBetaChannel { get; set; } = Constants.ApiVersion.IsPrerelease(); + public bool UseBetaChannel { get; set; } = (bool)SConfig.DefaultValues[nameof(SConfig.UseBetaChannel)]; /// SMAPI's GitHub project name, used to perform update checks. public string GitHubProjectName { get; set; } @@ -45,5 +72,28 @@ namespace StardewModdingAPI.Framework.Models /// The mod IDs SMAPI should ignore when performing update checks or validating update keys. public string[] SuppressUpdateChecks { get; set; } + + + /******** + ** Public methods + ********/ + /// Get the settings which have been customised by the player. + public IDictionary GetCustomSettings() + { + IDictionary custom = new Dictionary(); + + foreach (var pair in SConfig.DefaultValues) + { + object value = typeof(SConfig).GetProperty(pair.Key)?.GetValue(this); + if (!pair.Value.Equals(value)) + custom[pair.Key] = value; + } + + HashSet curSuppressUpdateChecks = new HashSet(this.SuppressUpdateChecks ?? new string[0], StringComparer.InvariantCultureIgnoreCase); + if (SConfig.DefaultSuppressUpdateChecks.Count != curSuppressUpdateChecks.Count || SConfig.DefaultSuppressUpdateChecks.Any(p => !curSuppressUpdateChecks.Contains(p))) + custom[nameof(this.SuppressUpdateChecks)] = "[" + string.Join(", ", this.SuppressUpdateChecks ?? new string[0]) + "]"; + + return custom; + } } } diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index fde28852..08d30a29 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -164,6 +164,13 @@ namespace StardewModdingAPI.Framework this.Monitor.Log("(Using custom --mods-path argument.)", LogLevel.Trace); this.Monitor.Log($"Log started at {DateTime.UtcNow:s} UTC", LogLevel.Trace); + // log custom settings + { + IDictionary customSettings = this.Settings.GetCustomSettings(); + if (customSettings.Any()) + this.Monitor.Log($"Loaded with custom settings: {string.Join(", ", customSettings.OrderBy(p => p.Key).Select(p => $"{p.Key}: {p.Value}"))}", LogLevel.Trace); + } + // validate platform #if SMAPI_FOR_WINDOWS if (Constants.Platform != Platform.Windows) diff --git a/src/SMAPI/SMAPI.config.json b/src/SMAPI/SMAPI.config.json index 450a32cc..225e4b3f 100644 --- a/src/SMAPI/SMAPI.config.json +++ b/src/SMAPI/SMAPI.config.json @@ -3,6 +3,7 @@ This file contains advanced configuration for SMAPI. You generally shouldn't change this file. +The default values are mirrored in StardewModdingAPI.Framework.Models.SConfig to log custom changes. -- cgit From 1b5055dfaafc6dcf77b5262b8290e8ca2c8179ed Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 23 Sep 2019 17:09:35 -0400 Subject: make console colors configurable --- docs/release-notes.md | 1 + src/SMAPI.Installer/InteractiveInstaller.cs | 8 +- .../ConsoleWriting/ColorSchemeConfig.cs | 15 ++++ .../ConsoleWriting/ColorfulConsoleWriter.cs | 88 +++++++++++++--------- .../ConsoleWriting/ConsoleLogLevel.cs | 30 ++++++++ src/SMAPI.Internal/ConsoleWriting/LogLevel.cs | 30 -------- src/SMAPI.Internal/SMAPI.Internal.projitems | 3 +- src/SMAPI/Framework/Models/SConfig.cs | 4 +- src/SMAPI/Framework/Monitor.cs | 6 +- src/SMAPI/Framework/SCore.cs | 4 +- src/SMAPI/SMAPI.config.json | 51 ++++++++++--- 11 files changed, 151 insertions(+), 89 deletions(-) create mode 100644 src/SMAPI.Internal/ConsoleWriting/ColorSchemeConfig.cs create mode 100644 src/SMAPI.Internal/ConsoleWriting/ConsoleLogLevel.cs delete mode 100644 src/SMAPI.Internal/ConsoleWriting/LogLevel.cs (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index ba64db0d..285384b0 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -43,6 +43,7 @@ For modders: * Improved mod scanning: * Now ignores metadata files and folders (like `__MACOSX` and `__folder_managed_by_vortex`) and content files (like `.txt` or `.png`), which avoids missing-manifest errors in some common cases. * Now detects XNB mods more accurately, and consolidates multi-folder XNB mods in logged messages. + * Added support for configuring console colors via `smapi-internal/config.json` (intended for players with unusual consoles). * Save Backup now works in the background, to avoid affecting startup time for players with a large number of saves. * The installer now recognises custom game paths stored in `stardewvalley.targets`. * Duplicate-mod errors now show the mod version in each folder. diff --git a/src/SMAPI.Installer/InteractiveInstaller.cs b/src/SMAPI.Installer/InteractiveInstaller.cs index 4d313a3b..964300ac 100644 --- a/src/SMAPI.Installer/InteractiveInstaller.cs +++ b/src/SMAPI.Installer/InteractiveInstaller.cs @@ -100,7 +100,7 @@ namespace StardewModdingApi.Installer public InteractiveInstaller(string bundlePath) { this.BundlePath = bundlePath; - this.ConsoleWriter = new ColorfulConsoleWriter(EnvironmentUtility.DetectPlatform(), MonitorColorScheme.AutoDetect); + this.ConsoleWriter = new ColorfulConsoleWriter(EnvironmentUtility.DetectPlatform()); } /// Run the install or uninstall script. @@ -217,8 +217,8 @@ namespace StardewModdingApi.Installer ** show theme selector ****/ // get theme writers - var lightBackgroundWriter = new ColorfulConsoleWriter(EnvironmentUtility.DetectPlatform(), MonitorColorScheme.LightBackground); - var darkBackgroundWriter = new ColorfulConsoleWriter(EnvironmentUtility.DetectPlatform(), MonitorColorScheme.DarkBackground); + var lightBackgroundWriter = new ColorfulConsoleWriter(platform, ColorfulConsoleWriter.GetDefaultColorSchemeConfig(MonitorColorScheme.LightBackground)); + var darkBackgroundWriter = new ColorfulConsoleWriter(platform, ColorfulConsoleWriter.GetDefaultColorSchemeConfig(MonitorColorScheme.DarkBackground)); // print question this.PrintPlain("Which text looks more readable?"); @@ -470,7 +470,7 @@ namespace StardewModdingApi.Installer { string text = File .ReadAllText(paths.ApiConfigPath) - .Replace(@"""ColorScheme"": ""AutoDetect""", $@"""ColorScheme"": ""{scheme}"""); + .Replace(@"""UseScheme"": ""AutoDetect""", $@"""UseScheme"": ""{scheme}"""); File.WriteAllText(paths.ApiConfigPath, text); } diff --git a/src/SMAPI.Internal/ConsoleWriting/ColorSchemeConfig.cs b/src/SMAPI.Internal/ConsoleWriting/ColorSchemeConfig.cs new file mode 100644 index 00000000..001840bf --- /dev/null +++ b/src/SMAPI.Internal/ConsoleWriting/ColorSchemeConfig.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; + +namespace StardewModdingAPI.Internal.ConsoleWriting +{ + /// The console color scheme options. + internal class ColorSchemeConfig + { + /// The default color scheme ID to use, or to select one automatically. + public MonitorColorScheme UseScheme { get; set; } + + /// The available console color schemes. + public IDictionary> Schemes { get; set; } + } +} diff --git a/src/SMAPI.Internal/ConsoleWriting/ColorfulConsoleWriter.cs b/src/SMAPI.Internal/ConsoleWriting/ColorfulConsoleWriter.cs index db016bae..aefda9b6 100644 --- a/src/SMAPI.Internal/ConsoleWriting/ColorfulConsoleWriter.cs +++ b/src/SMAPI.Internal/ConsoleWriting/ColorfulConsoleWriter.cs @@ -22,11 +22,16 @@ namespace StardewModdingAPI.Internal.ConsoleWriting *********/ /// Construct an instance. /// The target platform. - /// The console color scheme to use. - public ColorfulConsoleWriter(Platform platform, MonitorColorScheme colorScheme) + public ColorfulConsoleWriter(Platform platform) + : this(platform, ColorfulConsoleWriter.GetDefaultColorSchemeConfig(MonitorColorScheme.AutoDetect)) { } + + /// Construct an instance. + /// The target platform. + /// The colors to use for text written to the SMAPI console. + public ColorfulConsoleWriter(Platform platform, ColorSchemeConfig colorConfig) { this.SupportsColor = this.TestColorSupport(); - this.Colors = this.GetConsoleColorScheme(platform, colorScheme); + this.Colors = this.GetConsoleColorScheme(platform, colorConfig); } /// Write a message line to the log. @@ -54,6 +59,40 @@ namespace StardewModdingAPI.Internal.ConsoleWriting Console.WriteLine(message); } + /// Get the default color scheme config for cases where it's not configurable (e.g. the installer). + /// The default color scheme ID to use, or to select one automatically. + /// The colors here should be kept in sync with the SMAPI config file. + public static ColorSchemeConfig GetDefaultColorSchemeConfig(MonitorColorScheme useScheme) + { + return new ColorSchemeConfig + { + UseScheme = useScheme, + Schemes = new Dictionary> + { + [MonitorColorScheme.DarkBackground] = new Dictionary + { + [ConsoleLogLevel.Trace] = ConsoleColor.DarkGray, + [ConsoleLogLevel.Debug] = ConsoleColor.DarkGray, + [ConsoleLogLevel.Info] = ConsoleColor.White, + [ConsoleLogLevel.Warn] = ConsoleColor.Yellow, + [ConsoleLogLevel.Error] = ConsoleColor.Red, + [ConsoleLogLevel.Alert] = ConsoleColor.Magenta, + [ConsoleLogLevel.Success] = ConsoleColor.DarkGreen + }, + [MonitorColorScheme.LightBackground] = new Dictionary + { + [ConsoleLogLevel.Trace] = ConsoleColor.DarkGray, + [ConsoleLogLevel.Debug] = ConsoleColor.DarkGray, + [ConsoleLogLevel.Info] = ConsoleColor.Black, + [ConsoleLogLevel.Warn] = ConsoleColor.DarkYellow, + [ConsoleLogLevel.Error] = ConsoleColor.Red, + [ConsoleLogLevel.Alert] = ConsoleColor.DarkMagenta, + [ConsoleLogLevel.Success] = ConsoleColor.DarkGreen + } + } + }; + } + /********* ** Private methods @@ -74,47 +113,22 @@ namespace StardewModdingAPI.Internal.ConsoleWriting /// Get the color scheme to use for the current console. /// The target platform. - /// The console color scheme to use. - private IDictionary GetConsoleColorScheme(Platform platform, MonitorColorScheme colorScheme) + /// The colors to use for text written to the SMAPI console. + private IDictionary GetConsoleColorScheme(Platform platform, ColorSchemeConfig colorConfig) { - // auto detect color scheme - if (colorScheme == MonitorColorScheme.AutoDetect) + // get color scheme ID + MonitorColorScheme schemeID = colorConfig.UseScheme; + if (schemeID == MonitorColorScheme.AutoDetect) { - colorScheme = platform == Platform.Mac + schemeID = platform == Platform.Mac ? MonitorColorScheme.LightBackground // MacOS doesn't provide console background color info, but it's usually white. : ColorfulConsoleWriter.IsDark(Console.BackgroundColor) ? MonitorColorScheme.DarkBackground : MonitorColorScheme.LightBackground; } // get colors for scheme - switch (colorScheme) - { - case MonitorColorScheme.DarkBackground: - return new Dictionary - { - [ConsoleLogLevel.Trace] = ConsoleColor.DarkGray, - [ConsoleLogLevel.Debug] = ConsoleColor.DarkGray, - [ConsoleLogLevel.Info] = ConsoleColor.White, - [ConsoleLogLevel.Warn] = ConsoleColor.Yellow, - [ConsoleLogLevel.Error] = ConsoleColor.Red, - [ConsoleLogLevel.Alert] = ConsoleColor.Magenta, - [ConsoleLogLevel.Success] = ConsoleColor.DarkGreen - }; - - case MonitorColorScheme.LightBackground: - return new Dictionary - { - [ConsoleLogLevel.Trace] = ConsoleColor.DarkGray, - [ConsoleLogLevel.Debug] = ConsoleColor.DarkGray, - [ConsoleLogLevel.Info] = ConsoleColor.Black, - [ConsoleLogLevel.Warn] = ConsoleColor.DarkYellow, - [ConsoleLogLevel.Error] = ConsoleColor.Red, - [ConsoleLogLevel.Alert] = ConsoleColor.DarkMagenta, - [ConsoleLogLevel.Success] = ConsoleColor.DarkGreen - }; - - default: - throw new NotSupportedException($"Unknown color scheme '{colorScheme}'."); - } + return colorConfig.Schemes.TryGetValue(schemeID, out IDictionary scheme) + ? scheme + : throw new NotSupportedException($"Unknown color scheme '{schemeID}'."); } /// Get whether a console color should be considered dark, which is subjectively defined as 'white looks better than black on this text'. diff --git a/src/SMAPI.Internal/ConsoleWriting/ConsoleLogLevel.cs b/src/SMAPI.Internal/ConsoleWriting/ConsoleLogLevel.cs new file mode 100644 index 00000000..54564111 --- /dev/null +++ b/src/SMAPI.Internal/ConsoleWriting/ConsoleLogLevel.cs @@ -0,0 +1,30 @@ +namespace StardewModdingAPI.Internal.ConsoleWriting +{ + /// The log severity levels. + internal enum ConsoleLogLevel + { + /// Tracing info intended for developers. + Trace, + + /// Troubleshooting info that may be relevant to the player. + Debug, + + /// Info relevant to the player. This should be used judiciously. + Info, + + /// An issue the player should be aware of. This should be used rarely. + Warn, + + /// A message indicating something went wrong. + Error, + + /// Important information to highlight for the player when player action is needed (e.g. new version available). This should be used rarely to avoid alert fatigue. + Alert, + + /// A critical issue that generally signals an immediate end to the application. + Critical, + + /// A success message that generally signals a successful end to a task. + Success + } +} diff --git a/src/SMAPI.Internal/ConsoleWriting/LogLevel.cs b/src/SMAPI.Internal/ConsoleWriting/LogLevel.cs deleted file mode 100644 index 54564111..00000000 --- a/src/SMAPI.Internal/ConsoleWriting/LogLevel.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace StardewModdingAPI.Internal.ConsoleWriting -{ - /// The log severity levels. - internal enum ConsoleLogLevel - { - /// Tracing info intended for developers. - Trace, - - /// Troubleshooting info that may be relevant to the player. - Debug, - - /// Info relevant to the player. This should be used judiciously. - Info, - - /// An issue the player should be aware of. This should be used rarely. - Warn, - - /// A message indicating something went wrong. - Error, - - /// Important information to highlight for the player when player action is needed (e.g. new version available). This should be used rarely to avoid alert fatigue. - Alert, - - /// A critical issue that generally signals an immediate end to the application. - Critical, - - /// A success message that generally signals a successful end to a task. - Success - } -} diff --git a/src/SMAPI.Internal/SMAPI.Internal.projitems b/src/SMAPI.Internal/SMAPI.Internal.projitems index 1408cc46..7fcebc94 100644 --- a/src/SMAPI.Internal/SMAPI.Internal.projitems +++ b/src/SMAPI.Internal/SMAPI.Internal.projitems @@ -10,7 +10,8 @@ - + + \ No newline at end of file diff --git a/src/SMAPI/Framework/Models/SConfig.cs b/src/SMAPI/Framework/Models/SConfig.cs index 40ed9512..b778af5d 100644 --- a/src/SMAPI/Framework/Models/SConfig.cs +++ b/src/SMAPI/Framework/Models/SConfig.cs @@ -67,8 +67,8 @@ namespace StardewModdingAPI.Framework.Models /// Whether to generate a file in the mods folder with detailed metadata about the detected mods. public bool DumpMetadata { get; set; } - /// The console color scheme to use. - public MonitorColorScheme ColorScheme { get; set; } + /// The colors to use for text written to the SMAPI console. + public ColorSchemeConfig ConsoleColors { get; set; } /// The mod IDs SMAPI should ignore when performing update checks or validating update keys. public string[] SuppressUpdateChecks { get; set; } diff --git a/src/SMAPI/Framework/Monitor.cs b/src/SMAPI/Framework/Monitor.cs index 1fa55a9e..06cf1b46 100644 --- a/src/SMAPI/Framework/Monitor.cs +++ b/src/SMAPI/Framework/Monitor.cs @@ -50,9 +50,9 @@ namespace StardewModdingAPI.Framework /// The name of the module which logs messages using this instance. /// Intercepts access to the console output. /// The log file to which to write messages. - /// The console color scheme to use. + /// The colors to use for text written to the SMAPI console. /// Whether verbose logging is enabled. This enables more detailed diagnostic messages than are normally needed. - public Monitor(string source, ConsoleInterceptionManager consoleInterceptor, LogFileManager logFile, MonitorColorScheme colorScheme, bool isVerbose) + public Monitor(string source, ConsoleInterceptionManager consoleInterceptor, LogFileManager logFile, ColorSchemeConfig colorConfig, bool isVerbose) { // validate if (string.IsNullOrWhiteSpace(source)) @@ -61,7 +61,7 @@ namespace StardewModdingAPI.Framework // initialize this.Source = source; this.LogFile = logFile ?? throw new ArgumentNullException(nameof(logFile), "The log file manager cannot be null."); - this.ConsoleWriter = new ColorfulConsoleWriter(Constants.Platform, colorScheme); + this.ConsoleWriter = new ColorfulConsoleWriter(Constants.Platform, colorConfig); this.ConsoleInterceptor = consoleInterceptor; this.IsVerbose = isVerbose; } diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index 08d30a29..e293cefd 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -143,7 +143,7 @@ namespace StardewModdingAPI.Framework // init basics this.Settings = JsonConvert.DeserializeObject(File.ReadAllText(Constants.ApiConfigPath)); this.LogFile = new LogFileManager(logPath); - this.Monitor = new Monitor("SMAPI", this.ConsoleManager, this.LogFile, this.Settings.ColorScheme, this.Settings.VerboseLogging) + this.Monitor = new Monitor("SMAPI", this.ConsoleManager, this.LogFile, this.Settings.ConsoleColors, this.Settings.VerboseLogging) { WriteToConsole = writeToConsole, ShowTraceInConsole = this.Settings.DeveloperMode, @@ -1351,7 +1351,7 @@ namespace StardewModdingAPI.Framework /// The name of the module which will log messages with this instance. private Monitor GetSecondaryMonitor(string name) { - return new Monitor(name, this.ConsoleManager, this.LogFile, this.Settings.ColorScheme, this.Settings.VerboseLogging) + return new Monitor(name, this.ConsoleManager, this.LogFile, this.Settings.ConsoleColors, this.Settings.VerboseLogging) { WriteToConsole = this.Monitor.WriteToConsole, ShowTraceInConsole = this.Settings.DeveloperMode, diff --git a/src/SMAPI/SMAPI.config.json b/src/SMAPI/SMAPI.config.json index 225e4b3f..bccac678 100644 --- a/src/SMAPI/SMAPI.config.json +++ b/src/SMAPI/SMAPI.config.json @@ -10,12 +10,9 @@ The default values are mirrored in StardewModdingAPI.Framework.Models.SConfig to */ { /** - * The console color theme to use. The possible values are: - * - AutoDetect: SMAPI will assume a light background on Mac, and detect the background color automatically on Linux or Windows. - * - LightBackground: use darker text colors that look better on a white or light background. - * - DarkBackground: use lighter text colors that look better on a black or dark background. + * Whether SMAPI should log more information about the game context. */ - "ColorScheme": "AutoDetect", + "VerboseLogging": false, /** * Whether SMAPI should check for newer versions of SMAPI and mods when you load the game. If new @@ -57,11 +54,6 @@ The default values are mirrored in StardewModdingAPI.Framework.Models.SConfig to */ "WebApiBaseUrl": "https://api.smapi.io", - /** - * Whether SMAPI should log more information about the game context. - */ - "VerboseLogging": false, - /** * Whether SMAPI should log network traffic (may be very verbose). Best combined with VerboseLogging, which includes network metadata. */ @@ -73,6 +65,45 @@ The default values are mirrored in StardewModdingAPI.Framework.Models.SConfig to */ "DumpMetadata": false, + /** + * The colors to use for text written to the SMAPI console. + * + * The possible values for 'UseScheme' are: + * - AutoDetect: SMAPI will assume a light background on Mac, and detect the background color + * automatically on Linux or Windows. + * - LightBackground: use darker text colors that look better on a white or light background. + * - DarkBackground: use lighter text colors that look better on a black or dark background. + * + * For available color codes, see https://docs.microsoft.com/en-us/dotnet/api/system.consolecolor. + * + * (These values are synched with ColorfulConsoleWriter.GetDefaultColorSchemeConfig in the + * SMAPI code.) + */ + "ConsoleColors": { + "UseScheme": "AutoDetect", + + "Schemes": { + "DarkBackground": { + "Trace": "DarkGray", + "Debug": "DarkGray", + "Info": "White", + "Warn": "Yellow", + "Error": "Red", + "Alert": "Magenta", + "Success": "DarkGreen" + }, + "LightBackground": { + "Trace": "DarkGray", + "Debug": "DarkGray", + "Info": "Black", + "Warn": "DarkYellow", + "Error": "Red", + "Alert": "DarkMagenta", + "Success": "DarkGreen" + } + } + }, + /** * The mod IDs SMAPI should ignore when performing update checks or validating update keys. */ -- cgit From 9461494a35b789c679a799fc9c5db2321d19d803 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Thu, 26 Sep 2019 19:48:01 -0400 Subject: auto-fix save data when a custom NPC mod is removed --- docs/README.md | 11 ++-- docs/release-notes.md | 9 +++- src/SMAPI/Framework/SCore.cs | 3 +- src/SMAPI/Patches/DialogueErrorPatch.cs | 9 ++-- src/SMAPI/Patches/EventErrorPatch.cs | 7 +-- src/SMAPI/Patches/LoadContextPatch.cs | 7 ++- src/SMAPI/Patches/LoadErrorPatch.cs | 94 +++++++++++++++++++++++++++++++++ src/SMAPI/Patches/ObjectErrorPatch.cs | 9 ++-- 8 files changed, 127 insertions(+), 22 deletions(-) create mode 100644 src/SMAPI/Patches/LoadErrorPatch.cs (limited to 'docs/release-notes.md') diff --git a/docs/README.md b/docs/README.md index 4b9c97a1..625e7eeb 100644 --- a/docs/README.md +++ b/docs/README.md @@ -20,10 +20,13 @@ doesn't change any of your game files. It serves eight main purposes: many mods, and rewrites the mod so it's compatible._ 5. **Intercept errors.** - _SMAPI intercepts errors that happen in the game, displays the error details in the console - window, and in most cases automatically recovers the game. This prevents mods from accidentally - crashing the game, and makes it possible to troubleshoot errors in the game itself that would - otherwise show a generic 'program has stopped working' type of message._ + _SMAPI intercepts errors, shows the error info in the SMAPI console, and in most cases + automatically recovers the game. That prevents mods from crashing the game, and makes it + possible to troubleshoot errors in the game itself that would otherwise show a generic 'program + has stopped working' type of message._ + + _That also includes automatically fixing save data when a load would crash, e.g. due to a custom + NPC mod the player removed._ 6. **Provide update checks.** _SMAPI automatically checks for new versions of your installed mods, and notifies you when any diff --git a/docs/release-notes.md b/docs/release-notes.md index 285384b0..2a1b333e 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -8,12 +8,16 @@ These changes have not been released yet. For players: * **Updated for Stardew Valley 1.4.** SMAPI 3.0 adds compatibility with the latest game version, and improves mod APIs using changes in the game code. + * **Improved performance.** SMAPI should have less impact on game performance and startup time for some players. + * **Added more error recovery.** - SMAPI now detects and prevents more crashes due to game or mod bugs. + SMAPI now detects and prevents more crashes due to game or mod bugs, or due to removing some mods which add custom content. + * **Improved mod scanning.** SMAPI now supports some non-standard mod structures automatically, improves compatibility with the Vortex mod manager, and improves various error/skip messages related to mod loading. + * **Fixed many bugs and edge cases.** For modders: @@ -39,11 +43,12 @@ For modders: * Changes: * Updated for Stardew Valley 1.4. * Improved performance. - * Rewrote launch script on Linux to improve compatibility (thanks to kurumushi and toastal!). * Improved mod scanning: * Now ignores metadata files and folders (like `__MACOSX` and `__folder_managed_by_vortex`) and content files (like `.txt` or `.png`), which avoids missing-manifest errors in some common cases. * Now detects XNB mods more accurately, and consolidates multi-folder XNB mods in logged messages. + * SMAPI now automatically fixes your save if you remove a custom NPC mod. (Invalid NPCs are now removed on load, with a warning in the console.) * Added support for configuring console colors via `smapi-internal/config.json` (intended for players with unusual consoles). + * Improved launch script compatibility on Linux (thanks to kurumushi and toastal!). * Save Backup now works in the background, to avoid affecting startup time for players with a large number of saves. * The installer now recognises custom game paths stored in `stardewvalley.targets`. * Duplicate-mod errors now show the mod version in each folder. diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index e293cefd..bc893abc 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -239,7 +239,8 @@ namespace StardewModdingAPI.Framework new EventErrorPatch(this.MonitorForGame), new DialogueErrorPatch(this.MonitorForGame, this.Reflection), new ObjectErrorPatch(), - new LoadContextPatch(this.Reflection, this.GameInstance.OnLoadStageChanged) + new LoadContextPatch(this.Reflection, this.GameInstance.OnLoadStageChanged), + new LoadErrorPatch(this.Monitor) ); // add exit handler diff --git a/src/SMAPI/Patches/DialogueErrorPatch.cs b/src/SMAPI/Patches/DialogueErrorPatch.cs index f1c25c05..24f97259 100644 --- a/src/SMAPI/Patches/DialogueErrorPatch.cs +++ b/src/SMAPI/Patches/DialogueErrorPatch.cs @@ -10,6 +10,9 @@ using StardewValley; namespace StardewModdingAPI.Patches { /// A Harmony patch for the constructor which intercepts invalid dialogue lines and logs an error instead of crashing. + /// Patch methods must be static for Harmony to work correctly. See the Harmony documentation before renaming patch arguments. + [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony and methods are named for clarity.")] + [SuppressMessage("ReSharper", "IdentifierTypo", Justification = "Argument names are defined by Harmony and methods are named for clarity.")] internal class DialogueErrorPatch : IHarmonyPatch { /********* @@ -29,7 +32,7 @@ namespace StardewModdingAPI.Patches ** Accessors *********/ /// A unique name for this patch. - public string Name => $"{nameof(DialogueErrorPatch)}"; + public string Name => nameof(DialogueErrorPatch); /********* @@ -68,8 +71,6 @@ namespace StardewModdingAPI.Patches /// The dialogue being parsed. /// The NPC for which the dialogue is being parsed. /// Returns whether to execute the original method. - /// This method must be static for Harmony to work correctly. See the Harmony documentation before renaming arguments. - [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony.")] private static bool Before_Dialogue_Constructor(Dialogue __instance, string masterDialogue, NPC speaker) { // get private members @@ -109,8 +110,6 @@ namespace StardewModdingAPI.Patches /// The return value of the original method. /// The method being wrapped. /// Returns whether to execute the original method. - /// This method must be static for Harmony to work correctly. See the Harmony documentation before renaming arguments. - [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony.")] private static bool Before_NPC_CurrentDialogue(NPC __instance, ref Stack __result, MethodInfo __originalMethod) { if (DialogueErrorPatch.IsInterceptingCurrentDialogue) diff --git a/src/SMAPI/Patches/EventErrorPatch.cs b/src/SMAPI/Patches/EventErrorPatch.cs index cd530616..1dc7e8c3 100644 --- a/src/SMAPI/Patches/EventErrorPatch.cs +++ b/src/SMAPI/Patches/EventErrorPatch.cs @@ -7,6 +7,9 @@ using StardewValley; namespace StardewModdingAPI.Patches { /// A Harmony patch for the constructor which intercepts invalid dialogue lines and logs an error instead of crashing. + /// Patch methods must be static for Harmony to work correctly. See the Harmony documentation before renaming patch arguments. + [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony and methods are named for clarity.")] + [SuppressMessage("ReSharper", "IdentifierTypo", Justification = "Argument names are defined by Harmony and methods are named for clarity.")] internal class EventErrorPatch : IHarmonyPatch { /********* @@ -23,7 +26,7 @@ namespace StardewModdingAPI.Patches ** Accessors *********/ /// A unique name for this patch. - public string Name => $"{nameof(EventErrorPatch)}"; + public string Name => nameof(EventErrorPatch); /********* @@ -56,8 +59,6 @@ namespace StardewModdingAPI.Patches /// The precondition to be parsed. /// The method being wrapped. /// Returns whether to execute the original method. - /// This method must be static for Harmony to work correctly. See the Harmony documentation before renaming arguments. - [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony.")] private static bool Before_GameLocation_CheckEventPrecondition(GameLocation __instance, ref int __result, string precondition, MethodInfo __originalMethod) { if (EventErrorPatch.IsIntercepted) diff --git a/src/SMAPI/Patches/LoadContextPatch.cs b/src/SMAPI/Patches/LoadContextPatch.cs index 93a059aa..0cc8c8eb 100644 --- a/src/SMAPI/Patches/LoadContextPatch.cs +++ b/src/SMAPI/Patches/LoadContextPatch.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using Harmony; using StardewModdingAPI.Enums; using StardewModdingAPI.Framework.Patching; @@ -10,7 +11,9 @@ using StardewValley.Minigames; namespace StardewModdingAPI.Patches { /// Harmony patches which notify SMAPI for save creation load stages. - /// This patch hooks into , checks if TitleMenu.transitioningCharacterCreationMenu is true (which means the player is creating a new save file), then raises after the location list is cleared twice (the second clear happens right before locations are created), and when the method ends. + /// Patch methods must be static for Harmony to work correctly. See the Harmony documentation before renaming patch arguments. + [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony and methods are named for clarity.")] + [SuppressMessage("ReSharper", "IdentifierTypo", Justification = "Argument names are defined by Harmony and methods are named for clarity.")] internal class LoadContextPatch : IHarmonyPatch { /********* @@ -27,7 +30,7 @@ namespace StardewModdingAPI.Patches ** Accessors *********/ /// A unique name for this patch. - public string Name => $"{nameof(LoadContextPatch)}"; + public string Name => nameof(LoadContextPatch); /********* diff --git a/src/SMAPI/Patches/LoadErrorPatch.cs b/src/SMAPI/Patches/LoadErrorPatch.cs new file mode 100644 index 00000000..87e8ee14 --- /dev/null +++ b/src/SMAPI/Patches/LoadErrorPatch.cs @@ -0,0 +1,94 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using Harmony; +using StardewModdingAPI.Framework.Patching; +using StardewValley; +using StardewValley.Locations; + +namespace StardewModdingAPI.Patches +{ + /// A Harmony patch for which prevents some errors due to broken save data. + /// Patch methods must be static for Harmony to work correctly. See the Harmony documentation before renaming patch arguments. + [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony and methods are named for clarity.")] + [SuppressMessage("ReSharper", "IdentifierTypo", Justification = "Argument names are defined by Harmony and methods are named for clarity.")] + internal class LoadErrorPatch : IHarmonyPatch + { + /********* + ** Fields + *********/ + /// Writes messages to the console and log file. + private static IMonitor Monitor; + + + /********* + ** Accessors + *********/ + /// A unique name for this patch. + public string Name => nameof(LoadErrorPatch); + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// Writes messages to the console and log file. + public LoadErrorPatch(IMonitor monitor) + { + LoadErrorPatch.Monitor = monitor; + } + + + /// Apply the Harmony patch. + /// The Harmony instance. + public void Apply(HarmonyInstance harmony) + { + harmony.Patch( + original: AccessTools.Method(typeof(SaveGame), nameof(SaveGame.loadDataToLocations)), + prefix: new HarmonyMethod(this.GetType(), nameof(LoadErrorPatch.Before_SaveGame_LoadDataToLocations)) + ); + } + + + /********* + ** Private methods + *********/ + /// The method to call instead of . + /// The game locations being loaded. + /// Returns whether to execute the original method. + private static bool Before_SaveGame_LoadDataToLocations(List gamelocations) + { + // get building interiors + var interiors = + ( + from location in gamelocations.OfType() + from building in location.buildings + where building.indoors.Value != null + select building.indoors.Value + ); + + // remove custom NPCs which no longer exist + IDictionary data = Game1.content.Load>("Data\\NPCDispositions"); + foreach (GameLocation location in gamelocations.Concat(interiors)) + { + foreach (NPC npc in location.characters.ToArray()) + { + if (npc.isVillager() && !data.ContainsKey(npc.Name)) + { + try + { + npc.reloadSprite(); // this won't crash for special villagers like Bouncer + } + catch + { + LoadErrorPatch.Monitor.Log($"Removed invalid villager '{npc.Name}' to avoid a crash when loading save '{Constants.SaveFolderName}'. (Did you remove a custom NPC mod?)", LogLevel.Warn); + location.characters.Remove(npc); + } + } + } + } + + return true; + } + } +} diff --git a/src/SMAPI/Patches/ObjectErrorPatch.cs b/src/SMAPI/Patches/ObjectErrorPatch.cs index 5b918d39..d716b29b 100644 --- a/src/SMAPI/Patches/ObjectErrorPatch.cs +++ b/src/SMAPI/Patches/ObjectErrorPatch.cs @@ -8,13 +8,16 @@ using SObject = StardewValley.Object; namespace StardewModdingAPI.Patches { /// A Harmony patch for which intercepts crashes due to the item no longer existing. + /// Patch methods must be static for Harmony to work correctly. See the Harmony documentation before renaming patch arguments. + [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony and methods are named for clarity.")] + [SuppressMessage("ReSharper", "IdentifierTypo", Justification = "Argument names are defined by Harmony and methods are named for clarity.")] internal class ObjectErrorPatch : IHarmonyPatch { /********* ** Accessors *********/ /// A unique name for this patch. - public string Name => $"{nameof(ObjectErrorPatch)}"; + public string Name => nameof(ObjectErrorPatch); /********* @@ -45,8 +48,6 @@ namespace StardewModdingAPI.Patches /// The instance being patched. /// The patched method's return value. /// Returns whether to execute the original method. - /// This method must be static for Harmony to work correctly. See the Harmony documentation before renaming arguments. - [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony.")] private static bool Before_Object_GetDescription(SObject __instance, ref string __result) { // invalid bigcraftables crash instead of showing '???' like invalid non-bigcraftables @@ -63,8 +64,6 @@ namespace StardewModdingAPI.Patches /// The instance being patched. /// The item for which to draw a tooltip. /// Returns whether to execute the original method. - /// This method must be static for Harmony to work correctly. See the Harmony documentation before renaming arguments. - [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony.")] private static bool Before_IClickableMenu_DrawTooltip(IClickableMenu __instance, Item hoveredItem) { // invalid edible item cause crash when drawing tooltips -- cgit From 673510b3941dd35a127e4f4a8a406f34b72b6a66 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Tue, 1 Oct 2019 20:04:58 -0400 Subject: remove unused translation field & method --- docs/release-notes.md | 2 +- src/SMAPI.Tests/Core/TranslationTests.cs | 49 +++++++------------ .../Framework/ModHelpers/TranslationHelper.cs | 13 ++--- src/SMAPI/Framework/SCore.cs | 6 +-- src/SMAPI/Translation.cs | 55 +++++++++------------- 5 files changed, 47 insertions(+), 78 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 2a1b333e..26645210 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -90,7 +90,7 @@ For modders: * Breaking changes: * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialized when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialized). * Removed all deprecated APIs. - * Removed `Monitor.ExitGameImmediately`. + * Removed unused APIs: `Monitor.ExitGameImmediately`, `Translation.ModName`, and `Translation.Assert`. * Fixed `ICursorPosition.AbsolutePixels` not adjusted for zoom. * Changes: * Added support for content pack translations. diff --git a/src/SMAPI.Tests/Core/TranslationTests.cs b/src/SMAPI.Tests/Core/TranslationTests.cs index c098aca5..457f9fad 100644 --- a/src/SMAPI.Tests/Core/TranslationTests.cs +++ b/src/SMAPI.Tests/Core/TranslationTests.cs @@ -32,7 +32,7 @@ namespace SMAPI.Tests.Core var data = new Dictionary>(); // act - ITranslationHelper helper = new TranslationHelper("ModID", "ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data); + ITranslationHelper helper = new TranslationHelper("ModID", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data); Translation translation = helper.Get("key"); Translation[] translationList = helper.GetTranslations()?.ToArray(); @@ -55,7 +55,7 @@ namespace SMAPI.Tests.Core // act var actual = new Dictionary(); - TranslationHelper helper = new TranslationHelper("ModID", "ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data); + TranslationHelper helper = new TranslationHelper("ModID", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data); foreach (string locale in expected.Keys) { this.AssertSetLocale(helper, locale, LocalizedContentManager.LanguageCode.en); @@ -79,7 +79,7 @@ namespace SMAPI.Tests.Core // act var actual = new Dictionary(); - TranslationHelper helper = new TranslationHelper("ModID", "ModName", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data); + TranslationHelper helper = new TranslationHelper("ModID", "en", LocalizedContentManager.LanguageCode.en).SetTranslations(data); foreach (string locale in expected.Keys) { this.AssertSetLocale(helper, locale, LocalizedContentManager.LanguageCode.en); @@ -109,14 +109,14 @@ namespace SMAPI.Tests.Core [TestCase(" boop ", ExpectedResult = true)] public bool Translation_HasValue(string text) { - return new Translation("ModName", "pt-BR", "key", text).HasValue(); + return new Translation("pt-BR", "key", text).HasValue(); } [Test(Description = "Assert that the translation's ToString method returns the expected text for various inputs.")] public void Translation_ToString([ValueSource(nameof(TranslationTests.Samples))] string text) { // act - Translation translation = new Translation("ModName", "pt-BR", "key", text); + Translation translation = new Translation("pt-BR", "key", text); // assert if (translation.HasValue()) @@ -129,7 +129,7 @@ namespace SMAPI.Tests.Core public void Translation_ImplicitStringConversion([ValueSource(nameof(TranslationTests.Samples))] string text) { // act - Translation translation = new Translation("ModName", "pt-BR", "key", text); + Translation translation = new Translation("pt-BR", "key", text); // assert if (translation.HasValue()) @@ -142,7 +142,7 @@ namespace SMAPI.Tests.Core public void Translation_UsePlaceholder([Values(true, false)] bool value, [ValueSource(nameof(TranslationTests.Samples))] string text) { // act - Translation translation = new Translation("ModName", "pt-BR", "key", text).UsePlaceholder(value); + Translation translation = new Translation("pt-BR", "key", text).UsePlaceholder(value); // assert if (translation.HasValue()) @@ -153,24 +153,11 @@ namespace SMAPI.Tests.Core Assert.AreEqual(this.GetPlaceholderText("key"), translation.ToString(), "The translation returned an unexpected value given a null or empty input with the placeholder enabled."); } - [Test(Description = "Assert that the translation's Assert method throws the expected exception.")] - public void Translation_Assert([ValueSource(nameof(TranslationTests.Samples))] string text) - { - // act - Translation translation = new Translation("ModName", "pt-BR", "key", text); - - // assert - if (translation.HasValue()) - Assert.That(() => translation.Assert(), Throws.Nothing, "The assert unexpected threw an exception for a valid input."); - else - Assert.That(() => translation.Assert(), Throws.Exception.TypeOf(), "The assert didn't throw an exception for invalid input."); - } - [Test(Description = "Assert that the translation returns the expected text after setting the default.")] public void Translation_Default([ValueSource(nameof(TranslationTests.Samples))] string text, [ValueSource(nameof(TranslationTests.Samples))] string @default) { // act - Translation translation = new Translation("ModName", "pt-BR", "key", text).Default(@default); + Translation translation = new Translation("pt-BR", "key", text).Default(@default); // assert if (!string.IsNullOrEmpty(text)) @@ -195,7 +182,7 @@ namespace SMAPI.Tests.Core string expected = $"{start} tokens are properly replaced (including {middle} {middle}) {end}"; // act - Translation translation = new Translation("ModName", "pt-BR", "key", input); + Translation translation = new Translation("pt-BR", "key", input); switch (structure) { case "anonymous object": @@ -236,7 +223,7 @@ namespace SMAPI.Tests.Core string value = Guid.NewGuid().ToString("N"); // act - Translation translation = new Translation("ModName", "pt-BR", "key", text).Tokens(new Dictionary { [key] = value }); + Translation translation = new Translation("pt-BR", "key", text).Tokens(new Dictionary { [key] = value }); // assert Assert.AreEqual(value, translation.ToString(), "The translation returned an unexpected value given a valid base text."); @@ -252,7 +239,7 @@ namespace SMAPI.Tests.Core string value = Guid.NewGuid().ToString("N"); // act - Translation translation = new Translation("ModName", "pt-BR", "key", text).Tokens(new Dictionary { [key] = value }); + Translation translation = new Translation("pt-BR", "key", text).Tokens(new Dictionary { [key] = value }); // assert Assert.AreEqual(value, translation.ToString(), "The translation returned an unexpected value given a valid base text."); @@ -303,19 +290,19 @@ namespace SMAPI.Tests.Core { ["default"] = new[] { - new Translation(string.Empty, "default", "key A", "default A"), - new Translation(string.Empty, "default", "key C", "default C") + new Translation("default", "key A", "default A"), + new Translation("default", "key C", "default C") }, ["en"] = new[] { - new Translation(string.Empty, "en", "key A", "en A"), - new Translation(string.Empty, "en", "key B", "en B"), - new Translation(string.Empty, "en", "key C", "default C") + new Translation("en", "key A", "en A"), + new Translation("en", "key B", "en B"), + new Translation("en", "key C", "default C") }, ["zzz"] = new[] { - new Translation(string.Empty, "zzz", "key A", "zzz A"), - new Translation(string.Empty, "zzz", "key C", "default C") + new Translation("zzz", "key A", "zzz A"), + new Translation("zzz", "key C", "default C") } }; expected["en-us"] = expected["en"].ToArray(); diff --git a/src/SMAPI/Framework/ModHelpers/TranslationHelper.cs b/src/SMAPI/Framework/ModHelpers/TranslationHelper.cs index 3252e047..65850384 100644 --- a/src/SMAPI/Framework/ModHelpers/TranslationHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/TranslationHelper.cs @@ -11,9 +11,6 @@ namespace StardewModdingAPI.Framework.ModHelpers /********* ** Fields *********/ - /// The name of the relevant mod for error messages. - private readonly string ModName; - /// The translations for each locale. private readonly IDictionary> All = new Dictionary>(StringComparer.InvariantCultureIgnoreCase); @@ -36,15 +33,11 @@ namespace StardewModdingAPI.Framework.ModHelpers *********/ /// Construct an instance. /// The unique ID of the relevant mod. - /// The name of the relevant mod for error messages. /// The initial locale. /// The game's current language code. - public TranslationHelper(string modID, string modName, string locale, LocalizedContentManager.LanguageCode languageCode) + public TranslationHelper(string modID, string locale, LocalizedContentManager.LanguageCode languageCode) : base(modID) { - // save data - this.ModName = modName; - // set locale this.SetLocale(locale, languageCode); } @@ -60,7 +53,7 @@ namespace StardewModdingAPI.Framework.ModHelpers public Translation Get(string key) { this.ForLocale.TryGetValue(key, out Translation translation); - return translation ?? new Translation(this.ModName, this.Locale, key, null); + return translation ?? new Translation(this.Locale, key, null); } /// Get a translation for the current locale. @@ -105,7 +98,7 @@ namespace StardewModdingAPI.Framework.ModHelpers foreach (var pair in translations) { if (!this.ForLocale.ContainsKey(pair.Key)) - this.ForLocale.Add(pair.Key, new Translation(this.ModName, this.Locale, pair.Key, pair.Value)); + this.ForLocale.Add(pair.Key, new Translation(this.Locale, pair.Key, pair.Value)); } } } diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index bc893abc..a4b38a50 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -960,7 +960,7 @@ namespace StardewModdingAPI.Framework IManifest manifest = mod.Manifest; IMonitor monitor = this.GetSecondaryMonitor(mod.DisplayName); IContentHelper contentHelper = new ContentHelper(this.ContentCore, mod.DirectoryPath, manifest.UniqueID, mod.DisplayName, monitor); - TranslationHelper translationHelper = new TranslationHelper(manifest.UniqueID, manifest.Name, contentCore.GetLocale(), contentCore.Language); + TranslationHelper translationHelper = new TranslationHelper(manifest.UniqueID, contentCore.GetLocale(), contentCore.Language); IContentPack contentPack = new ContentPack(mod.DirectoryPath, manifest, contentHelper, translationHelper, jsonHelper); mod.SetMod(contentPack, monitor, translationHelper); this.ModRegistry.Add(mod); @@ -1024,7 +1024,7 @@ namespace StardewModdingAPI.Framework // init mod helpers IMonitor monitor = this.GetSecondaryMonitor(mod.DisplayName); - TranslationHelper translationHelper = new TranslationHelper(manifest.UniqueID, manifest.Name, contentCore.GetLocale(), contentCore.Language); + TranslationHelper translationHelper = new TranslationHelper(manifest.UniqueID, contentCore.GetLocale(), contentCore.Language); IModHelper modHelper; { IModEvents events = new ModEvents(mod, this.EventManager); @@ -1040,7 +1040,7 @@ namespace StardewModdingAPI.Framework { IMonitor packMonitor = this.GetSecondaryMonitor(packManifest.Name); IContentHelper packContentHelper = new ContentHelper(contentCore, packDirPath, packManifest.UniqueID, packManifest.Name, packMonitor); - ITranslationHelper packTranslationHelper = new TranslationHelper(packManifest.UniqueID, packManifest.Name, contentCore.GetLocale(), contentCore.Language); + ITranslationHelper packTranslationHelper = new TranslationHelper(packManifest.UniqueID, contentCore.GetLocale(), contentCore.Language); return new ContentPack(packDirPath, packManifest, packContentHelper, packTranslationHelper, this.Toolkit.JsonHelper); } diff --git a/src/SMAPI/Translation.cs b/src/SMAPI/Translation.cs index e8698e2c..2196c8a5 100644 --- a/src/SMAPI/Translation.cs +++ b/src/SMAPI/Translation.cs @@ -15,9 +15,6 @@ namespace StardewModdingAPI /// The placeholder text when the translation is null or empty, where {0} is the translation key. internal const string PlaceholderText = "(no translation:{0})"; - /// The name of the relevant mod for error messages. - private readonly string ModName; - /// The locale for which the translation was fetched. private readonly string Locale; @@ -39,36 +36,11 @@ namespace StardewModdingAPI ** Public methods *********/ /// Construct an instance. - /// The name of the relevant mod for error messages. - /// The locale for which the translation was fetched. - /// The translation key. - /// The underlying translation text. - internal Translation(string modName, string locale, string key, string text) - : this(modName, locale, key, text, string.Format(Translation.PlaceholderText, key)) { } - - /// Construct an instance. - /// The name of the relevant mod for error messages. /// The locale for which the translation was fetched. /// The translation key. /// The underlying translation text. - /// The value to return if the translations is undefined. - internal Translation(string modName, string locale, string key, string text, string placeholder) - { - this.ModName = modName; - this.Locale = locale; - this.Key = key; - this.Text = text; - this.Placeholder = placeholder; - } - - /// Throw an exception if the translation text is null or empty. - /// There's no available translation matching the requested key and locale. - public Translation Assert() - { - if (!this.HasValue()) - throw new KeyNotFoundException($"The '{this.ModName}' mod doesn't have a translation with key '{this.Key}' for the '{this.Locale}' locale or its fallbacks."); - return this; - } + internal Translation(string locale, string key, string text) + : this(locale, key, text, string.Format(Translation.PlaceholderText, key)) { } /// Replace the text if it's null or empty. If you set a null or empty value, the translation will show the fallback "no translation" placeholder (see if you want to disable that). Returns a new instance if changed. /// The default value. @@ -76,14 +48,14 @@ namespace StardewModdingAPI { return this.HasValue() ? this - : new Translation(this.ModName, this.Locale, this.Key, @default); + : new Translation(this.Locale, this.Key, @default); } /// Whether to return a "no translation" placeholder if the translation is null or empty. Returns a new instance. /// Whether to return a placeholder. public Translation UsePlaceholder(bool use) { - return new Translation(this.ModName, this.Locale, this.Key, this.Text, use ? string.Format(Translation.PlaceholderText, this.Key) : null); + return new Translation(this.Locale, this.Key, this.Text, use ? string.Format(Translation.PlaceholderText, this.Key) : null); } /// Replace tokens in the text like {{value}} with the given values. Returns a new instance. @@ -127,7 +99,7 @@ namespace StardewModdingAPI ? value : match.Value; }); - return new Translation(this.ModName, this.Locale, this.Key, text); + return new Translation(this.Locale, this.Key, text); } /// Get whether the translation has a defined value. @@ -150,5 +122,22 @@ namespace StardewModdingAPI { return translation?.ToString(); } + + + /********* + ** Private methods + *********/ + /// Construct an instance. + /// The locale for which the translation was fetched. + /// The translation key. + /// The underlying translation text. + /// The value to return if the translations is undefined. + private Translation(string locale, string key, string text, string placeholder) + { + this.Locale = locale; + this.Key = key; + this.Text = text; + this.Placeholder = placeholder; + } } } -- cgit From 845deb43d60147603ec31fe4ae5fd7d747556d8c Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Tue, 1 Oct 2019 21:27:49 -0400 Subject: add support for core translation files --- build/common.targets | 5 + build/prepare-install-package.targets | 4 + docs/README.md | 20 ++++ docs/release-notes.md | 5 + .../Framework/ModHelpers/TranslationHelper.cs | 78 ++----------- src/SMAPI/Framework/SCore.cs | 127 ++++++++++++-------- src/SMAPI/Framework/SGame.cs | 7 +- src/SMAPI/Framework/Translator.cs | 128 +++++++++++++++++++++ src/SMAPI/SMAPI.csproj | 3 + src/SMAPI/i18n/default.json | 3 + 10 files changed, 265 insertions(+), 115 deletions(-) create mode 100644 src/SMAPI/Framework/Translator.cs create mode 100644 src/SMAPI/i18n/default.json (limited to 'docs/release-notes.md') diff --git a/build/common.targets b/build/common.targets index eb92cddd..10cdbe2c 100644 --- a/build/common.targets +++ b/build/common.targets @@ -21,6 +21,10 @@ + + + + @@ -29,6 +33,7 @@ + diff --git a/build/prepare-install-package.targets b/build/prepare-install-package.targets index 18a69a24..e5286bf5 100644 --- a/build/prepare-install-package.targets +++ b/build/prepare-install-package.targets @@ -17,6 +17,9 @@ windows unix + + + @@ -46,6 +49,7 @@ + diff --git a/docs/README.md b/docs/README.md index 90204387..fdb60693 100644 --- a/docs/README.md +++ b/docs/README.md @@ -54,3 +54,23 @@ developers and other modders! ### For SMAPI developers * [Technical docs](technical/smapi.md) + +## Translating SMAPI +SMAPI rarely shows text in-game, so it only has a few translations. Contributions are welcome! See +[Modding:Translations](https://stardewvalleywiki.com/Modding:Translations) on the wiki for help +contributing translations. + +locale | status +---------- | :---------------- +default | ✓ [fully translated](../src/SMAPI/i18n/default.json) +Chinese | ❑ not translated +French | ❑ not translated +German | ❑ not translated +Hungarian | ❑ not translated +Italian | ❑ not translated +Japanese | ❑ not translated +Korean | ❑ not translated +Portuguese | ❑ not translated +Russian | ❑ not translated +Spanish | ❑ not translated +Turkish | ❑ not translated diff --git a/docs/release-notes.md b/docs/release-notes.md index 26645210..5d8253b4 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -113,6 +113,11 @@ For modders: * Fixed changes to `Data\NPCDispositions` not always propagated correctly to existing NPCs. * Fixed `LoadStageChanged` event not raising correct flags in some cases when creating a new save. +### For SMAPI maintainers +* Added support for core translation files. +* Migrated to new `.csproj` format. +* Internal refactoring. + ## 2.11.3 Released 13 September 2019 for Stardew Valley 1.3.36. diff --git a/src/SMAPI/Framework/ModHelpers/TranslationHelper.cs b/src/SMAPI/Framework/ModHelpers/TranslationHelper.cs index 65850384..be7768e8 100644 --- a/src/SMAPI/Framework/ModHelpers/TranslationHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/TranslationHelper.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Linq; using StardewValley; namespace StardewModdingAPI.Framework.ModHelpers @@ -11,21 +9,18 @@ namespace StardewModdingAPI.Framework.ModHelpers /********* ** Fields *********/ - /// The translations for each locale. - private readonly IDictionary> All = new Dictionary>(StringComparer.InvariantCultureIgnoreCase); - - /// The translations for the current locale, with locale fallback taken into account. - private IDictionary ForLocale; + /// The underlying translation manager. + private readonly Translator Translator; /********* ** Accessors *********/ /// The current locale. - public string Locale { get; private set; } + public string Locale => this.Translator.Locale; /// The game's current language code. - public LocalizedContentManager.LanguageCode LocaleEnum { get; private set; } + public LocalizedContentManager.LanguageCode LocaleEnum => this.Translator.LocaleEnum; /********* @@ -38,22 +33,21 @@ namespace StardewModdingAPI.Framework.ModHelpers public TranslationHelper(string modID, string locale, LocalizedContentManager.LanguageCode languageCode) : base(modID) { - // set locale - this.SetLocale(locale, languageCode); + this.Translator = new Translator(); + this.Translator.SetLocale(locale, languageCode); } /// Get all translations for the current locale. public IEnumerable GetTranslations() { - return this.ForLocale.Values.ToArray(); + return this.Translator.GetTranslations(); } /// Get a translation for the current locale. /// The translation key. public Translation Get(string key) { - this.ForLocale.TryGetValue(key, out Translation translation); - return translation ?? new Translation(this.Locale, key, null); + return this.Translator.Get(key); } /// Get a translation for the current locale. @@ -61,21 +55,14 @@ namespace StardewModdingAPI.Framework.ModHelpers /// An object containing token key/value pairs. This can be an anonymous object (like new { value = 42, name = "Cranberries" }), a dictionary, or a class instance. public Translation Get(string key, object tokens) { - return this.Get(key).Tokens(tokens); + return this.Translator.Get(key, tokens); } /// Set the translations to use. /// The translations to use. internal TranslationHelper SetTranslations(IDictionary> translations) { - // reset translations - this.All.Clear(); - foreach (var pair in translations) - this.All[pair.Key] = new Dictionary(pair.Value, StringComparer.InvariantCultureIgnoreCase); - - // rebuild cache - this.SetLocale(this.Locale, this.LocaleEnum); - + this.Translator.SetTranslations(translations); return this; } @@ -84,50 +71,7 @@ namespace StardewModdingAPI.Framework.ModHelpers /// The game's current language code. internal void SetLocale(string locale, LocalizedContentManager.LanguageCode localeEnum) { - this.Locale = locale.ToLower().Trim(); - this.LocaleEnum = localeEnum; - - this.ForLocale = new Dictionary(StringComparer.InvariantCultureIgnoreCase); - foreach (string next in this.GetRelevantLocales(this.Locale)) - { - // skip if locale not defined - if (!this.All.TryGetValue(next, out IDictionary translations)) - continue; - - // add missing translations - foreach (var pair in translations) - { - if (!this.ForLocale.ContainsKey(pair.Key)) - this.ForLocale.Add(pair.Key, new Translation(this.Locale, pair.Key, pair.Value)); - } - } - } - - - /********* - ** Private methods - *********/ - /// Get the locales which can provide translations for the given locale, in precedence order. - /// The locale for which to find valid locales. - private IEnumerable GetRelevantLocales(string locale) - { - // given locale - yield return locale; - - // broader locales (like pt-BR => pt) - while (true) - { - int dashIndex = locale.LastIndexOf('-'); - if (dashIndex <= 0) - break; - - locale = locale.Substring(0, dashIndex); - yield return locale; - } - - // default - if (locale != "default") - yield return "default"; + this.Translator.SetLocale(locale, localeEnum); } } } diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index a4b38a50..bd131762 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -61,6 +61,9 @@ namespace StardewModdingAPI.Framework /// Simplifies access to private game code. private readonly Reflector Reflection = new Reflector(); + /// Encapsulates access to SMAPI core translations. + private readonly Translator Translator = new Translator(); + /// The SMAPI configuration settings. private readonly SConfig Settings; @@ -223,6 +226,7 @@ namespace StardewModdingAPI.Framework monitor: this.Monitor, monitorForGame: this.MonitorForGame, reflection: this.Reflection, + translator: this.Translator, eventManager: this.EventManager, jsonHelper: this.Toolkit.JsonHelper, modRegistry: this.ModRegistry, @@ -232,6 +236,7 @@ namespace StardewModdingAPI.Framework cancellationToken: this.CancellationToken, logNetworkTraffic: this.Settings.LogNetworkTraffic ); + this.Translator.SetLocale(this.GameInstance.ContentCore.GetLocale(), this.GameInstance.ContentCore.Language); StardewValley.Program.gamePtr = this.GameInstance; // apply game patches @@ -466,6 +471,9 @@ namespace StardewModdingAPI.Framework string locale = this.ContentCore.GetLocale(); LocalizedContentManager.LanguageCode languageCode = this.ContentCore.Language; + // update core translations + this.Translator.SetLocale(locale, languageCode); + // update mod translation helpers foreach (IModMetadata mod in this.ModRegistry.GetAll()) mod.Translations.SetLocale(locale, languageCode); @@ -1027,6 +1035,14 @@ namespace StardewModdingAPI.Framework TranslationHelper translationHelper = new TranslationHelper(manifest.UniqueID, contentCore.GetLocale(), contentCore.Language); IModHelper modHelper; { + IContentPack CreateFakeContentPack(string packDirPath, IManifest packManifest) + { + IMonitor packMonitor = this.GetSecondaryMonitor(packManifest.Name); + IContentHelper packContentHelper = new ContentHelper(contentCore, packDirPath, packManifest.UniqueID, packManifest.Name, packMonitor); + ITranslationHelper packTranslationHelper = new TranslationHelper(packManifest.UniqueID, contentCore.GetLocale(), contentCore.Language); + return new ContentPack(packDirPath, packManifest, packContentHelper, packTranslationHelper, this.Toolkit.JsonHelper); + } + IModEvents events = new ModEvents(mod, this.EventManager); ICommandHelper commandHelper = new CommandHelper(mod, this.GameInstance.CommandManager); IContentHelper contentHelper = new ContentHelper(contentCore, mod.DirectoryPath, manifest.UniqueID, mod.DisplayName, monitor); @@ -1036,14 +1052,6 @@ namespace StardewModdingAPI.Framework IModRegistry modRegistryHelper = new ModRegistryHelper(manifest.UniqueID, this.ModRegistry, proxyFactory, monitor); IMultiplayerHelper multiplayerHelper = new MultiplayerHelper(manifest.UniqueID, this.GameInstance.Multiplayer); - IContentPack CreateFakeContentPack(string packDirPath, IManifest packManifest) - { - IMonitor packMonitor = this.GetSecondaryMonitor(packManifest.Name); - IContentHelper packContentHelper = new ContentHelper(contentCore, packDirPath, packManifest.UniqueID, packManifest.Name, packMonitor); - ITranslationHelper packTranslationHelper = new TranslationHelper(packManifest.UniqueID, contentCore.GetLocale(), contentCore.Language); - return new ContentPack(packDirPath, packManifest, packContentHelper, packTranslationHelper, this.Toolkit.JsonHelper); - } - modHelper = new ModHelper(manifest.UniqueID, mod.DirectoryPath, this.GameInstance.Input, events, contentHelper, contentPackHelper, commandHelper, dataHelper, modRegistryHelper, reflectionHelper, multiplayerHelper, translationHelper); } @@ -1205,60 +1213,85 @@ namespace StardewModdingAPI.Framework /// The mods for which to reload translations. private void ReloadTranslations(IEnumerable mods) { - JsonHelper jsonHelper = this.Toolkit.JsonHelper; + // core SMAPI translations + { + var translations = this.ReadTranslationFiles(Path.Combine(Constants.InternalFilesPath, "i18n"), out IList errors); + if (errors.Any() || !translations.Any()) + { + this.Monitor.Log("SMAPI couldn't load some core translations. You may need to reinstall SMAPI.", LogLevel.Warn); + foreach (string error in errors) + this.Monitor.Log($" - {error}", LogLevel.Warn); + } + this.Translator.SetTranslations(translations); + } + + // mod translations foreach (IModMetadata metadata in mods) { - // read translation files - IDictionary> translations = new Dictionary>(); - DirectoryInfo translationsDir = new DirectoryInfo(Path.Combine(metadata.DirectoryPath, "i18n")); - if (translationsDir.Exists) + var translations = this.ReadTranslationFiles(Path.Combine(metadata.DirectoryPath, "i18n"), out IList errors); + if (errors.Any()) { - foreach (FileInfo file in translationsDir.EnumerateFiles("*.json")) + metadata.LogAsMod("Mod couldn't load some translation files:", LogLevel.Warn); + foreach (string error in errors) + metadata.LogAsMod($" - {error}", LogLevel.Warn); + } + metadata.Translations.SetTranslations(translations); + } + } + + /// Read translations from a directory containing JSON translation files. + /// The folder path to search. + /// The errors indicating why translation files couldn't be parsed, indexed by translation filename. + private IDictionary> ReadTranslationFiles(string folderPath, out IList errors) + { + JsonHelper jsonHelper = this.Toolkit.JsonHelper; + + // read translation files + var translations = new Dictionary>(); + errors = new List(); + DirectoryInfo translationsDir = new DirectoryInfo(folderPath); + if (translationsDir.Exists) + { + foreach (FileInfo file in translationsDir.EnumerateFiles("*.json")) + { + string locale = Path.GetFileNameWithoutExtension(file.Name.ToLower().Trim()); + try { - string locale = Path.GetFileNameWithoutExtension(file.Name.ToLower().Trim()); - try - { - if (jsonHelper.ReadJsonFileIfExists(file.FullName, out IDictionary data)) - translations[locale] = data; - else - metadata.LogAsMod($"Mod's i18n/{locale}.json file couldn't be parsed.", LogLevel.Warn); - } - catch (Exception ex) + if (!jsonHelper.ReadJsonFileIfExists(file.FullName, out IDictionary data)) { - metadata.LogAsMod($"Mod's i18n/{locale}.json file couldn't be parsed: {ex.GetLogSummary()}", LogLevel.Warn); + errors.Add($"{file.Name} file couldn't be read"); // should never happen, since we're iterating files that exist + continue; } - } - } - // validate translations - foreach (string locale in translations.Keys.ToArray()) - { - // skip empty files - if (translations[locale] == null || !translations[locale].Keys.Any()) + translations[locale] = data; + } + catch (Exception ex) { - metadata.LogAsMod($"Mod's i18n/{locale}.json is empty and will be ignored.", LogLevel.Warn); - translations.Remove(locale); + errors.Add($"{file.Name} file couldn't be parsed: {ex.GetLogSummary()}"); continue; } + } + } - // handle duplicates - HashSet keys = new HashSet(StringComparer.InvariantCultureIgnoreCase); - HashSet duplicateKeys = new HashSet(StringComparer.InvariantCultureIgnoreCase); - foreach (string key in translations[locale].Keys.ToArray()) + // validate translations + foreach (string locale in translations.Keys.ToArray()) + { + // handle duplicates + HashSet keys = new HashSet(StringComparer.InvariantCultureIgnoreCase); + HashSet duplicateKeys = new HashSet(StringComparer.InvariantCultureIgnoreCase); + foreach (string key in translations[locale].Keys.ToArray()) + { + if (!keys.Add(key)) { - if (!keys.Add(key)) - { - duplicateKeys.Add(key); - translations[locale].Remove(key); - } + duplicateKeys.Add(key); + translations[locale].Remove(key); } - if (duplicateKeys.Any()) - metadata.LogAsMod($"Mod's i18n/{locale}.json has duplicate translation keys: [{string.Join(", ", duplicateKeys)}]. Keys are case-insensitive.", LogLevel.Warn); } - - // update translation - metadata.Translations.SetTranslations(translations); + if (duplicateKeys.Any()) + errors.Add($"{locale}.json has duplicate translation keys: [{string.Join(", ", duplicateKeys)}]. Keys are case-insensitive."); } + + return translations; } /// The method called when the user submits a core SMAPI command in the console. diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index cb1b9be5..89705352 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -83,6 +83,9 @@ namespace StardewModdingAPI.Framework /// Simplifies access to private game code. private readonly Reflector Reflection; + /// Encapsulates access to SMAPI core translations. + private readonly Translator Translator; + /// Propagates notification that SMAPI should exit. private readonly CancellationTokenSource CancellationToken; @@ -135,6 +138,7 @@ namespace StardewModdingAPI.Framework /// Encapsulates monitoring and logging for SMAPI. /// Encapsulates monitoring and logging on the game's behalf. /// Simplifies access to private game code. + /// Encapsulates access to arbitrary translations. /// Manages SMAPI events for mods. /// Encapsulates SMAPI's JSON file parsing. /// Tracks the installed mods. @@ -143,7 +147,7 @@ namespace StardewModdingAPI.Framework /// A callback to invoke when the game exits. /// Propagates notification that SMAPI should exit. /// Whether to log network traffic. - internal SGame(Monitor monitor, IMonitor monitorForGame, Reflector reflection, EventManager eventManager, JsonHelper jsonHelper, ModRegistry modRegistry, DeprecationManager deprecationManager, Action onGameInitialized, Action onGameExiting, CancellationTokenSource cancellationToken, bool logNetworkTraffic) + internal SGame(Monitor monitor, IMonitor monitorForGame, Reflector reflection, Translator translator, EventManager eventManager, JsonHelper jsonHelper, ModRegistry modRegistry, DeprecationManager deprecationManager, Action onGameInitialized, Action onGameExiting, CancellationTokenSource cancellationToken, bool logNetworkTraffic) { this.OnLoadingFirstAsset = SGame.ConstructorHack.OnLoadingFirstAsset; SGame.ConstructorHack = null; @@ -161,6 +165,7 @@ namespace StardewModdingAPI.Framework this.Events = eventManager; this.ModRegistry = modRegistry; this.Reflection = reflection; + this.Translator = translator; this.DeprecationManager = deprecationManager; this.OnGameInitialized = onGameInitialized; this.OnGameExiting = onGameExiting; diff --git a/src/SMAPI/Framework/Translator.cs b/src/SMAPI/Framework/Translator.cs new file mode 100644 index 00000000..f2738633 --- /dev/null +++ b/src/SMAPI/Framework/Translator.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using StardewValley; + +namespace StardewModdingAPI.Framework +{ + /// Encapsulates access to arbitrary translations. Translations are fetched with locale fallback, so missing translations are filled in from broader locales (like pt-BR.json < pt.json < default.json). + internal class Translator + { + /********* + ** Fields + *********/ + /// The translations for each locale. + private readonly IDictionary> All = new Dictionary>(StringComparer.InvariantCultureIgnoreCase); + + /// The translations for the current locale, with locale fallback taken into account. + private IDictionary ForLocale; + + + /********* + ** Accessors + *********/ + /// The current locale. + public string Locale { get; private set; } + + /// The game's current language code. + public LocalizedContentManager.LanguageCode LocaleEnum { get; private set; } + + + /********* + ** Public methods + *********/ + /// Construct an instance. + public Translator() + { + this.SetLocale(string.Empty, LocalizedContentManager.LanguageCode.en); + } + + /// Set the current locale and precache translations. + /// The current locale. + /// The game's current language code. + public void SetLocale(string locale, LocalizedContentManager.LanguageCode localeEnum) + { + this.Locale = locale.ToLower().Trim(); + this.LocaleEnum = localeEnum; + + this.ForLocale = new Dictionary(StringComparer.InvariantCultureIgnoreCase); + foreach (string next in this.GetRelevantLocales(this.Locale)) + { + // skip if locale not defined + if (!this.All.TryGetValue(next, out IDictionary translations)) + continue; + + // add missing translations + foreach (var pair in translations) + { + if (!this.ForLocale.ContainsKey(pair.Key)) + this.ForLocale.Add(pair.Key, new Translation(this.Locale, pair.Key, pair.Value)); + } + } + } + + /// Get all translations for the current locale. + public IEnumerable GetTranslations() + { + return this.ForLocale.Values.ToArray(); + } + + /// Get a translation for the current locale. + /// The translation key. + public Translation Get(string key) + { + this.ForLocale.TryGetValue(key, out Translation translation); + return translation ?? new Translation(this.Locale, key, null); + } + + /// Get a translation for the current locale. + /// The translation key. + /// An object containing token key/value pairs. This can be an anonymous object (like new { value = 42, name = "Cranberries" }), a dictionary, or a class instance. + public Translation Get(string key, object tokens) + { + return this.Get(key).Tokens(tokens); + } + + /// Set the translations to use. + /// The translations to use. + internal Translator SetTranslations(IDictionary> translations) + { + // reset translations + this.All.Clear(); + foreach (var pair in translations) + this.All[pair.Key] = new Dictionary(pair.Value, StringComparer.InvariantCultureIgnoreCase); + + // rebuild cache + this.SetLocale(this.Locale, this.LocaleEnum); + + return this; + } + + + /********* + ** Private methods + *********/ + /// Get the locales which can provide translations for the given locale, in precedence order. + /// The locale for which to find valid locales. + private IEnumerable GetRelevantLocales(string locale) + { + // given locale + yield return locale; + + // broader locales (like pt-BR => pt) + while (true) + { + int dashIndex = locale.LastIndexOf('-'); + if (dashIndex <= 0) + break; + + locale = locale.Substring(0, dashIndex); + yield return locale; + } + + // default + if (locale != "default") + yield return "default"; + } + } +} diff --git a/src/SMAPI/SMAPI.csproj b/src/SMAPI/SMAPI.csproj index 7c7bfc71..62002a40 100644 --- a/src/SMAPI/SMAPI.csproj +++ b/src/SMAPI/SMAPI.csproj @@ -99,6 +99,9 @@ SMAPI.metadata.json PreserveNewest + + PreserveNewest + PreserveNewest diff --git a/src/SMAPI/i18n/default.json b/src/SMAPI/i18n/default.json new file mode 100644 index 00000000..0db3279e --- /dev/null +++ b/src/SMAPI/i18n/default.json @@ -0,0 +1,3 @@ +{ + +} -- cgit From 65997c1243a60ae15cc0b832ebcd41d96c3ea06a Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Tue, 1 Oct 2019 21:41:15 -0400 Subject: auto-fix save data when a custom location mod is removed --- docs/README.md | 6 +++--- docs/release-notes.md | 4 ++-- src/SMAPI/Framework/SCore.cs | 2 +- src/SMAPI/Framework/SGame.cs | 19 +++++++++++++++++++ src/SMAPI/Patches/LoadErrorPatch.cs | 28 +++++++++++++++++++++++++++- src/SMAPI/i18n/default.json | 2 +- 6 files changed, 53 insertions(+), 8 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/README.md b/docs/README.md index fdb60693..54e9f26f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -23,10 +23,10 @@ doesn't change any of your game files. It serves eight main purposes: _SMAPI intercepts errors, shows the error info in the SMAPI console, and in most cases automatically recovers the game. That prevents mods from crashing the game, and makes it possible to troubleshoot errors in the game itself that would otherwise show a generic 'program - has stopped working' type of message._ + has stopped working' type of message._ - _That also includes automatically fixing save data when a load would crash, e.g. due to a custom - NPC mod the player removed._ + _SMAPI also automatically fixes save data in some cases when a load would crash, e.g. due to a + custom location or NPC mod that was removed._ 6. **Provide update checks.** _SMAPI automatically checks for new versions of your installed mods, and notifies you when any diff --git a/docs/release-notes.md b/docs/release-notes.md index 5d8253b4..41a98dbe 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -13,7 +13,7 @@ For players: SMAPI should have less impact on game performance and startup time for some players. * **Added more error recovery.** - SMAPI now detects and prevents more crashes due to game or mod bugs, or due to removing some mods which add custom content. + SMAPI now detects and prevents more crashes due to game/mod bugs, or due to removing mods which add custom locations or NPCs. * **Improved mod scanning.** SMAPI now supports some non-standard mod structures automatically, improves compatibility with the Vortex mod manager, and improves various error/skip messages related to mod loading. @@ -46,7 +46,7 @@ For modders: * Improved mod scanning: * Now ignores metadata files and folders (like `__MACOSX` and `__folder_managed_by_vortex`) and content files (like `.txt` or `.png`), which avoids missing-manifest errors in some common cases. * Now detects XNB mods more accurately, and consolidates multi-folder XNB mods in logged messages. - * SMAPI now automatically fixes your save if you remove a custom NPC mod. (Invalid NPCs are now removed on load, with a warning in the console.) + * SMAPI now automatically removes invalid content when loading a save to prevent crashes. A warning is shown in-game when this happens. This applies for locations and NPCs. * Added support for configuring console colors via `smapi-internal/config.json` (intended for players with unusual consoles). * Improved launch script compatibility on Linux (thanks to kurumushi and toastal!). * Save Backup now works in the background, to avoid affecting startup time for players with a large number of saves. diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index bd131762..bfdf1c51 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -245,7 +245,7 @@ namespace StardewModdingAPI.Framework new DialogueErrorPatch(this.MonitorForGame, this.Reflection), new ObjectErrorPatch(), new LoadContextPatch(this.Reflection, this.GameInstance.OnLoadStageChanged), - new LoadErrorPatch(this.Monitor) + new LoadErrorPatch(this.Monitor, this.GameInstance.OnSaveContentRemoved) ); // add exit handler diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index 89705352..13858fc5 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -65,6 +65,9 @@ namespace StardewModdingAPI.Framework /// Skipping a few frames ensures the game finishes initializing the world before mods try to change it. private readonly Countdown AfterLoadTimer = new Countdown(5); + /// Whether custom content was removed from the save data to avoid a crash. + private bool IsSaveContentRemoved; + /// Whether the game is saving and SMAPI has already raised . private bool IsBetweenSaveEvents; @@ -216,6 +219,12 @@ namespace StardewModdingAPI.Framework this.Events.ModMessageReceived.RaiseForMods(new ModMessageReceivedEventArgs(message), mod => mod != null && modIDs.Contains(mod.Manifest.UniqueID)); } + /// A callback invoked when custom content is removed from the save data to avoid a crash. + internal void OnSaveContentRemoved() + { + this.IsSaveContentRemoved = true; + } + /// A callback invoked when the game's low-level load stage changes. /// The new load stage. internal void OnLoadStageChanged(LoadStage newStage) @@ -457,6 +466,16 @@ namespace StardewModdingAPI.Framework this.Watchers.Reset(); WatcherSnapshot state = this.WatcherSnapshot; + /********* + ** Display in-game warnings + *********/ + // save content removed + if (this.IsSaveContentRemoved && Context.IsWorldReady) + { + this.IsSaveContentRemoved = false; + Game1.addHUDMessage(new HUDMessage(this.Translator.Get("warn.invalid-content-removed"), HUDMessage.error_type)); + } + /********* ** Pre-update events *********/ diff --git a/src/SMAPI/Patches/LoadErrorPatch.cs b/src/SMAPI/Patches/LoadErrorPatch.cs index 87e8ee14..eedb4164 100644 --- a/src/SMAPI/Patches/LoadErrorPatch.cs +++ b/src/SMAPI/Patches/LoadErrorPatch.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -20,6 +21,9 @@ namespace StardewModdingAPI.Patches /// Writes messages to the console and log file. private static IMonitor Monitor; + /// A callback invoked when custom content is removed from the save data to avoid a crash. + private static Action OnContentRemoved; + /********* ** Accessors @@ -33,9 +37,11 @@ namespace StardewModdingAPI.Patches *********/ /// Construct an instance. /// Writes messages to the console and log file. - public LoadErrorPatch(IMonitor monitor) + /// A callback invoked when custom content is removed from the save data to avoid a crash. + public LoadErrorPatch(IMonitor monitor, Action onContentRemoved) { LoadErrorPatch.Monitor = monitor; + LoadErrorPatch.OnContentRemoved = onContentRemoved; } @@ -58,6 +64,22 @@ namespace StardewModdingAPI.Patches /// Returns whether to execute the original method. private static bool Before_SaveGame_LoadDataToLocations(List gamelocations) { + bool removedAny = false; + + // remove invalid locations + foreach (GameLocation location in gamelocations.ToArray()) + { + if (location is Cellar) + continue; // missing cellars will be added by the game code + + if (Game1.getLocationFromName(location.name) == null) + { + LoadErrorPatch.Monitor.Log($"Removed invalid location '{location.Name}' to avoid a crash when loading save '{Constants.SaveFolderName}'. (Did you remove a custom location mod?)", LogLevel.Warn); + gamelocations.Remove(location); + removedAny = true; + } + } + // get building interiors var interiors = ( @@ -83,11 +105,15 @@ namespace StardewModdingAPI.Patches { LoadErrorPatch.Monitor.Log($"Removed invalid villager '{npc.Name}' to avoid a crash when loading save '{Constants.SaveFolderName}'. (Did you remove a custom NPC mod?)", LogLevel.Warn); location.characters.Remove(npc); + removedAny = true; } } } } + if (removedAny) + LoadErrorPatch.OnContentRemoved(); + return true; } } diff --git a/src/SMAPI/i18n/default.json b/src/SMAPI/i18n/default.json index 0db3279e..5a3e4a6e 100644 --- a/src/SMAPI/i18n/default.json +++ b/src/SMAPI/i18n/default.json @@ -1,3 +1,3 @@ { - + "warn.invalid-content-removed": "Invalid content was removed to prevent a crash (see the SMAPI console for info)." } -- cgit From b2bcda83d9490987bad36b657f5b55698352830c Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 2 Oct 2019 01:08:42 -0400 Subject: tweak docs --- docs/README.md | 2 +- docs/release-notes.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/README.md b/docs/README.md index 54e9f26f..2f0e4864 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,7 +19,7 @@ doesn't change any of your game files. It serves eight main purposes: _SMAPI detects when a mod accesses part of the game that changed in a game update which affects many mods, and rewrites the mod so it's compatible._ -5. **Intercept errors.** +5. **Intercept errors and automatically fix saves.** _SMAPI intercepts errors, shows the error info in the SMAPI console, and in most cases automatically recovers the game. That prevents mods from crashing the game, and makes it possible to troubleshoot errors in the game itself that would otherwise show a generic 'program diff --git a/docs/release-notes.md b/docs/release-notes.md index 41a98dbe..30a759be 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -7,12 +7,12 @@ These changes have not been released yet. ### Release highlights For players: * **Updated for Stardew Valley 1.4.** - SMAPI 3.0 adds compatibility with the latest game version, and improves mod APIs using changes in the game code. + SMAPI 3.0 adds compatibility with the latest game version, and improves mod APIs for changes in the game code. * **Improved performance.** SMAPI should have less impact on game performance and startup time for some players. -* **Added more error recovery.** +* **Automatic save fixing and more error recovery.** SMAPI now detects and prevents more crashes due to game/mod bugs, or due to removing mods which add custom locations or NPCs. * **Improved mod scanning.** @@ -37,7 +37,7 @@ For modders: SMAPI now automatically propagates asset changes for farm animal data, NPC default location data, critter textures, and `DayTimeMoneyBox` buttons. Every loaded texture now also has a `Name` field so mods can check which asset a texture was loaded for. * **Breaking changes:** - See _[migrate to SMAPI 3.0](https://stardewvalleywiki.com/Modding:Migrate_to_SMAPI_3.0)_ for more info. + See _[migrate to SMAPI 3.0](https://stardewvalleywiki.com/Modding:Migrate_to_SMAPI_3.0)_ and _[migrate to Stardew Valley 1.4](https://stardewvalleywiki.com/Modding:Migrate_to_Stardew_Valley_1.4)_ for more info. ### For players * Changes: -- cgit From 175ebf907134e1e32992f62637a5d7e43bfc6a20 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Thu, 3 Oct 2019 12:08:22 -0400 Subject: fix non-generic GetAPI not checking that all mods are loaded (#662) --- docs/release-notes.md | 1 + .../Framework/ModHelpers/ModRegistryHelper.cs | 24 ++++++++++++---------- 2 files changed, 14 insertions(+), 11 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 30a759be..9cfb70a6 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -112,6 +112,7 @@ For modders: * Fixed asset propagation for NPC portraits resetting any unique portraits (e.g. Maru's hospital portrait) to the default. * Fixed changes to `Data\NPCDispositions` not always propagated correctly to existing NPCs. * Fixed `LoadStageChanged` event not raising correct flags in some cases when creating a new save. + * Fixed `GetApi` without an interface not checking if all mods are loaded. ### For SMAPI maintainers * Added support for core translation files. diff --git a/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs b/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs index 24bed3bb..f42cb085 100644 --- a/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using System.Linq; using StardewModdingAPI.Framework.Reflection; namespace StardewModdingAPI.Framework.ModHelpers @@ -63,6 +62,14 @@ namespace StardewModdingAPI.Framework.ModHelpers /// Get the API provided by a mod, or null if it has none. This signature requires using the API to access the API's properties and methods. public object GetApi(string uniqueID) { + // validate ready + if (!this.Registry.AreAllModsInitialized) + { + this.Monitor.Log("Tried to access a mod-provided API before all mods were initialized.", LogLevel.Error); + return null; + } + + // get raw API IModMetadata mod = this.Registry.Get(uniqueID); if (mod?.Api != null && this.AccessedModApis.Add(mod.Manifest.UniqueID)) this.Monitor.Log($"Accessed mod-provided API for {mod.DisplayName}.", LogLevel.Trace); @@ -74,12 +81,12 @@ namespace StardewModdingAPI.Framework.ModHelpers /// The mod's unique ID. public TInterface GetApi(string uniqueID) where TInterface : class { - // validate - if (!this.Registry.AreAllModsInitialized) - { - this.Monitor.Log("Tried to access a mod-provided API before all mods were initialized.", LogLevel.Error); + // get raw API + object api = this.GetApi(uniqueID); + if (api == null) return null; - } + + // validate mapping if (!typeof(TInterface).IsInterface) { this.Monitor.Log($"Tried to map a mod-provided API to class '{typeof(TInterface).FullName}'; must be a public interface.", LogLevel.Error); @@ -91,11 +98,6 @@ namespace StardewModdingAPI.Framework.ModHelpers return null; } - // get raw API - object api = this.GetApi(uniqueID); - if (api == null) - return null; - // get API of type if (api is TInterface castApi) return castApi; -- cgit From be79a042060757b7cb48ccbcc29f395757049a8c Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 28 Oct 2019 15:59:12 -0400 Subject: make item spawn commands more robust --- docs/release-notes.md | 2 + .../Framework/ItemRepository.cs | 343 ++++++++++++--------- 2 files changed, 201 insertions(+), 144 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 9cfb70a6..b31950ed 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -57,6 +57,8 @@ For modders: * Updated SMAPI/game version map. * Fixes: * Fixed mods needing to load custom `Map` assets before the game accesses them (SMAPI will now do so automatically). + * Fixed Console Commands not including upgraded tools in item commands. + * Fixed Console Commands' item commands failing if a mod adds invalid item data. * Fixed Save Backup not pruning old backups if they're uncompressed. * Fixed issues when a farmhand reconnects before the game notices they're disconnected. * Fixed 'received message' logs shown in non-developer mode. diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs index 90cdb872..1dfb3129 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs @@ -1,4 +1,7 @@ +using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; using Microsoft.Xna.Framework; using StardewModdingAPI.Mods.ConsoleCommands.Framework.ItemData; using StardewValley; @@ -22,176 +25,228 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework ** Public methods *********/ /// Get all spawnable items. + [SuppressMessage("ReSharper", "AccessToModifiedClosure", Justification = "TryCreate invokes the lambda immediately.")] public IEnumerable GetAll() { - // get tools - yield return new SearchableItem(ItemType.Tool, ToolFactory.axe, ToolFactory.getToolFromDescription(ToolFactory.axe, 0)); - yield return new SearchableItem(ItemType.Tool, ToolFactory.hoe, ToolFactory.getToolFromDescription(ToolFactory.hoe, 0)); - yield return new SearchableItem(ItemType.Tool, ToolFactory.pickAxe, ToolFactory.getToolFromDescription(ToolFactory.pickAxe, 0)); - yield return new SearchableItem(ItemType.Tool, ToolFactory.wateringCan, ToolFactory.getToolFromDescription(ToolFactory.wateringCan, 0)); - yield return new SearchableItem(ItemType.Tool, ToolFactory.fishingRod, ToolFactory.getToolFromDescription(ToolFactory.fishingRod, 0)); - yield return new SearchableItem(ItemType.Tool, this.CustomIDOffset, new MilkPail()); // these don't have any sort of ID, so we'll just assign some arbitrary ones - yield return new SearchableItem(ItemType.Tool, this.CustomIDOffset + 1, new Shears()); - yield return new SearchableItem(ItemType.Tool, this.CustomIDOffset + 2, new Pan()); - yield return new SearchableItem(ItemType.Tool, this.CustomIDOffset + 3, new Wand()); - - // clothing - foreach (int id in Game1.clothingInformation.Keys) - yield return new SearchableItem(ItemType.Clothing, id, new Clothing(id)); - - // wallpapers - for (int id = 0; id < 112; id++) - yield return new SearchableItem(ItemType.Wallpaper, id, new Wallpaper(id) { Category = SObject.furnitureCategory }); - - // flooring - for (int id = 0; id < 40; id++) - yield return new SearchableItem(ItemType.Flooring, id, new Wallpaper(id, isFloor: true) { Category = SObject.furnitureCategory }); - - // equipment - foreach (int id in Game1.content.Load>("Data\\Boots").Keys) - yield return new SearchableItem(ItemType.Boots, id, new Boots(id)); - foreach (int id in Game1.content.Load>("Data\\hats").Keys) - yield return new SearchableItem(ItemType.Hat, id, new Hat(id)); - foreach (int id in Game1.objectInformation.Keys) + IEnumerable GetAllRaw() { - if (id >= Ring.ringLowerIndexRange && id <= Ring.ringUpperIndexRange) - yield return new SearchableItem(ItemType.Ring, id, new Ring(id)); - } - - // weapons - foreach (int id in Game1.content.Load>("Data\\weapons").Keys) - { - Item weapon = (id >= 32 && id <= 34) - ? (Item)new Slingshot(id) - : new MeleeWeapon(id); - yield return new SearchableItem(ItemType.Weapon, id, weapon); - } - - // furniture - foreach (int id in Game1.content.Load>("Data\\Furniture").Keys) - { - if (id == 1466 || id == 1468) - yield return new SearchableItem(ItemType.Furniture, id, new TV(id, Vector2.Zero)); - else - yield return new SearchableItem(ItemType.Furniture, id, new Furniture(id, Vector2.Zero)); - } - - // craftables - foreach (int id in Game1.bigCraftablesInformation.Keys) - yield return new SearchableItem(ItemType.BigCraftable, id, new SObject(Vector2.Zero, id)); + // get tools + for (int quality = Tool.stone; quality <= Tool.iridium; quality++) + { + yield return this.TryCreate(ItemType.Tool, ToolFactory.axe, () => ToolFactory.getToolFromDescription(ToolFactory.axe, quality)); + yield return this.TryCreate(ItemType.Tool, ToolFactory.hoe, () => ToolFactory.getToolFromDescription(ToolFactory.hoe, quality)); + yield return this.TryCreate(ItemType.Tool, ToolFactory.pickAxe, () => ToolFactory.getToolFromDescription(ToolFactory.pickAxe, quality)); + yield return this.TryCreate(ItemType.Tool, ToolFactory.wateringCan, () => ToolFactory.getToolFromDescription(ToolFactory.wateringCan, quality)); + if (quality != Tool.iridium) + yield return this.TryCreate(ItemType.Tool, ToolFactory.fishingRod, () => ToolFactory.getToolFromDescription(ToolFactory.fishingRod, quality)); + } + yield return this.TryCreate(ItemType.Tool, this.CustomIDOffset, () => new MilkPail()); // these don't have any sort of ID, so we'll just assign some arbitrary ones + yield return this.TryCreate(ItemType.Tool, this.CustomIDOffset + 1, () => new Shears()); + yield return this.TryCreate(ItemType.Tool, this.CustomIDOffset + 2, () => new Pan()); + yield return this.TryCreate(ItemType.Tool, this.CustomIDOffset + 3, () => new Wand()); + + // wallpapers + for (int id = 0; id < 112; id++) + yield return this.TryCreate(ItemType.Wallpaper, id, () => new Wallpaper(id) { Category = SObject.furnitureCategory }); + + // flooring + for (int id = 0; id < 40; id++) + yield return this.TryCreate(ItemType.Flooring, id, () => new Wallpaper(id, isFloor: true) { Category = SObject.furnitureCategory }); + + // equipment + foreach (int id in Game1.content.Load>("Data\\Boots").Keys) + yield return this.TryCreate(ItemType.Boots, id, () => new Boots(id)); + foreach (int id in Game1.content.Load>("Data\\hats").Keys) + yield return this.TryCreate(ItemType.Hat, id, () => new Hat(id)); + foreach (int id in Game1.objectInformation.Keys) + { + if (id >= Ring.ringLowerIndexRange && id <= Ring.ringUpperIndexRange) + yield return this.TryCreate(ItemType.Ring, id, () => new Ring(id)); + } - // secret notes - foreach (int id in Game1.content.Load>("Data\\SecretNotes").Keys) - { - SObject note = new SObject(79, 1); - note.name = $"{note.name} #{id}"; - yield return new SearchableItem(ItemType.Object, this.CustomIDOffset + id, note); - } + // weapons + foreach (int id in Game1.content.Load>("Data\\weapons").Keys) + { + yield return this.TryCreate(ItemType.Weapon, id, () => (id >= 32 && id <= 34) + ? (Item)new Slingshot(id) + : new MeleeWeapon(id) + ); + } - // objects - foreach (int id in Game1.objectInformation.Keys) - { - if (id == 79) - continue; // secret note handled above - if (id >= Ring.ringLowerIndexRange && id <= Ring.ringUpperIndexRange) - continue; // handled separated + // furniture + foreach (int id in Game1.content.Load>("Data\\Furniture").Keys) + { + if (id == 1466 || id == 1468) + yield return this.TryCreate(ItemType.Furniture, id, () => new TV(id, Vector2.Zero)); + else + yield return this.TryCreate(ItemType.Furniture, id, () => new Furniture(id, Vector2.Zero)); + } - SObject item = new SObject(id, 1); - yield return new SearchableItem(ItemType.Object, id, item); + // craftables + foreach (int id in Game1.bigCraftablesInformation.Keys) + yield return this.TryCreate(ItemType.BigCraftable, id, () => new SObject(Vector2.Zero, id)); - // fruit products - if (item.Category == SObject.FruitsCategory) + // secret notes + foreach (int id in Game1.content.Load>("Data\\SecretNotes").Keys) { - // wine - SObject wine = new SObject(348, 1) + yield return this.TryCreate(ItemType.Object, this.CustomIDOffset + id, () => { - Name = $"{item.Name} Wine", - Price = item.Price * 3 - }; - wine.preserve.Value = SObject.PreserveType.Wine; - wine.preservedParentSheetIndex.Value = item.ParentSheetIndex; - yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 2 + id, wine); - - // jelly - SObject jelly = new SObject(344, 1) - { - Name = $"{item.Name} Jelly", - Price = 50 + item.Price * 2 - }; - jelly.preserve.Value = SObject.PreserveType.Jelly; - jelly.preservedParentSheetIndex.Value = item.ParentSheetIndex; - yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 3 + id, jelly); + SObject note = new SObject(79, 1); + note.name = $"{note.name} #{id}"; + return note; + }); } - // vegetable products - else if (item.Category == SObject.VegetableCategory) + // objects + foreach (int id in Game1.objectInformation.Keys) { - // juice - SObject juice = new SObject(350, 1) + if (id == 79) + continue; // secret note handled above + if (id >= Ring.ringLowerIndexRange && id <= Ring.ringUpperIndexRange) + continue; // handled separated + + // spawn main item + SObject item; { - Name = $"{item.Name} Juice", - Price = (int)(item.Price * 2.25d) - }; - juice.preserve.Value = SObject.PreserveType.Juice; - juice.preservedParentSheetIndex.Value = item.ParentSheetIndex; - yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 4 + id, juice); - - // pickled - SObject pickled = new SObject(342, 1) + SearchableItem main = this.TryCreate(ItemType.Object, id, () => new SObject(id, 1)); + yield return main; + item = main?.Item as SObject; + } + if (item == null) + continue; + + // fruit products + if (item.Category == SObject.FruitsCategory) { - Name = $"Pickled {item.Name}", - Price = 50 + item.Price * 2 - }; - pickled.preserve.Value = SObject.PreserveType.Pickle; - pickled.preservedParentSheetIndex.Value = item.ParentSheetIndex; - yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 5 + id, pickled); - } + // wine + yield return this.TryCreate(ItemType.Object, this.CustomIDOffset * 2 + id, () => + { + SObject wine = new SObject(348, 1) + { + Name = $"{item.Name} Wine", + Price = item.Price * 3 + }; + wine.preserve.Value = SObject.PreserveType.Wine; + wine.preservedParentSheetIndex.Value = item.ParentSheetIndex; + return wine; + }); + + // jelly + yield return this.TryCreate(ItemType.Object, this.CustomIDOffset * 3 + id, () => + { + SObject jelly = new SObject(344, 1) + { + Name = $"{item.Name} Jelly", + Price = 50 + item.Price * 2 + }; + jelly.preserve.Value = SObject.PreserveType.Jelly; + jelly.preservedParentSheetIndex.Value = item.ParentSheetIndex; + return jelly; + }); + } - // flower honey - else if (item.Category == SObject.flowersCategory) - { - // get honey type - SObject.HoneyType? type = null; - switch (item.ParentSheetIndex) + // vegetable products + else if (item.Category == SObject.VegetableCategory) { - case 376: - type = SObject.HoneyType.Poppy; - break; - case 591: - type = SObject.HoneyType.Tulip; - break; - case 593: - type = SObject.HoneyType.SummerSpangle; - break; - case 595: - type = SObject.HoneyType.FairyRose; - break; - case 597: - type = SObject.HoneyType.BlueJazz; - break; - case 421: // sunflower standing in for all other flowers - type = SObject.HoneyType.Wild; - break; + // juice + yield return this.TryCreate(ItemType.Object, this.CustomIDOffset * 4 + id, () => + { + SObject juice = new SObject(350, 1) + { + Name = $"{item.Name} Juice", + Price = (int)(item.Price * 2.25d) + }; + juice.preserve.Value = SObject.PreserveType.Juice; + juice.preservedParentSheetIndex.Value = item.ParentSheetIndex; + return juice; + }); + + // pickled + yield return this.TryCreate(ItemType.Object, this.CustomIDOffset * 5 + id, () => + { + SObject pickled = new SObject(342, 1) + { + Name = $"Pickled {item.Name}", + Price = 50 + item.Price * 2 + }; + pickled.preserve.Value = SObject.PreserveType.Pickle; + pickled.preservedParentSheetIndex.Value = item.ParentSheetIndex; + return pickled; + }); } - // yield honey - if (type != null) + // flower honey + else if (item.Category == SObject.flowersCategory) { - SObject honey = new SObject(Vector2.Zero, 340, item.Name + " Honey", false, true, false, false) + // get honey type + SObject.HoneyType? type = null; + switch (item.ParentSheetIndex) { - Name = "Wild Honey" - }; - honey.honeyType.Value = type; + case 376: + type = SObject.HoneyType.Poppy; + break; + case 591: + type = SObject.HoneyType.Tulip; + break; + case 593: + type = SObject.HoneyType.SummerSpangle; + break; + case 595: + type = SObject.HoneyType.FairyRose; + break; + case 597: + type = SObject.HoneyType.BlueJazz; + break; + case 421: // sunflower standing in for all other flowers + type = SObject.HoneyType.Wild; + break; + } - if (type != SObject.HoneyType.Wild) + // yield honey + if (type != null) { - honey.Name = $"{item.Name} Honey"; - honey.Price += item.Price * 2; + yield return this.TryCreate(ItemType.Object, this.CustomIDOffset * 5 + id, () => + { + SObject honey = new SObject(Vector2.Zero, 340, item.Name + " Honey", false, true, false, false) + { + Name = "Wild Honey" + }; + honey.honeyType.Value = type; + + if (type != SObject.HoneyType.Wild) + { + honey.Name = $"{item.Name} Honey"; + honey.Price += item.Price * 2; + } + + return honey; + }); } - yield return new SearchableItem(ItemType.Object, this.CustomIDOffset * 5 + id, honey); } } } + + return GetAllRaw().Where(p => p != null); + } + + + /********* + ** Private methods + *********/ + /// Create a searchable item if valid. + /// The item type. + /// The unique ID (if different from the item's parent sheet index). + /// Create an item instance. + private SearchableItem TryCreate(ItemType type, int id, Func createItem) + { + try + { + return new SearchableItem(type, id, createItem()); + } + catch + { + return null; // if some item data is invalid, just don't include it + } } } } -- cgit From df7e814286641c27a64cf354c15d69ddcfae062d Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 3 Nov 2019 18:24:34 -0500 Subject: add support for using environment variables instead of command-line arguments (#665) --- docs/release-notes.md | 1 + docs/technical/smapi.md | 15 +++++++++++++-- src/SMAPI/Program.cs | 28 +++++++++++++++++----------- 3 files changed, 31 insertions(+), 13 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index b31950ed..47e12f83 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -48,6 +48,7 @@ For modders: * Now detects XNB mods more accurately, and consolidates multi-folder XNB mods in logged messages. * SMAPI now automatically removes invalid content when loading a save to prevent crashes. A warning is shown in-game when this happens. This applies for locations and NPCs. * Added support for configuring console colors via `smapi-internal/config.json` (intended for players with unusual consoles). + * Added support for specifying SMAPI command-line arguments as environment variables for Linux/Mac compatibility. * Improved launch script compatibility on Linux (thanks to kurumushi and toastal!). * Save Backup now works in the background, to avoid affecting startup time for players with a large number of saves. * The installer now recognises custom game paths stored in `stardewvalley.targets`. diff --git a/docs/technical/smapi.md b/docs/technical/smapi.md index f6994ba3..96f7dff5 100644 --- a/docs/technical/smapi.md +++ b/docs/technical/smapi.md @@ -40,14 +40,25 @@ argument | purpose `--uninstall` | Preselects the uninstall action, skipping the prompt asking what the user wants to do. `--game-path "path"` | Specifies the full path to the folder containing the Stardew Valley executable, skipping automatic detection and any prompt to choose a path. If the path is not valid, the installer displays an error. -SMAPI itself recognises two arguments, but these are intended for internal use or testing and may -change without warning. +SMAPI itself recognises two arguments **on Windows only**, but these are intended for internal use +or testing and may change without warning. On Linux/Mac, see _environment variables_ below. argument | purpose -------- | ------- `--no-terminal` | SMAPI won't write anything to the console window. (Messages will still be written to the log file.) `--mods-path` | The path to search for mods, if not the standard `Mods` folder. This can be a path relative to the game folder (like `--mods-path "Mods (test)"`) or an absolute path. +### Environment variables +The above SMAPI arguments don't work on Linux/Mac due to the way the game launcher works. You can +set temporary environment variables instead. For example: +> SMAPI_MODS_PATH="Mods (multiplayer)" /path/to/StardewValley + +environment variable | purpose +-------------------- | ------- +`SMAPI_NO_TERMINAL` | Equivalent to `--no-terminal` above. +`SMAPI_MODS_PATH` | Equivalent to `--mods-path` above. + + ### Compile flags SMAPI uses a small number of conditional compilation constants, which you can set by editing the `` element in `SMAPI.csproj`. Supported constants: diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index 2d143439..05d7ff66 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -116,21 +116,27 @@ namespace StardewModdingAPI /// This method is separate from because that can't contain any references to assemblies loaded by (e.g. via ), or Mono will incorrectly show an assembly resolution error before assembly resolution is set up. private static void Start(string[] args) { - // get flags from arguments - bool writeToConsole = !args.Contains("--no-terminal"); + // get flags + bool writeToConsole = !args.Contains("--no-terminal") && Environment.GetEnvironmentVariable("SMAPI_NO_TERMINAL") == null; - // get mods path from arguments - string modsPath = null; + // get mods path + string modsPath; { + string rawModsPath = null; + + // get from command line args int pathIndex = Array.LastIndexOf(args, "--mods-path") + 1; if (pathIndex >= 1 && args.Length >= pathIndex) - { - modsPath = args[pathIndex]; - if (!string.IsNullOrWhiteSpace(modsPath) && !Path.IsPathRooted(modsPath)) - modsPath = Path.Combine(Constants.ExecutionPath, modsPath); - } - if (string.IsNullOrWhiteSpace(modsPath)) - modsPath = Constants.DefaultModsPath; + rawModsPath = args[pathIndex]; + + // get from environment variables + if (string.IsNullOrWhiteSpace(rawModsPath)) + rawModsPath = Environment.GetEnvironmentVariable("SMAPI_MODS_PATH"); + + // normalise + modsPath = !string.IsNullOrWhiteSpace(rawModsPath) + ? Path.Combine(Constants.ExecutionPath, rawModsPath) + : Constants.DefaultModsPath; } // load SMAPI -- cgit From 01c612bc4aca5a1d8921432c94956f4d170d4d4b Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 4 Nov 2019 13:59:34 -0500 Subject: add friendly error for BadImageFormatException on launch --- docs/release-notes.md | 1 + src/SMAPI/Program.cs | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 47e12f83..7cd7b52b 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -50,6 +50,7 @@ For modders: * Added support for configuring console colors via `smapi-internal/config.json` (intended for players with unusual consoles). * Added support for specifying SMAPI command-line arguments as environment variables for Linux/Mac compatibility. * Improved launch script compatibility on Linux (thanks to kurumushi and toastal!). + * Made error messages more user-friendly in some cases. * Save Backup now works in the background, to avoid affecting startup time for players with a large number of saves. * The installer now recognises custom game paths stored in `stardewvalley.targets`. * Duplicate-mod errors now show the mod version in each folder. diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index d6e0888b..6bacf564 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -40,6 +40,11 @@ namespace StardewModdingAPI Program.AssertGameVersion(); Program.Start(args); } + catch (BadImageFormatException ex) when (ex.FileName == "StardewValley") + { + string executableName = Program.GetExecutableAssemblyName(); + Console.WriteLine($"SMAPI failed to initialize because your game's {executableName}.exe seems to be invalid.\nThis may be a pirated version which modified the executable in an incompatible way; if so, you can try a different download or buy a legitimate version.\n\nTechnical details:\n{ex}"); + } catch (Exception ex) { Console.WriteLine($"SMAPI failed to initialize: {ex}"); @@ -77,8 +82,7 @@ namespace StardewModdingAPI /// This must be checked *before* any references to , and this method should not reference itself to avoid errors in Mono. private static void AssertGamePresent() { - Platform platform = EnvironmentUtility.DetectPlatform(); - string gameAssemblyName = platform == Platform.Windows ? "Stardew Valley" : "StardewValley"; + string gameAssemblyName = Program.GetExecutableAssemblyName(); if (Type.GetType($"StardewValley.Game1, {gameAssemblyName}", throwOnError: false) == null) Program.PrintErrorAndExit("Oops! SMAPI can't find the game. Make sure you're running StardewModdingAPI.exe in your game folder. See the readme.txt file for details."); } @@ -102,6 +106,13 @@ namespace StardewModdingAPI } + /// Get the game's executable assembly name. + private static string GetExecutableAssemblyName() + { + Platform platform = EnvironmentUtility.DetectPlatform(); + return platform == Platform.Windows ? "Stardew Valley" : "StardewValley"; + } + /// Initialize SMAPI and launch the game. /// The command-line arguments. /// This method is separate from because that can't contain any references to assemblies loaded by (e.g. via ), or Mono will incorrectly show an assembly resolution error before assembly resolution is set up. -- cgit From 88dce820d52f7e09ce5424e13b34d6c10d5868ed Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 4 Nov 2019 16:50:00 -0500 Subject: no longer omit zero patch numbers when formatting versions --- docs/release-notes.md | 1 + src/SMAPI.Tests/Utilities/SemanticVersionTests.cs | 12 ++++++------ src/SMAPI.Toolkit/SemanticVersion.cs | 14 ++++---------- src/SMAPI/Framework/GameVersion.cs | 3 +++ 4 files changed, 14 insertions(+), 16 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 7cd7b52b..1d933f96 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -107,6 +107,7 @@ For modders: * Trace logs for a broken mod now list all detected issues (instead of the first one). * Trace logs when loading mods are now more clear. * Clarified update-check errors for mods with multiple update keys. + * `SemanticVersion` no longer omits `.0` patch numbers when formatting versions, for better [semver](https://semver.org/) conformity (e.g. `3.0` is now formatted as `3.0.0`). * Updated dependencies (including Json.NET 11.0.2 → 12.0.2 and Mono.Cecil 0.10.1 → 0.11). * Fixes: * Fixed custom maps loaded from `.xnb` files not having their tilesheet paths automatically adjusted. diff --git a/src/SMAPI.Tests/Utilities/SemanticVersionTests.cs b/src/SMAPI.Tests/Utilities/SemanticVersionTests.cs index 8da64c27..c91ec27f 100644 --- a/src/SMAPI.Tests/Utilities/SemanticVersionTests.cs +++ b/src/SMAPI.Tests/Utilities/SemanticVersionTests.cs @@ -18,10 +18,10 @@ namespace SMAPI.Tests.Utilities ** Constructor ****/ [Test(Description = "Assert that the constructor sets the expected values for all valid versions when constructed from a string.")] - [TestCase("1.0", ExpectedResult = "1.0")] - [TestCase("1.0.0", ExpectedResult = "1.0")] + [TestCase("1.0", ExpectedResult = "1.0.0")] + [TestCase("1.0.0", ExpectedResult = "1.0.0")] [TestCase("3000.4000.5000", ExpectedResult = "3000.4000.5000")] - [TestCase("1.2-some-tag.4", ExpectedResult = "1.2-some-tag.4")] + [TestCase("1.2-some-tag.4", ExpectedResult = "1.2.0-some-tag.4")] [TestCase("1.2.3-some-tag.4", ExpectedResult = "1.2.3-some-tag.4")] [TestCase("1.2.3-SoME-tAg.4", ExpectedResult = "1.2.3-SoME-tAg.4")] [TestCase("1.2.3-some-tag.4 ", ExpectedResult = "1.2.3-some-tag.4")] @@ -31,7 +31,7 @@ namespace SMAPI.Tests.Utilities } [Test(Description = "Assert that the constructor sets the expected values for all valid versions when constructed from the individual numbers.")] - [TestCase(1, 0, 0, null, ExpectedResult = "1.0")] + [TestCase(1, 0, 0, null, ExpectedResult = "1.0.0")] [TestCase(3000, 4000, 5000, null, ExpectedResult = "3000.4000.5000")] [TestCase(1, 2, 3, "", ExpectedResult = "1.2.3")] [TestCase(1, 2, 3, " ", ExpectedResult = "1.2.3")] @@ -66,7 +66,7 @@ namespace SMAPI.Tests.Utilities } [Test(Description = "Assert that the constructor sets the expected values for all valid versions when constructed from an assembly version.")] - [TestCase(1, 0, 0, ExpectedResult = "1.0")] + [TestCase(1, 0, 0, ExpectedResult = "1.0.0")] [TestCase(1, 2, 3, ExpectedResult = "1.2.3")] [TestCase(3000, 4000, 5000, ExpectedResult = "3000.4000.5000")] public string Constructor_FromAssemblyVersion(int major, int minor, int patch) @@ -247,7 +247,7 @@ namespace SMAPI.Tests.Utilities ** Serializable ****/ [Test(Description = "Assert that SemanticVersion can be round-tripped through JSON with no special configuration.")] - [TestCase("1.0")] + [TestCase("1.0.0")] public void Serializable(string versionStr) { // act diff --git a/src/SMAPI.Toolkit/SemanticVersion.cs b/src/SMAPI.Toolkit/SemanticVersion.cs index 6d5d65ac..2ce3578e 100644 --- a/src/SMAPI.Toolkit/SemanticVersion.cs +++ b/src/SMAPI.Toolkit/SemanticVersion.cs @@ -172,16 +172,10 @@ namespace StardewModdingAPI.Toolkit /// Get a string representation of the version. public override string ToString() { - // version - string result = this.PatchVersion != 0 - ? $"{this.MajorVersion}.{this.MinorVersion}.{this.PatchVersion}" - : $"{this.MajorVersion}.{this.MinorVersion}"; - - // tag - string tag = this.PrereleaseTag; - if (tag != null) - result += $"-{tag}"; - return result; + string version = $"{this.MajorVersion}.{this.MinorVersion}.{this.PatchVersion}"; + if (this.PrereleaseTag != null) + version += $"-{this.PrereleaseTag}"; + return version; } /// Parse a version string without throwing an exception if it fails. diff --git a/src/SMAPI/Framework/GameVersion.cs b/src/SMAPI/Framework/GameVersion.cs index b9ef12c8..cd88895c 100644 --- a/src/SMAPI/Framework/GameVersion.cs +++ b/src/SMAPI/Framework/GameVersion.cs @@ -12,6 +12,7 @@ namespace StardewModdingAPI.Framework /// A mapping of game to semantic versions. private static readonly IDictionary VersionMap = new Dictionary(StringComparer.InvariantCultureIgnoreCase) { + ["1.0"] = "1.0.0", ["1.01"] = "1.0.1", ["1.02"] = "1.0.2", ["1.03"] = "1.0.3", @@ -23,6 +24,8 @@ namespace StardewModdingAPI.Framework ["1.07"] = "1.0.7", ["1.07a"] = "1.0.8-prerelease1", ["1.08"] = "1.0.8", + ["1.1"] = "1.1.0", + ["1.2"] = "1.2.0", ["1.11"] = "1.1.1" }; -- cgit From 8b09a2776d9c0faf96fa90c923952033ce659477 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Thu, 7 Nov 2019 13:51:45 -0500 Subject: add support for CurseForge update keys (#605) --- docs/release-notes.md | 1 + .../Framework/UpdateData/ModRepositoryKey.cs | 3 + src/SMAPI.Web/Controllers/ModsApiController.cs | 5 +- .../Clients/CurseForge/CurseForgeClient.cs | 113 +++++++++++++++++++++ .../Framework/Clients/CurseForge/CurseForgeMod.cs | 23 +++++ .../Clients/CurseForge/ICurseForgeClient.cs | 17 ++++ .../CurseForge/ResponseModels/ModFileModel.cs | 12 +++ .../Clients/CurseForge/ResponseModels/ModModel.cs | 18 ++++ .../Framework/ConfigModels/ApiClientsConfig.cs | 7 ++ .../ModRepositories/CurseForgeRepository.cs | 63 ++++++++++++ src/SMAPI.Web/Startup.cs | 5 + src/SMAPI.Web/appsettings.json | 2 + 12 files changed, 268 insertions(+), 1 deletion(-) create mode 100644 src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeClient.cs create mode 100644 src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeMod.cs create mode 100644 src/SMAPI.Web/Framework/Clients/CurseForge/ICurseForgeClient.cs create mode 100644 src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModFileModel.cs create mode 100644 src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModModel.cs create mode 100644 src/SMAPI.Web/Framework/ModRepositories/CurseForgeRepository.cs (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 1d933f96..5c12c4cc 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -47,6 +47,7 @@ For modders: * Now ignores metadata files and folders (like `__MACOSX` and `__folder_managed_by_vortex`) and content files (like `.txt` or `.png`), which avoids missing-manifest errors in some common cases. * Now detects XNB mods more accurately, and consolidates multi-folder XNB mods in logged messages. * SMAPI now automatically removes invalid content when loading a save to prevent crashes. A warning is shown in-game when this happens. This applies for locations and NPCs. + * Added update checks for CurseForge mods. * Added support for configuring console colors via `smapi-internal/config.json` (intended for players with unusual consoles). * Added support for specifying SMAPI command-line arguments as environment variables for Linux/Mac compatibility. * Improved launch script compatibility on Linux (thanks to kurumushi and toastal!). diff --git a/src/SMAPI.Toolkit/Framework/UpdateData/ModRepositoryKey.cs b/src/SMAPI.Toolkit/Framework/UpdateData/ModRepositoryKey.cs index f6c402d5..765ca334 100644 --- a/src/SMAPI.Toolkit/Framework/UpdateData/ModRepositoryKey.cs +++ b/src/SMAPI.Toolkit/Framework/UpdateData/ModRepositoryKey.cs @@ -9,6 +9,9 @@ namespace StardewModdingAPI.Toolkit.Framework.UpdateData /// The Chucklefish mod repository. Chucklefish, + /// The CurseForge mod repository. + CurseForge, + /// A GitHub project containing releases. GitHub, diff --git a/src/SMAPI.Web/Controllers/ModsApiController.cs b/src/SMAPI.Web/Controllers/ModsApiController.cs index 8419b220..1412105a 100644 --- a/src/SMAPI.Web/Controllers/ModsApiController.cs +++ b/src/SMAPI.Web/Controllers/ModsApiController.cs @@ -14,6 +14,7 @@ using StardewModdingAPI.Toolkit.Framework.UpdateData; using StardewModdingAPI.Web.Framework.Caching.Mods; using StardewModdingAPI.Web.Framework.Caching.Wiki; using StardewModdingAPI.Web.Framework.Clients.Chucklefish; +using StardewModdingAPI.Web.Framework.Clients.CurseForge; using StardewModdingAPI.Web.Framework.Clients.GitHub; using StardewModdingAPI.Web.Framework.Clients.ModDrop; using StardewModdingAPI.Web.Framework.Clients.Nexus; @@ -61,10 +62,11 @@ namespace StardewModdingAPI.Web.Controllers /// The cache in which to store mod metadata. /// The config settings for mod update checks. /// The Chucklefish API client. + /// The CurseForge API client. /// The GitHub API client. /// The ModDrop API client. /// The Nexus API client. - public ModsApiController(IHostingEnvironment environment, IWikiCacheRepository wikiCache, IModCacheRepository modCache, IOptions configProvider, IChucklefishClient chucklefish, IGitHubClient github, IModDropClient modDrop, INexusClient nexus) + public ModsApiController(IHostingEnvironment environment, IWikiCacheRepository wikiCache, IModCacheRepository modCache, IOptions configProvider, IChucklefishClient chucklefish, ICurseForgeClient curseForge, IGitHubClient github, IModDropClient modDrop, INexusClient nexus) { this.ModDatabase = new ModToolkit().GetModDatabase(Path.Combine(environment.WebRootPath, "SMAPI.metadata.json")); ModUpdateCheckConfig config = configProvider.Value; @@ -78,6 +80,7 @@ namespace StardewModdingAPI.Web.Controllers new IModRepository[] { new ChucklefishRepository(chucklefish), + new CurseForgeRepository(curseForge), new GitHubRepository(github), new ModDropRepository(modDrop), new NexusRepository(nexus) diff --git a/src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeClient.cs b/src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeClient.cs new file mode 100644 index 00000000..140b854e --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeClient.cs @@ -0,0 +1,113 @@ +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Pathoschild.Http.Client; +using StardewModdingAPI.Toolkit; +using StardewModdingAPI.Web.Framework.Clients.CurseForge.ResponseModels; + +namespace StardewModdingAPI.Web.Framework.Clients.CurseForge +{ + /// An HTTP client for fetching mod metadata from the CurseForge API. + internal class CurseForgeClient : ICurseForgeClient + { + /********* + ** Fields + *********/ + /// The underlying HTTP client. + private readonly IClient Client; + + /// A regex pattern which matches a version number in a CurseForge mod file name. + private readonly Regex VersionInNamePattern = new Regex(@"^(?:.+? | *)v?(\d+\.\d+(?:\.\d+)?(?:-.+?)?) *(?:\.(?:zip|rar|7z))?$", RegexOptions.Compiled); + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The user agent for the API client. + /// The base URL for the CurseForge API. + public CurseForgeClient(string userAgent, string apiUrl) + { + this.Client = new FluentClient(apiUrl).SetUserAgent(userAgent); + } + + /// Get metadata about a mod. + /// The CurseForge mod ID. + /// Returns the mod info if found, else null. + public async Task GetModAsync(long id) + { + // get raw data + ModModel mod = await this.Client + .GetAsync($"addon/{id}") + .As(); + if (mod == null) + return null; + + // get latest versions + string invalidVersion = null; + ISemanticVersion latest = null; + foreach (ModFileModel file in mod.LatestFiles) + { + // extract version + ISemanticVersion version; + { + string raw = this.GetRawVersion(file); + if (raw == null) + continue; + + if (!SemanticVersion.TryParse(raw, out version)) + { + if (invalidVersion == null) + invalidVersion = raw; + continue; + } + } + + // track latest version + if (latest == null || version.IsNewerThan(latest)) + latest = version; + } + + // get error + string error = null; + if (latest == null && invalidVersion == null) + { + error = mod.LatestFiles.Any() + ? $"CurseForge mod {id} has no downloads which specify the version in a recognised format." + : $"CurseForge mod {id} has no downloads."; + } + + // generate result + return new CurseForgeMod + { + Name = mod.Name, + LatestVersion = latest?.ToString() ?? invalidVersion, + Url = mod.WebsiteUrl, + Error = error + }; + } + + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + public void Dispose() + { + this.Client?.Dispose(); + } + + + /********* + ** Private methods + *********/ + /// Get a raw version string for a mod file, if available. + /// The file whose version to get. + private string GetRawVersion(ModFileModel file) + { + Match match = this.VersionInNamePattern.Match(file.DisplayName); + if (!match.Success) + match = this.VersionInNamePattern.Match(file.FileName); + + return match.Success + ? match.Groups[1].Value + : null; + } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeMod.cs b/src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeMod.cs new file mode 100644 index 00000000..e5bb8cf1 --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeMod.cs @@ -0,0 +1,23 @@ +using Newtonsoft.Json; + +namespace StardewModdingAPI.Web.Framework.Clients.CurseForge +{ + /// Mod metadata from the CurseForge API. + internal class CurseForgeMod + { + /********* + ** Accessors + *********/ + /// The mod name. + public string Name { get; set; } + + /// The latest file version. + public string LatestVersion { get; set; } + + /// The mod's web URL. + public string Url { get; set; } + + /// A user-friendly error which indicates why fetching the mod info failed (if applicable). + public string Error { get; set; } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/CurseForge/ICurseForgeClient.cs b/src/SMAPI.Web/Framework/Clients/CurseForge/ICurseForgeClient.cs new file mode 100644 index 00000000..907b4087 --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/CurseForge/ICurseForgeClient.cs @@ -0,0 +1,17 @@ +using System; +using System.Threading.Tasks; + +namespace StardewModdingAPI.Web.Framework.Clients.CurseForge +{ + /// An HTTP client for fetching mod metadata from the CurseForge API. + internal interface ICurseForgeClient : IDisposable + { + /********* + ** Methods + *********/ + /// Get metadata about a mod. + /// The CurseForge mod ID. + /// Returns the mod info if found, else null. + Task GetModAsync(long id); + } +} diff --git a/src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModFileModel.cs b/src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModFileModel.cs new file mode 100644 index 00000000..9de74847 --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModFileModel.cs @@ -0,0 +1,12 @@ +namespace StardewModdingAPI.Web.Framework.Clients.CurseForge.ResponseModels +{ + /// Metadata from the CurseForge API about a mod file. + public class ModFileModel + { + /// The file name as downloaded. + public string FileName { get; set; } + + /// The file display name. + public string DisplayName { get; set; } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModModel.cs b/src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModModel.cs new file mode 100644 index 00000000..48cd185b --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/CurseForge/ResponseModels/ModModel.cs @@ -0,0 +1,18 @@ +namespace StardewModdingAPI.Web.Framework.Clients.CurseForge.ResponseModels +{ + /// An mod from the CurseForge API. + public class ModModel + { + /// The mod's unique ID on CurseForge. + public int ID { get; set; } + + /// The mod name. + public string Name { get; set; } + + /// The web URL for the mod page. + public string WebsiteUrl { get; set; } + + /// The available file downloads. + public ModFileModel[] LatestFiles { get; set; } + } +} diff --git a/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs b/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs index a0a1f42a..121690c5 100644 --- a/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs +++ b/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs @@ -23,6 +23,13 @@ namespace StardewModdingAPI.Web.Framework.ConfigModels public string ChucklefishModPageUrlFormat { get; set; } + /**** + ** CurseForge + ****/ + /// The base URL for the CurseForge API. + public string CurseForgeBaseUrl { get; set; } + + /**** ** GitHub ****/ diff --git a/src/SMAPI.Web/Framework/ModRepositories/CurseForgeRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/CurseForgeRepository.cs new file mode 100644 index 00000000..93ddc1eb --- /dev/null +++ b/src/SMAPI.Web/Framework/ModRepositories/CurseForgeRepository.cs @@ -0,0 +1,63 @@ +using System; +using System.Threading.Tasks; +using StardewModdingAPI.Toolkit.Framework.UpdateData; +using StardewModdingAPI.Web.Framework.Clients.CurseForge; + +namespace StardewModdingAPI.Web.Framework.ModRepositories +{ + /// An HTTP client for fetching mod metadata from CurseForge. + internal class CurseForgeRepository : RepositoryBase + { + /********* + ** Fields + *********/ + /// The underlying CurseForge API client. + private readonly ICurseForgeClient Client; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The underlying CurseForge API client. + public CurseForgeRepository(ICurseForgeClient client) + : base(ModRepositoryKey.CurseForge) + { + this.Client = client; + } + + /// Get metadata about a mod in the repository. + /// The mod ID in this repository. + public override async Task GetModInfoAsync(string id) + { + // validate ID format + if (!uint.TryParse(id, out uint curseID)) + return new ModInfoModel().SetError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid CurseForge mod ID, must be an integer ID."); + + // fetch info + try + { + CurseForgeMod mod = await this.Client.GetModAsync(curseID); + if (mod == null) + return new ModInfoModel().SetError(RemoteModStatus.DoesNotExist, "Found no CurseForge mod with this ID."); + if (mod.Error != null) + { + RemoteModStatus remoteStatus = RemoteModStatus.InvalidData; + return new ModInfoModel().SetError(remoteStatus, mod.Error); + } + + return new ModInfoModel(name: mod.Name, version: this.NormalizeVersion(mod.LatestVersion), url: mod.Url); + } + catch (Exception ex) + { + return new ModInfoModel().SetError(RemoteModStatus.TemporaryError, ex.ToString()); + } + } + + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + public override void Dispose() + { + this.Client.Dispose(); + } + } +} diff --git a/src/SMAPI.Web/Startup.cs b/src/SMAPI.Web/Startup.cs index bf69d543..8110b696 100644 --- a/src/SMAPI.Web/Startup.cs +++ b/src/SMAPI.Web/Startup.cs @@ -16,6 +16,7 @@ using StardewModdingAPI.Web.Framework.Caching; using StardewModdingAPI.Web.Framework.Caching.Mods; using StardewModdingAPI.Web.Framework.Caching.Wiki; using StardewModdingAPI.Web.Framework.Clients.Chucklefish; +using StardewModdingAPI.Web.Framework.Clients.CurseForge; using StardewModdingAPI.Web.Framework.Clients.GitHub; using StardewModdingAPI.Web.Framework.Clients.ModDrop; using StardewModdingAPI.Web.Framework.Clients.Nexus; @@ -119,6 +120,10 @@ namespace StardewModdingAPI.Web baseUrl: api.ChucklefishBaseUrl, modPageUrlFormat: api.ChucklefishModPageUrlFormat )); + services.AddSingleton(new CurseForgeClient( + userAgent: userAgent, + apiUrl: api.CurseForgeBaseUrl + )); services.AddSingleton(new GitHubClient( baseUrl: api.GitHubBaseUrl, diff --git a/src/SMAPI.Web/appsettings.json b/src/SMAPI.Web/appsettings.json index a440cf42..674bb672 100644 --- a/src/SMAPI.Web/appsettings.json +++ b/src/SMAPI.Web/appsettings.json @@ -30,6 +30,8 @@ "ChucklefishBaseUrl": "https://community.playstarbound.com", "ChucklefishModPageUrlFormat": "resources/{0}", + "CurseForgeBaseUrl": "https://addons-ecs.forgesvc.net/api/v2/", + "GitHubBaseUrl": "https://api.github.com", "GitHubAcceptHeader": "application/vnd.github.v3+json", "GitHubUsername": null, // see top note -- cgit From a03137372d8e1aea73da31115d4b47f6656759bc Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 8 Nov 2019 14:44:12 -0500 Subject: update release notes (#605) --- docs/release-notes.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 5c12c4cc..eace8be5 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -77,10 +77,12 @@ For modders: ### For the web UI * Mod compatibility list: + * Added support for CurseForge mods. + * Added metadata links and dev notes (if any) to advanced info. * Now loads faster (since data is fetched in a background service). * Now continues working with cached data when the wiki is offline. * Clicking a mod link now automatically adds it to the visible mods when the list is filtered. - * Added metadata links and dev notes (if any) to advanced info. + * JSON validator: * Added JSON validator at [json.smapi.io](https://json.smapi.io), which lets you validate a JSON file against predefined mod formats. * Added support for the `manifest.json` format. -- cgit From fd6a719b02d1d45d27509f44f09eefe52124ee20 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 9 Nov 2019 21:18:06 -0500 Subject: overhaul update checks This commit moves the core update-check logic serverside, and adds support for community-defined version mappings. For example, that means false update alerts can now be solved by the community for all players. --- docs/release-notes.md | 4 + docs/technical/web.md | 209 ++++++++++++++++++--- .../Framework/Clients/WebApi/ModEntryModel.cs | 18 +- .../Clients/WebApi/ModExtendedMetadataModel.cs | 24 ++- .../Framework/Clients/WebApi/ModSeachModel.cs | 36 ---- .../Clients/WebApi/ModSearchEntryModel.cs | 11 +- .../Framework/Clients/WebApi/ModSearchModel.cs | 52 +++++ .../Framework/Clients/WebApi/WebApiClient.cs | 8 +- .../Framework/Clients/Wiki/WikiClient.cs | 26 +++ .../Framework/Clients/Wiki/WikiModEntry.cs | 7 + .../Framework/ModData/ModDataModel.cs | 6 - .../Framework/ModData/ModDataRecord.cs | 31 --- .../ModData/ModDataRecordVersionedFields.cs | 24 --- src/SMAPI.Web/Controllers/ModsApiController.cs | 162 +++++++++++++--- .../Framework/Caching/Wiki/CachedWikiMod.cs | 24 ++- src/SMAPI.Web/Views/Index/Privacy.cshtml | 2 +- src/SMAPI.Web/wwwroot/SMAPI.metadata.json | 97 ---------- src/SMAPI/Framework/SCore.cs | 57 ++---- 18 files changed, 493 insertions(+), 305 deletions(-) delete mode 100644 src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSeachModel.cs create mode 100644 src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSearchModel.cs (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index eace8be5..5f643f07 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -18,6 +18,9 @@ For players: * **Improved mod scanning.** SMAPI now supports some non-standard mod structures automatically, improves compatibility with the Vortex mod manager, and improves various error/skip messages related to mod loading. +* **Overhauled update checks.** + SMAPI update checks are now handled entirely on the web server and support community-defined version mappings. For example, that means false update alerts can now be solved by the community for all players. + * **Fixed many bugs and edge cases.** For modders: @@ -50,6 +53,7 @@ For modders: * Added update checks for CurseForge mods. * Added support for configuring console colors via `smapi-internal/config.json` (intended for players with unusual consoles). * Added support for specifying SMAPI command-line arguments as environment variables for Linux/Mac compatibility. + * Overhauled update checks and added community-defined version mapping. * Improved launch script compatibility on Linux (thanks to kurumushi and toastal!). * Made error messages more user-friendly in some cases. * Save Backup now works in the background, to avoid affecting startup time for players with a large number of saves. diff --git a/docs/technical/web.md b/docs/technical/web.md index 719b9433..78d93625 100644 --- a/docs/technical/web.md +++ b/docs/technical/web.md @@ -116,54 +116,201 @@ SMAPI provides a web API at `api.smapi.io` for use by SMAPI and external tools. accessible but not officially released; it may change at any time. ### `/mods` endpoint -The API has one `/mods` endpoint. This provides mod info, including official versions and URLs -(from Chucklefish, GitHub, or Nexus), unofficial versions from the wiki, and optional mod metadata -from the wiki and SMAPI's internal data. This is used by SMAPI to perform update checks, and by -external tools to fetch mod data. +The API has one `/mods` endpoint. This crossreferences the mod against a variety of sources (e.g. +the wiki, Chucklefish, CurseForge, ModDrop, and Nexus) to provide metadata mainly intended for +update checks. -The API accepts a `POST` request with the mods to match, each of which **must** specify an ID and -may _optionally_ specify [update keys](https://stardewvalleywiki.com/Modding:Modder_Guide/APIs/Manifest#Update_checks). -The API will automatically try to fetch known update keys from the wiki and internal data based on -the given ID. +The API accepts a `POST` request with these fields: -``` -POST https://api.smapi.io/v2.0/mods + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    fieldsummary
    mods + +The mods for which to fetch metadata. Included fields: + + +field | summary +----- | ------- +`id` | The unique ID in the mod's `manifest.json`. This is used to crossreference with the wiki, and to index mods in the response. If it's unknown (e.g. you just have an update key), you can use a unique fake ID like `FAKE.Nexus.2400`. +`updateKeys` | _(optional)_ [Update keys](https://stardewvalleywiki.com/Modding:Modder_Guide/APIs/Manifest#Update_checks) which specify the mod pages to check, in addition to any mod pages linked to the `ID`. +`installedVersion` | _(optional)_ The installed version of the mod. If not specified, the API won't recommend an update. +`isBroken` | _(optional)_ Whether SMAPI failed to load the installed version of the mod, e.g. due to incompatibility. If true, the web API will be more permissive when recommending updates (e.g. allowing a stable → prerelease update). + +
    apiVersion + +_(optional)_ The installed version of SMAPI. If not specified, the API won't recommend an update. + +
    gameVersion + +_(optional)_ The installed version of Stardew Valley. This may be used to select updates. + +
    platform + +_(optional)_ The player's OS (`Android`, `Linux`, `Mac`, or `Windows`). This may be used to select updates. + +
    includeExtendedMetadata + +_(optional)_ Whether to include extra metadata that's not needed for SMAPI update checks, but which +may be useful to external tools. + +
    + +Example request: +```js +POST https://api.smapi.io/v3.0/mods { "mods": [ { - "id": "Pathoschild.LookupAnything", - "updateKeys": [ "nexus:541", "chucklefish:4250" ] + "id": "Pathoschild.ContentPatcher", + "updateKeys": [ "nexus:1915" ], + "installedVersion": "1.9.2", + "isBroken": false } ], + "apiVersion": "3.0.0", + "gameVersion": "1.4.0", + "platform": "Windows", "includeExtendedMetadata": true } ``` -The API will automatically aggregate versions and errors. Each mod will include... -* an `id` (matching what you passed in); -* up to three versions: `main` (e.g. 'latest version' field on Nexus), `optional` if newer (e.g. - optional files on Nexus), and `unofficial` if newer (from the wiki); -* `metadata` with mod info crossreferenced from the wiki and internal data (only if you specified - `includeExtendedMetadata: true`); -* and `errors` containing any error messages that occurred while fetching data. - -For example: +Response fields: + + + + + + + + + + + + + + + + + + + + + + + + + + +
    fieldsummary
    id + +The mod ID you specified in the request. + +
    suggestedUpdate + +The update version recommended by the web API, if any. This is based on some internal rules (e.g. +it won't recommend a prerelease update if the player has a working stable version) and context +(e.g. whether the player is in the game beta channel). Choosing an update version yourself isn't +recommended, but you can set `includeExtendedMetadata: true` and check the `metadata` field if you +really want to do that. + +
    errors + +Human-readable errors that occurred fetching the version info (e.g. if a mod page has an invalid +version). + +
    metadata + +Extra metadata that's not needed for SMAPI update checks but which may be useful to external tools, +if you set `includeExtendedMetadata: true` in the request. Included fields: + +field | summary +----- | ------- +`id` | The known `manifest.json` unique IDs for this mod defined on the wiki, if any. That includes historical versions of the mod. +`name` | The normalised name for this mod based on the crossreferenced sites. +`nexusID` | The mod ID on [Nexus Mods](https://www.nexusmods.com/stardewvalley/), if any. +`chucklefishID` | The mod ID in the [Chucklefish mod repo](https://community.playstarbound.com/resources/categories/stardew-valley.22/), if any. +`curseForgeID` | The mod project ID on [CurseForge](https://www.curseforge.com/stardewvalley), if any. +`curseForgeKey` | The mod key on [CurseForge](https://www.curseforge.com/stardewvalley), if any. This is used in the mod page URL. +`modDropID` | The mod ID on [ModDrop](https://www.moddrop.com/stardew-valley), if any. +`gitHubRepo` | The GitHub repository containing the mod code, if any. Specified in the `Owner/Repo` form. +`customSourceUrl` | The custom URL to the mod code, if any. This is used for mods which aren't stored in a GitHub repo. +`customUrl` | The custom URL to the mod page, if any. This is used for mods which aren't stored on one of the standard mod sites covered by the ID fields. +`main` | The primary mod version, if any. This depends on the mod site, but it's typically either the version of the mod itself or of its latest non-optional download. +`optional` | The latest optional download version, if any. +`unofficial` | The version of the unofficial update defined on the wiki for this mod, if any. +`unofficialForBeta` | Equivalent to `unofficial`, but for beta versions of SMAPI or Stardew Valley. +`hasBetaInfo` | Whether there's an ongoing Stardew Valley or SMAPI beta which may affect update checks. +`compatibilityStatus` | The compatibility status for the mod for the stable version of the game, as defined on the wiki, if any. See [possible values](https://github.com/Pathoschild/SMAPI/blob/develop/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiCompatibilityStatus.cs). +`compatibilitySummary` | The human-readable summary of the mod's compatibility in HTML format, if any. +`brokeIn` | The SMAPI or Stardew Valley version that broke this mod, if any. +`betaCompatibilityStatus`
    `betaCompatibilitySummary`
    `betaBrokeIn` | Equivalent to the preceding fields, but for beta versions of SMAPI or Stardew Valley. + + +
    + +Example response with `includeExtendedMetadata: false`: +```js +[ + { + "id": "Pathoschild.ContentPatcher", + "suggestedUpdate": { + "version": "1.10.0", + "url": "https://www.nexusmods.com/stardewvalley/mods/1915" + }, + "errors": [] + } +] ``` + +Example response with `includeExtendedMetadata: true`: +```js [ { - "id": "Pathoschild.LookupAnything", - "main": { - "version": "1.19", - "url": "https://www.nexusmods.com/stardewvalley/mods/541" + "id": "Pathoschild.ContentPatcher", + "suggestedUpdate": { + "version": "1.10.0", + "url": "https://www.nexusmods.com/stardewvalley/mods/1915" }, "metadata": { - "id": [ - "Pathoschild.LookupAnything", - "LookupAnything" - ], - "name": "Lookup Anything", - "nexusID": 541, + "id": [ "Pathoschild.ContentPatcher" ], + "name": "Content Patcher", + "nexusID": 1915, + "curseForgeID": 309243, + "curseForgeKey": "content-patcher", + "modDropID": 470174, "gitHubRepo": "Pathoschild/StardewMods", + "main": { + "version": "1.10", + "url": "https://www.nexusmods.com/stardewvalley/mods/1915" + }, + "hasBetaInfo": true, "compatibilityStatus": "Ok", "compatibilitySummary": "✓ use latest version." }, diff --git a/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModEntryModel.cs b/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModEntryModel.cs index 8a9c0a25..f1bcfccc 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModEntryModel.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModEntryModel.cs @@ -1,3 +1,5 @@ +using System; + namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi { /// Metadata about a mod. @@ -9,23 +11,31 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi /// The mod's unique ID (if known). public string ID { get; set; } + /// The update version recommended by the web API based on its version update and mapping rules. + public ModEntryVersionModel SuggestedUpdate { get; set; } + + /// Optional extended data which isn't needed for update checks. + public ModExtendedMetadataModel Metadata { get; set; } + /// The main version. + [Obsolete] public ModEntryVersionModel Main { get; set; } /// The latest optional version, if newer than . + [Obsolete] public ModEntryVersionModel Optional { get; set; } /// The latest unofficial version, if newer than and . + [Obsolete] public ModEntryVersionModel Unofficial { get; set; } /// The latest unofficial version for the current Stardew Valley or SMAPI beta, if any (see ). + [Obsolete] public ModEntryVersionModel UnofficialForBeta { get; set; } - /// Optional extended data which isn't needed for update checks. - public ModExtendedMetadataModel Metadata { get; set; } - /// Whether a Stardew Valley or SMAPI beta which affects mod compatibility is in progress. If this is true, should be used for beta versions of SMAPI instead of . - public bool HasBetaInfo { get; set; } + [Obsolete] + public bool? HasBetaInfo { get; set; } /// The errors that occurred while fetching update data. public string[] Errors { get; set; } = new string[0]; diff --git a/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModExtendedMetadataModel.cs b/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModExtendedMetadataModel.cs index 8074210c..4a697585 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModExtendedMetadataModel.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModExtendedMetadataModel.cs @@ -46,6 +46,17 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi /// The custom mod page URL (if applicable). public string CustomUrl { get; set; } + /// The main version. + public ModEntryVersionModel Main { get; set; } + + /// The latest optional version, if newer than . + public ModEntryVersionModel Optional { get; set; } + + /// The latest unofficial version, if newer than and . + public ModEntryVersionModel Unofficial { get; set; } + + /// The latest unofficial version for the current Stardew Valley or SMAPI beta, if any (see ). + public ModEntryVersionModel UnofficialForBeta { get; set; } /**** ** Stable compatibility @@ -60,7 +71,6 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi /// The game or SMAPI version which broke this mod, if applicable. public string BrokeIn { get; set; } - /**** ** Beta compatibility ****/ @@ -84,8 +94,18 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi /// Construct an instance. /// The mod metadata from the wiki (if available). /// The mod metadata from SMAPI's internal DB (if available). - public ModExtendedMetadataModel(WikiModEntry wiki, ModDataRecord db) + /// The main version. + /// The latest optional version, if newer than . + /// The latest unofficial version, if newer than and . + /// The latest unofficial version for the current Stardew Valley or SMAPI beta, if any. + public ModExtendedMetadataModel(WikiModEntry wiki, ModDataRecord db, ModEntryVersionModel main, ModEntryVersionModel optional, ModEntryVersionModel unofficial, ModEntryVersionModel unofficialForBeta) { + // versions + this.Main = main; + this.Optional = optional; + this.Unofficial = unofficial; + this.UnofficialForBeta = unofficialForBeta; + // wiki data if (wiki != null) { diff --git a/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSeachModel.cs b/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSeachModel.cs deleted file mode 100644 index a2eaad16..00000000 --- a/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSeachModel.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Linq; - -namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi -{ - /// Specifies mods whose update-check info to fetch. - public class ModSearchModel - { - /********* - ** Accessors - *********/ - /// The mods for which to find data. - public ModSearchEntryModel[] Mods { get; set; } - - /// Whether to include extended metadata for each mod. - public bool IncludeExtendedMetadata { get; set; } - - - /********* - ** Public methods - *********/ - /// Construct an empty instance. - public ModSearchModel() - { - // needed for JSON deserializing - } - - /// Construct an instance. - /// The mods to search. - /// Whether to include extended metadata for each mod. - public ModSearchModel(ModSearchEntryModel[] mods, bool includeExtendedMetadata) - { - this.Mods = mods.ToArray(); - this.IncludeExtendedMetadata = includeExtendedMetadata; - } - } -} diff --git a/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSearchEntryModel.cs b/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSearchEntryModel.cs index 886cd5a1..bf81e102 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSearchEntryModel.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSearchEntryModel.cs @@ -12,6 +12,12 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi /// The namespaced mod update keys (if available). public string[] UpdateKeys { get; set; } + /// The mod version installed by the local player. This is used for version mapping in some cases. + public ISemanticVersion InstalledVersion { get; set; } + + /// Whether the installed version is broken or could not be loaded. + public bool IsBroken { get; set; } + /********* ** Public methods @@ -24,10 +30,13 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi /// Construct an instance. /// The unique mod ID. + /// The version installed by the local player. This is used for version mapping in some cases. /// The namespaced mod update keys (if available). - public ModSearchEntryModel(string id, string[] updateKeys) + /// Whether the installed version is broken or could not be loaded. + public ModSearchEntryModel(string id, ISemanticVersion installedVersion, string[] updateKeys, bool isBroken = false) { this.ID = id; + this.InstalledVersion = installedVersion; this.UpdateKeys = updateKeys ?? new string[0]; } } diff --git a/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSearchModel.cs b/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSearchModel.cs new file mode 100644 index 00000000..73698173 --- /dev/null +++ b/src/SMAPI.Toolkit/Framework/Clients/WebApi/ModSearchModel.cs @@ -0,0 +1,52 @@ +using System.Linq; +using StardewModdingAPI.Toolkit.Utilities; + +namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi +{ + /// Specifies mods whose update-check info to fetch. + public class ModSearchModel + { + /********* + ** Accessors + *********/ + /// The mods for which to find data. + public ModSearchEntryModel[] Mods { get; set; } + + /// Whether to include extended metadata for each mod. + public bool IncludeExtendedMetadata { get; set; } + + /// The SMAPI version installed by the player. This is used for version mapping in some cases. + public ISemanticVersion ApiVersion { get; set; } + + /// The Stardew Valley version installed by the player. + public ISemanticVersion GameVersion { get; set; } + + /// The OS on which the player plays. + public Platform? Platform { get; set; } + + + /********* + ** Public methods + *********/ + /// Construct an empty instance. + public ModSearchModel() + { + // needed for JSON deserializing + } + + /// Construct an instance. + /// The mods to search. + /// The SMAPI version installed by the player. If this is null, the API won't provide a recommended update. + /// The Stardew Valley version installed by the player. + /// The OS on which the player plays. + /// Whether to include extended metadata for each mod. + public ModSearchModel(ModSearchEntryModel[] mods, ISemanticVersion apiVersion, ISemanticVersion gameVersion, Platform platform, bool includeExtendedMetadata) + { + this.Mods = mods.ToArray(); + this.ApiVersion = apiVersion; + this.GameVersion = gameVersion; + this.Platform = platform; + this.IncludeExtendedMetadata = includeExtendedMetadata; + } + } +} diff --git a/src/SMAPI.Toolkit/Framework/Clients/WebApi/WebApiClient.cs b/src/SMAPI.Toolkit/Framework/Clients/WebApi/WebApiClient.cs index 80c8f62b..f0a7c82a 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/WebApi/WebApiClient.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/WebApi/WebApiClient.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Net; using Newtonsoft.Json; using StardewModdingAPI.Toolkit.Serialization; +using StardewModdingAPI.Toolkit.Utilities; namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi { @@ -37,12 +38,15 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi /// Get metadata about a set of mods from the web API. /// The mod keys for which to fetch the latest version. + /// The SMAPI version installed by the player. If this is null, the API won't provide a recommended update. + /// The Stardew Valley version installed by the player. + /// The OS on which the player plays. /// Whether to include extended metadata for each mod. - public IDictionary GetModInfo(ModSearchEntryModel[] mods, bool includeExtendedMetadata = false) + public IDictionary GetModInfo(ModSearchEntryModel[] mods, ISemanticVersion apiVersion, ISemanticVersion gameVersion, Platform platform, bool includeExtendedMetadata = false) { return this.Post( $"v{this.Version}/mods", - new ModSearchModel(mods, includeExtendedMetadata) + new ModSearchModel(mods, apiVersion, gameVersion, platform, includeExtendedMetadata) ).ToDictionary(p => p.ID); } diff --git a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs index 610e14f1..384f23fc 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs @@ -102,6 +102,8 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki string anchor = this.GetAttribute(node, "id"); string contentPackFor = this.GetAttribute(node, "data-content-pack-for"); string devNote = this.GetAttribute(node, "data-dev-note"); + IDictionary mapLocalVersions = this.GetAttributeAsVersionMapping(node, "data-map-local-versions"); + IDictionary mapRemoteVersions = this.GetAttributeAsVersionMapping(node, "data-map-remote-versions"); // parse stable compatibility WikiCompatibilityInfo compatibility = new WikiCompatibilityInfo @@ -159,6 +161,8 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki Warnings = warnings, MetadataLinks = metadataLinks.ToArray(), DevNote = devNote, + MapLocalVersions = mapLocalVersions, + MapRemoteVersions = mapRemoteVersions, Anchor = anchor }; } @@ -223,6 +227,28 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki return null; } + /// Get an attribute value and parse it as a version mapping. + /// The element whose attributes to read. + /// The attribute name. + private IDictionary GetAttributeAsVersionMapping(HtmlNode element, string name) + { + // get raw value + string raw = this.GetAttribute(element, name); + if (raw?.Contains("→") != true) + return null; + + // parse + // Specified on the wiki in the form "remote version → mapped version; another remote version → mapped version" + IDictionary map = new Dictionary(StringComparer.InvariantCultureIgnoreCase); + foreach (string pair in raw.Split(';')) + { + string[] versions = pair.Split('→'); + if (versions.Length == 2 && !string.IsNullOrWhiteSpace(versions[0]) && !string.IsNullOrWhiteSpace(versions[1])) + map[versions[0].Trim()] = versions[1].Trim(); + } + return map; + } + /// Get the text of an element with the given class name. /// The metadata container. /// The field name. diff --git a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs index 51bb2336..931dcd43 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiModEntry.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki { @@ -62,6 +63,12 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki /// Special notes intended for developers who maintain unofficial updates or submit pull requests. public string DevNote { get; set; } + /// Maps local versions to a semantic version for update checks. + public IDictionary MapLocalVersions { get; set; } + + /// Maps remote versions to a semantic version for update checks. + public IDictionary MapRemoteVersions { get; set; } + /// The link anchor for the mod entry in the wiki compatibility list. public string Anchor { get; set; } } diff --git a/src/SMAPI.Toolkit/Framework/ModData/ModDataModel.cs b/src/SMAPI.Toolkit/Framework/ModData/ModDataModel.cs index dd0bd07b..8b40c301 100644 --- a/src/SMAPI.Toolkit/Framework/ModData/ModDataModel.cs +++ b/src/SMAPI.Toolkit/Framework/ModData/ModDataModel.cs @@ -25,12 +25,6 @@ namespace StardewModdingAPI.Toolkit.Framework.ModData /// public string FormerIDs { get; set; } - /// Maps local versions to a semantic version for update checks. - public IDictionary MapLocalVersions { get; set; } = new Dictionary(); - - /// Maps remote versions to a semantic version for update checks. - public IDictionary MapRemoteVersions { get; set; } = new Dictionary(); - /// The mod warnings to suppress, even if they'd normally be shown. public ModWarning SuppressWarnings { get; set; } diff --git a/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs b/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs index f01ada7c..c892d820 100644 --- a/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs +++ b/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs @@ -22,12 +22,6 @@ namespace StardewModdingAPI.Toolkit.Framework.ModData /// The mod warnings to suppress, even if they'd normally be shown. public ModWarning SuppressWarnings { get; set; } - /// Maps local versions to a semantic version for update checks. - public IDictionary MapLocalVersions { get; } - - /// Maps remote versions to a semantic version for update checks. - public IDictionary MapRemoteVersions { get; } - /// The versioned field data. public ModDataField[] Fields { get; } @@ -44,8 +38,6 @@ namespace StardewModdingAPI.Toolkit.Framework.ModData this.ID = model.ID; this.FormerIDs = model.GetFormerIDs().ToArray(); this.SuppressWarnings = model.SuppressWarnings; - this.MapLocalVersions = new Dictionary(model.MapLocalVersions, StringComparer.InvariantCultureIgnoreCase); - this.MapRemoteVersions = new Dictionary(model.MapRemoteVersions, StringComparer.InvariantCultureIgnoreCase); this.Fields = model.GetFields().ToArray(); } @@ -67,29 +59,6 @@ namespace StardewModdingAPI.Toolkit.Framework.ModData return false; } - /// Get a semantic local version for update checks. - /// The remote version to normalize. - public ISemanticVersion GetLocalVersionForUpdateChecks(ISemanticVersion version) - { - return this.MapLocalVersions != null && this.MapLocalVersions.TryGetValue(version.ToString(), out string newVersion) - ? new SemanticVersion(newVersion) - : version; - } - - /// Get a semantic remote version for update checks. - /// The remote version to normalize. - public string GetRemoteVersionForUpdateChecks(string version) - { - // normalize version if possible - if (SemanticVersion.TryParse(version, out ISemanticVersion parsed)) - version = parsed.ToString(); - - // fetch remote version - return this.MapRemoteVersions != null && this.MapRemoteVersions.TryGetValue(version, out string newVersion) - ? newVersion - : version; - } - /// Get the possible mod IDs. public IEnumerable GetIDs() { diff --git a/src/SMAPI.Toolkit/Framework/ModData/ModDataRecordVersionedFields.cs b/src/SMAPI.Toolkit/Framework/ModData/ModDataRecordVersionedFields.cs index 9e22990d..598da66a 100644 --- a/src/SMAPI.Toolkit/Framework/ModData/ModDataRecordVersionedFields.cs +++ b/src/SMAPI.Toolkit/Framework/ModData/ModDataRecordVersionedFields.cs @@ -26,29 +26,5 @@ namespace StardewModdingAPI.Toolkit.Framework.ModData /// The upper version for which the applies (if any). public ISemanticVersion StatusUpperVersion { get; set; } - - - /********* - ** Public methods - *********/ - /// Get a semantic local version for update checks. - /// The remote version to normalize. - public ISemanticVersion GetLocalVersionForUpdateChecks(ISemanticVersion version) - { - return this.DataRecord.GetLocalVersionForUpdateChecks(version); - } - - /// Get a semantic remote version for update checks. - /// The remote version to normalize. - public ISemanticVersion GetRemoteVersionForUpdateChecks(ISemanticVersion version) - { - if (version == null) - return null; - - string rawVersion = this.DataRecord.GetRemoteVersionForUpdateChecks(version.ToString()); - return rawVersion != null - ? new SemanticVersion(rawVersion) - : version; - } } } diff --git a/src/SMAPI.Web/Controllers/ModsApiController.cs b/src/SMAPI.Web/Controllers/ModsApiController.cs index f65b164f..fe220eb5 100644 --- a/src/SMAPI.Web/Controllers/ModsApiController.cs +++ b/src/SMAPI.Web/Controllers/ModsApiController.cs @@ -80,7 +80,7 @@ namespace StardewModdingAPI.Web.Controllers new IModRepository[] { new ChucklefishRepository(chucklefish), - new CurseForgeRepository(curseForge), + new CurseForgeRepository(curseForge), new GitHubRepository(github), new ModDropRepository(modDrop), new NexusRepository(nexus) @@ -90,12 +90,15 @@ namespace StardewModdingAPI.Web.Controllers /// Fetch version metadata for the given mods. /// The mod search criteria. + /// The requested API version. [HttpPost] - public async Task> PostAsync([FromBody] ModSearchModel model) + public async Task> PostAsync([FromBody] ModSearchModel model, [FromRoute] string version) { if (model?.Mods == null) return new ModEntryModel[0]; + bool legacyMode = SemanticVersion.TryParse(version, out ISemanticVersion parsedVersion) && parsedVersion.IsOlderThan("3.0.0-beta.20191109"); + // fetch wiki data WikiModEntry[] wikiData = this.WikiCache.GetWikiMods().Select(p => p.GetModel()).ToArray(); IDictionary mods = new Dictionary(StringComparer.CurrentCultureIgnoreCase); @@ -104,7 +107,25 @@ namespace StardewModdingAPI.Web.Controllers if (string.IsNullOrWhiteSpace(mod.ID)) continue; - ModEntryModel result = await this.GetModData(mod, wikiData, model.IncludeExtendedMetadata); + ModEntryModel result = await this.GetModData(mod, wikiData, model.IncludeExtendedMetadata || legacyMode, model.ApiVersion); + if (legacyMode) + { + result.Main = result.Metadata.Main; + result.Optional = result.Metadata.Optional; + result.Unofficial = result.Metadata.Unofficial; + result.UnofficialForBeta = result.Metadata.UnofficialForBeta; + result.HasBetaInfo = result.Metadata.BetaCompatibilityStatus != null; + result.SuggestedUpdate = null; + if (!model.IncludeExtendedMetadata) + result.Metadata = null; + } + else if (!model.IncludeExtendedMetadata && (model.ApiVersion == null || mod.InstalledVersion == null)) + { + var errors = new List(result.Errors); + errors.Add($"This API can't suggest an update because {nameof(model.ApiVersion)} or {nameof(mod.InstalledVersion)} are null, and you didn't specify {nameof(model.IncludeExtendedMetadata)} to get other info. See the SMAPI technical docs for usage."); + result.Errors = errors.ToArray(); + } + mods[mod.ID] = result; } @@ -120,8 +141,9 @@ namespace StardewModdingAPI.Web.Controllers /// The mod data to match. /// The wiki data. /// Whether to include extended metadata for each mod. + /// The SMAPI version installed by the player. /// Returns the mod data if found, else null. - private async Task GetModData(ModSearchEntryModel search, WikiModEntry[] wikiData, bool includeExtendedMetadata) + private async Task GetModData(ModSearchEntryModel search, WikiModEntry[] wikiData, bool includeExtendedMetadata, ISemanticVersion apiVersion) { // cross-reference data ModDataRecord record = this.ModDatabase.Get(search.ID); @@ -131,6 +153,10 @@ namespace StardewModdingAPI.Web.Controllers // get latest versions ModEntryModel result = new ModEntryModel { ID = search.ID }; IList errors = new List(); + ModEntryVersionModel main = null; + ModEntryVersionModel optional = null; + ModEntryVersionModel unofficial = null; + ModEntryVersionModel unofficialForBeta = null; foreach (UpdateKey updateKey in updateKeys) { // validate update key @@ -151,76 +177,118 @@ namespace StardewModdingAPI.Web.Controllers // handle main version if (data.Version != null) { - if (!SemanticVersion.TryParse(data.Version, out ISemanticVersion version)) + ISemanticVersion version = this.GetMappedVersion(data.Version, wikiEntry?.MapRemoteVersions); + if (version == null) { errors.Add($"The update key '{updateKey}' matches a mod with invalid semantic version '{data.Version}'."); continue; } - if (this.IsNewer(version, result.Main?.Version)) - result.Main = new ModEntryVersionModel(version, data.Url); + if (this.IsNewer(version, main?.Version)) + main = new ModEntryVersionModel(version, data.Url); } // handle optional version if (data.PreviewVersion != null) { - if (!SemanticVersion.TryParse(data.PreviewVersion, out ISemanticVersion version)) + ISemanticVersion version = this.GetMappedVersion(data.PreviewVersion, wikiEntry?.MapRemoteVersions); + if (version == null) { errors.Add($"The update key '{updateKey}' matches a mod with invalid optional semantic version '{data.PreviewVersion}'."); continue; } - if (this.IsNewer(version, result.Optional?.Version)) - result.Optional = new ModEntryVersionModel(version, data.Url); + if (this.IsNewer(version, optional?.Version)) + optional = new ModEntryVersionModel(version, data.Url); } } // get unofficial version - if (wikiEntry?.Compatibility.UnofficialVersion != null && this.IsNewer(wikiEntry.Compatibility.UnofficialVersion, result.Main?.Version) && this.IsNewer(wikiEntry.Compatibility.UnofficialVersion, result.Optional?.Version)) - result.Unofficial = new ModEntryVersionModel(wikiEntry.Compatibility.UnofficialVersion, $"{this.CompatibilityPageUrl}/#{wikiEntry.Anchor}"); + if (wikiEntry?.Compatibility.UnofficialVersion != null && this.IsNewer(wikiEntry.Compatibility.UnofficialVersion, main?.Version) && this.IsNewer(wikiEntry.Compatibility.UnofficialVersion, optional?.Version)) + unofficial = new ModEntryVersionModel(wikiEntry.Compatibility.UnofficialVersion, $"{this.CompatibilityPageUrl}/#{wikiEntry.Anchor}"); // get unofficial version for beta if (wikiEntry?.HasBetaInfo == true) { - result.HasBetaInfo = true; if (wikiEntry.BetaCompatibility.Status == WikiCompatibilityStatus.Unofficial) { if (wikiEntry.BetaCompatibility.UnofficialVersion != null) { - result.UnofficialForBeta = (wikiEntry.BetaCompatibility.UnofficialVersion != null && this.IsNewer(wikiEntry.BetaCompatibility.UnofficialVersion, result.Main?.Version) && this.IsNewer(wikiEntry.BetaCompatibility.UnofficialVersion, result.Optional?.Version)) + unofficialForBeta = (wikiEntry.BetaCompatibility.UnofficialVersion != null && this.IsNewer(wikiEntry.BetaCompatibility.UnofficialVersion, main?.Version) && this.IsNewer(wikiEntry.BetaCompatibility.UnofficialVersion, optional?.Version)) ? new ModEntryVersionModel(wikiEntry.BetaCompatibility.UnofficialVersion, $"{this.CompatibilityPageUrl}/#{wikiEntry.Anchor}") : null; } else - result.UnofficialForBeta = result.Unofficial; + unofficialForBeta = unofficial; } } // fallback to preview if latest is invalid - if (result.Main == null && result.Optional != null) + if (main == null && optional != null) { - result.Main = result.Optional; - result.Optional = null; + main = optional; + optional = null; } // special cases if (result.ID == "Pathoschild.SMAPI") { - if (result.Main != null) - result.Main.Url = "https://smapi.io/"; - if (result.Optional != null) - result.Optional.Url = "https://smapi.io/"; + if (main != null) + main.Url = "https://smapi.io/"; + if (optional != null) + optional.Url = "https://smapi.io/"; + } + + // get recommended update (if any) + ISemanticVersion installedVersion = this.GetMappedVersion(search.InstalledVersion?.ToString(), wikiEntry?.MapLocalVersions); + if (apiVersion != null && installedVersion != null) + { + // get newer versions + List updates = new List(); + if (this.IsRecommendedUpdate(installedVersion, main?.Version, useBetaChannel: true)) + updates.Add(main); + if (this.IsRecommendedUpdate(installedVersion, optional?.Version, useBetaChannel: installedVersion.IsPrerelease())) + updates.Add(optional); + if (this.IsRecommendedUpdate(installedVersion, unofficial?.Version, useBetaChannel: search.IsBroken)) + updates.Add(unofficial); + if (this.IsRecommendedUpdate(installedVersion, unofficialForBeta?.Version, useBetaChannel: apiVersion.IsPrerelease())) + updates.Add(unofficialForBeta); + + // get newest version + ModEntryVersionModel newest = null; + foreach (ModEntryVersionModel update in updates) + { + if (newest == null || update.Version.IsNewerThan(newest.Version)) + newest = update; + } + + // set field + result.SuggestedUpdate = newest != null + ? new ModEntryVersionModel(newest.Version, newest.Url) + : null; } // add extended metadata - if (includeExtendedMetadata && (wikiEntry != null || record != null)) - result.Metadata = new ModExtendedMetadataModel(wikiEntry, record); + if (includeExtendedMetadata) + result.Metadata = new ModExtendedMetadataModel(wikiEntry, record, main: main, optional: optional, unofficial: unofficial, unofficialForBeta: unofficialForBeta); // add result result.Errors = errors.ToArray(); return result; } + /// Get whether a given version should be offered to the user as an update. + /// The current semantic version. + /// The target semantic version. + /// Whether the user enabled the beta channel and should be offered prerelease updates. + private bool IsRecommendedUpdate(ISemanticVersion currentVersion, ISemanticVersion newVersion, bool useBetaChannel) + { + return + newVersion != null + && newVersion.IsNewerThan(currentVersion) + && (useBetaChannel || !newVersion.IsPrerelease()); + } + /// Get whether a version is newer than an version. /// The current version. /// The other version. @@ -260,7 +328,7 @@ namespace StardewModdingAPI.Web.Controllers /// The specified update keys. /// The mod's entry in SMAPI's internal database. /// The mod's entry in the wiki list. - public IEnumerable GetUpdateKeys(string[] specifiedKeys, ModDataRecord record, WikiModEntry entry) + private IEnumerable GetUpdateKeys(string[] specifiedKeys, ModDataRecord record, WikiModEntry entry) { IEnumerable GetRaw() { @@ -301,5 +369,49 @@ namespace StardewModdingAPI.Web.Controllers yield return key; } } + + /// Get a semantic local version for update checks. + /// The version to parse. + /// A map of version replacements. + private ISemanticVersion GetMappedVersion(string version, IDictionary map) + { + // try mapped version + string rawNewVersion = this.GetRawMappedVersion(version, map); + if (SemanticVersion.TryParse(rawNewVersion, out ISemanticVersion parsedNew)) + return parsedNew; + + // return original version + return SemanticVersion.TryParse(version, out ISemanticVersion parsedOld) + ? parsedOld + : null; + } + + /// Get a semantic local version for update checks. + /// The version to map. + /// A map of version replacements. + private string GetRawMappedVersion(string version, IDictionary map) + { + if (version == null || map == null || !map.Any()) + return version; + + // match exact raw version + if (map.ContainsKey(version)) + return map[version]; + + // match parsed version + if (SemanticVersion.TryParse(version, out ISemanticVersion parsed)) + { + if (map.ContainsKey(parsed.ToString())) + return map[parsed.ToString()]; + + foreach (var pair in map) + { + if (SemanticVersion.TryParse(pair.Key, out ISemanticVersion target) && parsed.Equals(target) && SemanticVersion.TryParse(pair.Value, out ISemanticVersion newVersion)) + return newVersion.ToString(); + } + } + + return version; + } } } diff --git a/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMod.cs b/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMod.cs index fddf99ee..8569984a 100644 --- a/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMod.cs +++ b/src/SMAPI.Web/Framework/Caching/Wiki/CachedWikiMod.cs @@ -1,6 +1,9 @@ using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; +using MongoDB.Bson.Serialization.Options; using StardewModdingAPI.Toolkit; using StardewModdingAPI.Toolkit.Framework.Clients.Wiki; @@ -109,6 +112,17 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki /// The URL to the latest unofficial update, if applicable. public string BetaUnofficialUrl { get; set; } + /**** + ** Version maps + ****/ + /// Maps local versions to a semantic version for update checks. + [BsonDictionaryOptions(Representation = DictionaryRepresentation.ArrayOfArrays)] + public IDictionary MapLocalVersions { get; set; } + + /// Maps remote versions to a semantic version for update checks. + [BsonDictionaryOptions(Representation = DictionaryRepresentation.ArrayOfArrays)] + public IDictionary MapRemoteVersions { get; set; } + /********* ** Accessors @@ -154,6 +168,10 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki this.BetaBrokeIn = mod.BetaCompatibility?.BrokeIn; this.BetaUnofficialVersion = mod.BetaCompatibility?.UnofficialVersion?.ToString(); this.BetaUnofficialUrl = mod.BetaCompatibility?.UnofficialUrl; + + // version maps + this.MapLocalVersions = mod.MapLocalVersions; + this.MapRemoteVersions = mod.MapRemoteVersions; } /// Reconstruct the original model. @@ -186,7 +204,11 @@ namespace StardewModdingAPI.Web.Framework.Caching.Wiki BrokeIn = this.MainBrokeIn, UnofficialVersion = this.MainUnofficialVersion != null ? new SemanticVersion(this.MainUnofficialVersion) : null, UnofficialUrl = this.MainUnofficialUrl - } + }, + + // version maps + MapLocalVersions = this.MapLocalVersions, + MapRemoteVersions = this.MapRemoteVersions }; // beta compatibility diff --git a/src/SMAPI.Web/Views/Index/Privacy.cshtml b/src/SMAPI.Web/Views/Index/Privacy.cshtml index 356580b4..914384a8 100644 --- a/src/SMAPI.Web/Views/Index/Privacy.cshtml +++ b/src/SMAPI.Web/Views/Index/Privacy.cshtml @@ -24,7 +24,7 @@

    This website and SMAPI's web API are hosted by Amazon Web Services. Their servers may automatically collect diagnostics like your IP address, but this information is not visible to SMAPI's web application or developers. For more information, see the Amazon Privacy Notice.

    Update checks

    -

    SMAPI notifies you when there's a new version of SMAPI or your mods available. To do so, it sends your SMAPI and mod versions to its web API. No personal information is stored by the web application, but see web logging.

    +

    SMAPI notifies you when there's a new version of SMAPI or your mods available. To do so, it sends your game/SMAPI/mod versions and platform type to its web API. No personal information is stored by the web application, but see web logging.

    You can disable update checks, and no information will be transmitted to the web API. To do so:

      diff --git a/src/SMAPI.Web/wwwroot/SMAPI.metadata.json b/src/SMAPI.Web/wwwroot/SMAPI.metadata.json index e4c0a6f6..553b6934 100644 --- a/src/SMAPI.Web/wwwroot/SMAPI.metadata.json +++ b/src/SMAPI.Web/wwwroot/SMAPI.metadata.json @@ -14,11 +14,6 @@ * other fields if no ID was specified. This doesn't include the latest ID, if any. Multiple * variants can be separated with '|'. * - * - MapLocalVersions and MapRemoteVersions correct local manifest versions and remote versions - * during update checks. For example, if the API returns version '1.1-1078' where '1078' is - * intended to be a build number, MapRemoteVersions can map it to '1.1' when comparing to the - * mod's current version. This is only meant to support legacy mods with injected update keys. - * * Versioned metadata * ================== * Each record can also specify extra metadata using the field keys below. @@ -122,91 +117,6 @@ "Default | UpdateKey": "Nexus:1820" }, - - /********* - ** Map versions - *********/ - "Adjust Artisan Prices": { - "ID": "ThatNorthernMonkey.AdjustArtisanPrices", - "FormerIDs": "1e36d4ca-c7ef-4dfb-9927-d27a6c3c8bdc", // changed in 0.0.2-pathoschild-update - "MapRemoteVersions": { "0.01": "0.0.1" } - }, - - "Almighty Farming Tool": { - "ID": "439", - "MapRemoteVersions": { - "1.21": "1.2.1", - "1.22-unofficial.3.mizzion": "1.2.2-unofficial.3.mizzion" - } - }, - - "Basic Sprinkler Improved": { - "ID": "lrsk_sdvm_bsi.0117171308", - "MapRemoteVersions": { "1.0.2": "1.0.1-release" } // manifest not updated - }, - - "Better Shipping Box": { - "ID": "Kithio:BetterShippingBox", - "MapLocalVersions": { "1.0.1": "1.0.2" } - }, - - "Chefs Closet": { - "ID": "Duder.ChefsCloset", - "MapLocalVersions": { "1.3-1": "1.3" } - }, - - "Configurable Machines": { - "ID": "21da6619-dc03-4660-9794-8e5b498f5b97", - "MapLocalVersions": { "1.2-beta": "1.2" } - }, - - "Crafting Counter": { - "ID": "lolpcgaming.CraftingCounter", - "MapRemoteVersions": { "1.1": "1.0" } // not updated in manifest - }, - - "Custom Linens": { - "ID": "Mevima.CustomLinens", - "MapRemoteVersions": { "1.1": "1.0" } // manifest not updated - }, - - "Dynamic Horses": { - "ID": "Bpendragon-DynamicHorses", - "MapRemoteVersions": { "1.2": "1.1-release" } // manifest not updated - }, - - "Dynamic Machines": { - "ID": "DynamicMachines", - "MapLocalVersions": { "1.1": "1.1.1" } - }, - - "Multiple Sprites and Portraits On Rotation (File Loading)": { - "ID": "FileLoading", - "MapLocalVersions": { "1.1": "1.12" } - }, - - "Relationship Status": { - "ID": "relationshipstatus", - "MapRemoteVersions": { "1.0.5": "1.0.4" } // not updated in manifest - }, - - "ReRegeneration": { - "ID": "lrsk_sdvm_rerg.0925160827", - "MapLocalVersions": { "1.1.2-release": "1.1.2" } - }, - - "Showcase Mod": { - "ID": "Igorious.Showcase", - "MapLocalVersions": { "0.9-500": "0.9" } - }, - - "Siv's Marriage Mod": { - "ID": "6266959802", // official version - "FormerIDs": "Siv.MarriageMod | medoli900.Siv's Marriage Mod", // 1.2.3-unofficial versions - "MapLocalVersions": { "0.0": "1.4" } - }, - - /********* ** Obsolete *********/ @@ -477,12 +387,6 @@ "~1.0.0 | Status": "AssumeBroken" // broke in Stardew Valley 1.3.29 (runtime errors) }, - "Skill Prestige: Cooking Adapter": { - "ID": "Alphablackwolf.CookingSkillPrestigeAdapter", - "FormerIDs": "20d6b8a3-b6e7-460b-a6e4-07c2b0cb6c63", // changed circa 1.1 - "MapRemoteVersions": { "1.2.3": "1.1" } // manifest not updated - }, - "Skull Cave Saver": { "ID": "cantorsdust.SkullCaveSaver", "FormerIDs": "8ac06349-26f7-4394-806c-95d48fd35774 | community.SkullCaveSaver", // changed in 1.1 and 1.2.2 @@ -501,7 +405,6 @@ "Stephan's Lots of Crops": { "ID": "stephansstardewcrops", - "MapRemoteVersions": { "1.41": "1.1" }, // manifest not updated "~1.1 | Status": "AssumeBroken" // broke in SDV 1.3 (overwrites vanilla items) }, diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index 50bd562a..77b17c8a 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -593,27 +593,19 @@ namespace StardewModdingAPI.Framework ISemanticVersion updateFound = null; try { - ModEntryModel response = client.GetModInfo(new[] { new ModSearchEntryModel("Pathoschild.SMAPI", new[] { $"GitHub:{this.Settings.GitHubProjectName}" }) }).Single().Value; - ISemanticVersion latestStable = response.Main?.Version; - ISemanticVersion latestBeta = response.Optional?.Version; + // fetch update check + ModEntryModel response = client.GetModInfo(new[] { new ModSearchEntryModel("Pathoschild.SMAPI", Constants.ApiVersion, new[] { $"GitHub:{this.Settings.GitHubProjectName}" }) }, apiVersion: Constants.ApiVersion, gameVersion: Constants.GameVersion, platform: Constants.Platform).Single().Value; + if (response.SuggestedUpdate != null) + this.Monitor.Log($"You can update SMAPI to {response.SuggestedUpdate.Version}: {Constants.HomePageUrl}", LogLevel.Alert); + else + this.Monitor.Log(" SMAPI okay.", LogLevel.Trace); - if (latestStable == null && response.Errors.Any()) + // show errors + if (response.Errors.Any()) { this.Monitor.Log("Couldn't check for a new version of SMAPI. This won't affect your game, but you may not be notified of new versions if this keeps happening.", LogLevel.Warn); this.Monitor.Log($"Error: {string.Join("\n", response.Errors)}", LogLevel.Trace); } - else if (this.IsValidUpdate(Constants.ApiVersion, latestBeta, this.Settings.UseBetaChannel)) - { - updateFound = latestBeta; - this.Monitor.Log($"You can update SMAPI to {latestBeta}: {Constants.HomePageUrl}", LogLevel.Alert); - } - else if (this.IsValidUpdate(Constants.ApiVersion, latestStable, this.Settings.UseBetaChannel)) - { - updateFound = latestStable; - this.Monitor.Log($"You can update SMAPI to {latestStable}: {Constants.HomePageUrl}", LogLevel.Alert); - } - else - this.Monitor.Log(" SMAPI okay.", LogLevel.Trace); } catch (Exception ex) { @@ -646,12 +638,12 @@ namespace StardewModdingAPI.Framework .GetUpdateKeys(validOnly: true) .Select(p => p.ToString()) .ToArray(); - searchMods.Add(new ModSearchEntryModel(mod.Manifest.UniqueID, updateKeys.ToArray())); + searchMods.Add(new ModSearchEntryModel(mod.Manifest.UniqueID, mod.Manifest.Version, updateKeys.ToArray(), isBroken: mod.Status == ModMetadataStatus.Failed)); } // fetch results this.Monitor.Log($" Checking for updates to {searchMods.Count} mods...", LogLevel.Trace); - IDictionary results = client.GetModInfo(searchMods.ToArray()); + IDictionary results = client.GetModInfo(searchMods.ToArray(), apiVersion: Constants.ApiVersion, gameVersion: Constants.GameVersion, platform: Constants.Platform); // extract update alerts & errors var updates = new List>(); @@ -672,20 +664,9 @@ namespace StardewModdingAPI.Framework ); } - // parse versions - bool useBetaInfo = result.HasBetaInfo && Constants.ApiVersion.IsPrerelease(); - ISemanticVersion localVersion = mod.DataRecord?.GetLocalVersionForUpdateChecks(mod.Manifest.Version) ?? mod.Manifest.Version; - ISemanticVersion latestVersion = mod.DataRecord?.GetRemoteVersionForUpdateChecks(result.Main?.Version) ?? result.Main?.Version; - ISemanticVersion optionalVersion = mod.DataRecord?.GetRemoteVersionForUpdateChecks(result.Optional?.Version) ?? result.Optional?.Version; - ISemanticVersion unofficialVersion = useBetaInfo ? result.UnofficialForBeta?.Version : result.Unofficial?.Version; - - // show update alerts - if (this.IsValidUpdate(localVersion, latestVersion, useBetaChannel: true)) - updates.Add(Tuple.Create(mod, latestVersion, result.Main?.Url)); - else if (this.IsValidUpdate(localVersion, optionalVersion, useBetaChannel: localVersion.IsPrerelease())) - updates.Add(Tuple.Create(mod, optionalVersion, result.Optional?.Url)); - else if (this.IsValidUpdate(localVersion, unofficialVersion, useBetaChannel: mod.Status == ModMetadataStatus.Failed)) - updates.Add(Tuple.Create(mod, unofficialVersion, useBetaInfo ? result.UnofficialForBeta?.Url : result.Unofficial?.Url)); + // handle update + if (result.SuggestedUpdate != null) + updates.Add(Tuple.Create(mod, result.SuggestedUpdate.Version, result.SuggestedUpdate.Url)); } // show update errors @@ -720,18 +701,6 @@ namespace StardewModdingAPI.Framework }).Start(); } - /// Get whether a given version should be offered to the user as an update. - /// The current semantic version. - /// The target semantic version. - /// Whether the user enabled the beta channel and should be offered prerelease updates. - private bool IsValidUpdate(ISemanticVersion currentVersion, ISemanticVersion newVersion, bool useBetaChannel) - { - return - newVersion != null - && newVersion.IsNewerThan(currentVersion) - && (useBetaChannel || !newVersion.IsPrerelease()); - } - /// Create a directory path if it doesn't exist. /// The directory path. private void VerifyPath(string path) -- cgit From 41a809a2e063eec9c39868768512084e0a14256f Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 2 Oct 2019 17:37:14 -0400 Subject: fix render events not raised during minigames --- docs/release-notes.md | 1 + src/SMAPI/Framework/SGame.cs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 5f643f07..3771ec19 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -123,6 +123,7 @@ For modders: * Fixed issue where, when a mod's `IAssetEditor` uses `asset.ReplaceWith` on a texture asset while playing in non-English, any changes from that point won't affect subsequent cached asset loads. * Fixed asset propagation for NPC portraits resetting any unique portraits (e.g. Maru's hospital portrait) to the default. * Fixed changes to `Data\NPCDispositions` not always propagated correctly to existing NPCs. + * Fixed `Rendering`/`Rendered` events not raised during minigames. * Fixed `LoadStageChanged` event not raising correct flags in some cases when creating a new save. * Fixed `GetApi` without an interface not checking if all mods are loaded. diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index cabbbc3a..aa84295c 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -908,6 +908,14 @@ namespace StardewModdingAPI.Framework } else if (Game1.currentMinigame != null) { + int batchEnds = 0; + + if (events.Rendering.HasListeners()) + { + Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + events.Rendering.RaiseEmpty(); + Game1.spriteBatch.End(); + } Game1.currentMinigame.draw(Game1.spriteBatch); if (Game1.globalFade && !Game1.menuUp && (!Game1.nameSelectUp || Game1.messagePause)) { @@ -917,11 +925,21 @@ namespace StardewModdingAPI.Framework } this.drawOverlays(Game1.spriteBatch); if (target_screen == null) + { + if (++batchEnds == 1 && events.Rendered.HasListeners()) + { + Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); + events.Rendered.RaiseEmpty(); + Game1.spriteBatch.End(); + } return; + } this.GraphicsDevice.SetRenderTarget((RenderTarget2D)null); this.GraphicsDevice.Clear(Game1.bgColor); Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone); Game1.spriteBatch.Draw((Texture2D)target_screen, Vector2.Zero, new Microsoft.Xna.Framework.Rectangle?(target_screen.Bounds), Microsoft.Xna.Framework.Color.White, 0.0f, Vector2.Zero, Game1.options.zoomLevel, SpriteEffects.None, 1f); + if (++batchEnds == 1) + events.Rendered.RaiseEmpty(); Game1.spriteBatch.End(); } else if (Game1.showingEndOfNightStuff) -- cgit From f0f348bd5f5f4aa27030febe8a057eab9c50db7d Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 24 Nov 2019 12:13:34 -0500 Subject: update packages --- docs/release-notes.md | 2 +- .../SMAPI.ModBuildConfig.Analyzer.Tests.csproj | 2 +- src/SMAPI.Tests/SMAPI.Tests.csproj | 4 ++-- src/SMAPI.Toolkit/SMAPI.Toolkit.csproj | 4 ++-- src/SMAPI.Web/SMAPI.Web.csproj | 16 ++++++++-------- src/SMAPI/SMAPI.csproj | 4 ++-- 6 files changed, 16 insertions(+), 16 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index 3771ec19..f11d285c 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -115,7 +115,7 @@ For modders: * Trace logs when loading mods are now more clear. * Clarified update-check errors for mods with multiple update keys. * `SemanticVersion` no longer omits `.0` patch numbers when formatting versions, for better [semver](https://semver.org/) conformity (e.g. `3.0` is now formatted as `3.0.0`). - * Updated dependencies (including Json.NET 11.0.2 → 12.0.2 and Mono.Cecil 0.10.1 → 0.11). + * Updated dependencies (including Json.NET 11.0.2 → 12.0.3 and Mono.Cecil 0.10.1 → 0.11.1). * Fixes: * Fixed custom maps loaded from `.xnb` files not having their tilesheet paths automatically adjusted. * Fixed custom maps loaded from the mod folder with tilesheets in a subfolder not working crossplatform. All tilesheet paths are now normalized for the OS automatically. diff --git a/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj b/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj index e7c3e3dc..7e3ce7d4 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj +++ b/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/SMAPI.Tests/SMAPI.Tests.csproj b/src/SMAPI.Tests/SMAPI.Tests.csproj index 84a05aee..639c22a4 100644 --- a/src/SMAPI.Tests/SMAPI.Tests.csproj +++ b/src/SMAPI.Tests/SMAPI.Tests.csproj @@ -16,8 +16,8 @@ - - + + diff --git a/src/SMAPI.Toolkit/SMAPI.Toolkit.csproj b/src/SMAPI.Toolkit/SMAPI.Toolkit.csproj index a932c41b..3bb7e313 100644 --- a/src/SMAPI.Toolkit/SMAPI.Toolkit.csproj +++ b/src/SMAPI.Toolkit/SMAPI.Toolkit.csproj @@ -13,8 +13,8 @@ - - + + diff --git a/src/SMAPI.Web/SMAPI.Web.csproj b/src/SMAPI.Web/SMAPI.Web.csproj index c6ee7594..8a7ca741 100644 --- a/src/SMAPI.Web/SMAPI.Web.csproj +++ b/src/SMAPI.Web/SMAPI.Web.csproj @@ -12,19 +12,19 @@ - - - - - + + + + + - - + + - + diff --git a/src/SMAPI/SMAPI.csproj b/src/SMAPI/SMAPI.csproj index 62002a40..4952116f 100644 --- a/src/SMAPI/SMAPI.csproj +++ b/src/SMAPI/SMAPI.csproj @@ -18,8 +18,8 @@ - - + + -- cgit From 6b047586425ae407e15c2a65ea4baa70a389d95b Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 24 Nov 2019 13:43:38 -0500 Subject: polish release notes --- docs/release-notes.md | 82 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 50 insertions(+), 32 deletions(-) (limited to 'docs/release-notes.md') diff --git a/docs/release-notes.md b/docs/release-notes.md index f11d285c..a891c495 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -1,80 +1,94 @@ ← [README](README.md) # Release notes -## 3.0 (upcoming release) -These changes have not been released yet. +## 3.0 +Released 26 November 2019 for Stardew Valley 1.4. ### Release highlights For players: * **Updated for Stardew Valley 1.4.** - SMAPI 3.0 adds compatibility with the latest game version, and improves mod APIs for changes in the game code. + SMAPI 3.0 adds compatibility with the latest game version, and improves mod APIs for changes in + the game code. * **Improved performance.** SMAPI should have less impact on game performance and startup time for some players. * **Automatic save fixing and more error recovery.** - SMAPI now detects and prevents more crashes due to game/mod bugs, or due to removing mods which add custom locations or NPCs. + SMAPI now detects and prevents more crashes due to game/mod bugs, and automatically fixes your + save if you remove some custom-content mods. * **Improved mod scanning.** - SMAPI now supports some non-standard mod structures automatically, improves compatibility with the Vortex mod manager, and improves various error/skip messages related to mod loading. + SMAPI now supports some non-standard mod structures automatically, improves compatibility with + the Vortex mod manager, and improves various error/skip messages related to mod loading. * **Overhauled update checks.** - SMAPI update checks are now handled entirely on the web server and support community-defined version mappings. For example, that means false update alerts can now be solved by the community for all players. + SMAPI update checks are now handled entirely on the web server and support community-defined + version mappings. In particular, false update alerts due to author mistakes can now be solved by + the community for all players. * **Fixed many bugs and edge cases.** For modders: * **New event system.** - SMAPI 3.0 removes the deprecated static events in favor of the new `helper.Events` API. The event engine has been rewritten to make events more efficient, add events that weren't possible before, make existing events more useful, and make event usage and behavior more consistent. When a mod makes changes in an event handler, those changes are now also reflected in the next event raise. + SMAPI 3.0 removes the deprecated static events in favor of the new `helper.Events` API. The event + engine is rewritten to make events more efficient, add events that weren't possible before, make + existing events more useful, and make event usage and behavior more consistent. When a mod makes + changes in an event handler, those changes are now also reflected in the next event raise. * **Improved mod build package.** - The [mod build package](https://www.nuget.org/packages/Pathoschild.Stardew.ModBuildConfig) has been improved to include the `assets` folder by default if present, support the new `.csproj` project format, enable mod `.pdb` files automatically (to provide line numbers in error messages), add optional Harmony support, and fix some bugs and edge cases. This also adds compatibility with SMAPI 3.0 and Stardew Valley 1.4, and drops support for older versions. + The [mod build package](https://www.nuget.org/packages/Pathoschild.Stardew.ModBuildConfig) now + includes the `assets` folder by default if present, supports the new `.csproj` project format, + enables mod `.pdb` files automatically (to provide line numbers in error messages), adds optional + Harmony support, and fixes some bugs and edge cases. This also adds compatibility with SMAPI 3.0 + and Stardew Valley 1.4, and drops support for older versions. -* **Mods now loaded earlier.** - SMAPI now loads mods much earlier, before the game is initialised. That lets mods do things that were difficult before, like intercepting some core assets. +* **Mods loaded earlier.** + SMAPI now loads mods much earlier, before the game is initialised. That lets mods do things that + were difficult before, like intercepting some core assets. -* **Added initial Android support.** - SMAPI now automatically detects when it's running on Android, and updates the `Constants.TargetPlatform` for mods to use. +* **Improved Android support.** + SMAPI now automatically detects when it's running on Android, and updates `Constants.TargetPlatform` + so mods can adjust their logic if needed. The Save Backup mod is also now Android-compatible. * **Improved asset propagation.** - SMAPI now automatically propagates asset changes for farm animal data, NPC default location data, critter textures, and `DayTimeMoneyBox` buttons. Every loaded texture now also has a `Name` field so mods can check which asset a texture was loaded for. + SMAPI now automatically propagates asset changes for farm animal data, NPC default location data, + critter textures, and `DayTimeMoneyBox` buttons. Every loaded texture now also has a `Name` field + so mods can check which asset a texture was loaded for. * **Breaking changes:** - See _[migrate to SMAPI 3.0](https://stardewvalleywiki.com/Modding:Migrate_to_SMAPI_3.0)_ and _[migrate to Stardew Valley 1.4](https://stardewvalleywiki.com/Modding:Migrate_to_Stardew_Valley_1.4)_ for more info. + See _[migrate to SMAPI 3.0](https://stardewvalleywiki.com/Modding:Migrate_to_SMAPI_3.0)_ and + _[migrate to Stardew Valley 1.4](https://stardewvalleywiki.com/Modding:Migrate_to_Stardew_Valley_1.4)_ + for more info. ### For players * Changes: * Updated for Stardew Valley 1.4. * Improved performance. + * Reworked update checks and added community-defined version mapping, to reduce false update alerts due to author mistakes. + * SMAPI now removes invalid locations/NPCs when loading a save to prevent crashes. A warning is shown in-game when this happens. + * Added update checks for CurseForge mods. + * Added support for editing console colors via `smapi-internal/config.json` (for players with unusual consoles). + * Added support for setting SMAPI CLI arguments as environment variables for Linux/macOS compatibility. * Improved mod scanning: - * Now ignores metadata files and folders (like `__MACOSX` and `__folder_managed_by_vortex`) and content files (like `.txt` or `.png`), which avoids missing-manifest errors in some common cases. + * Now ignores metadata files/folders (like `__MACOSX` and `__folder_managed_by_vortex`) and content files (like `.txt` or `.png`), which avoids missing-manifest errors in some cases. * Now detects XNB mods more accurately, and consolidates multi-folder XNB mods in logged messages. - * SMAPI now automatically removes invalid content when loading a save to prevent crashes. A warning is shown in-game when this happens. This applies for locations and NPCs. - * Added update checks for CurseForge mods. - * Added support for configuring console colors via `smapi-internal/config.json` (intended for players with unusual consoles). - * Added support for specifying SMAPI command-line arguments as environment variables for Linux/Mac compatibility. - * Overhauled update checks and added community-defined version mapping. * Improved launch script compatibility on Linux (thanks to kurumushi and toastal!). * Made error messages more user-friendly in some cases. * Save Backup now works in the background, to avoid affecting startup time for players with a large number of saves. - * The installer now recognises custom game paths stored in `stardewvalley.targets`. + * The installer now recognises custom game paths stored in [`stardewvalley.targets`](http://smapi.io/package/custom-game-path). * Duplicate-mod errors now show the mod version in each folder. * Update checks are now faster in some cases. * Updated mod compatibility list. * Updated SMAPI/game version map. * Fixes: - * Fixed mods needing to load custom `Map` assets before the game accesses them (SMAPI will now do so automatically). + * Fixed some assets not updated when you switch language to English. + * Fixed lag in some cases due to incorrect asset caching when playing in non-English. + * Fixed lag when a mod invalidates many NPC portraits/sprites at once. * Fixed Console Commands not including upgraded tools in item commands. * Fixed Console Commands' item commands failing if a mod adds invalid item data. * Fixed Save Backup not pruning old backups if they're uncompressed. * Fixed issues when a farmhand reconnects before the game notices they're disconnected. * Fixed 'received message' logs shown in non-developer mode. - * Fixed some assets not updated when you switch language to English. - * Fixed lag in some cases due to incorrect asset caching when playing in non-English. - * Fixed lag when a mod invalidates many NPC portraits/sprites at once. - * Fixed map reloads resetting tilesheet seasons. - * Fixed map reloads not updating door warps. - * Fixed outdoor tilesheets being seasonalised when added to an indoor location. * Fixed various error messages and inconsistent spelling. * Fixed update-check error if a Nexus mod is marked as adult content. * Fixed update-check error if the Chucklefish page for an update key doesn't exist. @@ -85,7 +99,7 @@ For modders: * Added metadata links and dev notes (if any) to advanced info. * Now loads faster (since data is fetched in a background service). * Now continues working with cached data when the wiki is offline. - * Clicking a mod link now automatically adds it to the visible mods when the list is filtered. + * Clicking a mod link now automatically adds it to the visible mods if the list is filtered. * JSON validator: * Added JSON validator at [json.smapi.io](https://json.smapi.io), which lets you validate a JSON file against predefined mod formats. @@ -99,10 +113,11 @@ For modders: ### For modders * Breaking changes: - * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialized when `Entry` is called (use the `GameLaunched` event if you need to run code when the game is initialized). + * Mods are now loaded much earlier in the game launch. This lets mods intercept any content asset, but the game is not fully initialized when `Entry` is called; use the `GameLaunched` event if you need to run code when the game is initialized. * Removed all deprecated APIs. * Removed unused APIs: `Monitor.ExitGameImmediately`, `Translation.ModName`, and `Translation.Assert`. * Fixed `ICursorPosition.AbsolutePixels` not adjusted for zoom. + * `SemanticVersion` no longer omits `.0` patch numbers when formatting versions, for better [semver](https://semver.org/) conformity (e.g. `3.0` is now formatted as `3.0.0`). * Changes: * Added support for content pack translations. * Added `IContentPack.HasFile`, `Context.IsGameLaunched`, and `SemanticVersion.TryParse`. @@ -114,13 +129,16 @@ For modders: * Trace logs for a broken mod now list all detected issues (instead of the first one). * Trace logs when loading mods are now more clear. * Clarified update-check errors for mods with multiple update keys. - * `SemanticVersion` no longer omits `.0` patch numbers when formatting versions, for better [semver](https://semver.org/) conformity (e.g. `3.0` is now formatted as `3.0.0`). * Updated dependencies (including Json.NET 11.0.2 → 12.0.3 and Mono.Cecil 0.10.1 → 0.11.1). * Fixes: + * Fixed map reloads resetting tilesheet seasons. + * Fixed map reloads not updating door warps. + * Fixed outdoor tilesheets being seasonalised when added to an indoor location. + * Fixed mods needing to load custom `Map` assets before the game accesses them. SMAPI now does so automatically. * Fixed custom maps loaded from `.xnb` files not having their tilesheet paths automatically adjusted. * Fixed custom maps loaded from the mod folder with tilesheets in a subfolder not working crossplatform. All tilesheet paths are now normalized for the OS automatically. * Fixed issue where mod changes weren't tracked correctly for raising events in some cases. Events now reflect a frozen snapshot of the game state, and any mod changes are reflected in the next event tick. - * Fixed issue where, when a mod's `IAssetEditor` uses `asset.ReplaceWith` on a texture asset while playing in non-English, any changes from that point won't affect subsequent cached asset loads. + * Fixed issue where, when a mod's `IAssetEditor` uses `asset.ReplaceWith` on a texture asset while playing in non-English, any changes from that point forth wouldn't affect subsequent cached asset loads. * Fixed asset propagation for NPC portraits resetting any unique portraits (e.g. Maru's hospital portrait) to the default. * Fixed changes to `Data\NPCDispositions` not always propagated correctly to existing NPCs. * Fixed `Rendering`/`Rendered` events not raised during minigames. -- cgit