diff options
author | Jesse Plamondon-Willard <github@jplamondonw.com> | 2017-07-08 12:54:06 -0400 |
---|---|---|
committer | Jesse Plamondon-Willard <github@jplamondonw.com> | 2017-07-08 12:54:06 -0400 |
commit | 1edd98aef027faa768f56cf0b3591e64e20ba096 (patch) | |
tree | aec210e2b44c9654f29572dd084206a4598896e1 /src/StardewModdingAPI | |
parent | 36930ffd7d363d6afd7f8cac4918c7d1c1c3e339 (diff) | |
parent | 8743c4115aa142113d791f2d2cd9ba811dcada2c (diff) | |
download | SMAPI-1edd98aef027faa768f56cf0b3591e64e20ba096.tar.gz SMAPI-1edd98aef027faa768f56cf0b3591e64e20ba096.tar.bz2 SMAPI-1edd98aef027faa768f56cf0b3591e64e20ba096.zip |
Merge branch 'develop' into stable
Diffstat (limited to 'src/StardewModdingAPI')
68 files changed, 2703 insertions, 681 deletions
diff --git a/src/StardewModdingAPI/Command.cs b/src/StardewModdingAPI/Command.cs index e2d08538..689bb18b 100644 --- a/src/StardewModdingAPI/Command.cs +++ b/src/StardewModdingAPI/Command.cs @@ -1,4 +1,5 @@ -using System; +#if !SMAPI_2_0 +using System; using System.Collections.Generic; using StardewModdingAPI.Events; using StardewModdingAPI.Framework; @@ -94,7 +95,7 @@ namespace StardewModdingAPI /// <param name="monitor">Encapsulates monitoring and logging.</param> public static void CallCommand(string input, IMonitor monitor) { - Command.DeprecationManager.Warn("Command.CallCommand", "1.9", DeprecationLevel.Info); + Command.DeprecationManager.Warn("Command.CallCommand", "1.9", DeprecationLevel.PendingRemoval); Command.CommandManager.Trigger(input); } @@ -107,7 +108,7 @@ namespace StardewModdingAPI name = name?.Trim().ToLower(); // raise deprecation warning - Command.DeprecationManager.Warn("Command.RegisterCommand", "1.9", DeprecationLevel.Info); + Command.DeprecationManager.Warn("Command.RegisterCommand", "1.9", DeprecationLevel.PendingRemoval); // validate if (Command.LegacyCommands.ContainsKey(name)) @@ -130,7 +131,7 @@ namespace StardewModdingAPI /// <param name="name">The command name to find.</param> public static Command FindCommand(string name) { - Command.DeprecationManager.Warn("Command.FindCommand", "1.9", DeprecationLevel.Info); + Command.DeprecationManager.Warn("Command.FindCommand", "1.9", DeprecationLevel.PendingRemoval); if (name == null) return null; @@ -155,3 +156,4 @@ namespace StardewModdingAPI } } } +#endif
\ No newline at end of file diff --git a/src/StardewModdingAPI/Config.cs b/src/StardewModdingAPI/Config.cs index 9f4bfad2..e166f414 100644 --- a/src/StardewModdingAPI/Config.cs +++ b/src/StardewModdingAPI/Config.cs @@ -1,4 +1,5 @@ -using System; +#if !SMAPI_2_0 +using System; using System.IO; using System.Linq; using Newtonsoft.Json; @@ -125,7 +126,7 @@ namespace StardewModdingAPI /// <summary>Construct an instance.</summary> protected Config() { - Config.DeprecationManager.Warn("the Config class", "1.0", DeprecationLevel.Info); + Config.DeprecationManager.Warn("the Config class", "1.0", DeprecationLevel.PendingRemoval); Config.DeprecationManager.MarkWarned($"{nameof(Mod)}.{nameof(Mod.BaseConfigPath)}", "1.0"); // typically used to construct config, avoid redundant warnings } } @@ -184,3 +185,4 @@ namespace StardewModdingAPI } } } +#endif
\ No newline at end of file diff --git a/src/StardewModdingAPI/Constants.cs b/src/StardewModdingAPI/Constants.cs index bd489b29..586cadeb 100644 --- a/src/StardewModdingAPI/Constants.cs +++ b/src/StardewModdingAPI/Constants.cs @@ -33,7 +33,12 @@ namespace StardewModdingAPI ** Public ****/ /// <summary>SMAPI's current semantic version.</summary> - public static ISemanticVersion ApiVersion { get; } = new SemanticVersion(1, 14, 1); // alpha-{DateTime.UtcNow:yyyyMMddHHmm} + public static ISemanticVersion ApiVersion { get; } = +#if SMAPI_2_0 + new SemanticVersion(2, 0, 0, $"alpha-{DateTime.UtcNow:yyyyMMddHHmm}"); +#else + new SemanticVersion(1, 15, 0); // alpha-{DateTime.UtcNow:yyyyMMddHHmm} +#endif /// <summary>The minimum supported version of Stardew Valley.</summary> public static ISemanticVersion MinimumGameVersion { get; } = new SemanticVersion("1.2.30"); @@ -169,6 +174,32 @@ namespace StardewModdingAPI new EventFinder("StardewModdingAPI.Events.GraphicsEvents", "OnPreRenderHudEventNoCheck"), new EventFinder("StardewModdingAPI.Events.GraphicsEvents", "OnPreRenderGuiEventNoCheck"), + // APIs removed in SMAPI 2.0 +#if SMAPI_2_0 + new TypeFinder("StardewModdingAPI.Command"), + new TypeFinder("StardewModdingAPI.Config"), + new TypeFinder("StardewModdingAPI.Log"), + new TypeFinder("StardewModdingAPI.Events.EventArgsCommand"), + new TypeFinder("StardewModdingAPI.Events.EventArgsFarmerChanged"), + new TypeFinder("StardewModdingAPI.Events.EventArgsLoadedGameChanged"), + new TypeFinder("StardewModdingAPI.Events.EventArgsNewDay"), + new TypeFinder("StardewModdingAPI.Events.EventArgsStringChanged"), + new PropertyFinder("StardewModdingAPI.Mod", "PathOnDisk"), + new PropertyFinder("StardewModdingAPI.Mod", "BaseConfigPath"), + new PropertyFinder("StardewModdingAPI.Mod", "PerSaveConfigFolder"), + new PropertyFinder("StardewModdingAPI.Mod", "PerSaveConfigPath"), + new EventFinder("StardewModdingAPI.Events.GameEvents", "Initialize"), + new EventFinder("StardewModdingAPI.Events.GameEvents", "LoadContent"), + new EventFinder("StardewModdingAPI.Events.GameEvents", "GameLoaded"), + new EventFinder("StardewModdingAPI.Events.GameEvents", "FirstUpdateTick"), + new EventFinder("StardewModdingAPI.Events.PlayerEvents", "LoadedGame"), + new EventFinder("StardewModdingAPI.Events.PlayerEvents", "FarmerChanged"), + new EventFinder("StardewModdingAPI.Events.TimeEvents", "DayOfMonthChanged"), + new EventFinder("StardewModdingAPI.Events.TimeEvents", "YearOfGameChanged"), + new EventFinder("StardewModdingAPI.Events.TimeEvents", "SeasonOfYearChanged"), + new EventFinder("StardewModdingAPI.Events.TimeEvents", "OnNewDay"), +#endif + /**** ** Rewriters change CIL as needed to fix incompatible code ****/ diff --git a/src/StardewModdingAPI/Events/ContentEvents.cs b/src/StardewModdingAPI/Events/ContentEvents.cs index 8fa9ae3c..4b4e2ad0 100644 --- a/src/StardewModdingAPI/Events/ContentEvents.cs +++ b/src/StardewModdingAPI/Events/ContentEvents.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using StardewModdingAPI.Framework; namespace StardewModdingAPI.Events @@ -8,21 +6,6 @@ namespace StardewModdingAPI.Events /// <summary>Events raised when the game loads content.</summary> public static class ContentEvents { - /********* - ** Properties - *********/ - /// <summary>Tracks the installed mods.</summary> - private static ModRegistry ModRegistry; - - /// <summary>Encapsulates monitoring and logging.</summary> - private static IMonitor Monitor; - - /// <summary>The mods using the experimental API for which a warning has been raised.</summary> - private static readonly HashSet<string> WarnedMods = new HashSet<string>(); - - /// <summary>The backing field for <see cref="AfterAssetLoaded"/>.</summary> - [SuppressMessage("ReSharper", "InconsistentNaming")] - private static event EventHandler<IContentEventHelper> _AfterAssetLoaded; /********* ** Events @@ -30,35 +13,10 @@ namespace StardewModdingAPI.Events /// <summary>Raised after the content language changes.</summary> public static event EventHandler<EventArgsValueChanged<string>> AfterLocaleChanged; - /// <summary>Raised when an XNB file is being read into the cache. Mods can change the data here before it's cached.</summary> -#if EXPERIMENTAL - public -#else - internal -#endif - static event EventHandler<IContentEventHelper> AfterAssetLoaded - { - add - { - ContentEvents.RaiseContentExperimentalWarning(); - ContentEvents._AfterAssetLoaded += value; - } - remove => ContentEvents._AfterAssetLoaded -= value; - } - /********* ** Internal methods *********/ - /// <summary>Injects types required for backwards compatibility.</summary> - /// <param name="modRegistry">Tracks the installed mods.</param> - /// <param name="monitor">Encapsulates monitoring and logging.</param> - internal static void Shim(ModRegistry modRegistry, IMonitor monitor) - { - ContentEvents.ModRegistry = modRegistry; - ContentEvents.Monitor = monitor; - } - /// <summary>Raise an <see cref="AfterLocaleChanged"/> event.</summary> /// <param name="monitor">Encapsulates monitoring and logging.</param> /// <param name="oldLocale">The previous locale.</param> @@ -67,28 +25,5 @@ namespace StardewModdingAPI.Events { monitor.SafelyRaiseGenericEvent($"{nameof(ContentEvents)}.{nameof(ContentEvents.AfterLocaleChanged)}", ContentEvents.AfterLocaleChanged?.GetInvocationList(), null, new EventArgsValueChanged<string>(oldLocale, newLocale)); } - - /// <summary>Raise an <see cref="AfterAssetLoaded"/> event.</summary> - /// <param name="monitor">Encapsulates monitoring and logging.</param> - /// <param name="contentHelper">Encapsulates access and changes to content being read from a data file.</param> - internal static void InvokeAfterAssetLoaded(IMonitor monitor, IContentEventHelper contentHelper) - { - monitor.SafelyRaiseGenericEvent($"{nameof(ContentEvents)}.{nameof(ContentEvents.AfterAssetLoaded)}", ContentEvents._AfterAssetLoaded?.GetInvocationList(), null, contentHelper); - } - - - /********* - ** Private methods - *********/ - /// <summary>Raise an 'experimental API' warning for a mod using the content API.</summary> - private static void RaiseContentExperimentalWarning() - { - string modName = ContentEvents.ModRegistry.GetModFromStack() ?? "An unknown mod"; - if (!ContentEvents.WarnedMods.Contains(modName)) - { - ContentEvents.WarnedMods.Add(modName); - ContentEvents.Monitor.Log($"{modName} used the undocumented and experimental content API, which may change or be removed without warning.", LogLevel.Warn); - } - } } } diff --git a/src/StardewModdingAPI/Events/EventArgsCommand.cs b/src/StardewModdingAPI/Events/EventArgsCommand.cs index 88a9e5a3..f0435904 100644 --- a/src/StardewModdingAPI/Events/EventArgsCommand.cs +++ b/src/StardewModdingAPI/Events/EventArgsCommand.cs @@ -1,4 +1,5 @@ -using System; +#if !SMAPI_2_0 +using System; namespace StardewModdingAPI.Events { @@ -24,3 +25,4 @@ namespace StardewModdingAPI.Events } } } +#endif
\ No newline at end of file diff --git a/src/StardewModdingAPI/Events/EventArgsFarmerChanged.cs b/src/StardewModdingAPI/Events/EventArgsFarmerChanged.cs index 699d90be..c34fc4ab 100644 --- a/src/StardewModdingAPI/Events/EventArgsFarmerChanged.cs +++ b/src/StardewModdingAPI/Events/EventArgsFarmerChanged.cs @@ -1,3 +1,4 @@ +#if !SMAPI_2_0 using System; using SFarmer = StardewValley.Farmer; @@ -29,3 +30,4 @@ namespace StardewModdingAPI.Events } } } +#endif
\ No newline at end of file diff --git a/src/StardewModdingAPI/Events/EventArgsInput.cs b/src/StardewModdingAPI/Events/EventArgsInput.cs new file mode 100644 index 00000000..e5eb7372 --- /dev/null +++ b/src/StardewModdingAPI/Events/EventArgsInput.cs @@ -0,0 +1,126 @@ +#if SMAPI_2_0 +using System; +using System.Linq; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Input; +using StardewModdingAPI.Utilities; +using StardewValley; + +namespace StardewModdingAPI.Events +{ + /// <summary>Event arguments when a button is pressed or released.</summary> + public class EventArgsInput : EventArgs + { + /********* + ** Accessors + *********/ + /// <summary>The button on the controller, keyboard, or mouse.</summary> + public SButton Button { get; } + + /// <summary>The current cursor position.</summary> + public ICursorPosition Cursor { get; set; } + + /// <summary>Whether the input is considered a 'click' by the game for enabling action.</summary> + public bool IsClick { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="button">The button on the controller, keyboard, or mouse.</param> + /// <param name="cursor">The cursor position.</param> + /// <param name="isClick">Whether the input is considered a 'click' by the game for enabling action.</param> + public EventArgsInput(SButton button, ICursorPosition cursor, bool isClick) + { + this.Button = button; + this.Cursor = cursor; + this.IsClick = isClick; + } + + /// <summary>Prevent the game from handling the vurrent button press. This doesn't prevent other mods from receiving the event.</summary> + public void SuppressButton() + { + this.SuppressButton(this.Button); + } + + /// <summary>Prevent the game from handling a button press. This doesn't prevent other mods from receiving the event.</summary> + /// <param name="button">The button to suppress.</param> + public void SuppressButton(SButton button) + { + // keyboard + if (this.Button.TryGetKeyboard(out Keys key)) + Game1.oldKBState = new KeyboardState(Game1.oldKBState.GetPressedKeys().Except(new[] { key }).ToArray()); + + // controller + else if (this.Button.TryGetController(out Buttons controllerButton)) + { + var newState = GamePad.GetState(PlayerIndex.One); + var thumbsticks = Game1.oldPadState.ThumbSticks; + var triggers = Game1.oldPadState.Triggers; + var buttons = Game1.oldPadState.Buttons; + var dpad = Game1.oldPadState.DPad; + + switch (controllerButton) + { + // d-pad + case Buttons.DPadDown: + dpad = new GamePadDPad(dpad.Up, newState.DPad.Down, dpad.Left, dpad.Right); + break; + case Buttons.DPadLeft: + dpad = new GamePadDPad(dpad.Up, dpad.Down, newState.DPad.Left, dpad.Right); + break; + case Buttons.DPadRight: + dpad = new GamePadDPad(dpad.Up, dpad.Down, dpad.Left, newState.DPad.Right); + break; + case Buttons.DPadUp: + dpad = new GamePadDPad(newState.DPad.Up, dpad.Down, dpad.Left, dpad.Right); + break; + + // trigger + case Buttons.LeftTrigger: + triggers = new GamePadTriggers(newState.Triggers.Left, triggers.Right); + break; + case Buttons.RightTrigger: + triggers = new GamePadTriggers(triggers.Left, newState.Triggers.Right); + break; + + // thumbstick + case Buttons.LeftThumbstickDown: + case Buttons.LeftThumbstickLeft: + case Buttons.LeftThumbstickRight: + case Buttons.LeftThumbstickUp: + thumbsticks = new GamePadThumbSticks(newState.ThumbSticks.Left, thumbsticks.Right); + break; + case Buttons.RightThumbstickDown: + case Buttons.RightThumbstickLeft: + case Buttons.RightThumbstickRight: + case Buttons.RightThumbstickUp: + thumbsticks = new GamePadThumbSticks(newState.ThumbSticks.Right, thumbsticks.Left); + break; + + // buttons + default: + var mask = + (buttons.A == ButtonState.Pressed ? Buttons.A : 0) + | (buttons.B == ButtonState.Pressed ? Buttons.B : 0) + | (buttons.Back == ButtonState.Pressed ? Buttons.Back : 0) + | (buttons.BigButton == ButtonState.Pressed ? Buttons.BigButton : 0) + | (buttons.LeftShoulder == ButtonState.Pressed ? Buttons.LeftShoulder : 0) + | (buttons.LeftStick == ButtonState.Pressed ? Buttons.LeftStick : 0) + | (buttons.RightShoulder == ButtonState.Pressed ? Buttons.RightShoulder : 0) + | (buttons.RightStick == ButtonState.Pressed ? Buttons.RightStick : 0) + | (buttons.Start == ButtonState.Pressed ? Buttons.Start : 0) + | (buttons.X == ButtonState.Pressed ? Buttons.X : 0) + | (buttons.Y == ButtonState.Pressed ? Buttons.Y : 0); + mask = mask ^ controllerButton; + buttons = new GamePadButtons(mask); + break; + } + + Game1.oldPadState = new GamePadState(thumbsticks, triggers, buttons, dpad); + } + } + } +} +#endif diff --git a/src/StardewModdingAPI/Events/EventArgsLoadedGameChanged.cs b/src/StardewModdingAPI/Events/EventArgsLoadedGameChanged.cs index 51d64016..d6fc4594 100644 --- a/src/StardewModdingAPI/Events/EventArgsLoadedGameChanged.cs +++ b/src/StardewModdingAPI/Events/EventArgsLoadedGameChanged.cs @@ -1,4 +1,5 @@ -using System; +#if !SMAPI_2_0 +using System; namespace StardewModdingAPI.Events { @@ -23,3 +24,4 @@ namespace StardewModdingAPI.Events } } } +#endif
\ No newline at end of file diff --git a/src/StardewModdingAPI/Events/EventArgsNewDay.cs b/src/StardewModdingAPI/Events/EventArgsNewDay.cs index aba837e4..5bd2ba66 100644 --- a/src/StardewModdingAPI/Events/EventArgsNewDay.cs +++ b/src/StardewModdingAPI/Events/EventArgsNewDay.cs @@ -1,4 +1,5 @@ -using System; +#if !SMAPI_2_0 +using System; namespace StardewModdingAPI.Events { @@ -33,3 +34,4 @@ namespace StardewModdingAPI.Events } } } +#endif
\ No newline at end of file diff --git a/src/StardewModdingAPI/Events/EventArgsStringChanged.cs b/src/StardewModdingAPI/Events/EventArgsStringChanged.cs index 85b6fab5..1498cb71 100644 --- a/src/StardewModdingAPI/Events/EventArgsStringChanged.cs +++ b/src/StardewModdingAPI/Events/EventArgsStringChanged.cs @@ -1,4 +1,5 @@ -using System; +#if !SMAPI_2_0 +using System; namespace StardewModdingAPI.Events { @@ -27,3 +28,4 @@ namespace StardewModdingAPI.Events } } } +#endif
\ No newline at end of file diff --git a/src/StardewModdingAPI/Events/GameEvents.cs b/src/StardewModdingAPI/Events/GameEvents.cs index 8e3cf662..557b451f 100644 --- a/src/StardewModdingAPI/Events/GameEvents.cs +++ b/src/StardewModdingAPI/Events/GameEvents.cs @@ -11,6 +11,7 @@ namespace StardewModdingAPI.Events /********* ** Properties *********/ +#if !SMAPI_2_0 /// <summary>Manages deprecation warnings.</summary> private static DeprecationManager DeprecationManager; @@ -29,6 +30,7 @@ namespace StardewModdingAPI.Events /// <summary>The backing field for <see cref="FirstUpdateTick"/>.</summary> [SuppressMessage("ReSharper", "InconsistentNaming")] private static event EventHandler _FirstUpdateTick; +#endif /********* @@ -40,13 +42,14 @@ namespace StardewModdingAPI.Events /// <summary>Raised during launch after configuring Stardew Valley, loading it into memory, and opening the game window. The window is still blank by this point.</summary> internal static event EventHandler GameLoadedInternal; +#if !SMAPI_2_0 /// <summary>Raised during launch after configuring XNA or MonoGame. The game window hasn't been opened by this point. Called after <see cref="Microsoft.Xna.Framework.Game.Initialize"/>.</summary> [Obsolete("The " + nameof(Mod) + "." + nameof(Mod.Entry) + " method is now called after the " + nameof(GameEvents.Initialize) + " event, so any contained logic can be done directly in " + nameof(Mod.Entry) + ".")] public static event EventHandler Initialize { add { - GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.Initialize)}", "1.10", DeprecationLevel.Info); + GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.Initialize)}", "1.10", DeprecationLevel.PendingRemoval); GameEvents._Initialize += value; } remove => GameEvents._Initialize -= value; @@ -58,7 +61,7 @@ namespace StardewModdingAPI.Events { add { - GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.LoadContent)}", "1.10", DeprecationLevel.Info); + GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.LoadContent)}", "1.10", DeprecationLevel.PendingRemoval); GameEvents._LoadContent += value; } remove => GameEvents._LoadContent -= value; @@ -70,7 +73,7 @@ namespace StardewModdingAPI.Events { add { - GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.GameLoaded)}", "1.12", DeprecationLevel.Info); + GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.GameLoaded)}", "1.12", DeprecationLevel.PendingRemoval); GameEvents._GameLoaded += value; } remove => GameEvents._GameLoaded -= value; @@ -82,11 +85,12 @@ namespace StardewModdingAPI.Events { add { - GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.FirstUpdateTick)}", "1.12", DeprecationLevel.Info); + GameEvents.DeprecationManager.Warn($"{nameof(GameEvents)}.{nameof(GameEvents.FirstUpdateTick)}", "1.12", DeprecationLevel.PendingRemoval); GameEvents._FirstUpdateTick += value; } remove => GameEvents._FirstUpdateTick -= value; } +#endif /// <summary>Raised when the game updates its state (≈60 times per second).</summary> public static event EventHandler UpdateTick; @@ -113,42 +117,52 @@ namespace StardewModdingAPI.Events /********* ** Internal methods *********/ +#if !SMAPI_2_0 /// <summary>Injects types required for backwards compatibility.</summary> /// <param name="deprecationManager">Manages deprecation warnings.</param> internal static void Shim(DeprecationManager deprecationManager) { GameEvents.DeprecationManager = deprecationManager; } +#endif - /// <summary>Raise an <see cref="Initialize"/> event.</summary> - /// <param name="monitor">Encapsulates logging and monitoring.</param> - internal static void InvokeInitialize(IMonitor monitor) + /// <summary>Raise an <see cref="InitializeInternal"/> event.</summary> + /// <param name="monitor">Encapsulates logging and monitoring.</param> + internal static void InvokeInitialize(IMonitor monitor) { monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.InitializeInternal)}", GameEvents.InitializeInternal?.GetInvocationList()); +#if !SMAPI_2_0 monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.Initialize)}", GameEvents._Initialize?.GetInvocationList()); +#endif } +#if !SMAPI_2_0 /// <summary>Raise a <see cref="LoadContent"/> event.</summary> /// <param name="monitor">Encapsulates logging and monitoring.</param> internal static void InvokeLoadContent(IMonitor monitor) { monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.LoadContent)}", GameEvents._LoadContent?.GetInvocationList()); } +#endif - /// <summary>Raise a <see cref="GameLoaded"/> event.</summary> + /// <summary>Raise a <see cref="GameLoadedInternal"/> event.</summary> /// <param name="monitor">Encapsulates monitoring and logging.</param> internal static void InvokeGameLoaded(IMonitor monitor) { monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.GameLoadedInternal)}", GameEvents.GameLoadedInternal?.GetInvocationList()); +#if !SMAPI_2_0 monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.GameLoaded)}", GameEvents._GameLoaded?.GetInvocationList()); +#endif } +#if !SMAPI_2_0 /// <summary>Raise a <see cref="FirstUpdateTick"/> event.</summary> /// <param name="monitor">Encapsulates monitoring and logging.</param> internal static void InvokeFirstUpdateTick(IMonitor monitor) { monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.FirstUpdateTick)}", GameEvents._FirstUpdateTick?.GetInvocationList()); } +#endif /// <summary>Raise an <see cref="UpdateTick"/> event.</summary> /// <param name="monitor">Encapsulates logging and monitoring.</param> diff --git a/src/StardewModdingAPI/Events/InputEvents.cs b/src/StardewModdingAPI/Events/InputEvents.cs new file mode 100644 index 00000000..285487af --- /dev/null +++ b/src/StardewModdingAPI/Events/InputEvents.cs @@ -0,0 +1,45 @@ +#if SMAPI_2_0 +using System; +using StardewModdingAPI.Framework; +using StardewModdingAPI.Utilities; + +namespace StardewModdingAPI.Events +{ + /// <summary>Events raised when the player uses a controller, keyboard, or mouse button.</summary> + public static class InputEvents + { + /********* + ** Events + *********/ + /// <summary>Raised when the player presses a button on the keyboard, controller, or mouse.</summary> + public static event EventHandler<EventArgsInput> ButtonPressed; + + /// <summary>Raised when the player releases a keyboard key on the keyboard, controller, or mouse.</summary> + public static event EventHandler<EventArgsInput> ButtonReleased; + + + /********* + ** Internal methods + *********/ + /// <summary>Raise a <see cref="ButtonPressed"/> event.</summary> + /// <param name="monitor">Encapsulates monitoring and logging.</param> + /// <param name="button">The button on the controller, keyboard, or mouse.</param> + /// <param name="cursor">The cursor position.</param> + /// <param name="isClick">Whether the input is considered a 'click' by the game for enabling action.</param> + internal static void InvokeButtonPressed(IMonitor monitor, SButton button, ICursorPosition cursor, bool isClick) + { + monitor.SafelyRaiseGenericEvent($"{nameof(InputEvents)}.{nameof(InputEvents.ButtonPressed)}", InputEvents.ButtonPressed?.GetInvocationList(), null, new EventArgsInput(button, cursor, isClick)); + } + + /// <summary>Raise a <see cref="ButtonReleased"/> event.</summary> + /// <param name="monitor">Encapsulates monitoring and logging.</param> + /// <param name="button">The button on the controller, keyboard, or mouse.</param> + /// <param name="cursor">The cursor position.</param> + /// <param name="isClick">Whether the input is considered a 'click' by the game for enabling action.</param> + internal static void InvokeButtonReleased(IMonitor monitor, SButton button, ICursorPosition cursor, bool isClick) + { + monitor.SafelyRaiseGenericEvent($"{nameof(InputEvents)}.{nameof(InputEvents.ButtonReleased)}", InputEvents.ButtonReleased?.GetInvocationList(), null, new EventArgsInput(button, cursor, isClick)); + } + } +} +#endif
\ No newline at end of file diff --git a/src/StardewModdingAPI/Events/PlayerEvents.cs b/src/StardewModdingAPI/Events/PlayerEvents.cs index 37649fee..acbdc562 100644 --- a/src/StardewModdingAPI/Events/PlayerEvents.cs +++ b/src/StardewModdingAPI/Events/PlayerEvents.cs @@ -15,6 +15,7 @@ namespace StardewModdingAPI.Events /********* ** Properties *********/ +#if !SMAPI_2_0 /// <summary>Manages deprecation warnings.</summary> private static DeprecationManager DeprecationManager; @@ -25,18 +26,20 @@ namespace StardewModdingAPI.Events /// <summary>The backing field for <see cref="FarmerChanged"/>.</summary> [SuppressMessage("ReSharper", "InconsistentNaming")] private static event EventHandler<EventArgsFarmerChanged> _FarmerChanged; +#endif /********* ** Events *********/ +#if !SMAPI_2_0 /// <summary>Raised after the player loads a saved game.</summary> [Obsolete("Use " + nameof(SaveEvents) + "." + nameof(SaveEvents.AfterLoad) + " instead")] public static event EventHandler<EventArgsLoadedGameChanged> LoadedGame { add { - PlayerEvents.DeprecationManager.Warn($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.LoadedGame)}", "1.6", DeprecationLevel.Info); + PlayerEvents.DeprecationManager.Warn($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.LoadedGame)}", "1.6", DeprecationLevel.PendingRemoval); PlayerEvents._LoadedGame += value; } remove => PlayerEvents._LoadedGame -= value; @@ -48,11 +51,12 @@ namespace StardewModdingAPI.Events { add { - PlayerEvents.DeprecationManager.Warn($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.FarmerChanged)}", "1.6", DeprecationLevel.Info); + PlayerEvents.DeprecationManager.Warn($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.FarmerChanged)}", "1.6", DeprecationLevel.PendingRemoval); PlayerEvents._FarmerChanged += value; } remove => PlayerEvents._FarmerChanged -= value; } +#endif /// <summary>Raised after the player's inventory changes in any way (added or removed item, sorted, etc).</summary> public static event EventHandler<EventArgsInventoryChanged> InventoryChanged; @@ -64,6 +68,7 @@ namespace StardewModdingAPI.Events /********* ** Internal methods *********/ +#if !SMAPI_2_0 /// <summary>Injects types required for backwards compatibility.</summary> /// <param name="deprecationManager">Manages deprecation warnings.</param> internal static void Shim(DeprecationManager deprecationManager) @@ -87,6 +92,7 @@ namespace StardewModdingAPI.Events { monitor.SafelyRaiseGenericEvent($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.FarmerChanged)}", PlayerEvents._FarmerChanged?.GetInvocationList(), null, new EventArgsFarmerChanged(priorFarmer, newFarmer)); } +#endif /// <summary>Raise an <see cref="InventoryChanged"/> event.</summary> /// <param name="monitor">Encapsulates monitoring and logging.</param> diff --git a/src/StardewModdingAPI/Events/TimeEvents.cs b/src/StardewModdingAPI/Events/TimeEvents.cs index 5dadf567..f0fdb4f2 100644 --- a/src/StardewModdingAPI/Events/TimeEvents.cs +++ b/src/StardewModdingAPI/Events/TimeEvents.cs @@ -11,6 +11,7 @@ namespace StardewModdingAPI.Events /********* ** Properties *********/ +#if !SMAPI_2_0 /// <summary>Manages deprecation warnings.</summary> private static DeprecationManager DeprecationManager; @@ -29,6 +30,8 @@ namespace StardewModdingAPI.Events /// <summary>The backing field for <see cref="YearOfGameChanged"/>.</summary> [SuppressMessage("ReSharper", "InconsistentNaming")] private static event EventHandler<EventArgsIntChanged> _YearOfGameChanged; +#endif + /********* ** Events @@ -39,13 +42,14 @@ namespace StardewModdingAPI.Events /// <summary>Raised after the in-game clock changes.</summary> public static event EventHandler<EventArgsIntChanged> TimeOfDayChanged; +#if !SMAPI_2_0 /// <summary>Raised after the day-of-month value changes, including when loading a save. This may happen before save; in most cases you should use <see cref="AfterDayStarted"/> instead.</summary> [Obsolete("Use " + nameof(TimeEvents) + "." + nameof(TimeEvents.AfterDayStarted) + " or " + nameof(SaveEvents) + " instead")] public static event EventHandler<EventArgsIntChanged> DayOfMonthChanged { add { - TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.DayOfMonthChanged)}", "1.14", DeprecationLevel.Info); + TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.DayOfMonthChanged)}", "1.14", DeprecationLevel.PendingRemoval); TimeEvents._DayOfMonthChanged += value; } remove => TimeEvents._DayOfMonthChanged -= value; @@ -57,7 +61,7 @@ namespace StardewModdingAPI.Events { add { - TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.YearOfGameChanged)}", "1.14", DeprecationLevel.Info); + TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.YearOfGameChanged)}", "1.14", DeprecationLevel.PendingRemoval); TimeEvents._YearOfGameChanged += value; } remove => TimeEvents._YearOfGameChanged -= value; @@ -69,7 +73,7 @@ namespace StardewModdingAPI.Events { add { - TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.SeasonOfYearChanged)}", "1.14", DeprecationLevel.Info); + TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.SeasonOfYearChanged)}", "1.14", DeprecationLevel.PendingRemoval); TimeEvents._SeasonOfYearChanged += value; } remove => TimeEvents._SeasonOfYearChanged -= value; @@ -81,22 +85,25 @@ namespace StardewModdingAPI.Events { add { - TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.OnNewDay)}", "1.6", DeprecationLevel.Info); + TimeEvents.DeprecationManager.Warn($"{nameof(TimeEvents)}.{nameof(TimeEvents.OnNewDay)}", "1.6", DeprecationLevel.PendingRemoval); TimeEvents._OnNewDay += value; } remove => TimeEvents._OnNewDay -= value; } +#endif /********* ** Internal methods *********/ +#if !SMAPI_2_0 /// <summary>Injects types required for backwards compatibility.</summary> /// <param name="deprecationManager">Manages deprecation warnings.</param> internal static void Shim(DeprecationManager deprecationManager) { TimeEvents.DeprecationManager = deprecationManager; } +#endif /// <summary>Raise an <see cref="AfterDayStarted"/> event.</summary> /// <param name="monitor">Encapsulates monitoring and logging.</param> @@ -105,7 +112,7 @@ namespace StardewModdingAPI.Events monitor.SafelyRaisePlainEvent($"{nameof(TimeEvents)}.{nameof(TimeEvents.AfterDayStarted)}", TimeEvents.AfterDayStarted?.GetInvocationList(), null, EventArgs.Empty); } - /// <summary>Raise a <see cref="InvokeDayOfMonthChanged"/> event.</summary> + /// <summary>Raise a <see cref="TimeOfDayChanged"/> event.</summary> /// <param name="monitor">Encapsulates monitoring and logging.</param> /// <param name="priorTime">The previous time in military time format (e.g. 6:00pm is 1800).</param> /// <param name="newTime">The current time in military time format (e.g. 6:10pm is 1810).</param> @@ -114,6 +121,7 @@ namespace StardewModdingAPI.Events monitor.SafelyRaiseGenericEvent($"{nameof(TimeEvents)}.{nameof(TimeEvents.TimeOfDayChanged)}", TimeEvents.TimeOfDayChanged?.GetInvocationList(), null, new EventArgsIntChanged(priorTime, newTime)); } +#if !SMAPI_2_0 /// <summary>Raise a <see cref="DayOfMonthChanged"/> event.</summary> /// <param name="monitor">Encapsulates monitoring and logging.</param> /// <param name="priorDay">The previous day value.</param> @@ -150,5 +158,6 @@ namespace StardewModdingAPI.Events { monitor.SafelyRaiseGenericEvent($"{nameof(TimeEvents)}.{nameof(TimeEvents.OnNewDay)}", TimeEvents._OnNewDay?.GetInvocationList(), null, new EventArgsNewDay(priorDay, newDay, isTransitioning)); } +#endif } } diff --git a/src/StardewModdingAPI/Framework/Content/AssetData.cs b/src/StardewModdingAPI/Framework/Content/AssetData.cs new file mode 100644 index 00000000..1ab9eebd --- /dev/null +++ b/src/StardewModdingAPI/Framework/Content/AssetData.cs @@ -0,0 +1,44 @@ +using System; + +namespace StardewModdingAPI.Framework.Content +{ + /// <summary>Base implementation for a content helper which encapsulates access and changes to content being read from a data file.</summary> + /// <typeparam name="TValue">The interface value type.</typeparam> + internal class AssetData<TValue> : AssetInfo, IAssetData<TValue> + { + /********* + ** Accessors + *********/ + /// <summary>The content data being read.</summary> + public TValue Data { get; protected set; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="locale">The content's locale code, if the content is localised.</param> + /// <param name="assetName">The normalised asset name being read.</param> + /// <param name="data">The content data being read.</param> + /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param> + public AssetData(string locale, string assetName, TValue data, Func<string, string> getNormalisedPath) + : base(locale, assetName, data.GetType(), getNormalisedPath) + { + this.Data = data; + } + + /// <summary>Replace the entire content value with the given value. This is generally not recommended, since it may break compatibility with other mods or different versions of the game.</summary> + /// <param name="value">The new content value.</param> + /// <exception cref="ArgumentNullException">The <paramref name="value"/> is null.</exception> + /// <exception cref="InvalidCastException">The <paramref name="value"/>'s type is not compatible with the loaded asset's type.</exception> + public void ReplaceWith(TValue value) + { + if (value == null) + throw new ArgumentNullException(nameof(value), "Can't set a loaded asset to a null value."); + if (!this.DataType.IsInstanceOfType(value)) + throw new InvalidCastException($"Can't replace loaded asset of type {this.GetFriendlyTypeName(this.DataType)} with value of type {this.GetFriendlyTypeName(value.GetType())}. The new type must be compatible to prevent game errors."); + + this.Data = value; + } + } +} diff --git a/src/StardewModdingAPI/Framework/Content/ContentEventHelperForDictionary.cs b/src/StardewModdingAPI/Framework/Content/AssetDataForDictionary.cs index 26f059e4..e9b29b12 100644 --- a/src/StardewModdingAPI/Framework/Content/ContentEventHelperForDictionary.cs +++ b/src/StardewModdingAPI/Framework/Content/AssetDataForDictionary.cs @@ -5,7 +5,7 @@ using System.Linq; namespace StardewModdingAPI.Framework.Content { /// <summary>Encapsulates access and changes to dictionary content being read from a data file.</summary> - internal class ContentEventHelperForDictionary<TKey, TValue> : ContentEventData<IDictionary<TKey, TValue>>, IContentEventHelperForDictionary<TKey, TValue> + internal class AssetDataForDictionary<TKey, TValue> : AssetData<IDictionary<TKey, TValue>>, IAssetDataForDictionary<TKey, TValue> { /********* ** Public methods @@ -15,7 +15,7 @@ namespace StardewModdingAPI.Framework.Content /// <param name="assetName">The normalised asset name being read.</param> /// <param name="data">The content data being read.</param> /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param> - public ContentEventHelperForDictionary(string locale, string assetName, IDictionary<TKey, TValue> data, Func<string, string> getNormalisedPath) + public AssetDataForDictionary(string locale, string assetName, IDictionary<TKey, TValue> data, Func<string, string> getNormalisedPath) : base(locale, assetName, data, getNormalisedPath) { } /// <summary>Add or replace an entry in the dictionary.</summary> diff --git a/src/StardewModdingAPI/Framework/Content/ContentEventHelperForImage.cs b/src/StardewModdingAPI/Framework/Content/AssetDataForImage.cs index da30590b..45c5588b 100644 --- a/src/StardewModdingAPI/Framework/Content/ContentEventHelperForImage.cs +++ b/src/StardewModdingAPI/Framework/Content/AssetDataForImage.cs @@ -5,7 +5,7 @@ using Microsoft.Xna.Framework.Graphics; namespace StardewModdingAPI.Framework.Content { /// <summary>Encapsulates access and changes to dictionary content being read from a data file.</summary> - internal class ContentEventHelperForImage : ContentEventData<Texture2D>, IContentEventHelperForImage + internal class AssetDataForImage : AssetData<Texture2D>, IAssetDataForImage { /********* ** Public methods @@ -15,7 +15,7 @@ namespace StardewModdingAPI.Framework.Content /// <param name="assetName">The normalised asset name being read.</param> /// <param name="data">The content data being read.</param> /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param> - public ContentEventHelperForImage(string locale, string assetName, Texture2D data, Func<string, string> getNormalisedPath) + public AssetDataForImage(string locale, string assetName, Texture2D data, Func<string, string> getNormalisedPath) : base(locale, assetName, data, getNormalisedPath) { } /// <summary>Overwrite part of the image.</summary> diff --git a/src/StardewModdingAPI/Framework/Content/ContentEventHelper.cs b/src/StardewModdingAPI/Framework/Content/AssetDataForObject.cs index 9bf1ea17..f30003e4 100644 --- a/src/StardewModdingAPI/Framework/Content/ContentEventHelper.cs +++ b/src/StardewModdingAPI/Framework/Content/AssetDataForObject.cs @@ -5,7 +5,7 @@ using Microsoft.Xna.Framework.Graphics; namespace StardewModdingAPI.Framework.Content { /// <summary>Encapsulates access and changes to content being read from a data file.</summary> - internal class ContentEventHelper : ContentEventData<object>, IContentEventHelper + internal class AssetDataForObject : AssetData<object>, IAssetData { /********* ** Public methods @@ -15,23 +15,30 @@ namespace StardewModdingAPI.Framework.Content /// <param name="assetName">The normalised asset name being read.</param> /// <param name="data">The content data being read.</param> /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param> - public ContentEventHelper(string locale, string assetName, object data, Func<string, string> getNormalisedPath) + public AssetDataForObject(string locale, string assetName, object data, Func<string, string> getNormalisedPath) : base(locale, assetName, data, getNormalisedPath) { } + /// <summary>Construct an instance.</summary> + /// <param name="info">The asset metadata.</param> + /// <param name="data">The content data being read.</param> + /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param> + public AssetDataForObject(IAssetInfo info, object data, Func<string, string> getNormalisedPath) + : this(info.Locale, info.AssetName, data, getNormalisedPath) { } + /// <summary>Get a helper to manipulate the data as a dictionary.</summary> /// <typeparam name="TKey">The expected dictionary key.</typeparam> /// <typeparam name="TValue">The expected dictionary balue.</typeparam> /// <exception cref="InvalidOperationException">The content being read isn't a dictionary.</exception> - public IContentEventHelperForDictionary<TKey, TValue> AsDictionary<TKey, TValue>() + public IAssetDataForDictionary<TKey, TValue> AsDictionary<TKey, TValue>() { - return new ContentEventHelperForDictionary<TKey, TValue>(this.Locale, this.AssetName, this.GetData<IDictionary<TKey, TValue>>(), this.GetNormalisedPath); + return new AssetDataForDictionary<TKey, TValue>(this.Locale, this.AssetName, this.GetData<IDictionary<TKey, TValue>>(), this.GetNormalisedPath); } /// <summary>Get a helper to manipulate the data as an image.</summary> /// <exception cref="InvalidOperationException">The content being read isn't an image.</exception> - public IContentEventHelperForImage AsImage() + public IAssetDataForImage AsImage() { - return new ContentEventHelperForImage(this.Locale, this.AssetName, this.GetData<Texture2D>(), this.GetNormalisedPath); + return new AssetDataForImage(this.Locale, this.AssetName, this.GetData<Texture2D>(), this.GetNormalisedPath); } /// <summary>Get the data as a given type.</summary> diff --git a/src/StardewModdingAPI/Framework/Content/ContentEventData.cs b/src/StardewModdingAPI/Framework/Content/AssetInfo.cs index 1a1779d4..d580dc06 100644 --- a/src/StardewModdingAPI/Framework/Content/ContentEventData.cs +++ b/src/StardewModdingAPI/Framework/Content/AssetInfo.cs @@ -4,9 +4,7 @@ using Microsoft.Xna.Framework.Graphics; namespace StardewModdingAPI.Framework.Content { - /// <summary>Base implementation for a content helper which encapsulates access and changes to content being read from a data file.</summary> - /// <typeparam name="TValue">The interface value type.</typeparam> - internal class ContentEventData<TValue> : EventArgs, IContentEventData<TValue> + internal class AssetInfo : IAssetInfo { /********* ** Properties @@ -21,12 +19,9 @@ namespace StardewModdingAPI.Framework.Content /// <summary>The content's locale code, if the content is localised.</summary> public string Locale { get; } - /// <summary>The normalised asset name being read. The format may change between platforms; see <see cref="IsAssetName"/> to compare with a known path.</summary> + /// <summary>The normalised asset name being read. The format may change between platforms; see <see cref="AssetNameEquals"/> to compare with a known path.</summary> public string AssetName { get; } - /// <summary>The content data being read.</summary> - public TValue Data { get; protected set; } - /// <summary>The content data type.</summary> public Type DataType { get; } @@ -37,48 +32,24 @@ namespace StardewModdingAPI.Framework.Content /// <summary>Construct an instance.</summary> /// <param name="locale">The content's locale code, if the content is localised.</param> /// <param name="assetName">The normalised asset name being read.</param> - /// <param name="data">The content data being read.</param> - /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param> - public ContentEventData(string locale, string assetName, TValue data, Func<string, string> getNormalisedPath) - : this(locale, assetName, data, data.GetType(), getNormalisedPath) { } - - /// <summary>Construct an instance.</summary> - /// <param name="locale">The content's locale code, if the content is localised.</param> - /// <param name="assetName">The normalised asset name being read.</param> - /// <param name="data">The content data being read.</param> - /// <param name="dataType">The content data type being read.</param> + /// <param name="type">The content type being read.</param> /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param> - public ContentEventData(string locale, string assetName, TValue data, Type dataType, Func<string, string> getNormalisedPath) + public AssetInfo(string locale, string assetName, Type type, Func<string, string> getNormalisedPath) { this.Locale = locale; this.AssetName = assetName; - this.Data = data; - this.DataType = dataType; + this.DataType = type; this.GetNormalisedPath = getNormalisedPath; } /// <summary>Get whether the asset name being loaded matches a given name after normalisation.</summary> /// <param name="path">The expected asset path, relative to the game's content folder and without the .xnb extension or locale suffix (like 'Data\ObjectInformation').</param> - public bool IsAssetName(string path) + public bool AssetNameEquals(string path) { path = this.GetNormalisedPath(path); return this.AssetName.Equals(path, StringComparison.InvariantCultureIgnoreCase); } - /// <summary>Replace the entire content value with the given value. This is generally not recommended, since it may break compatibility with other mods or different versions of the game.</summary> - /// <param name="value">The new content value.</param> - /// <exception cref="ArgumentNullException">The <paramref name="value"/> is null.</exception> - /// <exception cref="InvalidCastException">The <paramref name="value"/>'s type is not compatible with the loaded asset's type.</exception> - public void ReplaceWith(TValue value) - { - if (value == null) - throw new ArgumentNullException(nameof(value), "Can't set a loaded asset to a null value."); - if (!this.DataType.IsInstanceOfType(value)) - throw new InvalidCastException($"Can't replace loaded asset of type {this.GetFriendlyTypeName(this.DataType)} with value of type {this.GetFriendlyTypeName(value.GetType())}. The new type must be compatible to prevent game errors."); - - this.Data = value; - } - /********* ** Protected methods diff --git a/src/StardewModdingAPI/Framework/CursorPosition.cs b/src/StardewModdingAPI/Framework/CursorPosition.cs new file mode 100644 index 00000000..4f256da5 --- /dev/null +++ b/src/StardewModdingAPI/Framework/CursorPosition.cs @@ -0,0 +1,37 @@ +#if SMAPI_2_0 +using Microsoft.Xna.Framework; + +namespace StardewModdingAPI.Framework +{ + /// <summary>Defines a position on a given map at different reference points.</summary> + internal class CursorPosition : ICursorPosition + { + /********* + ** Accessors + *********/ + /// <summary>The pixel position relative to the top-left corner of the visible screen.</summary> + public Vector2 ScreenPixels { get; } + + /// <summary>The tile position under the cursor relative to the top-left corner of the map.</summary> + public Vector2 Tile { get; } + + /// <summary>The tile position that the game considers under the cursor for purposes of clicking actions. This may be different than <see cref="Tile"/> if that's too far from the player.</summary> + public Vector2 GrabTile { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="screenPixels">The pixel position relative to the top-left corner of the visible screen.</param> + /// <param name="tile">The tile position relative to the top-left corner of the map.</param> + /// <param name="grabTile">The tile position that the game considers under the cursor for purposes of clicking actions.</param> + public CursorPosition(Vector2 screenPixels, Vector2 tile, Vector2 grabTile) + { + this.ScreenPixels = screenPixels; + this.Tile = tile; + this.GrabTile = grabTile; + } + } +} +#endif diff --git a/src/StardewModdingAPI/Framework/DeprecationManager.cs b/src/StardewModdingAPI/Framework/DeprecationManager.cs index 6b95960b..153d8829 100644 --- a/src/StardewModdingAPI/Framework/DeprecationManager.cs +++ b/src/StardewModdingAPI/Framework/DeprecationManager.cs @@ -52,13 +52,12 @@ namespace StardewModdingAPI.Framework if (!this.MarkWarned(source ?? "<unknown>", nounPhrase, version)) return; + // show SMAPI 2.0 meta-warning + if(this.MarkWarned("SMAPI", "SMAPI 2.0 meta-warning", "2.0")) + this.Monitor.Log("Some mods may stop working in SMAPI 2.0 (but they'll work fine for now). Try updating mods with 'deprecated code' warnings; if that doesn't remove the warnings, let the mod authors know about this message or see http://community.playstarbound.com/threads/135000 for details.", LogLevel.Warn); + // build message - string message = source != null - ? $"{source} used {nounPhrase}, which is deprecated since SMAPI {version}." - : $"An unknown mod used {nounPhrase}, which is deprecated since SMAPI {version}."; - message += severity != DeprecationLevel.PendingRemoval - ? " This will break in a future version of SMAPI." - : " It will be removed soon, so the mod will break if it's not updated."; + string message = $"{source ?? "An unknown mod"} uses deprecated code ({nounPhrase})."; if (source == null) message += $"{Environment.NewLine}{Environment.StackTrace}"; @@ -70,7 +69,7 @@ namespace StardewModdingAPI.Framework break; case DeprecationLevel.Info: - this.Monitor.Log(message, LogLevel.Warn); + this.Monitor.Log(message, LogLevel.Debug); break; case DeprecationLevel.PendingRemoval: diff --git a/src/StardewModdingAPI/Framework/Exceptions/SParseException.cs b/src/StardewModdingAPI/Framework/Exceptions/SParseException.cs new file mode 100644 index 00000000..f7133ee7 --- /dev/null +++ b/src/StardewModdingAPI/Framework/Exceptions/SParseException.cs @@ -0,0 +1,17 @@ +using System; + +namespace StardewModdingAPI.Framework.Exceptions +{ + /// <summary>A format exception which provides a user-facing error message.</summary> + internal class SParseException : FormatException + { + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="message">The error message.</param> + /// <param name="ex">The underlying exception, if any.</param> + public SParseException(string message, Exception ex = null) + : base(message, ex) { } + } +} diff --git a/src/StardewModdingAPI/Framework/InternalExtensions.cs b/src/StardewModdingAPI/Framework/InternalExtensions.cs index b99d3798..2842bc83 100644 --- a/src/StardewModdingAPI/Framework/InternalExtensions.cs +++ b/src/StardewModdingAPI/Framework/InternalExtensions.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.Xna.Framework.Graphics; +using StardewModdingAPI.Framework.Reflection; using StardewValley; namespace StardewModdingAPI.Framework @@ -99,7 +100,7 @@ namespace StardewModdingAPI.Framework /// <summary>Get whether the sprite batch is between a begin and end pair.</summary> /// <param name="spriteBatch">The sprite batch to check.</param> /// <param name="reflection">The reflection helper with which to access private fields.</param> - public static bool IsOpen(this SpriteBatch spriteBatch, IReflectionHelper reflection) + public static bool IsOpen(this SpriteBatch spriteBatch, Reflector reflection) { // get field name const string fieldName = @@ -110,7 +111,7 @@ namespace StardewModdingAPI.Framework #endif // get result - return reflection.GetPrivateValue<bool>(Game1.spriteBatch, fieldName); + return reflection.GetPrivateField<bool>(Game1.spriteBatch, fieldName).GetValue(); } } } diff --git a/src/StardewModdingAPI/Framework/ModHelpers/BaseHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/BaseHelper.cs new file mode 100644 index 00000000..16032da1 --- /dev/null +++ b/src/StardewModdingAPI/Framework/ModHelpers/BaseHelper.cs @@ -0,0 +1,23 @@ +namespace StardewModdingAPI.Framework.ModHelpers +{ + /// <summary>The common base class for mod helpers.</summary> + internal abstract class BaseHelper : IModLinked + { + /********* + ** Accessors + *********/ + /// <summary>The unique ID of the mod for which the helper was created.</summary> + public string ModID { get; } + + + /********* + ** Protected methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="modID">The unique ID of the relevant mod.</param> + protected BaseHelper(string modID) + { + this.ModID = modID; + } + } +} diff --git a/src/StardewModdingAPI/Framework/CommandHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/CommandHelper.cs index 86734fc5..bdedb07c 100644 --- a/src/StardewModdingAPI/Framework/CommandHelper.cs +++ b/src/StardewModdingAPI/Framework/ModHelpers/CommandHelper.cs @@ -1,9 +1,9 @@ using System; -namespace StardewModdingAPI.Framework +namespace StardewModdingAPI.Framework.ModHelpers { /// <summary>Provides an API for managing console commands.</summary> - internal class CommandHelper : ICommandHelper + internal class CommandHelper : BaseHelper, ICommandHelper { /********* ** Accessors @@ -15,14 +15,15 @@ namespace StardewModdingAPI.Framework private readonly CommandManager CommandManager; - /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> + /// <param name="modID">The unique ID of the relevant mod.</param> /// <param name="modName">The friendly mod name for this instance.</param> /// <param name="commandManager">Manages console commands.</param> - public CommandHelper(string modName, CommandManager commandManager) + public CommandHelper(string modID, string modName, CommandManager commandManager) + : base(modID) { this.ModName = modName; this.CommandManager = commandManager; diff --git a/src/StardewModdingAPI/Framework/ContentHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/ContentHelper.cs index 7fd5e803..5f72176e 100644 --- a/src/StardewModdingAPI/Framework/ContentHelper.cs +++ b/src/StardewModdingAPI/Framework/ModHelpers/ContentHelper.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; @@ -11,10 +13,10 @@ using xTile; using xTile.Format; using xTile.Tiles; -namespace StardewModdingAPI.Framework +namespace StardewModdingAPI.Framework.ModHelpers { /// <summary>Provides an API for loading content assets.</summary> - internal class ContentHelper : IContentHelper + internal class ContentHelper : BaseHelper, IContentHelper { /********* ** Properties @@ -33,13 +35,31 @@ namespace StardewModdingAPI.Framework /********* + ** Accessors + *********/ + /// <summary>The observable implementation of <see cref="AssetEditors"/>.</summary> + internal ObservableCollection<IAssetEditor> ObservableAssetEditors { get; } = new ObservableCollection<IAssetEditor>(); + + /// <summary>The observable implementation of <see cref="AssetLoaders"/>.</summary> + internal ObservableCollection<IAssetLoader> ObservableAssetLoaders { get; } = new ObservableCollection<IAssetLoader>(); + + /// <summary>Interceptors which provide the initial versions of matching content assets.</summary> + internal IList<IAssetLoader> AssetLoaders => this.ObservableAssetLoaders; + + /// <summary>Interceptors which edit matching content assets after they're loaded.</summary> + internal IList<IAssetEditor> AssetEditors => this.ObservableAssetEditors; + + + /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="contentManager">SMAPI's underlying content manager.</param> /// <param name="modFolderPath">The absolute path to the mod folder.</param> + /// <param name="modID">The unique ID of the relevant mod.</param> /// <param name="modName">The friendly mod name for use in errors.</param> - public ContentHelper(SContentManager contentManager, string modFolderPath, string modName) + public ContentHelper(SContentManager contentManager, string modFolderPath, string modID, string modName) + : base(modID) { this.ContentManager = contentManager; this.ModFolderPath = modFolderPath; diff --git a/src/StardewModdingAPI/Framework/ModHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/ModHelper.cs index 5a8ce459..665b9cf4 100644 --- a/src/StardewModdingAPI/Framework/ModHelper.cs +++ b/src/StardewModdingAPI/Framework/ModHelpers/ModHelper.cs @@ -2,10 +2,10 @@ using System.IO; using StardewModdingAPI.Framework.Serialisation; -namespace StardewModdingAPI.Framework +namespace StardewModdingAPI.Framework.ModHelpers { /// <summary>Provides simplified APIs for writing mods.</summary> - internal class ModHelper : IModHelper, IDisposable + internal class ModHelper : BaseHelper, IModHelper, IDisposable { /********* ** Properties @@ -23,16 +23,16 @@ namespace StardewModdingAPI.Framework /// <summary>An API for loading content assets.</summary> public IContentHelper Content { get; } - /// <summary>Simplifies access to private game code.</summary> + /// <summary>An API for accessing private game code.</summary> public IReflectionHelper Reflection { get; } - /// <summary>Metadata about loaded mods.</summary> + /// <summary>an API for fetching metadata about loaded mods.</summary> public IModRegistry ModRegistry { get; } /// <summary>An API for managing console commands.</summary> public ICommandHelper ConsoleCommands { get; } - /// <summary>Provides translations stored in the mod's <c>i18n</c> folder, with one file per locale (like <c>en.json</c>) containing a flat key => value structure. Translations are fetched with locale fallback, so missing translations are filled in from broader locales (like <c>pt-BR.json</c> < <c>pt.json</c> < <c>default.json</c>).</summary> + /// <summary>An API for reading translations stored in the mod's <c>i18n</c> folder, with one file per locale (like <c>en.json</c>) containing a flat key => value structure. Translations are fetched with locale fallback, so missing translations are filled in from broader locales (like <c>pt-BR.json</c> < <c>pt.json</c> < <c>default.json</c>).</summary> public ITranslationHelper Translation { get; } @@ -40,35 +40,33 @@ namespace StardewModdingAPI.Framework ** Public methods *********/ /// <summary>Construct an instance.</summary> - /// <param name="displayName">The mod's display name.</param> + /// <param name="modID">The mod's unique ID.</param> /// <param name="modDirectory">The full path to the mod's folder.</param> /// <param name="jsonHelper">Encapsulate SMAPI's JSON parsing.</param> - /// <param name="modRegistry">Metadata about loaded mods.</param> - /// <param name="commandManager">Manages console commands.</param> - /// <param name="contentManager">The content manager which loads content assets.</param> - /// <param name="reflection">Simplifies access to private game code.</param> + /// <param name="contentHelper">An API for loading content assets.</param> + /// <param name="commandHelper">An API for managing console commands.</param> + /// <param name="modRegistry">an API for fetching metadata about loaded mods.</param> + /// <param name="reflectionHelper">An API for accessing private game code.</param> + /// <param name="translationHelper">An API for reading translations stored in the mod's <c>i18n</c> folder.</param> /// <exception cref="ArgumentNullException">An argument is null or empty.</exception> /// <exception cref="InvalidOperationException">The <paramref name="modDirectory"/> path does not exist on disk.</exception> - public ModHelper(string displayName, string modDirectory, JsonHelper jsonHelper, IModRegistry modRegistry, CommandManager commandManager, SContentManager contentManager, IReflectionHelper reflection) + public ModHelper(string modID, string modDirectory, JsonHelper jsonHelper, IContentHelper contentHelper, ICommandHelper commandHelper, IModRegistry modRegistry, IReflectionHelper reflectionHelper, ITranslationHelper translationHelper) + : base(modID) { - // validate + // validate directory if (string.IsNullOrWhiteSpace(modDirectory)) throw new ArgumentNullException(nameof(modDirectory)); - if (jsonHelper == null) - throw new ArgumentNullException(nameof(jsonHelper)); - if (modRegistry == null) - throw new ArgumentNullException(nameof(modRegistry)); if (!Directory.Exists(modDirectory)) throw new InvalidOperationException("The specified mod directory does not exist."); // initialise this.DirectoryPath = modDirectory; - this.JsonHelper = jsonHelper; - this.Content = new ContentHelper(contentManager, modDirectory, displayName); - this.ModRegistry = modRegistry; - this.ConsoleCommands = new CommandHelper(displayName, commandManager); - this.Reflection = reflection; - this.Translation = new TranslationHelper(displayName, contentManager.GetLocale(), contentManager.GetCurrentLanguage()); + this.JsonHelper = jsonHelper ?? throw new ArgumentNullException(nameof(jsonHelper)); + this.Content = contentHelper ?? throw new ArgumentNullException(nameof(contentHelper)); + this.ModRegistry = modRegistry ?? throw new ArgumentNullException(nameof(modRegistry)); + this.ConsoleCommands = commandHelper ?? throw new ArgumentNullException(nameof(commandHelper)); + this.Reflection = reflectionHelper ?? throw new ArgumentNullException(nameof(reflectionHelper)); + this.Translation = translationHelper ?? throw new ArgumentNullException(nameof(translationHelper)); } /**** diff --git a/src/StardewModdingAPI/Framework/ModHelpers/ModRegistryHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/ModRegistryHelper.cs new file mode 100644 index 00000000..9e824694 --- /dev/null +++ b/src/StardewModdingAPI/Framework/ModHelpers/ModRegistryHelper.cs @@ -0,0 +1,48 @@ +using System.Collections.Generic; + +namespace StardewModdingAPI.Framework.ModHelpers +{ + /// <summary>Provides metadata about installed mods.</summary> + internal class ModRegistryHelper : BaseHelper, IModRegistry + { + /********* + ** Properties + *********/ + /// <summary>The underlying mod registry.</summary> + private readonly ModRegistry Registry; + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="modID">The unique ID of the relevant mod.</param> + /// <param name="registry">The underlying mod registry.</param> + public ModRegistryHelper(string modID, ModRegistry registry) + : base(modID) + { + this.Registry = registry; + } + + /// <summary>Get metadata for all loaded mods.</summary> + public IEnumerable<IManifest> GetAll() + { + return this.Registry.GetAll(); + } + + /// <summary>Get metadata for a loaded mod.</summary> + /// <param name="uniqueID">The mod's unique ID.</param> + /// <returns>Returns the matching mod's metadata, or <c>null</c> if not found.</returns> + public IManifest Get(string uniqueID) + { + return this.Registry.Get(uniqueID); + } + + /// <summary>Get whether a mod has been loaded.</summary> + /// <param name="uniqueID">The mod's unique ID.</param> + public bool IsLoaded(string uniqueID) + { + return this.Registry.IsLoaded(uniqueID); + } + } +} diff --git a/src/StardewModdingAPI/Framework/ModHelpers/ReflectionHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/ReflectionHelper.cs new file mode 100644 index 00000000..9411a97a --- /dev/null +++ b/src/StardewModdingAPI/Framework/ModHelpers/ReflectionHelper.cs @@ -0,0 +1,160 @@ +using System; +using StardewModdingAPI.Framework.Reflection; + +namespace StardewModdingAPI.Framework.ModHelpers +{ + /// <summary>Provides helper methods for accessing private game code.</summary> + /// <remarks>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).</remarks> + internal class ReflectionHelper : BaseHelper, IReflectionHelper + { + /********* + ** Properties + *********/ + /// <summary>The underlying reflection helper.</summary> + private readonly Reflector Reflector; + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="modID">The unique ID of the relevant mod.</param> + /// <param name="reflector">The underlying reflection helper.</param> + public ReflectionHelper(string modID, Reflector reflector) + : base(modID) + { + this.Reflector = reflector; + } + + /**** + ** Fields + ****/ + /// <summary>Get a private instance field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="obj">The object which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + /// <returns>Returns the field wrapper, or <c>null</c> if the field doesn't exist and <paramref name="required"/> is <c>false</c>.</returns> + public IPrivateField<TValue> GetPrivateField<TValue>(object obj, string name, bool required = true) + { + return this.Reflector.GetPrivateField<TValue>(obj, name, required); + } + + /// <summary>Get a private static field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="type">The type which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + public IPrivateField<TValue> GetPrivateField<TValue>(Type type, string name, bool required = true) + { + return this.Reflector.GetPrivateField<TValue>(type, name, required); + } + + /**** + ** Properties + ****/ + /// <summary>Get a private instance property.</summary> + /// <typeparam name="TValue">The property type.</typeparam> + /// <param name="obj">The object which has the property.</param> + /// <param name="name">The property name.</param> + /// <param name="required">Whether to throw an exception if the private property is not found.</param> + public IPrivateProperty<TValue> GetPrivateProperty<TValue>(object obj, string name, bool required = true) + { + return this.Reflector.GetPrivateProperty<TValue>(obj, name, required); + } + + /// <summary>Get a private static property.</summary> + /// <typeparam name="TValue">The property type.</typeparam> + /// <param name="type">The type which has the property.</param> + /// <param name="name">The property name.</param> + /// <param name="required">Whether to throw an exception if the private property is not found.</param> + public IPrivateProperty<TValue> GetPrivateProperty<TValue>(Type type, string name, bool required = true) + { + return this.Reflector.GetPrivateProperty<TValue>(type, name, required); + } + + /**** + ** Field values + ** (shorthand since this is the most common case) + ****/ + /// <summary>Get the value of a private instance field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="obj">The object which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + /// <returns>Returns the field value, or the default value for <typeparamref name="TValue"/> if the field wasn't found and <paramref name="required"/> is false.</returns> + /// <remarks> + /// This is a shortcut for <see cref="GetPrivateField{TValue}(object,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>. + /// When <paramref name="required" /> is false, this will return the default value if reflection fails. If you need to check whether the field exists, use <see cref="GetPrivateField{TValue}(object,string,bool)" /> instead. + /// </remarks> + public TValue GetPrivateValue<TValue>(object obj, string name, bool required = true) + { + IPrivateField<TValue> field = this.GetPrivateField<TValue>(obj, name, required); + return field != null + ? field.GetValue() + : default(TValue); + } + + /// <summary>Get the value of a private static field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="type">The type which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + /// <returns>Returns the field value, or the default value for <typeparamref name="TValue"/> if the field wasn't found and <paramref name="required"/> is false.</returns> + /// <remarks> + /// This is a shortcut for <see cref="GetPrivateField{TValue}(Type,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>. + /// When <paramref name="required" /> is false, this will return the default value if reflection fails. If you need to check whether the field exists, use <see cref="GetPrivateField{TValue}(Type,string,bool)" /> instead. + /// </remarks> + public TValue GetPrivateValue<TValue>(Type type, string name, bool required = true) + { + IPrivateField<TValue> field = this.GetPrivateField<TValue>(type, name, required); + return field != null + ? field.GetValue() + : default(TValue); + } + + /**** + ** Methods + ****/ + /// <summary>Get a private instance method.</summary> + /// <param name="obj">The object which has the method.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + public IPrivateMethod GetPrivateMethod(object obj, string name, bool required = true) + { + return this.Reflector.GetPrivateMethod(obj, name, required); + } + + /// <summary>Get a private static method.</summary> + /// <param name="type">The type which has the method.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + public IPrivateMethod GetPrivateMethod(Type type, string name, bool required = true) + { + return this.Reflector.GetPrivateMethod(type, name, required); + } + + /**** + ** Methods by signature + ****/ + /// <summary>Get a private instance method.</summary> + /// <param name="obj">The object which has the method.</param> + /// <param name="name">The field name.</param> + /// <param name="argumentTypes">The argument types of the method signature to find.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + public IPrivateMethod GetPrivateMethod(object obj, string name, Type[] argumentTypes, bool required = true) + { + return this.Reflector.GetPrivateMethod(obj, name, argumentTypes, required); + } + + /// <summary>Get a private static method.</summary> + /// <param name="type">The type which has the method.</param> + /// <param name="name">The field name.</param> + /// <param name="argumentTypes">The argument types of the method signature to find.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + public IPrivateMethod GetPrivateMethod(Type type, string name, Type[] argumentTypes, bool required = true) + { + return this.Reflector.GetPrivateMethod(type, name, argumentTypes, required); + } + } +} diff --git a/src/StardewModdingAPI/Framework/TranslationHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/TranslationHelper.cs index fe387789..bbe3a81a 100644 --- a/src/StardewModdingAPI/Framework/TranslationHelper.cs +++ b/src/StardewModdingAPI/Framework/ModHelpers/TranslationHelper.cs @@ -3,10 +3,10 @@ using System.Collections.Generic; using System.Linq; using StardewValley; -namespace StardewModdingAPI.Framework +namespace StardewModdingAPI.Framework.ModHelpers { /// <summary>Provides translations stored in the mod's <c>i18n</c> folder, with one file per locale (like <c>en.json</c>) containing a flat key => value structure. Translations are fetched with locale fallback, so missing translations are filled in from broader locales (like <c>pt-BR.json</c> < <c>pt.json</c> < <c>default.json</c>).</summary> - internal class TranslationHelper : ITranslationHelper + internal class TranslationHelper : BaseHelper, ITranslationHelper { /********* ** Properties @@ -35,10 +35,12 @@ namespace StardewModdingAPI.Framework ** Public methods *********/ /// <summary>Construct an instance.</summary> + /// <param name="modID">The unique ID of the relevant mod.</param> /// <param name="modName">The name of the relevant mod for error messages.</param> /// <param name="locale">The initial locale.</param> /// <param name="languageCode">The game's current language code.</param> - public TranslationHelper(string modName, string locale, LocalizedContentManager.LanguageCode languageCode) + public TranslationHelper(string modID, string modName, string locale, LocalizedContentManager.LanguageCode languageCode) + : base(modID) { // save data this.ModName = modName; diff --git a/src/StardewModdingAPI/Framework/ModLoading/AssemblyLoader.cs b/src/StardewModdingAPI/Framework/ModLoading/AssemblyLoader.cs index 42bd7bfb..406d49e1 100644 --- a/src/StardewModdingAPI/Framework/ModLoading/AssemblyLoader.cs +++ b/src/StardewModdingAPI/Framework/ModLoading/AssemblyLoader.cs @@ -71,13 +71,15 @@ namespace StardewModdingAPI.Framework.ModLoading } // rewrite & load assemblies in leaf-to-root order + bool oneAssembly = assemblies.Length == 1; Assembly lastAssembly = null; foreach (AssemblyParseResult assembly in assemblies) { - bool changed = this.RewriteAssembly(assembly.Definition, assumeCompatible); + bool changed = this.RewriteAssembly(assembly.Definition, assumeCompatible, logPrefix: " "); if (changed) { - this.Monitor.Log($"Loading {assembly.File.Name} (rewritten in memory)...", LogLevel.Trace); + if (!oneAssembly) + this.Monitor.Log($" Loading {assembly.File.Name}.dll (rewritten in memory)...", LogLevel.Trace); using (MemoryStream outStream = new MemoryStream()) { assembly.Definition.Write(outStream); @@ -87,7 +89,8 @@ namespace StardewModdingAPI.Framework.ModLoading } else { - this.Monitor.Log($"Loading {assembly.File.Name}...", LogLevel.Trace); + if (!oneAssembly) + this.Monitor.Log($" Loading {assembly.File.Name}.dll...", LogLevel.Trace); lastAssembly = Assembly.UnsafeLoadFrom(assembly.File.FullName); } } @@ -161,12 +164,14 @@ namespace StardewModdingAPI.Framework.ModLoading /// <summary>Rewrite the types referenced by an assembly.</summary> /// <param name="assembly">The assembly to rewrite.</param> /// <param name="assumeCompatible">Assume the mod is compatible, even if incompatible code is detected.</param> + /// <param name="logPrefix">A string to prefix to log messages.</param> /// <returns>Returns whether the assembly was modified.</returns> /// <exception cref="IncompatibleInstructionException">An incompatible CIL instruction was found while rewriting the assembly.</exception> - private bool RewriteAssembly(AssemblyDefinition assembly, bool assumeCompatible) + private bool RewriteAssembly(AssemblyDefinition assembly, bool assumeCompatible, string logPrefix) { ModuleDefinition module = assembly.MainModule; HashSet<string> loggedMessages = new HashSet<string>(); + string filename = $"{assembly.Name.Name}.dll"; // swap assembly references if needed (e.g. XNA => MonoGame) bool platformChanged = false; @@ -175,7 +180,7 @@ namespace StardewModdingAPI.Framework.ModLoading // remove old assembly reference if (this.AssemblyMap.RemoveNames.Any(name => module.AssemblyReferences[i].Name == name)) { - this.LogOnce(this.Monitor, loggedMessages, $"Rewriting {assembly.Name.Name} for OS..."); + this.LogOnce(this.Monitor, loggedMessages, $"{logPrefix}Rewriting {filename} for OS..."); platformChanged = true; module.AssemblyReferences.RemoveAt(i); i--; @@ -205,15 +210,15 @@ namespace StardewModdingAPI.Framework.ModLoading { if (rewriter.Rewrite(module, method, this.AssemblyMap, platformChanged)) { - this.LogOnce(this.Monitor, loggedMessages, $"Rewrote {assembly.Name.Name} to fix {rewriter.NounPhrase}..."); + this.LogOnce(this.Monitor, loggedMessages, $"{logPrefix}Rewrote {filename} to fix {rewriter.NounPhrase}..."); anyRewritten = true; } } catch (IncompatibleInstructionException) { if (!assumeCompatible) - throw new IncompatibleInstructionException(rewriter.NounPhrase, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {assembly.Name.Name}."); - this.LogOnce(this.Monitor, loggedMessages, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {assembly.Name.Name}, but SMAPI is configured to allow it anyway. The mod may crash or behave unexpectedly.", LogLevel.Warn); + throw new IncompatibleInstructionException(rewriter.NounPhrase, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {filename}."); + this.LogOnce(this.Monitor, loggedMessages, $"{logPrefix}Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {filename}, but SMAPI is configured to allow it anyway. The mod may crash or behave unexpectedly.", LogLevel.Warn); } } @@ -227,15 +232,15 @@ namespace StardewModdingAPI.Framework.ModLoading { if (rewriter.Rewrite(module, cil, instruction, this.AssemblyMap, platformChanged)) { - this.LogOnce(this.Monitor, loggedMessages, $"Rewrote {assembly.Name.Name} to fix {rewriter.NounPhrase}..."); + this.LogOnce(this.Monitor, loggedMessages, $"{logPrefix}Rewrote {filename} to fix {rewriter.NounPhrase}..."); anyRewritten = true; } } catch (IncompatibleInstructionException) { if (!assumeCompatible) - throw new IncompatibleInstructionException(rewriter.NounPhrase, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {assembly.Name.Name}."); - this.LogOnce(this.Monitor, loggedMessages, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {assembly.Name.Name}, but SMAPI is configured to allow it anyway. The mod may crash or behave unexpectedly.", LogLevel.Warn); + throw new IncompatibleInstructionException(rewriter.NounPhrase, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {filename}."); + this.LogOnce(this.Monitor, loggedMessages, $"{logPrefix}Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {filename}, but SMAPI is configured to allow it anyway. The mod may crash or behave unexpectedly.", LogLevel.Warn); } } } diff --git a/src/StardewModdingAPI/Framework/ModLoading/ModResolver.cs b/src/StardewModdingAPI/Framework/ModLoading/ModResolver.cs index f5139ce5..38dddce7 100644 --- a/src/StardewModdingAPI/Framework/ModLoading/ModResolver.cs +++ b/src/StardewModdingAPI/Framework/ModLoading/ModResolver.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using StardewModdingAPI.Framework.Exceptions; using StardewModdingAPI.Framework.Models; using StardewModdingAPI.Framework.Serialisation; @@ -17,10 +18,13 @@ namespace StardewModdingAPI.Framework.ModLoading /// <param name="rootPath">The root path to search for mods.</param> /// <param name="jsonHelper">The JSON helper with which to read manifests.</param> /// <param name="compatibilityRecords">Metadata about mods that SMAPI should assume is compatible or broken, regardless of whether it detects incompatible code.</param> + /// <param name="disabledMods">Metadata about mods that SMAPI should consider obsolete and not load.</param> /// <returns>Returns the manifests by relative folder.</returns> - public IEnumerable<IModMetadata> ReadManifests(string rootPath, JsonHelper jsonHelper, IEnumerable<ModCompatibility> compatibilityRecords) + public IEnumerable<IModMetadata> ReadManifests(string rootPath, JsonHelper jsonHelper, IEnumerable<ModCompatibility> compatibilityRecords, IEnumerable<DisabledMod> disabledMods) { compatibilityRecords = compatibilityRecords.ToArray(); + disabledMods = disabledMods.ToArray(); + foreach (DirectoryInfo modDir in this.GetModFolders(rootPath)) { // read file @@ -42,25 +46,38 @@ namespace StardewModdingAPI.Framework.ModLoading else if (string.IsNullOrWhiteSpace(manifest.EntryDll)) error = "its manifest doesn't set an entry DLL."; } + catch (SParseException ex) + { + error = $"parsing its manifest failed: {ex.Message}"; + } catch (Exception ex) { error = $"parsing its manifest failed:\n{ex.GetLogSummary()}"; } - // get compatibility record + // validate metadata ModCompatibility compatibility = null; if (manifest != null) { + // get unique key for lookups string key = !string.IsNullOrWhiteSpace(manifest.UniqueID) ? manifest.UniqueID : manifest.EntryDll; + + // check if mod should be disabled + DisabledMod disabledMod = disabledMods.FirstOrDefault(mod => mod.ID.Contains(key, StringComparer.InvariantCultureIgnoreCase)); + if (disabledMod != null) + error = $"it's obsolete: {disabledMod.ReasonPhrase}"; + + // get compatibility record compatibility = ( from mod in compatibilityRecords where - mod.ID.Contains(key, StringComparer.InvariantCultureIgnoreCase) - && (mod.LowerSemanticVersion == null || !manifest.Version.IsOlderThan(mod.LowerSemanticVersion)) - && !manifest.Version.IsNewerThan(mod.UpperSemanticVersion) + mod.ID.Contains(key, StringComparer.InvariantCultureIgnoreCase) + && (mod.LowerSemanticVersion == null || !manifest.Version.IsOlderThan(mod.LowerSemanticVersion)) + && !manifest.Version.IsNewerThan(mod.UpperSemanticVersion) select mod ).FirstOrDefault(); } + // build metadata string displayName = !string.IsNullOrWhiteSpace(manifest?.Name) ? manifest.Name @@ -92,7 +109,7 @@ namespace StardewModdingAPI.Framework.ModLoading bool hasOfficialUrl = !string.IsNullOrWhiteSpace(mod.Compatibility.UpdateUrl); bool hasUnofficialUrl = !string.IsNullOrWhiteSpace(mod.Compatibility.UnofficialUpdateUrl); - string reasonPhrase = compatibility.ReasonPhrase ?? "it's not compatible with the latest version of the game"; + string reasonPhrase = compatibility.ReasonPhrase ?? "it's not compatible with the latest version of the game or SMAPI"; string error = $"{reasonPhrase}. Please check for a version newer than {compatibility.UpperVersionLabel ?? compatibility.UpperVersion} here:"; if (hasOfficialUrl) error += !hasUnofficialUrl ? $" {compatibility.UpdateUrl}" : $"{Environment.NewLine}- official mod: {compatibility.UpdateUrl}"; @@ -105,24 +122,36 @@ namespace StardewModdingAPI.Framework.ModLoading } // validate SMAPI version - if (!string.IsNullOrWhiteSpace(mod.Manifest.MinimumApiVersion)) + if (mod.Manifest.MinimumApiVersion?.IsNewerThan(apiVersion) == true) { - if (!SemanticVersion.TryParse(mod.Manifest.MinimumApiVersion, out ISemanticVersion minVersion)) - { - mod.SetStatus(ModMetadataStatus.Failed, $"it has an invalid minimum SMAPI version '{mod.Manifest.MinimumApiVersion}'. This should be a semantic version number like {apiVersion}."); - continue; - } - if (minVersion.IsNewerThan(apiVersion)) - { - mod.SetStatus(ModMetadataStatus.Failed, $"it needs SMAPI {minVersion} or later. Please update SMAPI to the latest version to use this mod."); - continue; - } + mod.SetStatus(ModMetadataStatus.Failed, $"it needs SMAPI {mod.Manifest.MinimumApiVersion} or later. Please update SMAPI to the latest version to use this mod."); + continue; } // validate DLL path string assemblyPath = Path.Combine(mod.DirectoryPath, mod.Manifest.EntryDll); if (!File.Exists(assemblyPath)) + { mod.SetStatus(ModMetadataStatus.Failed, $"its DLL '{mod.Manifest.EntryDll}' doesn't exist."); + continue; + } + + // validate required fields +#if SMAPI_2_0 + { + List<string> missingFields = new List<string>(3); + + if (string.IsNullOrWhiteSpace(mod.Manifest.Name)) + missingFields.Add(nameof(IManifest.Name)); + if (mod.Manifest.Version == null || mod.Manifest.Version.ToString() == "0.0") + missingFields.Add(nameof(IManifest.Version)); + if (string.IsNullOrWhiteSpace(mod.Manifest.UniqueID)) + missingFields.Add(nameof(IManifest.UniqueID)); + + if (missingFields.Any()) + mod.SetStatus(ModMetadataStatus.Failed, $"its manifest is missing required fields ({string.Join(", ", missingFields)})."); + } +#endif } } @@ -193,20 +222,51 @@ namespace StardewModdingAPI.Framework.ModLoading return states[mod] = ModDependencyStatus.Sorted; } + // get dependencies + var dependencies = + ( + from entry in mod.Manifest.Dependencies + let dependencyMod = mods.FirstOrDefault(m => string.Equals(m.Manifest?.UniqueID, entry.UniqueID, StringComparison.InvariantCultureIgnoreCase)) + orderby entry.UniqueID + select new + { + ID = entry.UniqueID, + MinVersion = entry.MinimumVersion, + Mod = dependencyMod, + IsRequired = +#if SMAPI_2_0 + entry.IsRequired +#else + true +#endif + } + ) + .ToArray(); + // missing required dependencies, mark failed { - string[] missingModIDs = + string[] failedIDs = (from entry in dependencies where entry.IsRequired && entry.Mod == null select entry.ID).ToArray(); + if (failedIDs.Any()) + { + sortedMods.Push(mod); + mod.SetStatus(ModMetadataStatus.Failed, $"it requires mods which aren't installed ({string.Join(", ", failedIDs)})."); + return states[mod] = ModDependencyStatus.Failed; + } + } + + // dependency min version not met, mark failed + { + string[] failedLabels = ( - from dependency in mod.Manifest.Dependencies - where mods.All(m => m.Manifest?.UniqueID != dependency.UniqueID) - orderby dependency.UniqueID - select dependency.UniqueID + from entry in dependencies + where entry.Mod != null && entry.MinVersion != null && entry.MinVersion.IsNewerThan(entry.Mod.Manifest.Version) + select $"{entry.Mod.DisplayName} (needs {entry.MinVersion} or later)" ) .ToArray(); - if (missingModIDs.Any()) + if (failedLabels.Any()) { sortedMods.Push(mod); - mod.SetStatus(ModMetadataStatus.Failed, $"it requires mods which aren't installed ({string.Join(", ", missingModIDs)})."); + mod.SetStatus(ModMetadataStatus.Failed, $"it needs newer versions of some mods: {string.Join(", ", failedLabels)}."); return states[mod] = ModDependencyStatus.Failed; } } @@ -215,20 +275,16 @@ namespace StardewModdingAPI.Framework.ModLoading { states[mod] = ModDependencyStatus.Checking; - // get mods to load first - IModMetadata[] modsToLoadFirst = - ( - from other in mods - where mod.Manifest.Dependencies.Any(required => required.UniqueID == other.Manifest?.UniqueID) - select other - ) - .ToArray(); - // recursively sort dependencies - foreach (IModMetadata requiredMod in modsToLoadFirst) + foreach (var dependency in dependencies) { + IModMetadata requiredMod = dependency.Mod; var subchain = new List<IModMetadata>(currentChain) { mod }; + // ignore missing optional dependency + if (!dependency.IsRequired && requiredMod == null) + continue; + // detect dependency loop if (states[requiredMod] == ModDependencyStatus.Checking) { diff --git a/src/StardewModdingAPI/Framework/ModRegistry.cs b/src/StardewModdingAPI/Framework/ModRegistry.cs index f9d3cfbf..a427bdb7 100644 --- a/src/StardewModdingAPI/Framework/ModRegistry.cs +++ b/src/StardewModdingAPI/Framework/ModRegistry.cs @@ -7,7 +7,7 @@ using System.Reflection; namespace StardewModdingAPI.Framework { /// <summary>Tracks the installed mods.</summary> - internal class ModRegistry : IModRegistry + internal class ModRegistry { /********* ** Properties @@ -23,7 +23,7 @@ namespace StardewModdingAPI.Framework ** Public methods *********/ /**** - ** IModRegistry + ** Basic metadata ****/ /// <summary>Get metadata for all loaded mods.</summary> public IEnumerable<IManifest> GetAll() @@ -47,7 +47,7 @@ namespace StardewModdingAPI.Framework } /**** - ** Internal methods + ** Mod data ****/ /// <summary>Register a mod as a possible source of deprecation warnings.</summary> /// <param name="metadata">The mod metadata.</param> diff --git a/src/StardewModdingAPI/Framework/Models/DisabledMod.cs b/src/StardewModdingAPI/Framework/Models/DisabledMod.cs new file mode 100644 index 00000000..170fa760 --- /dev/null +++ b/src/StardewModdingAPI/Framework/Models/DisabledMod.cs @@ -0,0 +1,22 @@ +namespace StardewModdingAPI.Framework.Models +{ + /// <summary>Metadata about for a mod that should never be loaded.</summary> + internal class DisabledMod + { + /********* + ** Accessors + *********/ + /**** + ** From config + ****/ + /// <summary>The unique mod IDs.</summary> + public string[] ID { get; set; } + + /// <summary>The mod name.</summary> + public string Name { get; set; } + + /// <summary>The reason phrase to show in the warning, or <c>null</c> to use the default value.</summary> + /// <example>"this mod is no longer supported or used"</example> + public string ReasonPhrase { get; set; } + } +} diff --git a/src/StardewModdingAPI/Framework/Models/Manifest.cs b/src/StardewModdingAPI/Framework/Models/Manifest.cs index be781585..08b88025 100644 --- a/src/StardewModdingAPI/Framework/Models/Manifest.cs +++ b/src/StardewModdingAPI/Framework/Models/Manifest.cs @@ -25,7 +25,8 @@ namespace StardewModdingAPI.Framework.Models public ISemanticVersion Version { get; set; } /// <summary>The minimum SMAPI version required by this mod, if any.</summary> - public string MinimumApiVersion { get; set; } + [JsonConverter(typeof(ManifestFieldConverter))] + public ISemanticVersion MinimumApiVersion { get; set; } /// <summary>The name of the DLL in the directory that has the <see cref="Mod.Entry"/> method.</summary> public string EntryDll { get; set; } @@ -37,9 +38,11 @@ namespace StardewModdingAPI.Framework.Models /// <summary>The unique mod ID.</summary> public string UniqueID { get; set; } +#if !SMAPI_2_0 /// <summary>Whether the mod uses per-save config files.</summary> [Obsolete("Use " + nameof(Mod) + "." + nameof(Mod.Helper) + "." + nameof(IModHelper.ReadConfig) + " instead")] public bool PerSaveConfigs { get; set; } +#endif /// <summary>Any manifest fields which didn't match a valid field.</summary> [JsonExtensionData] diff --git a/src/StardewModdingAPI/Framework/Models/ManifestDependency.cs b/src/StardewModdingAPI/Framework/Models/ManifestDependency.cs index 2f580c1d..25d92a29 100644 --- a/src/StardewModdingAPI/Framework/Models/ManifestDependency.cs +++ b/src/StardewModdingAPI/Framework/Models/ManifestDependency.cs @@ -9,15 +9,34 @@ /// <summary>The unique mod ID to require.</summary> public string UniqueID { get; set; } + /// <summary>The minimum required version (if any).</summary> + public ISemanticVersion MinimumVersion { get; set; } + +#if SMAPI_2_0 + /// <summary>Whether the dependency must be installed to use the mod.</summary> + public bool IsRequired { get; set; } +#endif /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="uniqueID">The unique mod ID to require.</param> - public ManifestDependency(string uniqueID) + /// <param name="minimumVersion">The minimum required version (if any).</param> + /// <param name="required">Whether the dependency must be installed to use the mod.</param> + public ManifestDependency(string uniqueID, string minimumVersion +#if SMAPI_2_0 + , bool required = true +#endif + ) { this.UniqueID = uniqueID; + this.MinimumVersion = !string.IsNullOrWhiteSpace(minimumVersion) + ? new SemanticVersion(minimumVersion) + : null; +#if SMAPI_2_0 + this.IsRequired = required; +#endif } } } diff --git a/src/StardewModdingAPI/Framework/Models/SConfig.cs b/src/StardewModdingAPI/Framework/Models/SConfig.cs index c3f0816e..b2ca4113 100644 --- a/src/StardewModdingAPI/Framework/Models/SConfig.cs +++ b/src/StardewModdingAPI/Framework/Models/SConfig.cs @@ -17,5 +17,8 @@ /// <summary>A list of mod versions which should be considered compatible or incompatible regardless of whether SMAPI detects incompatible code.</summary> public ModCompatibility[] ModCompatibility { get; set; } + + /// <summary>A list of mods which should be considered obsolete and not loaded.</summary> + public DisabledMod[] DisabledMods { get; set; } } } diff --git a/src/StardewModdingAPI/Framework/Monitor.cs b/src/StardewModdingAPI/Framework/Monitor.cs index 925efc33..6359b454 100644 --- a/src/StardewModdingAPI/Framework/Monitor.cs +++ b/src/StardewModdingAPI/Framework/Monitor.cs @@ -45,6 +45,11 @@ namespace StardewModdingAPI.Framework /// <summary>Whether SMAPI is aborting. Mods don't need to worry about this unless they have background tasks.</summary> public bool IsExiting => this.ExitTokenSource.IsCancellationRequested; +#if SMAPI_2_0 + /// <summary>Whether to show the full log stamps (with time/level/logger) in the console. If false, shows a simplified stamp with only the logger.</summary> + internal bool ShowFullStampInConsole { get; set; } +#endif + /// <summary>Whether to show trace messages in the console.</summary> internal bool ShowTraceInConsole { get; set; } @@ -92,6 +97,18 @@ namespace StardewModdingAPI.Framework this.ExitTokenSource.Cancel(); } +#if SMAPI_2_0 + /// <summary>Write a newline to the console and log file.</summary> + internal void Newline() + { + if (this.WriteToConsole) + this.ConsoleManager.ExclusiveWriteWithoutInterception(Console.WriteLine); + if (this.WriteToFile) + this.LogFile.WriteLine(""); + } +#endif + +#if !SMAPI_2_0 /// <summary>Log a message for the player or developer, using the specified console color.</summary> /// <param name="source">The name of the mod logging the message.</param> /// <param name="message">The message to log.</param> @@ -102,6 +119,7 @@ namespace StardewModdingAPI.Framework { this.LogImpl(source, message, level, color); } +#endif /********* @@ -124,7 +142,13 @@ namespace StardewModdingAPI.Framework { // generate message string levelStr = level.ToString().ToUpper().PadRight(Monitor.MaxLevelLength); - message = $"[{DateTime.Now:HH:mm:ss} {levelStr} {source}] {message}"; + + string fullMessage = $"[{DateTime.Now:HH:mm:ss} {levelStr} {source}] {message}"; +#if SMAPI_2_0 + string consoleMessage = this.ShowFullStampInConsole ? fullMessage : $"[{source}] {message}"; +#else + string consoleMessage = fullMessage; +#endif // write to console if (this.WriteToConsole && (this.ShowTraceInConsole || level != LogLevel.Trace)) @@ -136,17 +160,17 @@ namespace StardewModdingAPI.Framework if (background.HasValue) Console.BackgroundColor = background.Value; Console.ForegroundColor = color; - Console.WriteLine(message); + Console.WriteLine(consoleMessage); Console.ResetColor(); } else - Console.WriteLine(message); + Console.WriteLine(consoleMessage); }); } // write to log file if (this.WriteToFile) - this.LogFile.WriteLine(message); + this.LogFile.WriteLine(fullMessage); } } } diff --git a/src/StardewModdingAPI/Framework/Reflection/ReflectionHelper.cs b/src/StardewModdingAPI/Framework/Reflection/Reflector.cs index 7a5789dc..5c2d90fa 100644 --- a/src/StardewModdingAPI/Framework/Reflection/ReflectionHelper.cs +++ b/src/StardewModdingAPI/Framework/Reflection/Reflector.cs @@ -7,13 +7,13 @@ namespace StardewModdingAPI.Framework.Reflection { /// <summary>Provides helper methods for accessing private game code.</summary> /// <remarks>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).</remarks> - internal class ReflectionHelper : IReflectionHelper + internal class Reflector { /********* ** Properties *********/ /// <summary>The cached fields and methods found via reflection.</summary> - private readonly MemoryCache Cache = new MemoryCache(typeof(ReflectionHelper).FullName); + private readonly MemoryCache Cache = new MemoryCache(typeof(Reflector).FullName); /// <summary>The sliding cache expiration time.</summary> private readonly TimeSpan SlidingCacheExpiry = TimeSpan.FromMinutes(5); @@ -94,46 +94,6 @@ namespace StardewModdingAPI.Framework.Reflection } /**** - ** Field values - ** (shorthand since this is the most common case) - ****/ - /// <summary>Get the value of a private instance field.</summary> - /// <typeparam name="TValue">The field type.</typeparam> - /// <param name="obj">The object which has the field.</param> - /// <param name="name">The field name.</param> - /// <param name="required">Whether to throw an exception if the private field is not found.</param> - /// <returns>Returns the field value, or the default value for <typeparamref name="TValue"/> if the field wasn't found and <paramref name="required"/> is false.</returns> - /// <remarks> - /// This is a shortcut for <see cref="GetPrivateField{TValue}(object,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>. - /// When <paramref name="required" /> is false, this will return the default value if reflection fails. If you need to check whether the field exists, use <see cref="GetPrivateField{TValue}(object,string,bool)" /> instead. - /// </remarks> - public TValue GetPrivateValue<TValue>(object obj, string name, bool required = true) - { - IPrivateField<TValue> field = this.GetPrivateField<TValue>(obj, name, required); - return field != null - ? field.GetValue() - : default(TValue); - } - - /// <summary>Get the value of a private static field.</summary> - /// <typeparam name="TValue">The field type.</typeparam> - /// <param name="type">The type which has the field.</param> - /// <param name="name">The field name.</param> - /// <param name="required">Whether to throw an exception if the private field is not found.</param> - /// <returns>Returns the field value, or the default value for <typeparamref name="TValue"/> if the field wasn't found and <paramref name="required"/> is false.</returns> - /// <remarks> - /// This is a shortcut for <see cref="GetPrivateField{TValue}(Type,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>. - /// When <paramref name="required" /> is false, this will return the default value if reflection fails. If you need to check whether the field exists, use <see cref="GetPrivateField{TValue}(Type,string,bool)" /> instead. - /// </remarks> - public TValue GetPrivateValue<TValue>(Type type, string name, bool required = true) - { - IPrivateField<TValue> field = this.GetPrivateField<TValue>(type, name, required); - return field != null - ? field.GetValue() - : default(TValue); - } - - /**** ** Methods ****/ /// <summary>Get a private instance method.</summary> diff --git a/src/StardewModdingAPI/Framework/SContentManager.cs b/src/StardewModdingAPI/Framework/SContentManager.cs index acd3e108..669b0e7a 100644 --- a/src/StardewModdingAPI/Framework/SContentManager.cs +++ b/src/StardewModdingAPI/Framework/SContentManager.cs @@ -3,14 +3,16 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; -using System.Threading; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.AssemblyRewriters; -using StardewModdingAPI.Events; using StardewModdingAPI.Framework.Content; using StardewModdingAPI.Framework.Reflection; using StardewValley; +using StardewValley.BellsAndWhistles; +using StardewValley.Objects; +using StardewValley.Projectiles; namespace StardewModdingAPI.Framework { @@ -42,6 +44,12 @@ namespace StardewModdingAPI.Framework /********* ** Accessors *********/ + /// <summary>Interceptors which provide the initial versions of matching assets.</summary> + internal IDictionary<IModMetadata, IList<IAssetLoader>> Loaders { get; } = new Dictionary<IModMetadata, IList<IAssetLoader>>(); + + /// <summary>Interceptors which edit matching assets after they're loaded.</summary> + internal IDictionary<IModMetadata, IList<IAssetEditor>> Editors { get; } = new Dictionary<IModMetadata, IList<IAssetEditor>>(); + /// <summary>The absolute path to the <see cref="ContentManager.RootDirectory"/>.</summary> public string FullRootDirectory => Path.Combine(Constants.ExecutionPath, this.RootDirectory); @@ -52,22 +60,19 @@ namespace StardewModdingAPI.Framework /// <summary>Construct an instance.</summary> /// <param name="serviceProvider">The service provider to use to locate services.</param> /// <param name="rootDirectory">The root directory to search for content.</param> - /// <param name="monitor">Encapsulates monitoring and logging.</param> - public SContentManager(IServiceProvider serviceProvider, string rootDirectory, IMonitor monitor) - : this(serviceProvider, rootDirectory, Thread.CurrentThread.CurrentUICulture, null, monitor) { } - - /// <summary>Construct an instance.</summary> - /// <param name="serviceProvider">The service provider to use to locate services.</param> - /// <param name="rootDirectory">The root directory to search for content.</param> /// <param name="currentCulture">The current culture for which to localise content.</param> /// <param name="languageCodeOverride">The current language code for which to localise content.</param> /// <param name="monitor">Encapsulates monitoring and logging.</param> public SContentManager(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, string languageCodeOverride, IMonitor monitor) : base(serviceProvider, rootDirectory, currentCulture, languageCodeOverride) { + // validate + if (monitor == null) + throw new ArgumentNullException(nameof(monitor)); + // initialise + var reflection = new Reflector(); this.Monitor = monitor; - IReflectionHelper reflection = new ReflectionHelper(); // get underlying fields for interception this.Cache = reflection.GetPrivateField<Dictionary<string, object>>(this, "loadedAssets").GetValue(); @@ -117,22 +122,24 @@ namespace StardewModdingAPI.Framework /// <param name="assetName">The asset path relative to the loader root directory, not including the <c>.xnb</c> extension.</param> public override T Load<T>(string assetName) { - // get normalised metadata assetName = this.NormaliseAssetName(assetName); - string cacheLocale = this.GetCacheLocale(assetName); // skip if already loaded if (this.IsNormalisedKeyLoaded(assetName)) return base.Load<T>(assetName); - // load data - T data = base.Load<T>(assetName); + // load asset + T data; + { + IAssetInfo info = new AssetInfo(this.GetLocale(), assetName, typeof(T), this.NormaliseAssetName); + IAssetData asset = this.ApplyLoader<T>(info) ?? new AssetDataForObject(info, base.Load<T>(assetName), this.NormaliseAssetName); + asset = this.ApplyEditors<T>(info, asset); + data = (T)asset.Data; + } - // let mods intercept content - IContentEventHelper helper = new ContentEventHelper(cacheLocale, assetName, data, this.NormaliseAssetName); - ContentEvents.InvokeAfterAssetLoaded(this.Monitor, helper); - this.Cache[assetName] = helper.Data; - return (T)helper.Data; + // update cache & return data + this.Cache[assetName] = data; + return data; } /// <summary>Inject an asset into the cache.</summary> @@ -142,6 +149,7 @@ namespace StardewModdingAPI.Framework public void Inject<T>(string assetName, T value) { assetName = this.NormaliseAssetName(assetName); + this.Cache[assetName] = value; } @@ -151,6 +159,57 @@ namespace StardewModdingAPI.Framework return this.GetKeyLocale.Invoke<string>(); } + /// <summary>Reset the asset cache and reload the game's static assets.</summary> + /// <remarks>This implementation is derived from <see cref="Game1.LoadContent"/>.</remarks> + public void Reset() + { + this.Monitor.Log("Resetting asset cache...", LogLevel.Trace); + this.Cache.Clear(); + + // from Game1.LoadContent + Game1.daybg = this.Load<Texture2D>("LooseSprites\\daybg"); + Game1.nightbg = this.Load<Texture2D>("LooseSprites\\nightbg"); + Game1.menuTexture = this.Load<Texture2D>("Maps\\MenuTiles"); + Game1.lantern = this.Load<Texture2D>("LooseSprites\\Lighting\\lantern"); + Game1.windowLight = this.Load<Texture2D>("LooseSprites\\Lighting\\windowLight"); + Game1.sconceLight = this.Load<Texture2D>("LooseSprites\\Lighting\\sconceLight"); + Game1.cauldronLight = this.Load<Texture2D>("LooseSprites\\Lighting\\greenLight"); + Game1.indoorWindowLight = this.Load<Texture2D>("LooseSprites\\Lighting\\indoorWindowLight"); + Game1.shadowTexture = this.Load<Texture2D>("LooseSprites\\shadow"); + Game1.mouseCursors = this.Load<Texture2D>("LooseSprites\\Cursors"); + Game1.controllerMaps = this.Load<Texture2D>("LooseSprites\\ControllerMaps"); + Game1.animations = this.Load<Texture2D>("TileSheets\\animations"); + Game1.achievements = this.Load<Dictionary<int, string>>("Data\\Achievements"); + Game1.NPCGiftTastes = this.Load<Dictionary<string, string>>("Data\\NPCGiftTastes"); + Game1.dialogueFont = this.Load<SpriteFont>("Fonts\\SpriteFont1"); + Game1.smallFont = this.Load<SpriteFont>("Fonts\\SmallFont"); + Game1.tinyFont = this.Load<SpriteFont>("Fonts\\tinyFont"); + Game1.tinyFontBorder = this.Load<SpriteFont>("Fonts\\tinyFontBorder"); + Game1.objectSpriteSheet = this.Load<Texture2D>("Maps\\springobjects"); + Game1.cropSpriteSheet = this.Load<Texture2D>("TileSheets\\crops"); + Game1.emoteSpriteSheet = this.Load<Texture2D>("TileSheets\\emotes"); + Game1.debrisSpriteSheet = this.Load<Texture2D>("TileSheets\\debris"); + Game1.bigCraftableSpriteSheet = this.Load<Texture2D>("TileSheets\\Craftables"); + Game1.rainTexture = this.Load<Texture2D>("TileSheets\\rain"); + Game1.buffsIcons = this.Load<Texture2D>("TileSheets\\BuffsIcons"); + Game1.objectInformation = this.Load<Dictionary<int, string>>("Data\\ObjectInformation"); + Game1.bigCraftablesInformation = this.Load<Dictionary<int, string>>("Data\\BigCraftablesInformation"); + FarmerRenderer.hairStylesTexture = this.Load<Texture2D>("Characters\\Farmer\\hairstyles"); + FarmerRenderer.shirtsTexture = this.Load<Texture2D>("Characters\\Farmer\\shirts"); + FarmerRenderer.hatsTexture = this.Load<Texture2D>("Characters\\Farmer\\hats"); + FarmerRenderer.accessoriesTexture = this.Load<Texture2D>("Characters\\Farmer\\accessories"); + Furniture.furnitureTexture = this.Load<Texture2D>("TileSheets\\furniture"); + SpriteText.spriteTexture = this.Load<Texture2D>("LooseSprites\\font_bold"); + SpriteText.coloredTexture = this.Load<Texture2D>("LooseSprites\\font_colored"); + Tool.weaponsTexture = this.Load<Texture2D>("TileSheets\\weapons"); + Projectile.projectileSheet = this.Load<Texture2D>("TileSheets\\Projectiles"); + + // from Farmer constructor + if (Game1.player != null) + Game1.player.FarmerRenderer = new FarmerRenderer(this.Load<Texture2D>("Characters\\Farmer\\farmer_" + (Game1.player.isMale ? "" : "girl_") + "base")); + } + + /********* ** Private methods *********/ @@ -162,14 +221,151 @@ namespace StardewModdingAPI.Framework || this.Cache.ContainsKey($"{normalisedAssetName}.{this.GetKeyLocale.Invoke<string>()}"); // translated asset } - /// <summary>Get the locale for which the asset name was saved, if any.</summary> - /// <param name="normalisedAssetName">The normalised asset name.</param> - private string GetCacheLocale(string normalisedAssetName) + /// <summary>Load the initial asset from the registered <see cref="Loaders"/>.</summary> + /// <param name="info">The basic asset metadata.</param> + /// <returns>Returns the loaded asset metadata, or <c>null</c> if no loader matched.</returns> + private IAssetData ApplyLoader<T>(IAssetInfo info) + { + // find matching loaders + var loaders = this.GetInterceptors(this.Loaders) + .Where(entry => + { + try + { + return entry.Value.CanLoad<T>(info); + } + catch (Exception ex) + { + this.Monitor.Log($"{entry.Key.DisplayName} crashed when checking whether it could load asset '{info.AssetName}', and will be ignored. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); + return false; + } + }) + .ToArray(); + + // validate loaders + if (!loaders.Any()) + return null; + if (loaders.Length > 1) + { + string[] loaderNames = loaders.Select(p => p.Key.DisplayName).ToArray(); + this.Monitor.Log($"Multiple mods want to provide the '{info.AssetName}' asset ({string.Join(", ", loaderNames)}), but an asset can't be loaded multiple times. SMAPI will use the default asset instead; uninstall one of the mods to fix this. (Message for modders: you should usually use {typeof(IAssetEditor)} instead to avoid conflicts.)", LogLevel.Warn); + return null; + } + + // fetch asset from loader + IModMetadata mod = loaders[0].Key; + IAssetLoader loader = loaders[0].Value; + T data; + try + { + data = loader.Load<T>(info); + this.Monitor.Log($"{mod.DisplayName} loaded asset '{info.AssetName}'.", LogLevel.Trace); + } + catch (Exception ex) + { + this.Monitor.Log($"{mod.DisplayName} crashed when loading asset '{info.AssetName}'. SMAPI will use the default asset instead. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); + return null; + } + + // validate asset + if (data == null) + { + this.Monitor.Log($"{mod.DisplayName} incorrectly set asset '{info.AssetName}' to a null value; ignoring override.", LogLevel.Error); + return null; + } + + // return matched asset + return new AssetDataForObject(info, data, this.NormaliseAssetName); + } + + /// <summary>Apply any <see cref="Editors"/> to a loaded asset.</summary> + /// <typeparam name="T">The asset type.</typeparam> + /// <param name="info">The basic asset metadata.</param> + /// <param name="asset">The loaded asset.</param> + private IAssetData ApplyEditors<T>(IAssetInfo info, IAssetData asset) { - string locale = this.GetKeyLocale.Invoke<string>(); - return this.Cache.ContainsKey($"{normalisedAssetName}.{locale}") - ? locale - : null; + IAssetData GetNewData(object data) => new AssetDataForObject(info, data, this.NormaliseAssetName); + + // edit asset + foreach (var entry in this.GetInterceptors(this.Editors)) + { + // check for match + IModMetadata mod = entry.Key; + IAssetEditor editor = entry.Value; + try + { + if (!editor.CanEdit<T>(info)) + continue; + } + catch (Exception ex) + { + this.Monitor.Log($"{mod.DisplayName} crashed when checking whether it could edit asset '{info.AssetName}', and will be ignored. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); + continue; + } + + // try edit + object prevAsset = asset.Data; + try + { + editor.Edit<T>(asset); + this.Monitor.Log($"{mod.DisplayName} intercepted {info.AssetName}.", LogLevel.Trace); + } + catch (Exception ex) + { + this.Monitor.Log($"{mod.DisplayName} crashed when editing asset '{info.AssetName}', which may cause errors in-game. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); + } + + // validate edit + if (asset.Data == null) + { + this.Monitor.Log($"{mod.DisplayName} incorrectly set asset '{info.AssetName}' to a null value; ignoring override.", LogLevel.Warn); + asset = GetNewData(prevAsset); + } + else if (!(asset.Data is T)) + { + this.Monitor.Log($"{mod.DisplayName} incorrectly set asset '{asset.AssetName}' to incompatible type '{asset.Data.GetType()}', expected '{typeof(T)}'; ignoring override.", LogLevel.Warn); + asset = GetNewData(prevAsset); + } + } + + // return result + return asset; + } + + /// <summary>Get all registered interceptors from a list.</summary> + private IEnumerable<KeyValuePair<IModMetadata, T>> GetInterceptors<T>(IDictionary<IModMetadata, IList<T>> entries) + { + foreach (var entry in entries) + { + IModMetadata metadata = entry.Key; + IList<T> interceptors = entry.Value; + + // special case if mod is an interceptor + if (metadata.Mod is T modAsInterceptor) + yield return new KeyValuePair<IModMetadata, T>(metadata, modAsInterceptor); + + // registered editors + foreach (T interceptor in interceptors) + yield return new KeyValuePair<IModMetadata, T>(metadata, interceptor); + } + } + + /// <summary>Dispose all game resources.</summary> + /// <param name="disposing">Whether the content manager is disposing (rather than finalising).</param> + protected override void Dispose(bool disposing) + { + if (!disposing) + return; + + // Clear cache & reload all assets. While that may seem perverse during disposal, it's + // necessary due to limitations in the way SMAPI currently intercepts content assets. + // + // The game uses multiple content managers while SMAPI needs one and only one. The game + // only disposes some of its content managers when returning to title, which means SMAPI + // can't know which assets are meant to be disposed. Here we remove current assets from + // the cache, but don't dispose them to avoid crashing any code that still references + // them. The garbage collector will eventually clean up any unused assets. + this.Reset(); } } } diff --git a/src/StardewModdingAPI/Framework/SGame.cs b/src/StardewModdingAPI/Framework/SGame.cs index 602a522b..c7784c60 100644 --- a/src/StardewModdingAPI/Framework/SGame.cs +++ b/src/StardewModdingAPI/Framework/SGame.cs @@ -4,11 +4,14 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Threading; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using StardewModdingAPI.Events; +using StardewModdingAPI.Framework.Reflection; +using StardewModdingAPI.Utilities; using StardewValley; using StardewValley.BellsAndWhistles; using StardewValley.Locations; @@ -29,6 +32,12 @@ namespace StardewModdingAPI.Framework /**** ** SMAPI state ****/ + /// <summary>Encapsulates monitoring and logging.</summary> + private readonly IMonitor Monitor; + + /// <summary>SMAPI's content manager.</summary> + private readonly SContentManager SContentManager; + /// <summary>The maximum number of consecutive attempts SMAPI should make to recover from a draw error.</summary> private readonly Countdown DrawCrashTimer = new Countdown(60); // 60 ticks = roughly one second @@ -48,18 +57,19 @@ namespace StardewModdingAPI.Framework /// <summary>Whether the game's zoom level is at 100% (i.e. nothing should be scaled).</summary> public bool ZoomLevelIsOne => Game1.options.zoomLevel.Equals(1.0f); - /// <summary>Encapsulates monitoring and logging.</summary> - private readonly IMonitor Monitor; /**** ** Game state ****/ - /// <summary>Arrays of pressed controller buttons indexed by <see cref="PlayerIndex"/>.</summary> - private Buttons[] PreviousPressedButtons = new Buttons[0]; + /// <summary>A record of the buttons pressed as of the previous tick.</summary> + private SButton[] PreviousPressedButtons = new SButton[0]; /// <summary>A record of the keyboard state (i.e. the up/down state for each button) as of the previous tick.</summary> private KeyboardState PreviousKeyState; + /// <summary>A record of the controller state (i.e. the up/down state for each button) as of the previous tick.</summary> + private GamePadState PreviousControllerState; + /// <summary>A record of the mouse state (i.e. the cursor position, scroll amount, and the up/down state for each button) as of the previous tick.</summary> private MouseState PreviousMouseState; @@ -108,6 +118,7 @@ namespace StardewModdingAPI.Framework /// <summary>The time of day (in 24-hour military format) at last check.</summary> private int PreviousTime; +#if !SMAPI_2_0 /// <summary>The day of month (1–28) at last check.</summary> private int PreviousDay; @@ -122,6 +133,7 @@ namespace StardewModdingAPI.Framework /// <summary>The player character at last check.</summary> private SFarmer PreviousFarmer; +#endif /// <summary>The previous content locale.</summary> private LocalizedContentManager.LanguageCode? PreviousLocale; @@ -139,7 +151,7 @@ namespace StardewModdingAPI.Framework ** Private wrappers ****/ /// <summary>Simplifies access to private game code.</summary> - private static IReflectionHelper Reflection; + private static Reflector Reflection; // ReSharper disable ArrangeStaticMemberQualifier, ArrangeThisQualifier, InconsistentNaming /// <summary>Used to access private fields and methods.</summary> @@ -173,23 +185,22 @@ namespace StardewModdingAPI.Framework /// <summary>Construct an instance.</summary> /// <param name="monitor">Encapsulates monitoring and logging.</param> /// <param name="reflection">Simplifies access to private game code.</param> - internal SGame(IMonitor monitor, IReflectionHelper reflection) + internal SGame(IMonitor monitor, Reflector reflection) { + // initialise this.Monitor = monitor; this.FirstUpdate = true; SGame.Instance = this; SGame.Reflection = reflection; - Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef; // required by Stardew Valley + // set XNA option required by Stardew Valley + Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef; - // The game uses the default content manager instead of Game1.CreateContentManager in - // several cases (See http://community.playstarbound.com/threads/130058/page-27#post-3159274). - // The workaround is... - // 1. Override the default content manager. - // 2. Since Game1.content isn't initialised yet, and we need one main instance to - // support custom map tilesheets, detect when Game1.content is being initialised - // and use the same instance. - this.Content = new SContentManager(this.Content.ServiceProvider, this.Content.RootDirectory, this.Monitor); + // override content manager + this.Monitor?.Log("Overriding content manager...", LogLevel.Trace); + this.SContentManager = new SContentManager(this.Content.ServiceProvider, this.Content.RootDirectory, Thread.CurrentThread.CurrentUICulture, null, this.Monitor); + this.Content = this.SContentManager; + Game1.content = this.SContentManager; } /**** @@ -200,13 +211,19 @@ namespace StardewModdingAPI.Framework /// <param name="rootDirectory">The root directory to search for content.</param> protected override LocalizedContentManager CreateContentManager(IServiceProvider serviceProvider, string rootDirectory) { - // When Game1.content is being initialised, use SMAPI's main content manager instance. - // See comment in SGame constructor. - if (Game1.content == null && this.Content is SContentManager mainContentManager) - return mainContentManager; + // return default if SMAPI's content manager isn't initialised yet + if (this.SContentManager == null) + { + this.Monitor?.Log("SMAPI's content manager isn't initialised; skipping content manager interception.", LogLevel.Trace); + return base.CreateContentManager(serviceProvider, rootDirectory); + } - // build new instance - return new SContentManager(this.Content.ServiceProvider, this.Content.RootDirectory, this.Monitor); + // return single instance if valid + if (serviceProvider != this.Content.ServiceProvider) + throw new InvalidOperationException("SMAPI uses a single content manager internally. You can't get a new content manager with a different service provider."); + if (rootDirectory != this.Content.RootDirectory) + throw new InvalidOperationException($"SMAPI uses a single content manager internally. You can't get a new content manager with a different root directory (current is {this.Content.RootDirectory}, requested {rootDirectory})."); + return this.SContentManager; } /// <summary>The method called when the game is updating its state. This happens roughly 60 times per second.</summary> @@ -275,7 +292,9 @@ namespace StardewModdingAPI.Framework if (this.FirstUpdate) { GameEvents.InvokeInitialize(this.Monitor); +#if !SMAPI_2_0 GameEvents.InvokeLoadContent(this.Monitor); +#endif GameEvents.InvokeGameLoaded(this.Monitor); } @@ -305,7 +324,9 @@ namespace StardewModdingAPI.Framework Context.IsWorldReady = true; SaveEvents.InvokeAfterLoad(this.Monitor); +#if !SMAPI_2_0 PlayerEvents.InvokeLoadedGame(this.Monitor, new EventArgsLoadedGameChanged(Game1.hasLoadedGame)); +#endif TimeEvents.InvokeAfterDayStarted(this.Monitor); } this.AfterLoadTimer--; @@ -334,53 +355,96 @@ namespace StardewModdingAPI.Framework if (Game1.game1.IsActive) { // get latest state - KeyboardState keyState = Keyboard.GetState(); - MouseState mouseState = Mouse.GetState(); - Point mousePosition = new Point(Game1.getMouseX(), Game1.getMouseY()); + KeyboardState keyState; + GamePadState controllerState; + MouseState mouseState; + Point mousePosition; + try + { + keyState = Keyboard.GetState(); + controllerState = GamePad.GetState(PlayerIndex.One); + mouseState = Mouse.GetState(); + mousePosition = new Point(Game1.getMouseX(), Game1.getMouseY()); + } + catch (InvalidOperationException) // GetState() may crash for some players if window doesn't have focus but game1.IsActive == true + { + keyState = this.PreviousKeyState; + controllerState = this.PreviousControllerState; + mouseState = this.PreviousMouseState; + mousePosition = this.PreviousMousePosition; + } // analyse state - Keys[] currentlyPressedKeys = keyState.GetPressedKeys(); - Keys[] previousPressedKeys = this.PreviousKeyState.GetPressedKeys(); - Keys[] framePressedKeys = currentlyPressedKeys.Except(previousPressedKeys).ToArray(); - Keys[] frameReleasedKeys = previousPressedKeys.Except(currentlyPressedKeys).ToArray(); - - // raise key pressed - foreach (Keys key in framePressedKeys) - ControlEvents.InvokeKeyPressed(this.Monitor, key); - - // raise key released - foreach (Keys key in frameReleasedKeys) - ControlEvents.InvokeKeyReleased(this.Monitor, key); + SButton[] currentlyPressedKeys = this.GetPressedButtons(keyState, mouseState, controllerState).ToArray(); + SButton[] previousPressedKeys = this.PreviousPressedButtons; + SButton[] framePressedKeys = currentlyPressedKeys.Except(previousPressedKeys).ToArray(); + SButton[] frameReleasedKeys = previousPressedKeys.Except(currentlyPressedKeys).ToArray(); + bool isClick = framePressedKeys.Contains(SButton.MouseLeft) || (framePressedKeys.Contains(SButton.ControllerA) && !currentlyPressedKeys.Contains(SButton.ControllerX)); + + // get cursor position +#if SMAPI_2_0 + ICursorPosition cursor; + { + // cursor position + Vector2 screenPixels = new Vector2(Game1.getMouseX(), Game1.getMouseY()); + Vector2 tile = new Vector2((Game1.viewport.X + screenPixels.X) / Game1.tileSize, (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 + : Game1.player.GetGrabTile(); + cursor = new CursorPosition(screenPixels, tile, grabTile); + } +#endif - // raise controller button pressed - foreach (Buttons button in this.GetFramePressedButtons()) + // raise button pressed + foreach (SButton button in framePressedKeys) { - if (button == Buttons.LeftTrigger || button == Buttons.RightTrigger) +#if SMAPI_2_0 + InputEvents.InvokeButtonPressed(this.Monitor, button, cursor, isClick); +#endif + + // legacy events + if (button.TryGetKeyboard(out Keys key)) { - var triggers = GamePad.GetState(PlayerIndex.One).Triggers; - ControlEvents.InvokeTriggerPressed(this.Monitor, button, button == Buttons.LeftTrigger ? triggers.Left : triggers.Right); + if (key != Keys.None) + ControlEvents.InvokeKeyPressed(this.Monitor, key); + } + else if (button.TryGetController(out Buttons controllerButton)) + { + if (controllerButton == Buttons.LeftTrigger || controllerButton == Buttons.RightTrigger) + ControlEvents.InvokeTriggerPressed(this.Monitor, controllerButton, controllerButton == Buttons.LeftTrigger ? controllerState.Triggers.Left : controllerState.Triggers.Right); + else + ControlEvents.InvokeButtonPressed(this.Monitor, controllerButton); } - else - ControlEvents.InvokeButtonPressed(this.Monitor, button); } - // raise controller button released - foreach (Buttons button in this.GetFrameReleasedButtons()) + // raise button released + foreach (SButton button in frameReleasedKeys) { - if (button == Buttons.LeftTrigger || button == Buttons.RightTrigger) +#if SMAPI_2_0 + bool wasClick = + (button == SButton.MouseLeft && previousPressedKeys.Contains(SButton.MouseLeft)) // released left click + || (button == SButton.ControllerA && previousPressedKeys.Contains(SButton.ControllerA) && !previousPressedKeys.Contains(SButton.ControllerX)); + InputEvents.InvokeButtonReleased(this.Monitor, button, cursor, wasClick); +#endif + + // legacy events + if (button.TryGetKeyboard(out Keys key)) { - var triggers = GamePad.GetState(PlayerIndex.One).Triggers; - ControlEvents.InvokeTriggerReleased(this.Monitor, button, button == Buttons.LeftTrigger ? triggers.Left : triggers.Right); + if (key != Keys.None) + ControlEvents.InvokeKeyReleased(this.Monitor, key); + } + else if (button.TryGetController(out Buttons controllerButton)) + { + if (controllerButton == Buttons.LeftTrigger || controllerButton == Buttons.RightTrigger) + ControlEvents.InvokeTriggerReleased(this.Monitor, controllerButton, controllerButton == Buttons.LeftTrigger ? controllerState.Triggers.Left : controllerState.Triggers.Right); + else + ControlEvents.InvokeButtonReleased(this.Monitor, controllerButton); } - else - ControlEvents.InvokeButtonReleased(this.Monitor, button); } - // raise keyboard state changed + // raise legacy state-changed events if (keyState != this.PreviousKeyState) ControlEvents.InvokeKeyboardChanged(this.Monitor, this.PreviousKeyState, keyState); - - // raise mouse state changed if (mouseState != this.PreviousMouseState) ControlEvents.InvokeMouseChanged(this.Monitor, this.PreviousMouseState, mouseState, this.PreviousMousePosition, mousePosition); @@ -388,7 +452,8 @@ namespace StardewModdingAPI.Framework this.PreviousMouseState = mouseState; this.PreviousMousePosition = mousePosition; this.PreviousKeyState = keyState; - this.PreviousPressedButtons = this.GetButtonsDown(); + this.PreviousControllerState = controllerState; + this.PreviousPressedButtons = currentlyPressedKeys; } /********* @@ -438,9 +503,11 @@ namespace StardewModdingAPI.Framework if (this.GetHash(Game1.locations) != this.PreviousGameLocations) LocationEvents.InvokeLocationsChanged(this.Monitor, Game1.locations); +#if !SMAPI_2_0 // raise player changed if (Game1.player != this.PreviousFarmer) PlayerEvents.InvokeFarmerChanged(this.Monitor, this.PreviousFarmer, Game1.player); +#endif // raise events that shouldn't be triggered on initial load if (Game1.uniqueIDForThisGame == this.PreviousSaveID) @@ -471,12 +538,14 @@ namespace StardewModdingAPI.Framework // raise time changed if (Game1.timeOfDay != this.PreviousTime) TimeEvents.InvokeTimeOfDayChanged(this.Monitor, this.PreviousTime, Game1.timeOfDay); +#if !SMAPI_2_0 if (Game1.dayOfMonth != this.PreviousDay) TimeEvents.InvokeDayOfMonthChanged(this.Monitor, this.PreviousDay, Game1.dayOfMonth); if (Game1.currentSeason != this.PreviousSeason) TimeEvents.InvokeSeasonOfYearChanged(this.Monitor, this.PreviousSeason, Game1.currentSeason); if (Game1.year != this.PreviousYear) TimeEvents.InvokeYearOfGameChanged(this.Monitor, this.PreviousYear, Game1.year); +#endif // raise mine level changed if (Game1.mine != null && Game1.mine.mineLevel != this.PreviousMineLevel) @@ -486,7 +555,6 @@ namespace StardewModdingAPI.Framework // update state this.PreviousGameLocations = this.GetHash(Game1.locations); this.PreviousGameLocation = Game1.currentLocation; - this.PreviousFarmer = Game1.player; this.PreviousCombatLevel = Game1.player.combatLevel; this.PreviousFarmingLevel = Game1.player.farmingLevel; this.PreviousFishingLevel = Game1.player.fishingLevel; @@ -496,21 +564,26 @@ namespace StardewModdingAPI.Framework this.PreviousItems = Game1.player.items.Where(n => n != null).ToDictionary(n => n, n => n.Stack); this.PreviousLocationObjects = this.GetHash(Game1.currentLocation.objects); this.PreviousTime = Game1.timeOfDay; + this.PreviousMineLevel = Game1.mine?.mineLevel ?? 0; + this.PreviousSaveID = Game1.uniqueIDForThisGame; +#if !SMAPI_2_0 + this.PreviousFarmer = Game1.player; this.PreviousDay = Game1.dayOfMonth; this.PreviousSeason = Game1.currentSeason; this.PreviousYear = Game1.year; - this.PreviousMineLevel = Game1.mine?.mineLevel ?? 0; - this.PreviousSaveID = Game1.uniqueIDForThisGame; +#endif } /********* ** Game day transition event (obsolete) *********/ +#if !SMAPI_2_0 if (Game1.newDay != this.PreviousIsNewDay) { TimeEvents.InvokeOnNewDay(this.Monitor, this.PreviousDay, Game1.dayOfMonth, Game1.newDay); this.PreviousIsNewDay = Game1.newDay; } +#endif /********* ** Game update @@ -530,7 +603,9 @@ namespace StardewModdingAPI.Framework GameEvents.InvokeUpdateTick(this.Monitor); if (this.FirstUpdate) { +#if !SMAPI_2_0 GameEvents.InvokeFirstUpdateTick(this.Monitor); +#endif this.FirstUpdate = false; } if (this.CurrentUpdateTick % 2 == 0) @@ -1270,120 +1345,66 @@ namespace StardewModdingAPI.Framework this.PreviousSaveID = 0; } - /// <summary>Get the controller buttons which are currently pressed.</summary> - private Buttons[] GetButtonsDown() - { - var state = GamePad.GetState(PlayerIndex.One); - var buttons = new List<Buttons>(); - if (state.IsConnected) - { - if (state.Buttons.A == ButtonState.Pressed) buttons.Add(Buttons.A); - if (state.Buttons.B == ButtonState.Pressed) buttons.Add(Buttons.B); - if (state.Buttons.Back == ButtonState.Pressed) buttons.Add(Buttons.Back); - if (state.Buttons.BigButton == ButtonState.Pressed) buttons.Add(Buttons.BigButton); - if (state.Buttons.LeftShoulder == ButtonState.Pressed) buttons.Add(Buttons.LeftShoulder); - if (state.Buttons.LeftStick == ButtonState.Pressed) buttons.Add(Buttons.LeftStick); - if (state.Buttons.RightShoulder == ButtonState.Pressed) buttons.Add(Buttons.RightShoulder); - if (state.Buttons.RightStick == ButtonState.Pressed) buttons.Add(Buttons.RightStick); - if (state.Buttons.Start == ButtonState.Pressed) buttons.Add(Buttons.Start); - if (state.Buttons.X == ButtonState.Pressed) buttons.Add(Buttons.X); - if (state.Buttons.Y == ButtonState.Pressed) buttons.Add(Buttons.Y); - if (state.DPad.Up == ButtonState.Pressed) buttons.Add(Buttons.DPadUp); - if (state.DPad.Down == ButtonState.Pressed) buttons.Add(Buttons.DPadDown); - if (state.DPad.Left == ButtonState.Pressed) buttons.Add(Buttons.DPadLeft); - if (state.DPad.Right == ButtonState.Pressed) buttons.Add(Buttons.DPadRight); - if (state.Triggers.Left > 0.2f) buttons.Add(Buttons.LeftTrigger); - if (state.Triggers.Right > 0.2f) buttons.Add(Buttons.RightTrigger); - } - return buttons.ToArray(); - } - - /// <summary>Get the controller buttons which were pressed after the last update.</summary> - private Buttons[] GetFramePressedButtons() + /// <summary>Get the buttons pressed in the given stats.</summary> + /// <param name="keyboard">The keyboard state.</param> + /// <param name="mouse">The mouse state.</param> + /// <param name="controller">The controller state.</param> + private IEnumerable<SButton> GetPressedButtons(KeyboardState keyboard, MouseState mouse, GamePadState controller) { - var state = GamePad.GetState(PlayerIndex.One); - var buttons = new List<Buttons>(); - if (state.IsConnected) + // keyboard + foreach (Keys key in keyboard.GetPressedKeys()) + yield return key.ToSButton(); + + // mouse + if (mouse.LeftButton == ButtonState.Pressed) + yield return SButton.MouseLeft; + if (mouse.RightButton == ButtonState.Pressed) + yield return SButton.MouseRight; + if (mouse.MiddleButton == ButtonState.Pressed) + yield return SButton.MouseMiddle; + if (mouse.XButton1 == ButtonState.Pressed) + yield return SButton.MouseX1; + if (mouse.XButton2 == ButtonState.Pressed) + yield return SButton.MouseX2; + + // controller + if (controller.IsConnected) { - if (this.WasButtonJustPressed(Buttons.A, state.Buttons.A)) buttons.Add(Buttons.A); - if (this.WasButtonJustPressed(Buttons.B, state.Buttons.B)) buttons.Add(Buttons.B); - if (this.WasButtonJustPressed(Buttons.Back, state.Buttons.Back)) buttons.Add(Buttons.Back); - if (this.WasButtonJustPressed(Buttons.BigButton, state.Buttons.BigButton)) buttons.Add(Buttons.BigButton); - if (this.WasButtonJustPressed(Buttons.LeftShoulder, state.Buttons.LeftShoulder)) buttons.Add(Buttons.LeftShoulder); - if (this.WasButtonJustPressed(Buttons.LeftStick, state.Buttons.LeftStick)) buttons.Add(Buttons.LeftStick); - if (this.WasButtonJustPressed(Buttons.RightShoulder, state.Buttons.RightShoulder)) buttons.Add(Buttons.RightShoulder); - if (this.WasButtonJustPressed(Buttons.RightStick, state.Buttons.RightStick)) buttons.Add(Buttons.RightStick); - if (this.WasButtonJustPressed(Buttons.Start, state.Buttons.Start)) buttons.Add(Buttons.Start); - if (this.WasButtonJustPressed(Buttons.X, state.Buttons.X)) buttons.Add(Buttons.X); - if (this.WasButtonJustPressed(Buttons.Y, state.Buttons.Y)) buttons.Add(Buttons.Y); - if (this.WasButtonJustPressed(Buttons.DPadUp, state.DPad.Up)) buttons.Add(Buttons.DPadUp); - if (this.WasButtonJustPressed(Buttons.DPadDown, state.DPad.Down)) buttons.Add(Buttons.DPadDown); - if (this.WasButtonJustPressed(Buttons.DPadLeft, state.DPad.Left)) buttons.Add(Buttons.DPadLeft); - if (this.WasButtonJustPressed(Buttons.DPadRight, state.DPad.Right)) buttons.Add(Buttons.DPadRight); - if (this.WasButtonJustPressed(Buttons.LeftTrigger, state.Triggers.Left)) buttons.Add(Buttons.LeftTrigger); - if (this.WasButtonJustPressed(Buttons.RightTrigger, state.Triggers.Right)) buttons.Add(Buttons.RightTrigger); + if (controller.Buttons.A == ButtonState.Pressed) + yield return SButton.ControllerA; + if (controller.Buttons.B == ButtonState.Pressed) + yield return SButton.ControllerB; + if (controller.Buttons.Back == ButtonState.Pressed) + yield return SButton.ControllerBack; + if (controller.Buttons.BigButton == ButtonState.Pressed) + yield return SButton.BigButton; + if (controller.Buttons.LeftShoulder == ButtonState.Pressed) + yield return SButton.LeftShoulder; + if (controller.Buttons.LeftStick == ButtonState.Pressed) + yield return SButton.LeftStick; + if (controller.Buttons.RightShoulder == ButtonState.Pressed) + yield return SButton.RightShoulder; + if (controller.Buttons.RightStick == ButtonState.Pressed) + yield return SButton.RightStick; + if (controller.Buttons.Start == ButtonState.Pressed) + yield return SButton.ControllerStart; + if (controller.Buttons.X == ButtonState.Pressed) + yield return SButton.ControllerX; + if (controller.Buttons.Y == ButtonState.Pressed) + yield return SButton.ControllerY; + if (controller.DPad.Up == ButtonState.Pressed) + yield return SButton.DPadUp; + if (controller.DPad.Down == ButtonState.Pressed) + yield return SButton.DPadDown; + if (controller.DPad.Left == ButtonState.Pressed) + yield return SButton.DPadLeft; + if (controller.DPad.Right == ButtonState.Pressed) + yield return SButton.DPadRight; + if (controller.Triggers.Left > 0.2f) + yield return SButton.LeftTrigger; + if (controller.Triggers.Right > 0.2f) + yield return SButton.RightTrigger; } - return buttons.ToArray(); - } - - /// <summary>Get the controller buttons which were released after the last update.</summary> - private Buttons[] GetFrameReleasedButtons() - { - var state = GamePad.GetState(PlayerIndex.One); - var buttons = new List<Buttons>(); - if (state.IsConnected) - { - if (this.WasButtonJustReleased(Buttons.A, state.Buttons.A)) buttons.Add(Buttons.A); - if (this.WasButtonJustReleased(Buttons.B, state.Buttons.B)) buttons.Add(Buttons.B); - if (this.WasButtonJustReleased(Buttons.Back, state.Buttons.Back)) buttons.Add(Buttons.Back); - if (this.WasButtonJustReleased(Buttons.BigButton, state.Buttons.BigButton)) buttons.Add(Buttons.BigButton); - if (this.WasButtonJustReleased(Buttons.LeftShoulder, state.Buttons.LeftShoulder)) buttons.Add(Buttons.LeftShoulder); - if (this.WasButtonJustReleased(Buttons.LeftStick, state.Buttons.LeftStick)) buttons.Add(Buttons.LeftStick); - if (this.WasButtonJustReleased(Buttons.RightShoulder, state.Buttons.RightShoulder)) buttons.Add(Buttons.RightShoulder); - if (this.WasButtonJustReleased(Buttons.RightStick, state.Buttons.RightStick)) buttons.Add(Buttons.RightStick); - if (this.WasButtonJustReleased(Buttons.Start, state.Buttons.Start)) buttons.Add(Buttons.Start); - if (this.WasButtonJustReleased(Buttons.X, state.Buttons.X)) buttons.Add(Buttons.X); - if (this.WasButtonJustReleased(Buttons.Y, state.Buttons.Y)) buttons.Add(Buttons.Y); - if (this.WasButtonJustReleased(Buttons.DPadUp, state.DPad.Up)) buttons.Add(Buttons.DPadUp); - if (this.WasButtonJustReleased(Buttons.DPadDown, state.DPad.Down)) buttons.Add(Buttons.DPadDown); - if (this.WasButtonJustReleased(Buttons.DPadLeft, state.DPad.Left)) buttons.Add(Buttons.DPadLeft); - if (this.WasButtonJustReleased(Buttons.DPadRight, state.DPad.Right)) buttons.Add(Buttons.DPadRight); - if (this.WasButtonJustReleased(Buttons.LeftTrigger, state.Triggers.Left)) buttons.Add(Buttons.LeftTrigger); - if (this.WasButtonJustReleased(Buttons.RightTrigger, state.Triggers.Right)) buttons.Add(Buttons.RightTrigger); - } - return buttons.ToArray(); - } - - /// <summary>Get whether a controller button was pressed since the last check.</summary> - /// <param name="button">The controller button to check.</param> - /// <param name="buttonState">The last known state.</param> - private bool WasButtonJustPressed(Buttons button, ButtonState buttonState) - { - return buttonState == ButtonState.Pressed && !this.PreviousPressedButtons.Contains(button); - } - - /// <summary>Get whether a controller button was released since the last check.</summary> - /// <param name="button">The controller button to check.</param> - /// <param name="buttonState">The last known state.</param> - private bool WasButtonJustReleased(Buttons button, ButtonState buttonState) - { - return buttonState == ButtonState.Released && this.PreviousPressedButtons.Contains(button); - } - - /// <summary>Get whether an analogue controller button was pressed since the last check.</summary> - /// <param name="button">The controller button to check.</param> - /// <param name="value">The last known value.</param> - private bool WasButtonJustPressed(Buttons button, float value) - { - return this.WasButtonJustPressed(button, value > 0.2f ? ButtonState.Pressed : ButtonState.Released); - } - - /// <summary>Get whether an analogue controller button was released since the last check.</summary> - /// <param name="button">The controller button to check.</param> - /// <param name="value">The last known value.</param> - private bool WasButtonJustReleased(Buttons button, float value) - { - return this.WasButtonJustReleased(button, value > 0.2f ? ButtonState.Pressed : ButtonState.Released); } /// <summary>Get the player inventory changes between two states.</summary> diff --git a/src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs b/src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs index 64d8738e..3193aa3c 100644 --- a/src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs +++ b/src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; using Microsoft.Xna.Framework.Input; using Newtonsoft.Json; +using StardewModdingAPI.Utilities; namespace StardewModdingAPI.Framework.Serialisation { @@ -19,7 +20,7 @@ namespace StardewModdingAPI.Framework.Serialisation ObjectCreationHandling = ObjectCreationHandling.Replace, // avoid issue where default ICollection<T> values are duplicated each time the config is loaded Converters = new List<JsonConverter> { - new SelectiveStringEnumConverter(typeof(Buttons), typeof(Keys)) + new SelectiveStringEnumConverter(typeof(Buttons), typeof(Keys), typeof(SButton)) } }; @@ -51,7 +52,21 @@ namespace StardewModdingAPI.Framework.Serialisation } // deserialise model - return JsonConvert.DeserializeObject<TModel>(json, this.JsonSettings); + try + { + return JsonConvert.DeserializeObject<TModel>(json, this.JsonSettings); + } + catch (JsonReaderException ex) + { + string message = $"The file at {fullPath} doesn't seem to be valid JSON."; + + string text = File.ReadAllText(fullPath); + if (text.Contains("“") || text.Contains("”")) + message += " Found curly quotes in the text; note that only straight quotes are allowed in JSON."; + + message += $"\nTechnical details: {ex.Message}"; + throw new JsonReaderException(message); + } } /// <summary>Save to a JSON file.</summary> diff --git a/src/StardewModdingAPI/Framework/Serialisation/ManifestFieldConverter.cs b/src/StardewModdingAPI/Framework/Serialisation/ManifestFieldConverter.cs index 6b5a6aaa..5be0f0b6 100644 --- a/src/StardewModdingAPI/Framework/Serialisation/ManifestFieldConverter.cs +++ b/src/StardewModdingAPI/Framework/Serialisation/ManifestFieldConverter.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using StardewModdingAPI.Framework.Exceptions; using StardewModdingAPI.Framework.Models; namespace StardewModdingAPI.Framework.Serialisation @@ -36,12 +37,32 @@ namespace StardewModdingAPI.Framework.Serialisation // semantic version if (objectType == typeof(ISemanticVersion)) { - JObject obj = JObject.Load(reader); - int major = obj.Value<int>(nameof(ISemanticVersion.MajorVersion)); - int minor = obj.Value<int>(nameof(ISemanticVersion.MinorVersion)); - int patch = obj.Value<int>(nameof(ISemanticVersion.PatchVersion)); - string build = obj.Value<string>(nameof(ISemanticVersion.Build)); - return new SemanticVersion(major, minor, patch, build); + JToken token = JToken.Load(reader); + switch (token.Type) + { + case JTokenType.Object: + { + JObject obj = (JObject)token; + int major = obj.Value<int>(nameof(ISemanticVersion.MajorVersion)); + int minor = obj.Value<int>(nameof(ISemanticVersion.MinorVersion)); + int patch = obj.Value<int>(nameof(ISemanticVersion.PatchVersion)); + string build = obj.Value<string>(nameof(ISemanticVersion.Build)); + return new SemanticVersion(major, minor, patch, build); + } + + case JTokenType.String: + { + string str = token.Value<string>(); + 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."); + return version; + } + + default: + throw new SParseException($"Can't parse semantic version from {token.Type}, must be an object or string."); + } } // manifest dependency @@ -51,7 +72,13 @@ namespace StardewModdingAPI.Framework.Serialisation foreach (JObject obj in JArray.Load(reader).Children<JObject>()) { string uniqueID = obj.Value<string>(nameof(IManifestDependency.UniqueID)); - result.Add(new ManifestDependency(uniqueID)); + string minVersion = obj.Value<string>(nameof(IManifestDependency.MinimumVersion)); +#if SMAPI_2_0 + bool required = obj.Value<bool?>(nameof(IManifestDependency.IsRequired)) ?? true; + result.Add(new ManifestDependency(uniqueID, minVersion, required)); +#else + result.Add(new ManifestDependency(uniqueID, minVersion)); +#endif } return result.ToArray(); } diff --git a/src/StardewModdingAPI/IAssetData.cs b/src/StardewModdingAPI/IAssetData.cs new file mode 100644 index 00000000..c3021144 --- /dev/null +++ b/src/StardewModdingAPI/IAssetData.cs @@ -0,0 +1,47 @@ +using System; + +namespace StardewModdingAPI +{ + /// <summary>Generic metadata and methods for a content asset being loaded.</summary> + /// <typeparam name="TValue">The expected data type.</typeparam> + public interface IAssetData<TValue> : IAssetInfo + { + /********* + ** Accessors + *********/ + /// <summary>The content data being read.</summary> + TValue Data { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Replace the entire content value with the given value. This is generally not recommended, since it may break compatibility with other mods or different versions of the game.</summary> + /// <param name="value">The new content value.</param> + /// <exception cref="ArgumentNullException">The <paramref name="value"/> is null.</exception> + /// <exception cref="InvalidCastException">The <paramref name="value"/>'s type is not compatible with the loaded asset's type.</exception> + void ReplaceWith(TValue value); + } + + /// <summary>Generic metadata and methods for a content asset being loaded.</summary> + public interface IAssetData : IAssetData<object> + { + /********* + ** Public methods + *********/ + /// <summary>Get a helper to manipulate the data as a dictionary.</summary> + /// <typeparam name="TKey">The expected dictionary key.</typeparam> + /// <typeparam name="TValue">The expected dictionary value.</typeparam> + /// <exception cref="InvalidOperationException">The content being read isn't a dictionary.</exception> + IAssetDataForDictionary<TKey, TValue> AsDictionary<TKey, TValue>(); + + /// <summary>Get a helper to manipulate the data as an image.</summary> + /// <exception cref="InvalidOperationException">The content being read isn't an image.</exception> + IAssetDataForImage AsImage(); + + /// <summary>Get the data as a given type.</summary> + /// <typeparam name="TData">The expected data type.</typeparam> + /// <exception cref="InvalidCastException">The data can't be converted to <typeparamref name="TData"/>.</exception> + TData GetData<TData>(); + } +} diff --git a/src/StardewModdingAPI/IContentEventHelperForDictionary.cs b/src/StardewModdingAPI/IAssetDataForDictionary.cs index 2f9d5a65..53c24346 100644 --- a/src/StardewModdingAPI/IContentEventHelperForDictionary.cs +++ b/src/StardewModdingAPI/IAssetDataForDictionary.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; namespace StardewModdingAPI { /// <summary>Encapsulates access and changes to dictionary content being read from a data file.</summary> - public interface IContentEventHelperForDictionary<TKey, TValue> : IContentEventData<IDictionary<TKey, TValue>> + public interface IAssetDataForDictionary<TKey, TValue> : IAssetData<IDictionary<TKey, TValue>> { /********* ** Public methods diff --git a/src/StardewModdingAPI/IContentEventHelperForImage.cs b/src/StardewModdingAPI/IAssetDataForImage.cs index 1158c868..4584a20e 100644 --- a/src/StardewModdingAPI/IContentEventHelperForImage.cs +++ b/src/StardewModdingAPI/IAssetDataForImage.cs @@ -5,7 +5,7 @@ using Microsoft.Xna.Framework.Graphics; namespace StardewModdingAPI { /// <summary>Encapsulates access and changes to dictionary content being read from a data file.</summary> - public interface IContentEventHelperForImage : IContentEventData<Texture2D> + public interface IAssetDataForImage : IAssetData<Texture2D> { /********* ** Public methods diff --git a/src/StardewModdingAPI/IAssetEditor.cs b/src/StardewModdingAPI/IAssetEditor.cs new file mode 100644 index 00000000..d2c6f295 --- /dev/null +++ b/src/StardewModdingAPI/IAssetEditor.cs @@ -0,0 +1,17 @@ +namespace StardewModdingAPI +{ + /// <summary>Edits matching content assets.</summary> + public interface IAssetEditor + { + /********* + ** Public methods + *********/ + /// <summary>Get whether this instance can edit the given asset.</summary> + /// <param name="asset">Basic metadata about the asset being loaded.</param> + bool CanEdit<T>(IAssetInfo asset); + + /// <summary>Edit a matched asset.</summary> + /// <param name="asset">A helper which encapsulates metadata about an asset and enables changes to it.</param> + void Edit<T>(IAssetData asset); + } +} diff --git a/src/StardewModdingAPI/IAssetInfo.cs b/src/StardewModdingAPI/IAssetInfo.cs new file mode 100644 index 00000000..5dd58e2e --- /dev/null +++ b/src/StardewModdingAPI/IAssetInfo.cs @@ -0,0 +1,28 @@ +using System; + +namespace StardewModdingAPI +{ + /// <summary>Basic metadata for a content asset.</summary> + public interface IAssetInfo + { + /********* + ** Accessors + *********/ + /// <summary>The content's locale code, if the content is localised.</summary> + string Locale { get; } + + /// <summary>The normalised asset name being read. The format may change between platforms; see <see cref="AssetNameEquals"/> to compare with a known path.</summary> + string AssetName { get; } + + /// <summary>The content data type.</summary> + Type DataType { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Get whether the asset name being loaded matches a given name after normalisation.</summary> + /// <param name="path">The expected asset path, relative to the game's content folder and without the .xnb extension or locale suffix (like 'Data\ObjectInformation').</param> + bool AssetNameEquals(string path); + } +} diff --git a/src/StardewModdingAPI/IAssetLoader.cs b/src/StardewModdingAPI/IAssetLoader.cs new file mode 100644 index 00000000..ad97b941 --- /dev/null +++ b/src/StardewModdingAPI/IAssetLoader.cs @@ -0,0 +1,17 @@ +namespace StardewModdingAPI +{ + /// <summary>Provides the initial version for matching assets loaded by the game. SMAPI will raise an error if two mods try to load the same asset; in most cases you should use <see cref="IAssetEditor"/> instead.</summary> + public interface IAssetLoader + { + /********* + ** Public methods + *********/ + /// <summary>Get whether this instance can load the initial version of the given asset.</summary> + /// <param name="asset">Basic metadata about the asset being loaded.</param> + bool CanLoad<T>(IAssetInfo asset); + + /// <summary>Load a matched asset.</summary> + /// <param name="asset">Basic metadata about the asset being loaded.</param> + T Load<T>(IAssetInfo asset); + } +} diff --git a/src/StardewModdingAPI/ICommandHelper.cs b/src/StardewModdingAPI/ICommandHelper.cs index 3a51ffb4..fb562e32 100644 --- a/src/StardewModdingAPI/ICommandHelper.cs +++ b/src/StardewModdingAPI/ICommandHelper.cs @@ -3,7 +3,7 @@ namespace StardewModdingAPI { /// <summary>Provides an API for managing console commands.</summary> - public interface ICommandHelper + public interface ICommandHelper : IModLinked { /********* ** Public methods diff --git a/src/StardewModdingAPI/IContentEventData.cs b/src/StardewModdingAPI/IContentEventData.cs deleted file mode 100644 index 7e2d4df1..00000000 --- a/src/StardewModdingAPI/IContentEventData.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; - -namespace StardewModdingAPI -{ - /// <summary>Generic metadata and methods for a content asset being loaded.</summary> - /// <typeparam name="TValue">The expected data type.</typeparam> - public interface IContentEventData<TValue> - { - /********* - ** Accessors - *********/ - /// <summary>The content's locale code, if the content is localised.</summary> - string Locale { get; } - - /// <summary>The normalised asset name being read. The format may change between platforms; see <see cref="IsAssetName"/> to compare with a known path.</summary> - string AssetName { get; } - - /// <summary>The content data being read.</summary> - TValue Data { get; } - - /// <summary>The content data type.</summary> - Type DataType { get; } - - - /********* - ** Public methods - *********/ - /// <summary>Get whether the asset name being loaded matches a given name after normalisation.</summary> - /// <param name="path">The expected asset path, relative to the game's content folder and without the .xnb extension or locale suffix (like 'Data\ObjectInformation').</param> - bool IsAssetName(string path); - - /// <summary>Replace the entire content value with the given value. This is generally not recommended, since it may break compatibility with other mods or different versions of the game.</summary> - /// <param name="value">The new content value.</param> - /// <exception cref="ArgumentNullException">The <paramref name="value"/> is null.</exception> - /// <exception cref="InvalidCastException">The <paramref name="value"/>'s type is not compatible with the loaded asset's type.</exception> - void ReplaceWith(TValue value); - } -} diff --git a/src/StardewModdingAPI/IContentEventHelper.cs b/src/StardewModdingAPI/IContentEventHelper.cs deleted file mode 100644 index 421a1e06..00000000 --- a/src/StardewModdingAPI/IContentEventHelper.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; - -namespace StardewModdingAPI -{ - /// <summary>Encapsulates access and changes to content being read from a data file.</summary> - public interface IContentEventHelper : IContentEventData<object> - { - /********* - ** Public methods - *********/ - /// <summary>Get a helper to manipulate the data as a dictionary.</summary> - /// <typeparam name="TKey">The expected dictionary key.</typeparam> - /// <typeparam name="TValue">The expected dictionary balue.</typeparam> - /// <exception cref="InvalidOperationException">The content being read isn't a dictionary.</exception> - IContentEventHelperForDictionary<TKey, TValue> AsDictionary<TKey, TValue>(); - - /// <summary>Get a helper to manipulate the data as an image.</summary> - /// <exception cref="InvalidOperationException">The content being read isn't an image.</exception> - IContentEventHelperForImage AsImage(); - - /// <summary>Get the data as a given type.</summary> - /// <typeparam name="TData">The expected data type.</typeparam> - /// <exception cref="InvalidCastException">The data can't be converted to <typeparamref name="TData"/>.</exception> - TData GetData<TData>(); - } -} diff --git a/src/StardewModdingAPI/IContentHelper.cs b/src/StardewModdingAPI/IContentHelper.cs index 1d520135..32a9ff19 100644 --- a/src/StardewModdingAPI/IContentHelper.cs +++ b/src/StardewModdingAPI/IContentHelper.cs @@ -5,7 +5,7 @@ using Microsoft.Xna.Framework.Graphics; namespace StardewModdingAPI { /// <summary>Provides an API for loading content assets.</summary> - public interface IContentHelper + public interface IContentHelper : IModLinked { /// <summary>Load content from the game folder or mod folder (if not already cached), and return it. When loading a <c>.png</c> file, this must be called outside the game's draw loop.</summary> /// <typeparam name="T">The expected data type. The main supported types are <see cref="Texture2D"/> and dictionaries; other types may be supported by the game's content pipeline.</typeparam> diff --git a/src/StardewModdingAPI/ICursorPosition.cs b/src/StardewModdingAPI/ICursorPosition.cs new file mode 100644 index 00000000..d03cda71 --- /dev/null +++ b/src/StardewModdingAPI/ICursorPosition.cs @@ -0,0 +1,19 @@ +#if SMAPI_2_0 +using Microsoft.Xna.Framework; + +namespace StardewModdingAPI +{ + /// <summary>Represents a cursor position in the different coordinate systems.</summary> + public interface ICursorPosition + { + /// <summary>The pixel position relative to the top-left corner of the visible screen.</summary> + Vector2 ScreenPixels { get; } + + /// <summary>The tile position under the cursor relative to the top-left corner of the map.</summary> + Vector2 Tile { get; } + + /// <summary>The tile position that the game considers under the cursor for purposes of clicking actions. This may be different than <see cref="Tile"/> if that's too far from the player.</summary> + Vector2 GrabTile { get; } + } +} +#endif diff --git a/src/StardewModdingAPI/IManifest.cs b/src/StardewModdingAPI/IManifest.cs index 9533aadb..407db1ce 100644 --- a/src/StardewModdingAPI/IManifest.cs +++ b/src/StardewModdingAPI/IManifest.cs @@ -21,7 +21,7 @@ namespace StardewModdingAPI ISemanticVersion Version { get; } /// <summary>The minimum SMAPI version required by this mod, if any.</summary> - string MinimumApiVersion { get; } + ISemanticVersion MinimumApiVersion { get; } /// <summary>The unique mod ID.</summary> string UniqueID { get; } diff --git a/src/StardewModdingAPI/IManifestDependency.cs b/src/StardewModdingAPI/IManifestDependency.cs index 7bd2e8b6..027c1d59 100644 --- a/src/StardewModdingAPI/IManifestDependency.cs +++ b/src/StardewModdingAPI/IManifestDependency.cs @@ -8,5 +8,13 @@ *********/ /// <summary>The unique mod ID to require.</summary> string UniqueID { get; } + + /// <summary>The minimum required version (if any).</summary> + ISemanticVersion MinimumVersion { get; } + +#if SMAPI_2_0 + /// <summary>Whether the dependency must be installed to use the mod.</summary> + bool IsRequired { get; } +#endif } } diff --git a/src/StardewModdingAPI/IModLinked.cs b/src/StardewModdingAPI/IModLinked.cs new file mode 100644 index 00000000..172ee30c --- /dev/null +++ b/src/StardewModdingAPI/IModLinked.cs @@ -0,0 +1,12 @@ +namespace StardewModdingAPI +{ + /// <summary>An instance linked to a mod.</summary> + public interface IModLinked + { + /********* + ** Accessors + *********/ + /// <summary>The unique ID of the mod for which the instance was created.</summary> + string ModID { get; } + } +} diff --git a/src/StardewModdingAPI/IModRegistry.cs b/src/StardewModdingAPI/IModRegistry.cs index 676c9734..5ef3fd65 100644 --- a/src/StardewModdingAPI/IModRegistry.cs +++ b/src/StardewModdingAPI/IModRegistry.cs @@ -2,8 +2,8 @@ namespace StardewModdingAPI { - /// <summary>Provides metadata about loaded mods.</summary> - public interface IModRegistry + /// <summary>Provides an API for fetching metadata about loaded mods.</summary> + public interface IModRegistry : IModLinked { /// <summary>Get metadata for all loaded mods.</summary> IEnumerable<IManifest> GetAll(); diff --git a/src/StardewModdingAPI/IReflectionHelper.cs b/src/StardewModdingAPI/IReflectionHelper.cs index 77943c6c..fb2c7861 100644 --- a/src/StardewModdingAPI/IReflectionHelper.cs +++ b/src/StardewModdingAPI/IReflectionHelper.cs @@ -2,8 +2,8 @@ namespace StardewModdingAPI { - /// <summary>Simplifies access to private game code.</summary> - public interface IReflectionHelper + /// <summary>Provides an API for accessing private game code.</summary> + public interface IReflectionHelper : IModLinked { /********* ** Public methods diff --git a/src/StardewModdingAPI/ITranslationHelper.cs b/src/StardewModdingAPI/ITranslationHelper.cs index dac83025..c4b72444 100644 --- a/src/StardewModdingAPI/ITranslationHelper.cs +++ b/src/StardewModdingAPI/ITranslationHelper.cs @@ -4,7 +4,7 @@ using StardewValley; namespace StardewModdingAPI { /// <summary>Provides translations stored in the mod's <c>i18n</c> folder, with one file per locale (like <c>en.json</c>) containing a flat key => value structure. Translations are fetched with locale fallback, so missing translations are filled in from broader locales (like <c>pt-BR.json</c> < <c>pt.json</c> < <c>default.json</c>).</summary> - public interface ITranslationHelper + public interface ITranslationHelper : IModLinked { /********* ** Accessors diff --git a/src/StardewModdingAPI/Log.cs b/src/StardewModdingAPI/Log.cs index d58cebfe..46f1caae 100644 --- a/src/StardewModdingAPI/Log.cs +++ b/src/StardewModdingAPI/Log.cs @@ -1,3 +1,4 @@ +#if !SMAPI_2_0 using System; using System.Threading; using StardewModdingAPI.Framework; @@ -306,7 +307,7 @@ namespace StardewModdingAPI /// <summary>Raise a deprecation warning.</summary> private static void WarnDeprecated() { - Log.DeprecationManager.Warn($"the {nameof(Log)} class", "1.1", DeprecationLevel.Info); + Log.DeprecationManager.Warn($"the {nameof(Log)} class", "1.1", DeprecationLevel.PendingRemoval); } /// <summary>Get the name of the mod logging a message from the stack.</summary> @@ -315,4 +316,5 @@ namespace StardewModdingAPI return Log.ModRegistry.GetModFromStack() ?? "<unknown mod>"; } } -}
\ No newline at end of file +} +#endif
\ No newline at end of file diff --git a/src/StardewModdingAPI/Mod.cs b/src/StardewModdingAPI/Mod.cs index 171088cf..cb36c596 100644 --- a/src/StardewModdingAPI/Mod.cs +++ b/src/StardewModdingAPI/Mod.cs @@ -11,11 +11,14 @@ namespace StardewModdingAPI /********* ** Properties *********/ +#if !SMAPI_2_0 /// <summary>Manages deprecation warnings.</summary> private static DeprecationManager DeprecationManager; + /// <summary>The backing field for <see cref="Mod.PathOnDisk"/>.</summary> private string _pathOnDisk; +#endif /********* @@ -30,13 +33,14 @@ namespace StardewModdingAPI /// <summary>The mod's manifest.</summary> public IManifest ModManifest { get; internal set; } +#if !SMAPI_2_0 /// <summary>The full path to the mod's directory on the disk.</summary> [Obsolete("Use " + nameof(Mod.Helper) + "." + nameof(IModHelper.DirectoryPath) + " instead")] public string PathOnDisk { get { - Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.PathOnDisk)}", "1.0", DeprecationLevel.Info); + Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.PathOnDisk)}", "1.0", DeprecationLevel.PendingRemoval); return this._pathOnDisk; } internal set { this._pathOnDisk = value; } @@ -48,7 +52,7 @@ namespace StardewModdingAPI { get { - Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.BaseConfigPath)}", "1.0", DeprecationLevel.Info); + Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.BaseConfigPath)}", "1.0", DeprecationLevel.PendingRemoval); Mod.DeprecationManager.MarkWarned($"{nameof(Mod)}.{nameof(Mod.PathOnDisk)}", "1.0"); // avoid redundant warnings return Path.Combine(this.PathOnDisk, "config.json"); } @@ -64,16 +68,18 @@ namespace StardewModdingAPI { get { - Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.PerSaveConfigPath)}", "1.0", DeprecationLevel.Info); + Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.PerSaveConfigPath)}", "1.0", DeprecationLevel.PendingRemoval); Mod.DeprecationManager.MarkWarned($"{nameof(Mod)}.{nameof(Mod.PerSaveConfigFolder)}", "1.0"); // avoid redundant warnings return Context.IsSaveLoaded ? Path.Combine(this.PerSaveConfigFolder, $"{Constants.SaveFolderName}.json") : ""; } } +#endif /********* ** Public methods *********/ +#if !SMAPI_2_0 /// <summary>Injects types required for backwards compatibility.</summary> /// <param name="deprecationManager">Manages deprecation warnings.</param> internal static void Shim(DeprecationManager deprecationManager) @@ -84,6 +90,7 @@ namespace StardewModdingAPI /// <summary>The mod entry point, called after the mod is first loaded.</summary> [Obsolete("This overload is obsolete since SMAPI 1.0.")] public virtual void Entry(params object[] objects) { } +#endif /// <summary>The mod entry point, called after the mod is first loaded.</summary> /// <param name="helper">Provides simplified APIs for writing mods.</param> @@ -101,11 +108,12 @@ namespace StardewModdingAPI /********* ** Private methods *********/ +#if !SMAPI_2_0 /// <summary>Get the full path to the per-save configuration file for the current save (if <see cref="Manifest.PerSaveConfigs"/> is <c>true</c>).</summary> [Obsolete] private string GetPerSaveConfigFolder() { - Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.PerSaveConfigFolder)}", "1.0", DeprecationLevel.Info); + Mod.DeprecationManager.Warn($"{nameof(Mod)}.{nameof(Mod.PerSaveConfigFolder)}", "1.0", DeprecationLevel.PendingRemoval); Mod.DeprecationManager.MarkWarned($"{nameof(Mod)}.{nameof(Mod.PathOnDisk)}", "1.0"); // avoid redundant warnings if (!((Manifest)this.ModManifest).PerSaveConfigs) @@ -115,6 +123,7 @@ namespace StardewModdingAPI } return Path.Combine(this.PathOnDisk, "psconfigs"); } +#endif /// <summary>Release or reset unmanaged resources when the game exits. There's no guarantee this will be called on every exit.</summary> /// <param name="disposing">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.</param> diff --git a/src/StardewModdingAPI/Program.cs b/src/StardewModdingAPI/Program.cs index d75d5193..97e18322 100644 --- a/src/StardewModdingAPI/Program.cs +++ b/src/StardewModdingAPI/Program.cs @@ -4,6 +4,8 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; +using System.Runtime.ExceptionServices; +using System.Security; using System.Threading; #if SMAPI_FOR_WINDOWS using System.Management; @@ -15,6 +17,7 @@ using StardewModdingAPI.Events; using StardewModdingAPI.Framework; using StardewModdingAPI.Framework.Logging; using StardewModdingAPI.Framework.Models; +using StardewModdingAPI.Framework.ModHelpers; using StardewModdingAPI.Framework.ModLoading; using StardewModdingAPI.Framework.Reflection; using StardewModdingAPI.Framework.Serialisation; @@ -43,7 +46,7 @@ namespace StardewModdingAPI private readonly CancellationTokenSource CancellationTokenSource = new CancellationTokenSource(); /// <summary>Simplifies access to private game code.</summary> - private readonly IReflectionHelper Reflection = new ReflectionHelper(); + private readonly Reflector Reflection = new Reflector(); /// <summary>The underlying game instance.</summary> private SGame GameInstance; @@ -115,6 +118,7 @@ namespace StardewModdingAPI } /// <summary>Launch SMAPI.</summary> + [HandleProcessCorruptedStateExceptions, SecurityCritical] // let try..catch handle corrupted state exceptions public void RunInteractively() { // initialise SMAPI @@ -123,7 +127,9 @@ namespace StardewModdingAPI // init logging this.Monitor.Log($"SMAPI {Constants.ApiVersion} with Stardew Valley {Constants.GetGameDisplayVersion(Constants.GameVersion)} on {this.GetFriendlyPlatformName()}", LogLevel.Info); this.Monitor.Log($"Mods go here: {Constants.ModPath}"); +#if !SMAPI_2_0 this.Monitor.Log("Preparing SMAPI..."); +#endif // validate paths this.VerifyPath(Constants.ModPath); @@ -207,7 +213,11 @@ namespace StardewModdingAPI } // start game +#if SMAPI_2_0 + this.Monitor.Log("Starting game...", LogLevel.Trace); +#else this.Monitor.Log("Starting game..."); +#endif try { this.IsGameRunning = true; @@ -224,6 +234,7 @@ namespace StardewModdingAPI } } +#if !SMAPI_2_0 /// <summary>Get a monitor for legacy code which doesn't have one passed in.</summary> [Obsolete("This method should only be used when needed for backwards compatibility.")] internal IMonitor GetLegacyMonitorForMod() @@ -231,6 +242,7 @@ namespace StardewModdingAPI string modName = this.ModRegistry.GetModFromStack() ?? "unknown"; return this.GetSecondaryMonitor(modName); } +#endif /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> public void Dispose() @@ -321,17 +333,18 @@ namespace StardewModdingAPI this.DeprecationManager = new DeprecationManager(this.Monitor, this.ModRegistry); this.CommandManager = new CommandManager(); +#if !SMAPI_2_0 // inject compatibility shims #pragma warning disable 618 Command.Shim(this.CommandManager, this.DeprecationManager, this.ModRegistry); Config.Shim(this.DeprecationManager); Log.Shim(this.DeprecationManager, this.GetSecondaryMonitor("legacy mod"), this.ModRegistry); Mod.Shim(this.DeprecationManager); - ContentEvents.Shim(this.ModRegistry, this.Monitor); GameEvents.Shim(this.DeprecationManager); PlayerEvents.Shim(this.DeprecationManager); TimeEvents.Shim(this.DeprecationManager); #pragma warning restore 618 +#endif // redirect direct console output { @@ -344,6 +357,9 @@ namespace StardewModdingAPI if (this.Settings.DeveloperMode) { this.Monitor.ShowTraceInConsole = true; +#if SMAPI_2_0 + this.Monitor.ShowFullStampInConsole = true; +#endif this.Monitor.Log($"You configured SMAPI to run in developer mode. The console may 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) @@ -355,19 +371,23 @@ namespace StardewModdingAPI // validate XNB integrity if (!this.ValidateContentIntegrity()) - this.Monitor.Log("SMAPI found problems in the game's XNB files which may cause errors or crashes while you're playing. Consider uninstalling XNB mods or reinstalling the game.", LogLevel.Warn); + 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); // load mods - int modsLoaded; { +#if SMAPI_2_0 + this.Monitor.Log("Loading mod metadata...", LogLevel.Trace); +#else this.Monitor.Log("Loading mod metadata..."); +#endif ModResolver resolver = new ModResolver(); // load manifests - IModMetadata[] mods = resolver.ReadManifests(Constants.ModPath, new JsonHelper(), this.Settings.ModCompatibility).ToArray(); + IModMetadata[] mods = resolver.ReadManifests(Constants.ModPath, new JsonHelper(), this.Settings.ModCompatibility, this.Settings.DisabledMods).ToArray(); resolver.ValidateManifests(mods, Constants.ApiVersion); // check for deprecated metadata +#if !SMAPI_2_0 IList<Action> deprecationWarnings = new List<Action>(); foreach (IModMetadata mod in mods.Where(m => m.Status != ModMetadataStatus.Failed)) { @@ -389,7 +409,7 @@ namespace StardewModdingAPI // per-save directories if ((mod.Manifest as Manifest)?.PerSaveConfigs == true) { - deprecationWarnings.Add(() => this.DeprecationManager.Warn(mod.DisplayName, $"{nameof(Manifest)}.{nameof(Manifest.PerSaveConfigs)}", "1.0", DeprecationLevel.Info)); + deprecationWarnings.Add(() => this.DeprecationManager.Warn(mod.DisplayName, $"{nameof(Manifest)}.{nameof(Manifest.PerSaveConfigs)}", "1.0", DeprecationLevel.PendingRemoval)); try { string psDir = Path.Combine(mod.DirectoryPath, "psconfigs"); @@ -403,14 +423,19 @@ namespace StardewModdingAPI } } } +#endif // process dependencies mods = resolver.ProcessDependencies(mods).ToArray(); // load mods - modsLoaded = this.LoadMods(mods, new JsonHelper(), this.ContentManager, deprecationWarnings); +#if SMAPI_2_0 + this.LoadMods(mods, new JsonHelper(), this.ContentManager); +#else + this.LoadMods(mods, new JsonHelper(), this.ContentManager, deprecationWarnings); foreach (Action warning in deprecationWarnings) warning(); +#endif } if (this.Monitor.IsExiting) { @@ -419,6 +444,7 @@ namespace StardewModdingAPI } // update window titles + int modsLoaded = this.ModRegistry.GetMods().Count(); this.GameInstance.Window.Title = $"Stardew Valley {Constants.GetGameDisplayVersion(Constants.GameVersion)} - running SMAPI {Constants.ApiVersion} with {modsLoaded} mods"; Console.Title = $"SMAPI {Constants.ApiVersion} - running Stardew Valley {Constants.GetGameDisplayVersion(Constants.GameVersion)} with {modsLoaded} mods"; @@ -443,7 +469,9 @@ namespace StardewModdingAPI private void RunConsoleLoop() { // prepare console +#if !SMAPI_2_0 this.Monitor.Log("Starting console..."); +#endif this.Monitor.Log("Type 'help' for help, or 'help <cmd>' for a command's usage", LogLevel.Info); this.CommandManager.Add("SMAPI", "help", "Lists command documentation.\n\nUsage: help\nLists all available commands.\n\nUsage: help <cmd>\n- cmd: The name of a command whose documentation to display.", this.HandleCommand); this.CommandManager.Add("SMAPI", "reload_i18n", "Reloads translation files for all mods.\n\nUsage: reload_i18n", this.HandleCommand); @@ -483,20 +511,21 @@ namespace StardewModdingAPI /// <returns>Returns whether all integrity checks passed.</returns> private bool ValidateContentIntegrity() { - this.Monitor.Log("Detecting common issues..."); + this.Monitor.Log("Detecting common issues...", LogLevel.Trace); bool issuesFound = false; - // object format (commonly broken by outdated files) { - void LogIssue(int id, string issue) => this.Monitor.Log($"Detected issue: item #{id} in Content\\Data\\ObjectInformation is invalid ({issue}).", LogLevel.Warn); + // detect issues + bool hasObjectIssues = false; + void LogIssue(int id, string issue) => this.Monitor.Log($@"Detected issue: item #{id} in Content\Data\ObjectInformation.xnb is invalid ({issue}).", LogLevel.Trace); foreach (KeyValuePair<int, string> entry in Game1.objectInformation) { // must not be empty if (string.IsNullOrWhiteSpace(entry.Value)) { LogIssue(entry.Key, "entry is empty"); - issuesFound = true; + hasObjectIssues = true; continue; } @@ -505,7 +534,7 @@ namespace StardewModdingAPI if (fields.Length < SObject.objectInfoDescriptionIndex + 1) { LogIssue(entry.Key, "too few fields for an object"); - issuesFound = true; + hasObjectIssues = true; continue; } @@ -516,11 +545,18 @@ namespace StardewModdingAPI if (fields.Length < SObject.objectInfoBuffDurationIndex + 1) { LogIssue(entry.Key, "too few fields for a cooking item"); - issuesFound = true; + hasObjectIssues = true; } break; } } + + // log error + if (hasObjectIssues) + { + issuesFound = true; + this.Monitor.Log(@"Your Content\Data\ObjectInformation.xnb file seems to be broken or outdated.", LogLevel.Warn); + } } return !issuesFound; @@ -567,125 +603,221 @@ namespace StardewModdingAPI /// <param name="mods">The mods to load.</param> /// <param name="jsonHelper">The JSON helper with which to read mods' JSON files.</param> /// <param name="contentManager">The content manager to use for mod content.</param> +#if !SMAPI_2_0 /// <param name="deprecationWarnings">A list to populate with any deprecation warnings.</param> - /// <returns>Returns the number of mods successfully loaded.</returns> - private int LoadMods(IModMetadata[] mods, JsonHelper jsonHelper, SContentManager contentManager, IList<Action> deprecationWarnings) + private void LoadMods(IModMetadata[] mods, JsonHelper jsonHelper, SContentManager contentManager, IList<Action> deprecationWarnings) +#else + private void LoadMods(IModMetadata[] mods, JsonHelper jsonHelper, SContentManager contentManager) +#endif { +#if SMAPI_2_0 + this.Monitor.Log("Loading mods...", LogLevel.Trace); +#else this.Monitor.Log("Loading mods..."); - void LogSkip(IModMetadata mod, string reasonPhrase, LogLevel level = LogLevel.Error) => this.Monitor.Log($"Skipped {mod.DisplayName} because {reasonPhrase}", level); - +#endif // load mod assemblies - int modsLoaded = 0; - AssemblyLoader modAssemblyLoader = new AssemblyLoader(Constants.TargetPlatform, this.Monitor); - AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => modAssemblyLoader.ResolveAssembly(e.Name); - foreach (IModMetadata metadata in mods) + IDictionary<IModMetadata, string> skippedMods = new Dictionary<IModMetadata, string>(); { - // validate status - if (metadata.Status == ModMetadataStatus.Failed) - { - LogSkip(metadata, metadata.Error); - continue; - } - - // get basic info - IManifest manifest = metadata.Manifest; - string assemblyPath = Path.Combine(metadata.DirectoryPath, metadata.Manifest.EntryDll); + void TrackSkip(IModMetadata mod, string reasonPhrase) => skippedMods[mod] = reasonPhrase; - // preprocess & load mod assembly - Assembly modAssembly; - try - { - modAssembly = modAssemblyLoader.Load(assemblyPath, assumeCompatible: metadata.Compatibility?.Compatibility == ModCompatibilityType.AssumeCompatible); - } - catch (IncompatibleInstructionException ex) - { - LogSkip(metadata, $"it's not compatible with the latest version of the game (detected {ex.NounPhrase}). Please check for a newer version of the mod (you have v{manifest.Version})."); - continue; - } - catch (Exception ex) + AssemblyLoader modAssemblyLoader = new AssemblyLoader(Constants.TargetPlatform, this.Monitor); + AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => modAssemblyLoader.ResolveAssembly(e.Name); + foreach (IModMetadata metadata in mods) { - LogSkip(metadata, $"its DLL '{manifest.EntryDll}' couldn't be loaded:\n{ex.GetLogSummary()}"); - continue; - } + // get basic info + IManifest manifest = metadata.Manifest; + string assemblyPath = metadata.Manifest?.EntryDll != null + ? Path.Combine(metadata.DirectoryPath, metadata.Manifest.EntryDll) + : null; + this.Monitor.Log(assemblyPath != null + ? $"Loading {metadata.DisplayName} from {assemblyPath.Replace(Constants.ModPath, "").TrimStart(Path.DirectorySeparatorChar)}..." + : $"Loading {metadata.DisplayName}...", LogLevel.Trace); + + // validate status + if (metadata.Status == ModMetadataStatus.Failed) + { + this.Monitor.Log($" Failed: {metadata.Error}", LogLevel.Trace); + TrackSkip(metadata, metadata.Error); + continue; + } - // validate assembly - try - { - int modEntries = modAssembly.DefinedTypes.Count(type => typeof(Mod).IsAssignableFrom(type) && !type.IsAbstract); - if (modEntries == 0) + // preprocess & load mod assembly + Assembly modAssembly; + try { - LogSkip(metadata, $"its DLL has no '{nameof(Mod)}' subclass."); + modAssembly = modAssemblyLoader.Load(assemblyPath, assumeCompatible: metadata.Compatibility?.Compatibility == ModCompatibilityType.AssumeCompatible); + } + catch (IncompatibleInstructionException ex) + { + TrackSkip(metadata, $"it's not compatible with the latest version of the game or SMAPI (detected {ex.NounPhrase}). Please check for a newer version of the mod."); continue; } - if (modEntries > 1) + catch (Exception ex) { - LogSkip(metadata, $"its DLL contains multiple '{nameof(Mod)}' subclasses."); + TrackSkip(metadata, $"its DLL '{manifest.EntryDll}' couldn't be loaded:\n{ex.GetLogSummary()}"); continue; } - } - catch (Exception ex) - { - LogSkip(metadata, $"its DLL couldn't be loaded:\n{ex.GetLogSummary()}"); - continue; - } - // initialise mod - try - { - // get implementation - TypeInfo modEntryType = modAssembly.DefinedTypes.First(type => typeof(Mod).IsAssignableFrom(type) && !type.IsAbstract); - Mod mod = (Mod)modAssembly.CreateInstance(modEntryType.ToString()); - if (mod == null) + // validate assembly + try { - LogSkip(metadata, "its entry class couldn't be instantiated."); + int modEntries = modAssembly.DefinedTypes.Count(type => typeof(Mod).IsAssignableFrom(type) && !type.IsAbstract); + if (modEntries == 0) + { + TrackSkip(metadata, $"its DLL has no '{nameof(Mod)}' subclass."); + continue; + } + if (modEntries > 1) + { + TrackSkip(metadata, $"its DLL contains multiple '{nameof(Mod)}' subclasses."); + continue; + } + } + catch (Exception ex) + { + TrackSkip(metadata, $"its DLL couldn't be loaded:\n{ex.GetLogSummary()}"); continue; } - // inject data - mod.ModManifest = manifest; - mod.Helper = new ModHelper(metadata.DisplayName, metadata.DirectoryPath, jsonHelper, this.ModRegistry, this.CommandManager, contentManager, this.Reflection); - mod.Monitor = this.GetSecondaryMonitor(metadata.DisplayName); - mod.PathOnDisk = metadata.DirectoryPath; - - // track mod - metadata.SetMod(mod); - this.ModRegistry.Add(metadata); - modsLoaded++; - this.Monitor.Log($"Loaded {metadata.DisplayName} by {manifest.Author}, v{manifest.Version} | {manifest.Description}", LogLevel.Info); + // initialise mod + try + { + // get implementation + TypeInfo modEntryType = modAssembly.DefinedTypes.First(type => typeof(Mod).IsAssignableFrom(type) && !type.IsAbstract); + Mod mod = (Mod)modAssembly.CreateInstance(modEntryType.ToString()); + if (mod == null) + { + TrackSkip(metadata, "its entry class couldn't be instantiated."); + continue; + } + +#if !SMAPI_2_0 + // prevent mods from using SMAPI 2.0 content interception before release + // ReSharper disable SuspiciousTypeConversion.Global + if (mod is IAssetEditor || mod is IAssetLoader) + { + TrackSkip(metadata, $"its entry class implements {nameof(IAssetEditor)} or {nameof(IAssetLoader)}. These are part of a prototype API that isn't available for mods to use yet."); + } + // ReSharper restore SuspiciousTypeConversion.Global +#endif + + // inject data + { + ICommandHelper commandHelper = new CommandHelper(manifest.UniqueID, metadata.DisplayName, this.CommandManager); + IContentHelper contentHelper = new ContentHelper(contentManager, metadata.DirectoryPath, manifest.UniqueID, metadata.DisplayName); + IReflectionHelper reflectionHelper = new ReflectionHelper(manifest.UniqueID, this.Reflection); + IModRegistry modRegistryHelper = new ModRegistryHelper(manifest.UniqueID, this.ModRegistry); + ITranslationHelper translationHelper = new TranslationHelper(manifest.UniqueID, manifest.Name, contentManager.GetLocale(), contentManager.GetCurrentLanguage()); + + mod.ModManifest = manifest; + mod.Helper = new ModHelper(manifest.UniqueID, metadata.DirectoryPath, jsonHelper, contentHelper, commandHelper, modRegistryHelper, reflectionHelper, translationHelper); + mod.Monitor = this.GetSecondaryMonitor(metadata.DisplayName); +#if !SMAPI_2_0 + mod.PathOnDisk = metadata.DirectoryPath; +#endif + } + + // track mod + metadata.SetMod(mod); + this.ModRegistry.Add(metadata); + } + catch (Exception ex) + { + TrackSkip(metadata, $"initialisation failed:\n{ex.GetLogSummary()}"); + } } - catch (Exception ex) + } + IModMetadata[] loadedMods = this.ModRegistry.GetMods().ToArray(); + + // log skipped mods +#if SMAPI_2_0 + this.Monitor.Newline(); +#endif + if (skippedMods.Any()) + { + this.Monitor.Log($"Skipped {skippedMods.Count} mods:", LogLevel.Error); + foreach (var pair in skippedMods.OrderBy(p => p.Key.DisplayName)) { - LogSkip(metadata, $"initialisation failed:\n{ex.GetLogSummary()}"); + IModMetadata mod = pair.Key; + string reason = pair.Value; + + if (mod.Manifest?.Version != null) + this.Monitor.Log($" {mod.DisplayName} {mod.Manifest.Version} because {reason}", LogLevel.Error); + else + this.Monitor.Log($" {mod.DisplayName} because {reason}", LogLevel.Error); } +#if SMAPI_2_0 + this.Monitor.Newline(); +#endif } + // log loaded mods + this.Monitor.Log($"Loaded {loadedMods.Length} mods" + (loadedMods.Length > 0 ? ":" : "."), LogLevel.Info); + foreach (IModMetadata metadata in loadedMods.OrderBy(p => p.DisplayName)) + { + IManifest manifest = metadata.Manifest; + this.Monitor.Log( + $" {metadata.DisplayName} {manifest.Version}" + + (!string.IsNullOrWhiteSpace(manifest.Author) ? $" by {manifest.Author}" : "") + + (!string.IsNullOrWhiteSpace(manifest.Description) ? $" | {manifest.Description}" : ""), + LogLevel.Info + ); + } +#if SMAPI_2_0 + this.Monitor.Newline(); +#endif + // initialise translations this.ReloadTranslations(); // initialise loaded mods - foreach (IModMetadata metadata in this.ModRegistry.GetMods()) + foreach (IModMetadata metadata in loadedMods) { + // add interceptors + if (metadata.Mod.Helper.Content is ContentHelper helper) + { + this.ContentManager.Editors[metadata] = helper.ObservableAssetEditors; + this.ContentManager.Loaders[metadata] = helper.ObservableAssetLoaders; + } + + // call entry method try { IMod mod = metadata.Mod; - - // call entry methods - (mod as Mod)?.Entry(); // deprecated since 1.0 mod.Entry(mod.Helper); +#if !SMAPI_2_0 + (mod as Mod)?.Entry(); // deprecated since 1.0 // raise deprecation warning for old Entry() methods if (this.DeprecationManager.IsVirtualMethodImplemented(mod.GetType(), typeof(Mod), nameof(Mod.Entry), new[] { typeof(object[]) })) - deprecationWarnings.Add(() => this.DeprecationManager.Warn(metadata.DisplayName, $"{nameof(Mod)}.{nameof(Mod.Entry)}(object[]) instead of {nameof(Mod)}.{nameof(Mod.Entry)}({nameof(IModHelper)})", "1.0", DeprecationLevel.Info)); + deprecationWarnings.Add(() => this.DeprecationManager.Warn(metadata.DisplayName, $"{nameof(Mod)}.{nameof(Mod.Entry)}(object[]) instead of {nameof(Mod)}.{nameof(Mod.Entry)}({nameof(IModHelper)})", "1.0", DeprecationLevel.PendingRemoval)); +#endif } catch (Exception ex) { - this.Monitor.Log($"The {metadata.DisplayName} mod failed on entry initialisation. It will still be loaded, but may not function correctly.\n{ex.GetLogSummary()}", LogLevel.Warn); + this.Monitor.Log($"{metadata.DisplayName} failed on entry and might not work correctly. Technical details:\n{ex.GetLogSummary()}", LogLevel.Error); } } - // print result - this.Monitor.Log($"Loaded {modsLoaded} mods."); - return modsLoaded; + // reset cache when needed + // only register listeners after Entry to avoid repeatedly reloading assets during load + foreach (IModMetadata metadata in loadedMods) + { + if (metadata.Mod.Helper.Content is ContentHelper helper) + { + helper.ObservableAssetEditors.CollectionChanged += (sender, e) => + { + if (e.NewItems.Count > 0) + this.ContentManager.Reset(); + }; + helper.ObservableAssetLoaders.CollectionChanged += (sender, e) => + { + if (e.NewItems.Count > 0) + this.ContentManager.Reset(); + }; + } + } + this.ContentManager.Reset(); } /// <summary>Reload translations for all mods.</summary> @@ -737,8 +869,22 @@ namespace StardewModdingAPI } else { +#if SMAPI_2_0 + string message = "The following commands are registered:\n"; + IGrouping<string, string>[] groups = (from command in this.CommandManager.GetAll() orderby command.ModName, command.Name group command.Name by command.ModName).ToArray(); + foreach (var group in groups) + { + string modName = group.Key; + string[] commandNames = group.ToArray(); + message += $"{modName}:\n {string.Join("\n ", commandNames)}\n\n"; + } + message += "For more information about a command, type 'help command_name'."; + + this.Monitor.Log(message, LogLevel.Info); +#else this.Monitor.Log("The following commands are registered: " + string.Join(", ", this.CommandManager.GetAll().Select(p => p.Name)) + ".", LogLevel.Info); this.Monitor.Log("For more information about a command, type 'help command_name'.", LogLevel.Info); +#endif } break; @@ -783,7 +929,14 @@ namespace StardewModdingAPI /// <param name="name">The name of the module which will log messages with this instance.</param> private Monitor GetSecondaryMonitor(string name) { - return new Monitor(name, this.ConsoleManager, this.LogFile, this.CancellationTokenSource) { WriteToConsole = this.Monitor.WriteToConsole, ShowTraceInConsole = this.Settings.DeveloperMode }; + return new Monitor(name, this.ConsoleManager, this.LogFile, this.CancellationTokenSource) + { + WriteToConsole = this.Monitor.WriteToConsole, + ShowTraceInConsole = this.Settings.DeveloperMode, +#if SMAPI_2_0 + ShowFullStampInConsole = this.Settings.DeveloperMode +#endif + }; } /// <summary>Get a human-readable name for the current platform.</summary> diff --git a/src/StardewModdingAPI/SemanticVersion.cs b/src/StardewModdingAPI/SemanticVersion.cs index a2adb657..4b27c819 100644 --- a/src/StardewModdingAPI/SemanticVersion.cs +++ b/src/StardewModdingAPI/SemanticVersion.cs @@ -10,8 +10,14 @@ namespace StardewModdingAPI ** Properties *********/ /// <summary>A regular expression matching a semantic version string.</summary> - /// <remarks>Derived from https://github.com/maxhauser/semver.</remarks> - private static readonly Regex Regex = new Regex(@"^(?<major>\d+)(\.(?<minor>\d+))?(\.(?<patch>\d+))?(?<build>.*)$", RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture); + /// <remarks> + /// This pattern is derived from the BNF documentation in the <a href="https://github.com/mojombo/semver">semver repo</a>, + /// with three important deviations intended to support Stardew Valley mod conventions: + /// - allows short-form "x.y" versions; + /// - allows hyphens in prerelease tags as synonyms for dots (like "-unofficial-update.3"); + /// - doesn't allow '+build' suffixes. + /// </remarks> + private static readonly Regex Regex = new Regex(@"^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)(\.(?<patch>0|[1-9]\d*))?(?:-(?<prerelease>([a-z0-9]+[\-\.]?)+))?$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.ExplicitCapture); /********* @@ -48,17 +54,22 @@ namespace StardewModdingAPI /// <summary>Construct an instance.</summary> /// <param name="version">The semantic version string.</param> + /// <exception cref="ArgumentNullException">The <paramref name="version"/> is null.</exception> /// <exception cref="FormatException">The <paramref name="version"/> is not a valid semantic version.</exception> public SemanticVersion(string version) { - var match = SemanticVersion.Regex.Match(version); + // parse + if (version == null) + throw new ArgumentNullException(nameof(version), "The input version string can't be null."); + var match = SemanticVersion.Regex.Match(version.Trim()); if (!match.Success) - throw new FormatException($"The input '{version}' is not a valid semantic version."); + throw new FormatException($"The input '{version}' isn't a valid semantic version."); + // initialise 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.Build = match.Groups["build"].Success ? this.GetNormalisedTag(match.Groups["build"].Value) : null; + this.Build = match.Groups["prerelease"].Success ? this.GetNormalisedTag(match.Groups["prerelease"].Value) : null; } /// <summary>Get an integer indicating whether this version precedes (less than 0), supercedes (more than 0), or is equivalent to (0) the specified version.</summary> @@ -93,8 +104,8 @@ namespace StardewModdingAPI return curOlder; // compare two pre-release tag values - string[] curParts = this.Build.Split('.'); - string[] otherParts = other.Build.Split('.'); + string[] curParts = this.Build.Split('.', '-'); + string[] otherParts = other.Build.Split('.', '-'); for (int i = 0; i < curParts.Length; i++) { // longer prerelease tag supercedes if otherwise equal @@ -200,6 +211,7 @@ namespace StardewModdingAPI } } + /********* ** Private methods *********/ @@ -207,11 +219,9 @@ namespace StardewModdingAPI /// <param name="tag">The tag to normalise.</param> private string GetNormalisedTag(string tag) { - tag = tag?.Trim().Trim('-', '.'); - if (string.IsNullOrWhiteSpace(tag)) + tag = tag?.Trim(); + if (string.IsNullOrWhiteSpace(tag) || tag == "0") // '0' from incorrect examples in old SMAPI documentation return null; - if (tag == "0") - return null; // from incorrect examples in old SMAPI documentation return tag; } } diff --git a/src/StardewModdingAPI/StardewModdingAPI.config.json b/src/StardewModdingAPI/StardewModdingAPI.config.json index f62db90c..4e871636 100644 --- a/src/StardewModdingAPI/StardewModdingAPI.config.json +++ b/src/StardewModdingAPI/StardewModdingAPI.config.json @@ -27,6 +27,23 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "VerboseLogging": false, /** + * A list of mods SMAPI should consider obsolete and not load. Changing this field is not + * recommended and may destabilise your game. + */ + "DisabledMods": [ + { + "Name": "Modder Serialization Utility", + "ID": [ "SerializerUtils-0-1" ], + "ReasonPhrase": "it's no longer used by any mods, and is no longer maintained." + }, + { + "Name": "StarDustCore", + "ID": [ "StarDustCore" ], + "ReasonPhrase": "it was only used by earlier versions of Save Anywhere (which no longer uses it), and is no longer maintained." + } + ], + + /** * A list of mod versions SMAPI should consider compatible or broken regardless of whether it * detects incompatible code. Each record can be set to `AssumeCompatible` or `AssumeBroken`. * Changing this field is not recommended and may destabilise your game. @@ -316,14 +333,6 @@ This file contains advanced configuration for SMAPI. You generally shouldn't cha "Notes": "Needs update for SDV 1.2." }, { - "Name": "StarDustCore", - "ID": [ "StarDustCore" ], - "UpperVersion": "1.0", - "Compatibility": "AssumeBroken", - "UpdateUrl": "http://www.nexusmods.com/stardewvalley/mods/683", - "Notes": "Obsolete (originally needed by Save Anywhere); broken in SDV 1.2." - }, - { "Name": "Teleporter", "ID": [ "Teleporter" ], "UpperVersion": "1.0.2", diff --git a/src/StardewModdingAPI/StardewModdingAPI.csproj b/src/StardewModdingAPI/StardewModdingAPI.csproj index ae454a35..f778660d 100644 --- a/src/StardewModdingAPI/StardewModdingAPI.csproj +++ b/src/StardewModdingAPI/StardewModdingAPI.csproj @@ -93,7 +93,10 @@ <Compile Include="Command.cs" /> <Compile Include="ContentSource.cs" /> <Compile Include="Events\ContentEvents.cs" /> + <Compile Include="Events\EventArgsInput.cs" /> <Compile Include="Events\EventArgsValueChanged.cs" /> + <Compile Include="Events\InputEvents.cs" /> + <Compile Include="Framework\Content\AssetInfo.cs" /> <Compile Include="Framework\Exceptions\SContentLoadException.cs" /> <Compile Include="Framework\Command.cs" /> <Compile Include="Config.cs" /> @@ -124,6 +127,14 @@ <Compile Include="Events\GraphicsEvents.cs" /> <Compile Include="Framework\Countdown.cs" /> <Compile Include="Framework\IModMetadata.cs" /> + <Compile Include="Framework\Models\DisabledMod.cs" /> + <Compile Include="Framework\ModHelpers\BaseHelper.cs" /> + <Compile Include="Framework\ModHelpers\CommandHelper.cs" /> + <Compile Include="Framework\ModHelpers\ContentHelper.cs" /> + <Compile Include="Framework\ModHelpers\ModHelper.cs" /> + <Compile Include="Framework\ModHelpers\ModRegistryHelper.cs" /> + <Compile Include="Framework\ModHelpers\ReflectionHelper.cs" /> + <Compile Include="Framework\ModHelpers\TranslationHelper.cs" /> <Compile Include="Framework\ModLoading\InvalidModStateException.cs" /> <Compile Include="Framework\ModLoading\ModDependencyStatus.cs" /> <Compile Include="Framework\ModLoading\ModMetadataStatus.cs" /> @@ -131,15 +142,13 @@ <Compile Include="Framework\ModLoading\AssemblyDefinitionResolver.cs" /> <Compile Include="Framework\ModLoading\AssemblyParseResult.cs" /> <Compile Include="Framework\CommandManager.cs" /> - <Compile Include="Framework\ContentHelper.cs" /> - <Compile Include="Framework\Content\ContentEventData.cs" /> - <Compile Include="Framework\Content\ContentEventHelper.cs" /> - <Compile Include="Framework\Content\ContentEventHelperForDictionary.cs" /> - <Compile Include="Framework\Content\ContentEventHelperForImage.cs" /> + <Compile Include="Framework\Content\AssetData.cs" /> + <Compile Include="Framework\Content\AssetDataForObject.cs" /> + <Compile Include="Framework\Content\AssetDataForDictionary.cs" /> + <Compile Include="Framework\Content\AssetDataForImage.cs" /> <Compile Include="Context.cs" /> <Compile Include="Framework\Logging\ConsoleInterceptionManager.cs" /> <Compile Include="Framework\Logging\InterceptingTextWriter.cs" /> - <Compile Include="Framework\CommandHelper.cs" /> <Compile Include="Framework\Models\ManifestDependency.cs" /> <Compile Include="Framework\Models\ModCompatibilityType.cs" /> <Compile Include="Framework\Models\SConfig.cs" /> @@ -147,15 +156,17 @@ <Compile Include="Framework\Reflection\PrivateProperty.cs" /> <Compile Include="Framework\RequestExitDelegate.cs" /> <Compile Include="Framework\SContentManager.cs" /> + <Compile Include="Framework\Exceptions\SParseException.cs" /> <Compile Include="Framework\Serialisation\JsonHelper.cs" /> <Compile Include="Framework\Serialisation\SelectiveStringEnumConverter.cs" /> <Compile Include="Framework\Serialisation\ManifestFieldConverter.cs" /> - <Compile Include="Framework\TranslationHelper.cs" /> + <Compile Include="IAssetEditor.cs" /> + <Compile Include="IAssetInfo.cs" /> + <Compile Include="IAssetLoader.cs" /> <Compile Include="ICommandHelper.cs" /> - <Compile Include="IContentEventData.cs" /> - <Compile Include="IContentEventHelper.cs" /> - <Compile Include="IContentEventHelperForDictionary.cs" /> - <Compile Include="IContentEventHelperForImage.cs" /> + <Compile Include="IAssetData.cs" /> + <Compile Include="IAssetDataForDictionary.cs" /> + <Compile Include="IAssetDataForImage.cs" /> <Compile Include="IContentHelper.cs" /> <Compile Include="IManifestDependency.cs" /> <Compile Include="IModRegistry.cs" /> @@ -173,10 +184,11 @@ <Compile Include="Framework\Reflection\CacheEntry.cs" /> <Compile Include="Framework\Reflection\PrivateField.cs" /> <Compile Include="Framework\Reflection\PrivateMethod.cs" /> - <Compile Include="Framework\Reflection\ReflectionHelper.cs" /> + <Compile Include="Framework\Reflection\Reflector.cs" /> <Compile Include="IManifest.cs" /> <Compile Include="IMod.cs" /> <Compile Include="IModHelper.cs" /> + <Compile Include="IModLinked.cs" /> <Compile Include="Framework\Logging\LogFileManager.cs" /> <Compile Include="IPrivateProperty.cs" /> <Compile Include="ISemanticVersion.cs" /> @@ -192,7 +204,6 @@ <Compile Include="Framework\Monitor.cs" /> <Compile Include="Framework\Models\Manifest.cs" /> <Compile Include="Mod.cs" /> - <Compile Include="Framework\ModHelper.cs" /> <Compile Include="PatchMode.cs" /> <Compile Include="Program.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> @@ -202,6 +213,10 @@ <Compile Include="IReflectionHelper.cs" /> <Compile Include="SemanticVersion.cs" /> <Compile Include="Translation.cs" /> + <Compile Include="ICursorPosition.cs" /> + <Compile Include="Utilities\SDate.cs" /> + <Compile Include="Utilities\SButton.cs" /> + <Compile Include="Framework\CursorPosition.cs" /> </ItemGroup> <ItemGroup> <None Include="App.config"> @@ -269,8 +284,8 @@ <StartProgram>$(GamePath)\StardewModdingAPI.exe</StartProgram> <StartWorkingDirectory>$(GamePath)</StartWorkingDirectory> </PropertyGroup> - + <!-- Somehow this makes Visual Studio for Mac recognise the previous section. --> <!-- Nobody knows why. --> <PropertyGroup Condition="'$(RunConfiguration)' == 'Default'" /> -</Project> +</Project>
\ No newline at end of file diff --git a/src/StardewModdingAPI/Utilities/SButton.cs b/src/StardewModdingAPI/Utilities/SButton.cs new file mode 100644 index 00000000..f4fccfff --- /dev/null +++ b/src/StardewModdingAPI/Utilities/SButton.cs @@ -0,0 +1,659 @@ +using System; +using Microsoft.Xna.Framework.Input; + +namespace StardewModdingAPI.Utilities +{ + /// <summary>A unified button constant which includes all controller, keyboard, and mouse buttons.</summary> + /// <remarks>Derived from <see cref="Keys"/>, <see cref="Buttons"/>, and <see cref="System.Windows.Forms.MouseButtons"/>.</remarks> +#if SMAPI_2_0 + public +#else + internal +#endif + enum SButton + { + /// <summary>No valid key.</summary> + None = 0, + + /********* + ** Mouse + *********/ + /// <summary>The left mouse button.</summary> + MouseLeft = 1000, + + /// <summary>The right mouse button.</summary> + MouseRight = 1001, + + /// <summary>The middle mouse button.</summary> + MouseMiddle = 1002, + + /// <summary>The first mouse XButton.</summary> + MouseX1 = 1003, + + /// <summary>The second mouse XButton.</summary> + MouseX2 = 1004, + + /********* + ** Controller + *********/ + /// <summary>The 'A' button on a controller.</summary> + ControllerA = SButtonExtensions.ControllerOffset + Buttons.A, + + /// <summary>The 'B' button on a controller.</summary> + ControllerB = SButtonExtensions.ControllerOffset + Buttons.B, + + /// <summary>The 'X' button on a controller.</summary> + ControllerX = SButtonExtensions.ControllerOffset + Buttons.X, + + /// <summary>The 'Y' button on a controller.</summary> + ControllerY = SButtonExtensions.ControllerOffset + Buttons.Y, + + /// <summary>The back button on a controller.</summary> + ControllerBack = SButtonExtensions.ControllerOffset + Buttons.Back, + + /// <summary>The start button on a controller.</summary> + ControllerStart = SButtonExtensions.ControllerOffset + Buttons.Start, + + /// <summary>The up button on the directional pad of a controller.</summary> + DPadUp = SButtonExtensions.ControllerOffset + Buttons.DPadUp, + + /// <summary>The down button on the directional pad of a controller.</summary> + DPadDown = SButtonExtensions.ControllerOffset + Buttons.DPadDown, + + /// <summary>The left button on the directional pad of a controller.</summary> + DPadLeft = SButtonExtensions.ControllerOffset + Buttons.DPadLeft, + + /// <summary>The right button on the directional pad of a controller.</summary> + DPadRight = SButtonExtensions.ControllerOffset + Buttons.DPadRight, + + /// <summary>The left bumper (shoulder) button on a controller.</summary> + LeftShoulder = SButtonExtensions.ControllerOffset + Buttons.LeftShoulder, + + /// <summary>The right bumper (shoulder) button on a controller.</summary> + RightShoulder = SButtonExtensions.ControllerOffset + Buttons.RightShoulder, + + /// <summary>The left trigger on a controller.</summary> + LeftTrigger = SButtonExtensions.ControllerOffset + Buttons.LeftTrigger, + + /// <summary>The right trigger on a controller.</summary> + RightTrigger = SButtonExtensions.ControllerOffset + Buttons.RightTrigger, + + /// <summary>The left analog stick on a controller (when pressed).</summary> + LeftStick = SButtonExtensions.ControllerOffset + Buttons.LeftStick, + + /// <summary>The right analog stick on a controller (when pressed).</summary> + RightStick = SButtonExtensions.ControllerOffset + Buttons.RightStick, + + /// <summary>The 'big button' on a controller.</summary> + BigButton = SButtonExtensions.ControllerOffset + Buttons.BigButton, + + /// <summary>The left analog stick on a controller (when pushed left).</summary> + LeftThumbstickLeft = SButtonExtensions.ControllerOffset + Buttons.LeftThumbstickLeft, + + /// <summary>The left analog stick on a controller (when pushed right).</summary> + LeftThumbstickRight = SButtonExtensions.ControllerOffset + Buttons.LeftThumbstickRight, + + /// <summary>The left analog stick on a controller (when pushed down).</summary> + LeftThumbstickDown = SButtonExtensions.ControllerOffset + Buttons.LeftThumbstickDown, + + /// <summary>The left analog stick on a controller (when pushed up).</summary> + LeftThumbstickUp = SButtonExtensions.ControllerOffset + Buttons.LeftThumbstickUp, + + /// <summary>The right analog stick on a controller (when pushed left).</summary> + RightThumbstickLeft = SButtonExtensions.ControllerOffset + Buttons.RightThumbstickLeft, + + /// <summary>The right analog stick on a controller (when pushed right).</summary> + RightThumbstickRight = SButtonExtensions.ControllerOffset + Buttons.RightThumbstickRight, + + /// <summary>The right analog stick on a controller (when pushed down).</summary> + RightThumbstickDown = SButtonExtensions.ControllerOffset + Buttons.RightThumbstickDown, + + /// <summary>The right analog stick on a controller (when pushed up).</summary> + RightThumbstickUp = SButtonExtensions.ControllerOffset + Buttons.RightThumbstickUp, + + /********* + ** Keyboard + *********/ + /// <summary>The A button on a keyboard.</summary> + A = Keys.A, + + /// <summary>The Add button on a keyboard.</summary> + Add = Keys.Add, + + /// <summary>The Applications button on a keyboard.</summary> + Apps = Keys.Apps, + + /// <summary>The Attn button on a keyboard.</summary> + Attn = Keys.Attn, + + /// <summary>The B button on a keyboard.</summary> + B = Keys.B, + + /// <summary>The Backspace button on a keyboard.</summary> + Back = Keys.Back, + + /// <summary>The Browser Back button on a keyboard in Windows 2000/XP.</summary> + BrowserBack = Keys.BrowserBack, + + /// <summary>The Browser Favorites button on a keyboard in Windows 2000/XP.</summary> + BrowserFavorites = Keys.BrowserFavorites, + + /// <summary>The Browser Favorites button on a keyboard in Windows 2000/XP.</summary> + BrowserForward = Keys.BrowserForward, + + /// <summary>The Browser Home button on a keyboard in Windows 2000/XP.</summary> + BrowserHome = Keys.BrowserHome, + + /// <summary>The Browser Refresh button on a keyboard in Windows 2000/XP.</summary> + BrowserRefresh = Keys.BrowserRefresh, + + /// <summary>The Browser Search button on a keyboard in Windows 2000/XP.</summary> + BrowserSearch = Keys.BrowserSearch, + + /// <summary>The Browser Stop button on a keyboard in Windows 2000/XP.</summary> + BrowserStop = Keys.BrowserStop, + + /// <summary>The C button on a keyboard.</summary> + C = Keys.C, + + /// <summary>The Caps Lock button on a keyboard.</summary> + CapsLock = Keys.CapsLock, + + /// <summary>The Green ChatPad button on a keyboard.</summary> + ChatPadGreen = Keys.ChatPadGreen, + + /// <summary>The Orange ChatPad button on a keyboard.</summary> + ChatPadOrange = Keys.ChatPadOrange, + + /// <summary>The CrSel button on a keyboard.</summary> + Crsel = Keys.Crsel, + + /// <summary>The D button on a keyboard.</summary> + D = Keys.D, + + /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary> + D0 = Keys.D0, + + /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary> + D1 = Keys.D1, + + /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary> + D2 = Keys.D2, + + /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary> + D3 = Keys.D3, + + /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary> + D4 = Keys.D4, + + /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary> + D5 = Keys.D5, + + /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary> + D6 = Keys.D6, + + /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary> + D7 = Keys.D7, + + /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary> + D8 = Keys.D8, + + /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary> + D9 = Keys.D9, + + /// <summary>The Decimal button on a keyboard.</summary> + Decimal = Keys.Decimal, + + /// <summary>The Delete button on a keyboard.</summary> + Delete = Keys.Delete, + + /// <summary>The Divide button on a keyboard.</summary> + Divide = Keys.Divide, + + /// <summary>The Down arrow button on a keyboard.</summary> + Down = Keys.Down, + + /// <summary>The E button on a keyboard.</summary> + E = Keys.E, + + /// <summary>The End button on a keyboard.</summary> + End = Keys.End, + + /// <summary>The Enter button on a keyboard.</summary> + Enter = Keys.Enter, + + /// <summary>The Erase EOF button on a keyboard.</summary> + EraseEof = Keys.EraseEof, + + /// <summary>The Escape button on a keyboard.</summary> + Escape = Keys.Escape, + + /// <summary>The Execute button on a keyboard.</summary> + Execute = Keys.Execute, + + /// <summary>The ExSel button on a keyboard.</summary> + Exsel = Keys.Exsel, + + /// <summary>The F button on a keyboard.</summary> + F = Keys.F, + + /// <summary>The F1 button on a keyboard.</summary> + F1 = Keys.F1, + + /// <summary>The F10 button on a keyboard.</summary> + F10 = Keys.F10, + + /// <summary>The F11 button on a keyboard.</summary> + F11 = Keys.F11, + + /// <summary>The F12 button on a keyboard.</summary> + F12 = Keys.F12, + + /// <summary>The F13 button on a keyboard.</summary> + F13 = Keys.F13, + + /// <summary>The F14 button on a keyboard.</summary> + F14 = Keys.F14, + + /// <summary>The F15 button on a keyboard.</summary> + F15 = Keys.F15, + + /// <summary>The F16 button on a keyboard.</summary> + F16 = Keys.F16, + + /// <summary>The F17 button on a keyboard.</summary> + F17 = Keys.F17, + + /// <summary>The F18 button on a keyboard.</summary> + F18 = Keys.F18, + + /// <summary>The F19 button on a keyboard.</summary> + F19 = Keys.F19, + + /// <summary>The F2 button on a keyboard.</summary> + F2 = Keys.F2, + + /// <summary>The F20 button on a keyboard.</summary> + F20 = Keys.F20, + + /// <summary>The F21 button on a keyboard.</summary> + F21 = Keys.F21, + + /// <summary>The F22 button on a keyboard.</summary> + F22 = Keys.F22, + + /// <summary>The F23 button on a keyboard.</summary> + F23 = Keys.F23, + + /// <summary>The F24 button on a keyboard.</summary> + F24 = Keys.F24, + + /// <summary>The F3 button on a keyboard.</summary> + F3 = Keys.F3, + + /// <summary>The F4 button on a keyboard.</summary> + F4 = Keys.F4, + + /// <summary>The F5 button on a keyboard.</summary> + F5 = Keys.F5, + + /// <summary>The F6 button on a keyboard.</summary> + F6 = Keys.F6, + + /// <summary>The F7 button on a keyboard.</summary> + F7 = Keys.F7, + + /// <summary>The F8 button on a keyboard.</summary> + F8 = Keys.F8, + + /// <summary>The F9 button on a keyboard.</summary> + F9 = Keys.F9, + + /// <summary>The G button on a keyboard.</summary> + G = Keys.G, + + /// <summary>The H button on a keyboard.</summary> + H = Keys.H, + + /// <summary>The Help button on a keyboard.</summary> + Help = Keys.Help, + + /// <summary>The Home button on a keyboard.</summary> + Home = Keys.Home, + + /// <summary>The I button on a keyboard.</summary> + I = Keys.I, + + /// <summary>The IME Convert button on a keyboard.</summary> + ImeConvert = Keys.ImeConvert, + + /// <summary>The IME NoConvert button on a keyboard.</summary> + ImeNoConvert = Keys.ImeNoConvert, + + /// <summary>The INS button on a keyboard.</summary> + Insert = Keys.Insert, + + /// <summary>The J button on a keyboard.</summary> + J = Keys.J, + + /// <summary>The K button on a keyboard.</summary> + K = Keys.K, + + /// <summary>The Kana button on a Japanese keyboard.</summary> + Kana = Keys.Kana, + + /// <summary>The Kanji button on a Japanese keyboard.</summary> + Kanji = Keys.Kanji, + + /// <summary>The L button on a keyboard.</summary> + L = Keys.L, + + /// <summary>The Start Applications 1 button on a keyboard in Windows 2000/XP.</summary> + LaunchApplication1 = Keys.LaunchApplication1, + + /// <summary>The Start Applications 2 button on a keyboard in Windows 2000/XP.</summary> + LaunchApplication2 = Keys.LaunchApplication2, + + /// <summary>The Start Mail button on a keyboard in Windows 2000/XP.</summary> + LaunchMail = Keys.LaunchMail, + + /// <summary>The Left arrow button on a keyboard.</summary> + Left = Keys.Left, + + /// <summary>The Left Alt button on a keyboard.</summary> + LeftAlt = Keys.LeftAlt, + + /// <summary>The Left Control button on a keyboard.</summary> + LeftControl = Keys.LeftControl, + + /// <summary>The Left Shift button on a keyboard.</summary> + LeftShift = Keys.LeftShift, + + /// <summary>The Left Windows button on a keyboard.</summary> + LeftWindows = Keys.LeftWindows, + + /// <summary>The M button on a keyboard.</summary> + M = Keys.M, + + /// <summary>The MediaNextTrack button on a keyboard in Windows 2000/XP.</summary> + MediaNextTrack = Keys.MediaNextTrack, + + /// <summary>The MediaPlayPause button on a keyboard in Windows 2000/XP.</summary> + MediaPlayPause = Keys.MediaPlayPause, + + /// <summary>The MediaPreviousTrack button on a keyboard in Windows 2000/XP.</summary> + MediaPreviousTrack = Keys.MediaPreviousTrack, + + /// <summary>The MediaStop button on a keyboard in Windows 2000/XP.</summary> + MediaStop = Keys.MediaStop, + + /// <summary>The Multiply button on a keyboard.</summary> + Multiply = Keys.Multiply, + + /// <summary>The N button on a keyboard.</summary> + N = Keys.N, + + /// <summary>The Num Lock button on a keyboard.</summary> + NumLock = Keys.NumLock, + + /// <summary>The Numeric keypad 0 button on a keyboard.</summary> + NumPad0 = Keys.NumPad0, + + /// <summary>The Numeric keypad 1 button on a keyboard.</summary> + NumPad1 = Keys.NumPad1, + + /// <summary>The Numeric keypad 2 button on a keyboard.</summary> + NumPad2 = Keys.NumPad2, + + /// <summary>The Numeric keypad 3 button on a keyboard.</summary> + NumPad3 = Keys.NumPad3, + + /// <summary>The Numeric keypad 4 button on a keyboard.</summary> + NumPad4 = Keys.NumPad4, + + /// <summary>The Numeric keypad 5 button on a keyboard.</summary> + NumPad5 = Keys.NumPad5, + + /// <summary>The Numeric keypad 6 button on a keyboard.</summary> + NumPad6 = Keys.NumPad6, + + /// <summary>The Numeric keypad 7 button on a keyboard.</summary> + NumPad7 = Keys.NumPad7, + + /// <summary>The Numeric keypad 8 button on a keyboard.</summary> + NumPad8 = Keys.NumPad8, + + /// <summary>The Numeric keypad 9 button on a keyboard.</summary> + NumPad9 = Keys.NumPad9, + + /// <summary>The O button on a keyboard.</summary> + O = Keys.O, + + /// <summary>A miscellaneous button on a keyboard; can vary by keyboard.</summary> + Oem8 = Keys.Oem8, + + /// <summary>The OEM Auto button on a keyboard.</summary> + OemAuto = Keys.OemAuto, + + /// <summary>The OEM Angle Bracket or Backslash button on the RT 102 keyboard in Windows 2000/XP.</summary> + OemBackslash = Keys.OemBackslash, + + /// <summary>The Clear button on a keyboard.</summary> + OemClear = Keys.OemClear, + + /// <summary>The OEM Close Bracket button on a US standard keyboard in Windows 2000/XP.</summary> + OemCloseBrackets = Keys.OemCloseBrackets, + + /// <summary>The ',' button on a keyboard in any country/region in Windows 2000/XP.</summary> + OemComma = Keys.OemComma, + + /// <summary>The OEM Copy button on a keyboard.</summary> + OemCopy = Keys.OemCopy, + + /// <summary>The OEM Enlarge Window button on a keyboard.</summary> + OemEnlW = Keys.OemEnlW, + + /// <summary>The '-' button on a keyboard in any country/region in Windows 2000/XP.</summary> + OemMinus = Keys.OemMinus, + + /// <summary>The OEM Open Bracket button on a US standard keyboard in Windows 2000/XP.</summary> + OemOpenBrackets = Keys.OemOpenBrackets, + + /// <summary>The '.' button on a keyboard in any country/region.</summary> + OemPeriod = Keys.OemPeriod, + + /// <summary>The OEM Pipe button on a US standard keyboard.</summary> + OemPipe = Keys.OemPipe, + + /// <summary>The '+' button on a keyboard in Windows 2000/XP.</summary> + OemPlus = Keys.OemPlus, + + /// <summary>The OEM Question Mark button on a US standard keyboard.</summary> + OemQuestion = Keys.OemQuestion, + + /// <summary>The OEM Single/Double Quote button on a US standard keyboard.</summary> + OemQuotes = Keys.OemQuotes, + + /// <summary>The OEM Semicolon button on a US standard keyboard.</summary> + OemSemicolon = Keys.OemSemicolon, + + /// <summary>The OEM Tilde button on a US standard keyboard.</summary> + OemTilde = Keys.OemTilde, + + /// <summary>The P button on a keyboard.</summary> + P = Keys.P, + + /// <summary>The PA1 button on a keyboard.</summary> + Pa1 = Keys.Pa1, + + /// <summary>The Page Down button on a keyboard.</summary> + PageDown = Keys.PageDown, + + /// <summary>The Page Up button on a keyboard.</summary> + PageUp = Keys.PageUp, + + /// <summary>The Pause button on a keyboard.</summary> + Pause = Keys.Pause, + + /// <summary>The Play button on a keyboard.</summary> + Play = Keys.Play, + + /// <summary>The Print button on a keyboard.</summary> + Print = Keys.Print, + + /// <summary>The Print Screen button on a keyboard.</summary> + PrintScreen = Keys.PrintScreen, + + /// <summary>The IME Process button on a keyboard in Windows 95/98/ME/NT 4.0/2000/XP.</summary> + ProcessKey = Keys.ProcessKey, + + /// <summary>The Q button on a keyboard.</summary> + Q = Keys.Q, + + /// <summary>The R button on a keyboard.</summary> + R = Keys.R, + + /// <summary>The Right Arrow button on a keyboard.</summary> + Right = Keys.Right, + + /// <summary>The Right Alt button on a keyboard.</summary> + RightAlt = Keys.RightAlt, + + /// <summary>The Right Control button on a keyboard.</summary> + RightControl = Keys.RightControl, + + /// <summary>The Right Shift button on a keyboard.</summary> + RightShift = Keys.RightShift, + + /// <summary>The Right Windows button on a keyboard.</summary> + RightWindows = Keys.RightWindows, + + /// <summary>The S button on a keyboard.</summary> + S = Keys.S, + + /// <summary>The Scroll Lock button on a keyboard.</summary> + Scroll = Keys.Scroll, + + /// <summary>The Select button on a keyboard.</summary> + Select = Keys.Select, + + /// <summary>The Select Media button on a keyboard in Windows 2000/XP.</summary> + SelectMedia = Keys.SelectMedia, + + /// <summary>The Separator button on a keyboard.</summary> + Separator = Keys.Separator, + + /// <summary>The Computer Sleep button on a keyboard.</summary> + Sleep = Keys.Sleep, + + /// <summary>The Space bar on a keyboard.</summary> + Space = Keys.Space, + + /// <summary>The Subtract button on a keyboard.</summary> + Subtract = Keys.Subtract, + + /// <summary>The T button on a keyboard.</summary> + T = Keys.T, + + /// <summary>The Tab button on a keyboard.</summary> + Tab = Keys.Tab, + + /// <summary>The U button on a keyboard.</summary> + U = Keys.U, + + /// <summary>The Up Arrow button on a keyboard.</summary> + Up = Keys.Up, + + /// <summary>The V button on a keyboard.</summary> + V = Keys.V, + + /// <summary>The Volume Down button on a keyboard in Windows 2000/XP.</summary> + VolumeDown = Keys.VolumeDown, + + /// <summary>The Volume Mute button on a keyboard in Windows 2000/XP.</summary> + VolumeMute = Keys.VolumeMute, + + /// <summary>The Volume Up button on a keyboard in Windows 2000/XP.</summary> + VolumeUp = Keys.VolumeUp, + + /// <summary>The W button on a keyboard.</summary> + W = Keys.W, + + /// <summary>The X button on a keyboard.</summary> + X = Keys.X, + + /// <summary>The Y button on a keyboard.</summary> + Y = Keys.Y, + + /// <summary>The Z button on a keyboard.</summary> + Z = Keys.Z, + + /// <summary>The Zoom button on a keyboard.</summary> + Zoom = Keys.Zoom + } + + /// <summary>Provides extension methods for <see cref="SButton"/>.</summary> +#if SMAPI_2_0 + public +#else + internal +#endif + static class SButtonExtensions + { + /********* + ** Accessors + *********/ + /// <summary>The offset added to <see cref="Buttons"/> values when converting them to <see cref="SButton"/> to avoid collisions with <see cref="Keys"/> values.</summary> + internal const int ControllerOffset = 2000; + + + /********* + ** Public methods + *********/ + /// <summary>Get the <see cref="SButton"/> equivalent for the given button.</summary> + /// <param name="key">The keyboard button to convert.</param> + internal static SButton ToSButton(this Keys key) + { + return (SButton)key; + } + + /// <summary>Get the <see cref="SButton"/> equivalent for the given button.</summary> + /// <param name="key">The controller button to convert.</param> + internal static SButton ToSButton(this Buttons key) + { + return (SButton)(SButtonExtensions.ControllerOffset + key); + } + + /// <summary>Get the <see cref="Keys"/> equivalent for the given button.</summary> + /// <param name="input">The button to convert.</param> + /// <param name="key">The keyboard equivalent.</param> + /// <returns>Returns whether the value was converted successfully.</returns> + public static bool TryGetKeyboard(this SButton input, out Keys key) + { + if (Enum.IsDefined(typeof(Keys), (int)input)) + { + key = (Keys)input; + return true; + } + + key = Keys.None; + return false; + } + + /// <summary>Get the <see cref="Buttons"/> equivalent for the given button.</summary> + /// <param name="input">The button to convert.</param> + /// <param name="button">The controller equivalent.</param> + /// <returns>Returns whether the value was converted successfully.</returns> + public static bool TryGetController(this SButton input, out Buttons button) + { + if (Enum.IsDefined(typeof(Keys), (int)input - SButtonExtensions.ControllerOffset)) + { + button = (Buttons)(input - SButtonExtensions.ControllerOffset); + return true; + } + + button = 0; + return false; + } + } +} diff --git a/src/StardewModdingAPI/Utilities/SDate.cs b/src/StardewModdingAPI/Utilities/SDate.cs new file mode 100644 index 00000000..e0613491 --- /dev/null +++ b/src/StardewModdingAPI/Utilities/SDate.cs @@ -0,0 +1,222 @@ +using System; +using System.Linq; +using StardewValley; + +namespace StardewModdingAPI.Utilities +{ + /// <summary>Represents a Stardew Valley date.</summary> + public class SDate : IEquatable<SDate> + { + /********* + ** Properties + *********/ + /// <summary>The internal season names in order.</summary> + private readonly string[] Seasons = { "spring", "summer", "fall", "winter" }; + + /// <summary>The number of seasons in a year.</summary> + private int SeasonsInYear => this.Seasons.Length; + + /// <summary>The number of days in a season.</summary> + private readonly int DaysInSeason = 28; + + + /********* + ** Accessors + *********/ + /// <summary>The day of month.</summary> + public int Day { get; } + + /// <summary>The season name.</summary> + public string Season { get; } + + /// <summary>The year.</summary> + public int Year { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="day">The day of month.</param> + /// <param name="season">The season name.</param> + /// <exception cref="ArgumentException">One of the arguments has an invalid value (like day 35).</exception> + public SDate(int day, string season) + : this(day, season, Game1.year) { } + + /// <summary>Construct an instance.</summary> + /// <param name="day">The day of month.</param> + /// <param name="season">The season name.</param> + /// <param name="year">The year.</param> + /// <exception cref="ArgumentException">One of the arguments has an invalid value (like day 35).</exception> + public SDate(int day, string season, int year) + { + // validate + if (season == null) + throw new ArgumentNullException(nameof(season)); + if (!this.Seasons.Contains(season)) + throw new ArgumentException($"Unknown season '{season}', must be one of [{string.Join(", ", this.Seasons)}]."); + if (day < 1 || day > this.DaysInSeason) + 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."); + + // initialise + this.Day = day; + this.Season = season; + this.Year = year; + } + + /// <summary>Get the current in-game date.</summary> + public static SDate Now() + { + return new SDate(Game1.dayOfMonth, Game1.currentSeason, Game1.year); + } + + /// <summary>Get a new date with the given number of days added.</summary> + /// <param name="offset">The number of days to add.</param> + /// <returns>Returns the resulting date.</returns> + /// <exception cref="ArithmeticException">The offset would result in an invalid date (like year 0).</exception> + public SDate AddDays(int offset) + { + // simple case + int day = this.Day + offset; + string season = this.Season; + int year = this.Year; + + // handle season transition + if (day > this.DaysInSeason || day < 1) + { + // get season index + int curSeasonIndex = this.GetSeasonIndex(); + + // get season offset + int seasonOffset = day / this.DaysInSeason; + if (day < 1) + seasonOffset -= 1; + + // get new date + day = this.GetWrappedIndex(day, this.DaysInSeason); + season = this.Seasons[this.GetWrappedIndex(curSeasonIndex + seasonOffset, this.Seasons.Length)]; + year += seasonOffset / this.Seasons.Length; + } + + // validate + if (year < 1) + throw new ArithmeticException($"Adding {offset} days to {this} would result in invalid date {day:00} {season} {year}."); + + // return new date + return new SDate(day, season, year); + } + + /// <summary>Get a string representation of the date. This is mainly intended for debugging or console messages.</summary> + public override string ToString() + { + return $"{this.Day:00} {this.Season} Y{this.Year}"; + } + + /**** + ** IEquatable + ****/ + /// <summary>Get whether this instance is equal to another.</summary> + /// <param name="other">The other value to compare.</param> + public bool Equals(SDate other) + { + return this == other; + } + + /// <summary>Get whether this instance is equal to another.</summary> + /// <param name="obj">The other value to compare.</param> + public override bool Equals(object obj) + { + return obj is SDate other && this == other; + } + + /// <summary>Get a hash code which uniquely identifies a date.</summary> + public override int GetHashCode() + { + // return the number of days since 01 spring Y1 + int yearIndex = this.Year - 1; + return + yearIndex * this.DaysInSeason * this.SeasonsInYear + + this.GetSeasonIndex() * this.DaysInSeason + + this.Day; + } + + /**** + ** Operators + ****/ + /// <summary>Get whether one date is equal to another.</summary> + /// <param name="date">The base date to compare.</param> + /// <param name="other">The other date to compare.</param> + /// <returns>The equality of the dates</returns> + public static bool operator ==(SDate date, SDate other) + { + return date?.GetHashCode() == other?.GetHashCode(); + } + + /// <summary>Get whether one date is not equal to another.</summary> + /// <param name="date">The base date to compare.</param> + /// <param name="other">The other date to compare.</param> + public static bool operator !=(SDate date, SDate other) + { + return date?.GetHashCode() != other?.GetHashCode(); + } + + /// <summary>Get whether one date is more than another.</summary> + /// <param name="date">The base date to compare.</param> + /// <param name="other">The other date to compare.</param> + public static bool operator >(SDate date, SDate other) + { + return date?.GetHashCode() > other?.GetHashCode(); + } + + /// <summary>Get whether one date is more than or equal to another.</summary> + /// <param name="date">The base date to compare.</param> + /// <param name="other">The other date to compare.</param> + public static bool operator >=(SDate date, SDate other) + { + return date?.GetHashCode() >= other?.GetHashCode(); + } + + /// <summary>Get whether one date is less than or equal to another.</summary> + /// <param name="date">The base date to compare.</param> + /// <param name="other">The other date to compare.</param> + public static bool operator <=(SDate date, SDate other) + { + return date?.GetHashCode() <= other?.GetHashCode(); + } + + /// <summary>Get whether one date is less than another.</summary> + /// <param name="date">The base date to compare.</param> + /// <param name="other">The other date to compare.</param> + public static bool operator <(SDate date, SDate other) + { + return date?.GetHashCode() < other?.GetHashCode(); + } + + + /********* + ** Private methods + *********/ + /// <summary>Get the current season index.</summary> + /// <exception cref="InvalidOperationException">The current season wasn't recognised.</exception> + private int GetSeasonIndex() + { + int index = Array.IndexOf(this.Seasons, this.Season); + if (index == -1) + throw new InvalidOperationException($"The current season '{this.Season}' wasn't recognised."); + return index; + } + + /// <summary>Get the real index in an array which should be treated as a two-way loop.</summary> + /// <param name="index">The index in the looped array.</param> + /// <param name="length">The number of elements in the array.</param> + private int GetWrappedIndex(int index, int length) + { + int wrapped = index % length; + if (wrapped < 0) + wrapped += length; + return wrapped; + } + } +} |