From a432477ea31c32e62fb347aef75861ab7ef62510 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 30 Dec 2016 12:04:27 -0500 Subject: fallback to launching SMAPI without a terminal on Linux if the terminal is unavailable (#198) --- src/StardewModdingAPI/Framework/Monitor.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src/StardewModdingAPI/Framework') diff --git a/src/StardewModdingAPI/Framework/Monitor.cs b/src/StardewModdingAPI/Framework/Monitor.cs index cf46a474..0989bb7e 100644 --- a/src/StardewModdingAPI/Framework/Monitor.cs +++ b/src/StardewModdingAPI/Framework/Monitor.cs @@ -37,6 +37,9 @@ namespace StardewModdingAPI.Framework /// Whether to show trace messages in the console. internal bool ShowTraceInConsole { get; set; } + /// Whether to write anything to the console. This should be disabled if no console is available. + internal bool WriteToConsole { get; set; } = true; + /********* ** Public methods @@ -108,7 +111,7 @@ namespace StardewModdingAPI.Framework message = $"[{DateTime.Now:HH:mm:ss} {levelStr} {source}] {message}"; // log - if (this.ShowTraceInConsole || level != LogLevel.Trace) + if (this.WriteToConsole && (this.ShowTraceInConsole || level != LogLevel.Trace)) { Console.ForegroundColor = color; Console.WriteLine(message); -- cgit From 40bc8f57c71d12d49bad24074cfe3279efe12850 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 14 Jan 2017 00:59:19 -0500 Subject: add support for incompatible mod version ranges --- release-notes.md | 3 +++ .../Framework/Models/IncompatibleMod.cs | 18 ++++++++++++------ src/StardewModdingAPI/Program.cs | 2 +- src/StardewModdingAPI/StardewModdingAPI.data.json | 10 +++++----- 4 files changed, 21 insertions(+), 12 deletions(-) (limited to 'src/StardewModdingAPI/Framework') diff --git a/release-notes.md b/release-notes.md index 6cedbc4f..6c667c31 100644 --- a/release-notes.md +++ b/release-notes.md @@ -8,6 +8,9 @@ For players: * Fixed issue where SMAPI couldn't be launched from Steam for some Linux players. * Updated list of incompatible mods. +For SMAPI developers: + * Added support for specifying a lower bound in mod incompatibility data. + ## 1.5 See [log](https://github.com/Pathoschild/SMAPI/compare/1.4...1.5). diff --git a/src/StardewModdingAPI/Framework/Models/IncompatibleMod.cs b/src/StardewModdingAPI/Framework/Models/IncompatibleMod.cs index 9bf06552..bcc62bb4 100644 --- a/src/StardewModdingAPI/Framework/Models/IncompatibleMod.cs +++ b/src/StardewModdingAPI/Framework/Models/IncompatibleMod.cs @@ -14,8 +14,11 @@ namespace StardewModdingAPI.Framework.Models /// The mod name. public string Name { get; set; } + /// The oldest incompatible mod version, or null for all past versions. + public string LowerVersion { get; set; } + /// The most recent incompatible mod version. - public string Version { get; set; } + public string UpperVersion { get; set; } /// The URL the user can check for an official updated version. public string UpdateUrl { get; set; } @@ -23,7 +26,7 @@ namespace StardewModdingAPI.Framework.Models /// The URL the user can check for an unofficial updated version. public string UnofficialUpdateUrl { get; set; } - /// A regular expression matching version strings to consider compatible, even if they technically precede . + /// A regular expression matching version strings to consider compatible, even if they technically precede . public string ForceCompatibleVersion { get; set; } @@ -34,14 +37,17 @@ namespace StardewModdingAPI.Framework.Models /// The current version of the matching mod. public bool IsCompatible(ISemanticVersion version) { - ISemanticVersion incompatibleVersion = new SemanticVersion(this.Version); + ISemanticVersion lowerVersion = this.LowerVersion != null ? new SemanticVersion(this.LowerVersion) : null; + ISemanticVersion upperVersion = new SemanticVersion(this.UpperVersion); - // allow newer versions - if (version.IsNewerThan(incompatibleVersion)) + // ignore versions not in range + if (lowerVersion != null && version.IsOlderThan(lowerVersion)) + return true; + if (version.IsNewerThan(upperVersion)) return true; // allow versions matching override return !string.IsNullOrWhiteSpace(this.ForceCompatibleVersion) && Regex.IsMatch(version.ToString(), this.ForceCompatibleVersion, RegexOptions.IgnoreCase); } } -} \ No newline at end of file +} diff --git a/src/StardewModdingAPI/Program.cs b/src/StardewModdingAPI/Program.cs index 58dbd87d..9d08c823 100644 --- a/src/StardewModdingAPI/Program.cs +++ b/src/StardewModdingAPI/Program.cs @@ -402,7 +402,7 @@ namespace StardewModdingAPI { if (!compatibility.IsCompatible(manifest.Version)) { - string warning = $"Skipped {compatibility.Name} ≤v{compatibility.Version} because this version is not compatible with the latest version of the game. Please check for a newer version of the mod here:"; + string warning = $"Skipped {compatibility.Name} {manifest.Version} because this version is not compatible with the latest version of the game. Please check for a newer version of the mod here:"; if (!string.IsNullOrWhiteSpace(compatibility.UpdateUrl)) warning += $"{Environment.NewLine}- official mod: {compatibility.UpdateUrl}"; if (!string.IsNullOrWhiteSpace(compatibility.UnofficialUpdateUrl)) diff --git a/src/StardewModdingAPI/StardewModdingAPI.data.json b/src/StardewModdingAPI/StardewModdingAPI.data.json index f350e8c5..464286af 100644 --- a/src/StardewModdingAPI/StardewModdingAPI.data.json +++ b/src/StardewModdingAPI/StardewModdingAPI.data.json @@ -9,15 +9,15 @@ This file contains advanced metadata for SMAPI. You shouldn't change this file. { "ID": "SPDSprinklersMod", "Name": "Better Sprinklers", - "Version": "2.1", + "UpperVersion": "2.1", "UpdateUrl": "http://www.nexusmods.com/stardewvalley/mods/41", "UnofficialUpdateUrl": "http://community.playstarbound.com/threads/125031", - "ForceCompatibleVersion": "^2.1-EntoPatch" + "ForceCompatibleVersion": "^2.1-EntoPatch" }, { "ID": "SPDChestLabel", "Name": "Chest Label System", - "Version": "1.5", + "UpperVersion": "1.5", "UpdateUrl": "http://www.nexusmods.com/stardewvalley/mods/242", "UnofficialUpdateUrl": "http://community.playstarbound.com/threads/125031", "ForceCompatibleVersion": "^1.5-EntoPatch" @@ -25,14 +25,14 @@ This file contains advanced metadata for SMAPI. You shouldn't change this file. { "ID": "CJBCheatsMenu", "Name": "CJB Cheats Menu", - "Version": "1.12", + "UpperVersion": "1.12", "UpdateUrl": "http://www.nexusmods.com/stardewvalley/mods/4", "ForceCompatibleVersion": "^1.12-EntoPatch" }, { "ID": "CJBItemSpawner", "Name": "CJB Item Spawner", - "Version": "1.5", + "UpperVersion": "1.5", "UpdateUrl": "http://www.nexusmods.com/stardewvalley/mods/93", "ForceCompatibleVersion": "^1.5-EntoPatch" } -- cgit From 0ac9e47ea2af8d09baa2df9568aa30dce790c950 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 14 Jan 2017 01:11:42 -0500 Subject: add support for custom incompatible-mod-version error text --- release-notes.md | 1 + src/StardewModdingAPI/Framework/Models/IncompatibleMod.cs | 4 ++++ src/StardewModdingAPI/Program.cs | 3 ++- 3 files changed, 7 insertions(+), 1 deletion(-) (limited to 'src/StardewModdingAPI/Framework') diff --git a/release-notes.md b/release-notes.md index 6c667c31..bede8849 100644 --- a/release-notes.md +++ b/release-notes.md @@ -10,6 +10,7 @@ For players: For SMAPI developers: * Added support for specifying a lower bound in mod incompatibility data. + * Added support for custom incompatible-mod-version error text. ## 1.5 See [log](https://github.com/Pathoschild/SMAPI/compare/1.4...1.5). diff --git a/src/StardewModdingAPI/Framework/Models/IncompatibleMod.cs b/src/StardewModdingAPI/Framework/Models/IncompatibleMod.cs index bcc62bb4..bcf5639c 100644 --- a/src/StardewModdingAPI/Framework/Models/IncompatibleMod.cs +++ b/src/StardewModdingAPI/Framework/Models/IncompatibleMod.cs @@ -29,6 +29,10 @@ namespace StardewModdingAPI.Framework.Models /// A regular expression matching version strings to consider compatible, even if they technically precede . public string ForceCompatibleVersion { get; set; } + /// The reason phrase to show in the warning, or null to use the default value. + /// "this version is incompatible with the latest version of the game" + public string ReasonPhrase { get; set; } + /********* ** Public methods diff --git a/src/StardewModdingAPI/Program.cs b/src/StardewModdingAPI/Program.cs index 9d08c823..e5c27e71 100644 --- a/src/StardewModdingAPI/Program.cs +++ b/src/StardewModdingAPI/Program.cs @@ -402,7 +402,8 @@ namespace StardewModdingAPI { if (!compatibility.IsCompatible(manifest.Version)) { - string warning = $"Skipped {compatibility.Name} {manifest.Version} because this version is not compatible with the latest version of the game. Please check for a newer version of the mod here:"; + string reasonPhrase = compatibility.ReasonPhrase ?? "this version is not compatible with the latest version of the game"; + string warning = $"Skipped {compatibility.Name} {manifest.Version} because {reasonPhrase}. Please check for a newer version of the mod here:"; if (!string.IsNullOrWhiteSpace(compatibility.UpdateUrl)) warning += $"{Environment.NewLine}- official mod: {compatibility.UpdateUrl}"; if (!string.IsNullOrWhiteSpace(compatibility.UnofficialUpdateUrl)) -- cgit From 83bdcd28386cebd36890565065912be4e3443603 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 14 Jan 2017 12:43:50 -0500 Subject: fix error loading mods if they have a .cache folder created on a different platform (#211) --- release-notes.md | 1 + .../Framework/AssemblyRewriting/CacheEntry.cs | 19 +++++++++++++++++-- src/StardewModdingAPI/Framework/ModAssemblyLoader.cs | 7 +++++-- 3 files changed, 23 insertions(+), 4 deletions(-) (limited to 'src/StardewModdingAPI/Framework') diff --git a/release-notes.md b/release-notes.md index 1c0409ea..8b4df6d7 100644 --- a/release-notes.md +++ b/release-notes.md @@ -6,6 +6,7 @@ See [log](https://github.com/Pathoschild/SMAPI/compare/stable...develop). For players: * Fixed issue where the installer couldn't find the game for some players on 32-bit Windows. * Fixed issue where SMAPI couldn't be launched from Steam for some Linux players. +* Fixed error loading mods if they have a `.cache` folder created on a different platform. * Updated list of incompatible mods. For mod developers: diff --git a/src/StardewModdingAPI/Framework/AssemblyRewriting/CacheEntry.cs b/src/StardewModdingAPI/Framework/AssemblyRewriting/CacheEntry.cs index a747eaa8..4c3b86fe 100644 --- a/src/StardewModdingAPI/Framework/AssemblyRewriting/CacheEntry.cs +++ b/src/StardewModdingAPI/Framework/AssemblyRewriting/CacheEntry.cs @@ -1,4 +1,5 @@ using System.IO; +using StardewModdingAPI.AssemblyRewriters; namespace StardewModdingAPI.Framework.AssemblyRewriting { @@ -14,6 +15,12 @@ namespace StardewModdingAPI.Framework.AssemblyRewriting /// The SMAPI version used to rewrite the assembly. public readonly string ApiVersion; + /// The target platform. + public readonly Platform Platform; + + /// The value for the machine used to rewrite the assembly. + public readonly string MachineName; + /// Whether to use the cached assembly instead of the original assembly. public readonly bool UseCachedAssembly; @@ -24,11 +31,15 @@ namespace StardewModdingAPI.Framework.AssemblyRewriting /// Construct an instance. /// The MD5 hash for the original assembly. /// The SMAPI version used to rewrite the assembly. + /// The target platform. + /// The value for the machine used to rewrite the assembly. /// Whether to use the cached assembly instead of the original assembly. - public CacheEntry(string hash, string apiVersion, bool useCachedAssembly) + public CacheEntry(string hash, string apiVersion, Platform platform, string machineName, bool useCachedAssembly) { this.Hash = hash; this.ApiVersion = apiVersion; + this.Platform = platform; + this.MachineName = machineName; this.UseCachedAssembly = useCachedAssembly; } @@ -36,10 +47,14 @@ namespace StardewModdingAPI.Framework.AssemblyRewriting /// The paths for the cached assembly. /// The MD5 hash of the original assembly. /// The current SMAPI version. - public bool IsUpToDate(CachePaths paths, string hash, ISemanticVersion currentVersion) + /// The target platform. + /// The value for the machine reading the assembly. + public bool IsUpToDate(CachePaths paths, string hash, ISemanticVersion currentVersion, Platform platform, string machineName) { return hash == this.Hash && this.ApiVersion == currentVersion.ToString() + && this.Platform == platform + && this.MachineName == machineName && (!this.UseCachedAssembly || File.Exists(paths.Assembly)); } } diff --git a/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs b/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs index a2c4ac23..e4760398 100644 --- a/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs +++ b/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs @@ -29,6 +29,8 @@ namespace StardewModdingAPI.Framework /// Encapsulates monitoring and logging. private readonly IMonitor Monitor; + /// The current game platform. + private readonly Platform TargetPlatform; /********* ** Public methods @@ -40,6 +42,7 @@ namespace StardewModdingAPI.Framework public ModAssemblyLoader(string cacheDirName, Platform targetPlatform, IMonitor monitor) { this.CacheDirName = cacheDirName; + this.TargetPlatform = targetPlatform; this.Monitor = monitor; this.AssemblyMap = Constants.GetAssemblyMap(targetPlatform); this.AssemblyTypeRewriter = new AssemblyTypeRewriter(this.AssemblyMap, monitor); @@ -58,7 +61,7 @@ namespace StardewModdingAPI.Framework CachePaths cachePaths = this.GetCachePaths(assemblyPath); { CacheEntry cacheEntry = File.Exists(cachePaths.Metadata) ? JsonConvert.DeserializeObject(File.ReadAllText(cachePaths.Metadata)) : null; - if (cacheEntry != null && cacheEntry.IsUpToDate(cachePaths, hash, Constants.ApiVersion)) + if (cacheEntry != null && cacheEntry.IsUpToDate(cachePaths, hash, Constants.ApiVersion, this.TargetPlatform, Environment.MachineName)) return new RewriteResult(assemblyPath, cachePaths, assemblyBytes, cacheEntry.Hash, cacheEntry.UseCachedAssembly, isNewerThanCache: false); // no rewrite needed } this.Monitor.Log($"Preprocessing {Path.GetFileName(assemblyPath)} for compatibility...", LogLevel.Trace); @@ -99,7 +102,7 @@ namespace StardewModdingAPI.Framework // cache all results foreach (RewriteResult result in results) { - CacheEntry cacheEntry = new CacheEntry(result.Hash, Constants.ApiVersion.ToString(), forceCacheAssemblies || result.UseCachedAssembly); + CacheEntry cacheEntry = new CacheEntry(result.Hash, Constants.ApiVersion.ToString(), this.TargetPlatform, Environment.MachineName, forceCacheAssemblies || result.UseCachedAssembly); File.WriteAllText(result.CachePaths.Metadata, JsonConvert.SerializeObject(cacheEntry)); if (forceCacheAssemblies || result.UseCachedAssembly) File.WriteAllBytes(result.CachePaths.Assembly, result.AssemblyBytes); -- cgit From 90e92ef61f0808688abf638ee5cb941215c1586f Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 14 Jan 2017 15:05:38 -0500 Subject: fix error when the console doesn't support colour (#206) --- release-notes.md | 1 + .../InteractiveInstaller.cs | 58 ++++++++++++++++------ src/StardewModdingAPI/Framework/Monitor.cs | 28 +++++++++-- src/StardewModdingAPI/LogWriter.cs | 11 ++-- 4 files changed, 76 insertions(+), 22 deletions(-) (limited to 'src/StardewModdingAPI/Framework') diff --git a/release-notes.md b/release-notes.md index 6189b386..cea89fc9 100644 --- a/release-notes.md +++ b/release-notes.md @@ -9,6 +9,7 @@ For players: * Fixed issue where SMAPI couldn't be launched from Steam for some Linux players. * Fixed issue where values in `config.json` were duplicated in some cases. * Fixed error loading mods that were released with a `.cache` folder from a different platform. +* Fixed error when the console doesn't support colour. * Updated list of incompatible mods. For mod developers: diff --git a/src/StardewModdingAPI.Installer/InteractiveInstaller.cs b/src/StardewModdingAPI.Installer/InteractiveInstaller.cs index 5f89caf2..d7279cf7 100644 --- a/src/StardewModdingAPI.Installer/InteractiveInstaller.cs +++ b/src/StardewModdingAPI.Installer/InteractiveInstaller.cs @@ -77,6 +77,9 @@ namespace StardewModdingApi.Installer "StardewModdingAPI-settings.json" // 1.0-1.4 }; + /// Whether the current console supports color formatting. + private static readonly bool ConsoleSupportsColor = InteractiveInstaller.GetConsoleSupportsColor(); + /********* ** Public methods @@ -253,18 +256,18 @@ namespace StardewModdingApi.Installer /**** ** exit ****/ - Console.ForegroundColor = ConsoleColor.DarkGreen; - Console.WriteLine("Done!"); + this.PrintColor("Done!", ConsoleColor.DarkGreen); if (platform == Platform.Windows) { - Console.WriteLine(action == ScriptAction.Install - ? "Don't forget to launch StardewModdingAPI.exe instead of the normal game executable. See the readme.txt for details." - : "If you manually changed shortcuts or Steam to launch SMAPI, don't forget to change those back." + this.PrintColor( + action == ScriptAction.Install + ? "Don't forget to launch StardewModdingAPI.exe instead of the normal game executable. See the readme.txt for details." + : "If you manually changed shortcuts or Steam to launch SMAPI, don't forget to change those back.", + ConsoleColor.DarkGreen ); } else if (action == ScriptAction.Install) - Console.WriteLine("You can launch the game the same way as before to play with mods."); - Console.ResetColor(); + this.PrintColor("You can launch the game the same way as before to play with mods.", ConsoleColor.DarkGreen); Console.ReadKey(); } @@ -287,6 +290,20 @@ namespace StardewModdingApi.Installer } } + /// Test whether the current console supports color formatting. + private static bool GetConsoleSupportsColor() + { + try + { + Console.ResetColor(); + return true; + } + catch (Exception) + { + return false; + } + } + #if SMAPI_FOR_WINDOWS /// Get the value of a key in the Windows registry. /// The full path of the registry key relative to HKLM. @@ -306,30 +323,39 @@ namespace StardewModdingApi.Installer /// The text to print. private void PrintDebug(string text) { - Console.ForegroundColor = ConsoleColor.DarkGray; - Console.WriteLine(text); - Console.ResetColor(); + this.PrintColor(text, ConsoleColor.DarkGray); } /// Print a warning message. /// The text to print. private void PrintWarning(string text) { - Console.ForegroundColor = ConsoleColor.DarkYellow; - Console.WriteLine(text); - Console.ResetColor(); + this.PrintColor(text, ConsoleColor.DarkYellow); } /// Print an error and pause the console if needed. /// The error text. private void ExitError(string error) { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine(error); - Console.ResetColor(); + this.PrintColor(error, ConsoleColor.Red); Console.ReadLine(); } + /// Print a message to the console. + /// The message text. + /// The text foreground color. + private void PrintColor(string text, ConsoleColor color) + { + if (InteractiveInstaller.ConsoleSupportsColor) + { + Console.ForegroundColor = color; + Console.WriteLine(text); + Console.ResetColor(); + } + else + Console.WriteLine(text); + } + /// Interactively ask the user to choose a value. /// The message to print. /// The allowed options (not case sensitive). diff --git a/src/StardewModdingAPI/Framework/Monitor.cs b/src/StardewModdingAPI/Framework/Monitor.cs index 0989bb7e..b492e5c7 100644 --- a/src/StardewModdingAPI/Framework/Monitor.cs +++ b/src/StardewModdingAPI/Framework/Monitor.cs @@ -34,6 +34,9 @@ namespace StardewModdingAPI.Framework /********* ** Accessors *********/ + /// Whether the current console supports color codes. + internal static readonly bool ConsoleSupportsColor = Monitor.GetConsoleSupportsColor(); + /// Whether to show trace messages in the console. internal bool ShowTraceInConsole { get; set; } @@ -113,11 +116,30 @@ namespace StardewModdingAPI.Framework // log if (this.WriteToConsole && (this.ShowTraceInConsole || level != LogLevel.Trace)) { - Console.ForegroundColor = color; - Console.WriteLine(message); - Console.ResetColor(); + if (Monitor.ConsoleSupportsColor) + { + Console.ForegroundColor = color; + Console.WriteLine(message); + Console.ResetColor(); + } + else + Console.WriteLine(message); } this.LogFile.WriteLine(message); } + + /// Test whether the current console supports color formatting. + private static bool GetConsoleSupportsColor() + { + try + { + Console.ResetColor(); + return true; + } + catch (Exception) + { + return false; + } + } } } \ No newline at end of file diff --git a/src/StardewModdingAPI/LogWriter.cs b/src/StardewModdingAPI/LogWriter.cs index 058fa649..9c2ef515 100644 --- a/src/StardewModdingAPI/LogWriter.cs +++ b/src/StardewModdingAPI/LogWriter.cs @@ -42,9 +42,14 @@ namespace StardewModdingAPI string output = $"[{message.LogTime}] {message.Message}"; if (message.PrintConsole) { - Console.ForegroundColor = message.Colour; - Console.WriteLine(message); - Console.ForegroundColor = ConsoleColor.Gray; + if (Monitor.ConsoleSupportsColor) + { + Console.ForegroundColor = message.Colour; + Console.WriteLine(message); + Console.ResetColor(); + } + else + Console.WriteLine(message); } this.LogFile.WriteLine(output); } -- cgit From f957af71d1533e6b3635c7f4ac31807367a99195 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 14 Jan 2017 15:53:28 -0500 Subject: fix console color support check (#206) --- src/StardewModdingAPI.Installer/InteractiveInstaller.cs | 4 ++-- src/StardewModdingAPI/Framework/Monitor.cs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'src/StardewModdingAPI/Framework') diff --git a/src/StardewModdingAPI.Installer/InteractiveInstaller.cs b/src/StardewModdingAPI.Installer/InteractiveInstaller.cs index d7279cf7..ef813eb3 100644 --- a/src/StardewModdingAPI.Installer/InteractiveInstaller.cs +++ b/src/StardewModdingAPI.Installer/InteractiveInstaller.cs @@ -295,12 +295,12 @@ namespace StardewModdingApi.Installer { try { - Console.ResetColor(); + Console.ForegroundColor = Console.ForegroundColor; return true; } catch (Exception) { - return false; + return false; // Mono bug } } diff --git a/src/StardewModdingAPI/Framework/Monitor.cs b/src/StardewModdingAPI/Framework/Monitor.cs index b492e5c7..39b567d8 100644 --- a/src/StardewModdingAPI/Framework/Monitor.cs +++ b/src/StardewModdingAPI/Framework/Monitor.cs @@ -133,12 +133,12 @@ namespace StardewModdingAPI.Framework { try { - Console.ResetColor(); + Console.ForegroundColor = Console.ForegroundColor; return true; } catch (Exception) { - return false; + return false; // Mono bug } } } -- cgit From 64a72c45e3c4b504c7a1b61a539f1cbc9b9d23cc Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 15 Jan 2017 19:21:26 -0500 Subject: deprecate events replaced by save events (#215) --- release-notes.md | 5 +++ src/StardewModdingAPI/Events/PlayerEvents.cs | 20 +++++++++-- src/StardewModdingAPI/Events/TimeEvents.cs | 10 +++++- .../Framework/InternalExtensions.cs | 21 ++++++++++++ src/StardewModdingAPI/Framework/ModRegistry.cs | 40 +++++++++++++++++----- 5 files changed, 84 insertions(+), 12 deletions(-) (limited to 'src/StardewModdingAPI/Framework') diff --git a/release-notes.md b/release-notes.md index ffcfd560..6b1ee02f 100644 --- a/release-notes.md +++ b/release-notes.md @@ -13,6 +13,11 @@ For players: * Updated list of incompatible mods. For mod developers: +* Added three events: `SaveEvents.BeforeSave`, `SaveEvents.AfterSave`, and `SaveEvents.AfterLoad`. +* Deprecated three events: + * `TimeEvents.OnNewDay` is unreliable, use `TimeEvents.DayOfMonthChanged` or `SaveEvents` instead; + * `PlayerEvents.LoadedGame` is replaced by `SaveEvents.AfterLoad`; + * `PlayerEvents.FarmerChanged` serves no purpose. * Fixed error when reading a custom JSON file from a directory that doesn't exist. For SMAPI developers: diff --git a/src/StardewModdingAPI/Events/PlayerEvents.cs b/src/StardewModdingAPI/Events/PlayerEvents.cs index 3f301b07..dd3ff220 100644 --- a/src/StardewModdingAPI/Events/PlayerEvents.cs +++ b/src/StardewModdingAPI/Events/PlayerEvents.cs @@ -14,9 +14,11 @@ namespace StardewModdingAPI.Events ** Events *********/ /// Raised after the player loads a saved game. + [Obsolete("Use " + nameof(SaveEvents) + "." + nameof(SaveEvents.AfterLoad) + " instead")] public static event EventHandler LoadedGame; /// Raised after the game assigns a new player character. This happens just before ; it's unclear how this would happen any other time. + [Obsolete("should no longer be used")] public static event EventHandler FarmerChanged; /// Raised after the player's inventory changes in any way (added or removed item, sorted, etc). @@ -34,7 +36,14 @@ namespace StardewModdingAPI.Events /// Whether the save has been loaded. This is always true. internal static void InvokeLoadedGame(IMonitor monitor, EventArgsLoadedGameChanged loaded) { - monitor.SafelyRaiseGenericEvent($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.LoadedGame)}", PlayerEvents.LoadedGame?.GetInvocationList(), null, loaded); + if (PlayerEvents.LoadedGame == null) + return; + + string name = $"{nameof(PlayerEvents)}.{nameof(PlayerEvents.LoadedGame)}"; + Delegate[] handlers = PlayerEvents.LoadedGame.GetInvocationList(); + + Program.DeprecationManager.WarnForEvent(handlers, name, "1.6", DeprecationLevel.Notice); + monitor.SafelyRaiseGenericEvent(name, handlers, null, loaded); } /// Raise a event. @@ -43,7 +52,14 @@ namespace StardewModdingAPI.Events /// The new player character. internal static void InvokeFarmerChanged(IMonitor monitor, Farmer priorFarmer, Farmer newFarmer) { - monitor.SafelyRaiseGenericEvent($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.FarmerChanged)}", PlayerEvents.FarmerChanged?.GetInvocationList(), null, new EventArgsFarmerChanged(priorFarmer, newFarmer)); + if (PlayerEvents.FarmerChanged == null) + return; + + string name = $"{nameof(PlayerEvents)}.{nameof(PlayerEvents.FarmerChanged)}"; + Delegate[] handlers = PlayerEvents.FarmerChanged.GetInvocationList(); + + Program.DeprecationManager.WarnForEvent(handlers, name, "1.6", DeprecationLevel.Notice); + monitor.SafelyRaiseGenericEvent(name, handlers, null, new EventArgsFarmerChanged(priorFarmer, newFarmer)); } /// Raise an event. diff --git a/src/StardewModdingAPI/Events/TimeEvents.cs b/src/StardewModdingAPI/Events/TimeEvents.cs index 1b367230..dedd7e77 100644 --- a/src/StardewModdingAPI/Events/TimeEvents.cs +++ b/src/StardewModdingAPI/Events/TimeEvents.cs @@ -22,6 +22,7 @@ namespace StardewModdingAPI.Events public static event EventHandler SeasonOfYearChanged; /// Raised when the player is transitioning to a new day and the game is performing its day update logic. This event is triggered twice: once after the game starts transitioning, and again after it finishes. + [Obsolete("Use " + nameof(TimeEvents) + "." + nameof(DayOfMonthChanged) + " or " + nameof(SaveEvents) + " instead")] public static event EventHandler OnNewDay; @@ -71,7 +72,14 @@ namespace StardewModdingAPI.Events /// Whether the game just started the transition (true) or finished it (false). internal static void InvokeOnNewDay(IMonitor monitor, int priorDay, int newDay, bool isTransitioning) { - monitor.SafelyRaiseGenericEvent($"{nameof(TimeEvents)}.{nameof(TimeEvents.OnNewDay)}", TimeEvents.OnNewDay?.GetInvocationList(), null, new EventArgsNewDay(priorDay, newDay, isTransitioning)); + if (TimeEvents.OnNewDay == null) + return; + + string name = $"{nameof(TimeEvents)}.{nameof(TimeEvents.OnNewDay)}"; + Delegate[] handlers = TimeEvents.OnNewDay.GetInvocationList(); + + Program.DeprecationManager.WarnForEvent(handlers, name, "1.6", DeprecationLevel.Notice); + monitor.SafelyRaiseGenericEvent(name, handlers, null, new EventArgsNewDay(priorDay, newDay, isTransitioning)); } } } diff --git a/src/StardewModdingAPI/Framework/InternalExtensions.cs b/src/StardewModdingAPI/Framework/InternalExtensions.cs index 415785d9..c4bd2d35 100644 --- a/src/StardewModdingAPI/Framework/InternalExtensions.cs +++ b/src/StardewModdingAPI/Framework/InternalExtensions.cs @@ -86,5 +86,26 @@ namespace StardewModdingAPI.Framework // anything else return exception.ToString(); } + + /**** + ** Deprecation + ****/ + /// Log a deprecation warning for mods using an event. + /// The deprecation manager to extend. + /// The event handlers. + /// A noun phrase describing what is deprecated. + /// The SMAPI version which deprecated it. + /// How deprecated the code is. + public static void WarnForEvent(this DeprecationManager deprecationManager, Delegate[] handlers, string nounPhrase, string version, DeprecationLevel severity) + { + if (handlers == null || !handlers.Any()) + return; + + foreach (Delegate handler in handlers) + { + string modName = Program.ModRegistry.GetModFrom(handler) ?? "an unknown mod"; // suppress stack trace for unknown mods, not helpful here + deprecationManager.Warn(modName, nounPhrase, version, severity); + } + } } } diff --git a/src/StardewModdingAPI/Framework/ModRegistry.cs b/src/StardewModdingAPI/Framework/ModRegistry.cs index b593142d..51ec7123 100644 --- a/src/StardewModdingAPI/Framework/ModRegistry.cs +++ b/src/StardewModdingAPI/Framework/ModRegistry.cs @@ -36,6 +36,34 @@ namespace StardewModdingAPI.Framework return (from mod in this.Mods select mod); } + /// Get the friendly mod name which handles a delegate. + /// The delegate to follow. + /// Returns the mod name, or null if the delegate isn't implemented by a known mod. + public string GetModFrom(Delegate @delegate) + { + return @delegate?.Target != null + ? this.GetModFrom(@delegate.Target.GetType()) + : null; + } + + /// Get the friendly mod name which defines a type. + /// The type to check. + /// Returns the mod name, or null if the type isn't part of a known mod. + public string GetModFrom(Type type) + { + // null + if (type == null) + return null; + + // known type + string assemblyName = type.Assembly.FullName; + if (this.ModNamesByAssembly.ContainsKey(assemblyName)) + return this.ModNamesByAssembly[assemblyName]; + + // not found + return null; + } + /// Get the friendly name for the closest assembly registered as a source of deprecation warnings. /// Returns the source name, or null if no registered assemblies were found. public string GetModFromStack() @@ -49,16 +77,10 @@ namespace StardewModdingAPI.Framework // search stack for a source assembly foreach (StackFrame frame in frames) { - // get assembly name MethodBase method = frame.GetMethod(); - Type type = method.ReflectedType; - if (type == null) - continue; - string assemblyName = type.Assembly.FullName; - - // get name if it's a registered source - if (this.ModNamesByAssembly.ContainsKey(assemblyName)) - return this.ModNamesByAssembly[assemblyName]; + string name = this.GetModFrom(method.ReflectedType); + if (name != null) + return name; } // no known assembly found -- cgit