From 68528f7decadccb4c5ed62f3fff10aeff22dcd43 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Fri, 23 Feb 2018 19:05:23 -0500 Subject: overhaul events to track the mod which added each handler, and log errors under their name (#451) --- docs/release-notes.md | 1 + src/SMAPI/Events/ContentEvents.cs | 28 ++- src/SMAPI/Events/ControlEvents.cs | 123 +++++------- src/SMAPI/Events/GameEvents.cs | 110 +++++------ src/SMAPI/Events/GraphicsEvents.cs | 120 +++++------- src/SMAPI/Events/InputEvents.cs | 46 ++--- src/SMAPI/Events/LocationEvents.cs | 61 +++--- src/SMAPI/Events/MenuEvents.cs | 44 +++-- src/SMAPI/Events/MineEvents.cs | 29 ++- src/SMAPI/Events/PlayerEvents.cs | 45 ++--- src/SMAPI/Events/SaveEvents.cs | 84 ++++----- src/SMAPI/Events/SpecialisedEvents.cs | 25 ++- src/SMAPI/Events/TimeEvents.cs | 41 ++-- src/SMAPI/Framework/Events/EventManager.cs | 249 +++++++++++++++++++++++++ src/SMAPI/Framework/Events/ManagedEvent.cs | 119 ++++++++++++ src/SMAPI/Framework/Events/ManagedEventBase.cs | 81 ++++++++ src/SMAPI/Framework/InternalExtensions.cs | 58 ------ src/SMAPI/Framework/SGame.cs | 142 +++++++------- src/SMAPI/Program.cs | 26 ++- src/SMAPI/StardewModdingAPI.csproj | 3 + 20 files changed, 910 insertions(+), 525 deletions(-) create mode 100644 src/SMAPI/Framework/Events/EventManager.cs create mode 100644 src/SMAPI/Framework/Events/ManagedEvent.cs create mode 100644 src/SMAPI/Framework/Events/ManagedEventBase.cs diff --git a/docs/release-notes.md b/docs/release-notes.md index a0f6ef28..08f945e4 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -3,6 +3,7 @@ * For players: * **Added support for content packs**. _Content packs are collections of files for a SMAPI mod to load. These can be installed directly under `Mods` like a normal SMAPI mod, get automatic update and compatibility checks, and provide convenient APIs to the mods that read them._ + * Added mod detection to unhandled errors (i.e. most errors will now mention which mod caused them). * Added install scripts for Linux/Mac (no more manual terminal commands!). * Added the required mod's name and URL to dependency errors. * Fixed unhandled mod errors being logged under `[SMAPI]` instead of the mod name. diff --git a/src/SMAPI/Events/ContentEvents.cs b/src/SMAPI/Events/ContentEvents.cs index 4b4e2ad0..63645258 100644 --- a/src/SMAPI/Events/ContentEvents.cs +++ b/src/SMAPI/Events/ContentEvents.cs @@ -1,29 +1,37 @@ -using System; -using StardewModdingAPI.Framework; +using System; +using StardewModdingAPI.Framework.Events; namespace StardewModdingAPI.Events { /// Events raised when the game loads content. public static class ContentEvents { + /********* + ** Properties + *********/ + /// The core event manager. + private static EventManager EventManager; + /********* ** Events *********/ /// Raised after the content language changes. - public static event EventHandler> AfterLocaleChanged; + public static event EventHandler> AfterLocaleChanged + { + add => ContentEvents.EventManager.Content_LocaleChanged.Add(value); + remove => ContentEvents.EventManager.Content_LocaleChanged.Remove(value); + } /********* - ** Internal methods + ** Public methods *********/ - /// Raise an event. - /// Encapsulates monitoring and logging. - /// The previous locale. - /// The current locale. - internal static void InvokeAfterLocaleChanged(IMonitor monitor, string oldLocale, string newLocale) + /// Initialise the events. + /// The core event manager. + internal static void Init(EventManager eventManager) { - monitor.SafelyRaiseGenericEvent($"{nameof(ContentEvents)}.{nameof(ContentEvents.AfterLocaleChanged)}", ContentEvents.AfterLocaleChanged?.GetInvocationList(), null, new EventArgsValueChanged(oldLocale, newLocale)); + ContentEvents.EventManager = eventManager; } } } diff --git a/src/SMAPI/Events/ControlEvents.cs b/src/SMAPI/Events/ControlEvents.cs index 80d0f547..973bb245 100644 --- a/src/SMAPI/Events/ControlEvents.cs +++ b/src/SMAPI/Events/ControlEvents.cs @@ -1,7 +1,6 @@ -using System; -using Microsoft.Xna.Framework; +using System; using Microsoft.Xna.Framework.Input; -using StardewModdingAPI.Framework; +using StardewModdingAPI.Framework.Events; namespace StardewModdingAPI.Events { @@ -9,104 +8,80 @@ namespace StardewModdingAPI.Events public static class ControlEvents { /********* - ** Events + ** Properties *********/ - /// Raised when the changes. That happens when the player presses or releases a key. - public static event EventHandler KeyboardChanged; - - /// Raised when the player presses a keyboard key. - public static event EventHandler KeyPressed; - - /// Raised when the player releases a keyboard key. - public static event EventHandler KeyReleased; - - /// Raised when the changes. That happens when the player moves the mouse, scrolls the mouse wheel, or presses/releases a button. - public static event EventHandler MouseChanged; - - /// The player pressed a controller button. This event isn't raised for trigger buttons. - public static event EventHandler ControllerButtonPressed; - - /// The player released a controller button. This event isn't raised for trigger buttons. - public static event EventHandler ControllerButtonReleased; - - /// The player pressed a controller trigger button. - public static event EventHandler ControllerTriggerPressed; - - /// The player released a controller trigger button. - public static event EventHandler ControllerTriggerReleased; + /// The core event manager. + private static EventManager EventManager; /********* - ** Internal methods + ** Events *********/ - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The previous keyboard state. - /// The current keyboard state. - internal static void InvokeKeyboardChanged(IMonitor monitor, KeyboardState priorState, KeyboardState newState) + /// Raised when the changes. That happens when the player presses or releases a key. + public static event EventHandler KeyboardChanged { - monitor.SafelyRaiseGenericEvent($"{nameof(ControlEvents)}.{nameof(ControlEvents.KeyboardChanged)}", ControlEvents.KeyboardChanged?.GetInvocationList(), null, new EventArgsKeyboardStateChanged(priorState, newState)); + add => ControlEvents.EventManager.Control_KeyboardChanged.Add(value); + remove => ControlEvents.EventManager.Control_KeyboardChanged.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The previous mouse state. - /// The current mouse state. - /// The previous mouse position on the screen adjusted for the zoom level. - /// The current mouse position on the screen adjusted for the zoom level. - internal static void InvokeMouseChanged(IMonitor monitor, MouseState priorState, MouseState newState, Point priorPosition, Point newPosition) + /// Raised when the player presses a keyboard key. + public static event EventHandler KeyPressed { - monitor.SafelyRaiseGenericEvent($"{nameof(ControlEvents)}.{nameof(ControlEvents.MouseChanged)}", ControlEvents.MouseChanged?.GetInvocationList(), null, new EventArgsMouseStateChanged(priorState, newState, priorPosition, newPosition)); + add => ControlEvents.EventManager.Control_KeyPressed.Add(value); + remove => ControlEvents.EventManager.Control_KeyPressed.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The keyboard button that was pressed. - internal static void InvokeKeyPressed(IMonitor monitor, Keys key) + /// Raised when the player releases a keyboard key. + public static event EventHandler KeyReleased { - monitor.SafelyRaiseGenericEvent($"{nameof(ControlEvents)}.{nameof(ControlEvents.KeyPressed)}", ControlEvents.KeyPressed?.GetInvocationList(), null, new EventArgsKeyPressed(key)); + add => ControlEvents.EventManager.Control_KeyReleased.Add(value); + remove => ControlEvents.EventManager.Control_KeyReleased.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The keyboard button that was released. - internal static void InvokeKeyReleased(IMonitor monitor, Keys key) + /// Raised when the changes. That happens when the player moves the mouse, scrolls the mouse wheel, or presses/releases a button. + public static event EventHandler MouseChanged { - monitor.SafelyRaiseGenericEvent($"{nameof(ControlEvents)}.{nameof(ControlEvents.KeyReleased)}", ControlEvents.KeyReleased?.GetInvocationList(), null, new EventArgsKeyPressed(key)); + add => ControlEvents.EventManager.Control_MouseChanged.Add(value); + remove => ControlEvents.EventManager.Control_MouseChanged.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The controller button that was pressed. - internal static void InvokeButtonPressed(IMonitor monitor, Buttons button) + /// The player pressed a controller button. This event isn't raised for trigger buttons. + public static event EventHandler ControllerButtonPressed { - monitor.SafelyRaiseGenericEvent($"{nameof(ControlEvents)}.{nameof(ControlEvents.ControllerButtonPressed)}", ControlEvents.ControllerButtonPressed?.GetInvocationList(), null, new EventArgsControllerButtonPressed(PlayerIndex.One, button)); + add => ControlEvents.EventManager.Control_ControllerButtonPressed.Add(value); + remove => ControlEvents.EventManager.Control_ControllerButtonPressed.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The controller button that was released. - internal static void InvokeButtonReleased(IMonitor monitor, Buttons button) + /// The player released a controller button. This event isn't raised for trigger buttons. + public static event EventHandler ControllerButtonReleased { - monitor.SafelyRaiseGenericEvent($"{nameof(ControlEvents)}.{nameof(ControlEvents.ControllerButtonReleased)}", ControlEvents.ControllerButtonReleased?.GetInvocationList(), null, new EventArgsControllerButtonReleased(PlayerIndex.One, button)); + add => ControlEvents.EventManager.Control_ControllerButtonReleased.Add(value); + remove => ControlEvents.EventManager.Control_ControllerButtonReleased.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The trigger button that was pressed. - /// The current trigger value. - internal static void InvokeTriggerPressed(IMonitor monitor, Buttons button, float value) + /// The player pressed a controller trigger button. + public static event EventHandler ControllerTriggerPressed { - monitor.SafelyRaiseGenericEvent($"{nameof(ControlEvents)}.{nameof(ControlEvents.ControllerTriggerPressed)}", ControlEvents.ControllerTriggerPressed?.GetInvocationList(), null, new EventArgsControllerTriggerPressed(PlayerIndex.One, button, value)); + add => ControlEvents.EventManager.Control_ControllerTriggerPressed.Add(value); + remove => ControlEvents.EventManager.Control_ControllerTriggerPressed.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The trigger button that was pressed. - /// The current trigger value. - internal static void InvokeTriggerReleased(IMonitor monitor, Buttons button, float value) + /// The player released a controller trigger button. + public static event EventHandler ControllerTriggerReleased + { + add => ControlEvents.EventManager.Control_ControllerTriggerReleased.Add(value); + remove => ControlEvents.EventManager.Control_ControllerTriggerReleased.Remove(value); + } + + + /********* + ** Public methods + *********/ + /// Initialise the events. + /// The core event manager. + internal static void Init(EventManager eventManager) { - monitor.SafelyRaiseGenericEvent($"{nameof(ControlEvents)}.{nameof(ControlEvents.ControllerTriggerReleased)}", ControlEvents.ControllerTriggerReleased?.GetInvocationList(), null, new EventArgsControllerTriggerReleased(PlayerIndex.One, button, value)); + ControlEvents.EventManager = eventManager; } } } diff --git a/src/SMAPI/Events/GameEvents.cs b/src/SMAPI/Events/GameEvents.cs index 3466470d..92879280 100644 --- a/src/SMAPI/Events/GameEvents.cs +++ b/src/SMAPI/Events/GameEvents.cs @@ -1,5 +1,5 @@ using System; -using StardewModdingAPI.Framework; +using StardewModdingAPI.Framework.Events; namespace StardewModdingAPI.Events { @@ -7,100 +7,80 @@ namespace StardewModdingAPI.Events public static class GameEvents { /********* - ** Events + ** Properties *********/ - /// Raised during launch after configuring XNA or MonoGame. The game window hasn't been opened by this point. Called after . - internal static event EventHandler InitializeInternal; - - /// Raised when the game updates its state (≈60 times per second). - public static event EventHandler UpdateTick; - - /// Raised every other tick (≈30 times per second). - public static event EventHandler SecondUpdateTick; - - /// Raised every fourth tick (≈15 times per second). - public static event EventHandler FourthUpdateTick; - - /// Raised every eighth tick (≈8 times per second). - public static event EventHandler EighthUpdateTick; - - /// Raised every 15th tick (≈4 times per second). - public static event EventHandler QuarterSecondTick; - - /// Raised every 30th tick (≈twice per second). - public static event EventHandler HalfSecondTick; - - /// Raised every 60th tick (≈once per second). - public static event EventHandler OneSecondTick; - - /// Raised once after the game initialises and all methods have been called. - public static event EventHandler FirstUpdateTick; + /// The core event manager. + private static EventManager EventManager; /********* - ** Internal methods + ** Events *********/ - /// Raise an event. - /// Encapsulates logging and monitoring. - internal static void InvokeInitialize(IMonitor monitor) + /// Raised when the game updates its state (≈60 times per second). + public static event EventHandler UpdateTick { - monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.InitializeInternal)}", GameEvents.InitializeInternal?.GetInvocationList()); + add => GameEvents.EventManager.Game_UpdateTick.Add(value); + remove => GameEvents.EventManager.Game_UpdateTick.Remove(value); } - /// Raise an event. - /// Encapsulates logging and monitoring. - internal static void InvokeUpdateTick(IMonitor monitor) + /// Raised every other tick (≈30 times per second). + public static event EventHandler SecondUpdateTick { - monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.UpdateTick)}", GameEvents.UpdateTick?.GetInvocationList()); + add => GameEvents.EventManager.Game_SecondUpdateTick.Add(value); + remove => GameEvents.EventManager.Game_SecondUpdateTick.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - internal static void InvokeSecondUpdateTick(IMonitor monitor) + /// Raised every fourth tick (≈15 times per second). + public static event EventHandler FourthUpdateTick { - monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.SecondUpdateTick)}", GameEvents.SecondUpdateTick?.GetInvocationList()); + add => GameEvents.EventManager.Game_FourthUpdateTick.Add(value); + remove => GameEvents.EventManager.Game_FourthUpdateTick.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - internal static void InvokeFourthUpdateTick(IMonitor monitor) + /// Raised every eighth tick (≈8 times per second). + public static event EventHandler EighthUpdateTick { - monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.FourthUpdateTick)}", GameEvents.FourthUpdateTick?.GetInvocationList()); + add => GameEvents.EventManager.Game_EighthUpdateTick.Add(value); + remove => GameEvents.EventManager.Game_EighthUpdateTick.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - internal static void InvokeEighthUpdateTick(IMonitor monitor) + /// Raised every 15th tick (≈4 times per second). + public static event EventHandler QuarterSecondTick { - monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.EighthUpdateTick)}", GameEvents.EighthUpdateTick?.GetInvocationList()); + add => GameEvents.EventManager.Game_QuarterSecondTick.Add(value); + remove => GameEvents.EventManager.Game_QuarterSecondTick.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - internal static void InvokeQuarterSecondTick(IMonitor monitor) + /// Raised every 30th tick (≈twice per second). + public static event EventHandler HalfSecondTick { - monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.QuarterSecondTick)}", GameEvents.QuarterSecondTick?.GetInvocationList()); + add => GameEvents.EventManager.Game_HalfSecondTick.Add(value); + remove => GameEvents.EventManager.Game_HalfSecondTick.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - internal static void InvokeHalfSecondTick(IMonitor monitor) + /// Raised every 60th tick (≈once per second). + public static event EventHandler OneSecondTick { - monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.HalfSecondTick)}", GameEvents.HalfSecondTick?.GetInvocationList()); + add => GameEvents.EventManager.Game_OneSecondTick.Add(value); + remove => GameEvents.EventManager.Game_OneSecondTick.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - internal static void InvokeOneSecondTick(IMonitor monitor) + /// Raised once after the game initialises and all methods have been called. + public static event EventHandler FirstUpdateTick { - monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.OneSecondTick)}", GameEvents.OneSecondTick?.GetInvocationList()); + add => GameEvents.EventManager.Game_FirstUpdateTick.Add(value); + remove => GameEvents.EventManager.Game_FirstUpdateTick.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - internal static void InvokeFirstUpdateTick(IMonitor monitor) + + /********* + ** Public methods + *********/ + /// Initialise the events. + /// The core event manager. + internal static void Init(EventManager eventManager) { - monitor.SafelyRaisePlainEvent($"{nameof(GameEvents)}.{nameof(GameEvents.FirstUpdateTick)}", GameEvents.FirstUpdateTick?.GetInvocationList()); + GameEvents.EventManager = eventManager; } } } diff --git a/src/SMAPI/Events/GraphicsEvents.cs b/src/SMAPI/Events/GraphicsEvents.cs index fff51bed..e1ff4ee7 100644 --- a/src/SMAPI/Events/GraphicsEvents.cs +++ b/src/SMAPI/Events/GraphicsEvents.cs @@ -1,116 +1,88 @@ -using System; -using StardewModdingAPI.Framework; +using System; +using StardewModdingAPI.Framework.Events; namespace StardewModdingAPI.Events { /// Events raised during the game's draw loop, when the game is rendering content to the window. public static class GraphicsEvents { + /********* + ** Properties + *********/ + /// The core event manager. + private static EventManager EventManager; + + /********* ** Events *********/ - /**** - ** Generic events - ****/ /// Raised after the game window is resized. - public static event EventHandler Resize; + public static event EventHandler Resize + { + add => GraphicsEvents.EventManager.Graphics_Resize.Add(value); + remove => GraphicsEvents.EventManager.Graphics_Resize.Remove(value); + } /**** ** Main render events ****/ /// Raised before drawing the world to the screen. - public static event EventHandler OnPreRenderEvent; + public static event EventHandler OnPreRenderEvent + { + add => GraphicsEvents.EventManager.Graphics_OnPreRenderEvent.Add(value); + remove => GraphicsEvents.EventManager.Graphics_OnPreRenderEvent.Remove(value); + } /// Raised after drawing the world to the screen. - public static event EventHandler OnPostRenderEvent; - - /**** - ** HUD events - ****/ - /// Raised before drawing the HUD (item toolbar, clock, etc) to the screen. The HUD is available at this point, but not necessarily visible. (For example, the event is raised even if a menu is open.) - public static event EventHandler OnPreRenderHudEvent; - - /// Raised after drawing the HUD (item toolbar, clock, etc) to the screen. The HUD is available at this point, but not necessarily visible. (For example, the event is raised even if a menu is open.) - public static event EventHandler OnPostRenderHudEvent; - - /**** - ** GUI events - ****/ - /// Raised before drawing a menu to the screen during a draw loop. This includes the game's internal menus like the title screen. - public static event EventHandler OnPreRenderGuiEvent; - - /// Raised after drawing a menu to the screen during a draw loop. This includes the game's internal menus like the title screen. - public static event EventHandler OnPostRenderGuiEvent; - - - /********* - ** Internal methods - *********/ - /**** - ** Generic events - ****/ - /// Raise a event. - /// Encapsulates monitoring and logging. - internal static void InvokeResize(IMonitor monitor) + public static event EventHandler OnPostRenderEvent { - monitor.SafelyRaisePlainEvent($"{nameof(GraphicsEvents)}.{nameof(GraphicsEvents.Resize)}", GraphicsEvents.Resize?.GetInvocationList()); + add => GraphicsEvents.EventManager.Graphics_OnPostRenderEvent.Add(value); + remove => GraphicsEvents.EventManager.Graphics_OnPostRenderEvent.Remove(value); } /**** - ** Main render events + ** HUD events ****/ - /// Raise an event. - /// Encapsulates monitoring and logging. - internal static void InvokeOnPreRenderEvent(IMonitor monitor) - { - monitor.SafelyRaisePlainEvent($"{nameof(GraphicsEvents)}.{nameof(GraphicsEvents.OnPreRenderEvent)}", GraphicsEvents.OnPreRenderEvent?.GetInvocationList()); - } - - /// Raise an event. - /// Encapsulates monitoring and logging. - internal static void InvokeOnPostRenderEvent(IMonitor monitor) + /// Raised before drawing the HUD (item toolbar, clock, etc) to the screen. The HUD is available at this point, but not necessarily visible. (For example, the event is raised even if a menu is open.) + public static event EventHandler OnPreRenderHudEvent { - monitor.SafelyRaisePlainEvent($"{nameof(GraphicsEvents)}.{nameof(GraphicsEvents.OnPostRenderEvent)}", GraphicsEvents.OnPostRenderEvent?.GetInvocationList()); + add => GraphicsEvents.EventManager.Graphics_OnPreRenderHudEvent.Add(value); + remove => GraphicsEvents.EventManager.Graphics_OnPreRenderHudEvent.Remove(value); } - /// Get whether there are any post-render event listeners. - internal static bool HasPostRenderListeners() + /// Raised after drawing the HUD (item toolbar, clock, etc) to the screen. The HUD is available at this point, but not necessarily visible. (For example, the event is raised even if a menu is open.) + public static event EventHandler OnPostRenderHudEvent { - return GraphicsEvents.OnPostRenderEvent != null; + add => GraphicsEvents.EventManager.Graphics_OnPostRenderHudEvent.Add(value); + remove => GraphicsEvents.EventManager.Graphics_OnPostRenderHudEvent.Remove(value); } /**** ** GUI events ****/ - /// Raise an event. - /// Encapsulates monitoring and logging. - internal static void InvokeOnPreRenderGuiEvent(IMonitor monitor) + /// Raised before drawing a menu to the screen during a draw loop. This includes the game's internal menus like the title screen. + public static event EventHandler OnPreRenderGuiEvent { - monitor.SafelyRaisePlainEvent($"{nameof(GraphicsEvents)}.{nameof(GraphicsEvents.OnPreRenderGuiEvent)}", GraphicsEvents.OnPreRenderGuiEvent?.GetInvocationList()); + add => GraphicsEvents.EventManager.Graphics_OnPreRenderGuiEvent.Add(value); + remove => GraphicsEvents.EventManager.Graphics_OnPreRenderGuiEvent.Remove(value); } - /// Raise an event. - /// Encapsulates monitoring and logging. - internal static void InvokeOnPostRenderGuiEvent(IMonitor monitor) + /// Raised after drawing a menu to the screen during a draw loop. This includes the game's internal menus like the title screen. + public static event EventHandler OnPostRenderGuiEvent { - monitor.SafelyRaisePlainEvent($"{nameof(GraphicsEvents)}.{nameof(GraphicsEvents.OnPostRenderGuiEvent)}", GraphicsEvents.OnPostRenderGuiEvent?.GetInvocationList()); + add => GraphicsEvents.EventManager.Graphics_OnPostRenderGuiEvent.Add(value); + remove => GraphicsEvents.EventManager.Graphics_OnPostRenderGuiEvent.Remove(value); } - /**** - ** HUD events - ****/ - /// Raise an event. - /// Encapsulates monitoring and logging. - internal static void InvokeOnPreRenderHudEvent(IMonitor monitor) - { - monitor.SafelyRaisePlainEvent($"{nameof(GraphicsEvents)}.{nameof(GraphicsEvents.OnPreRenderHudEvent)}", GraphicsEvents.OnPreRenderHudEvent?.GetInvocationList()); - } - /// Raise an event. - /// Encapsulates monitoring and logging. - internal static void InvokeOnPostRenderHudEvent(IMonitor monitor) + /********* + ** Public methods + *********/ + /// Initialise the events. + /// The core event manager. + internal static void Init(EventManager eventManager) { - monitor.SafelyRaisePlainEvent($"{nameof(GraphicsEvents)}.{nameof(GraphicsEvents.OnPostRenderHudEvent)}", GraphicsEvents.OnPostRenderHudEvent?.GetInvocationList()); + GraphicsEvents.EventManager = eventManager; } } } diff --git a/src/SMAPI/Events/InputEvents.cs b/src/SMAPI/Events/InputEvents.cs index 985aed99..84d7ce5d 100644 --- a/src/SMAPI/Events/InputEvents.cs +++ b/src/SMAPI/Events/InputEvents.cs @@ -1,44 +1,44 @@ using System; -using StardewModdingAPI.Framework; +using StardewModdingAPI.Framework.Events; namespace StardewModdingAPI.Events { /// Events raised when the player uses a controller, keyboard, or mouse button. public static class InputEvents { + /********* + ** Properties + *********/ + /// The core event manager. + private static EventManager EventManager; + + /********* ** Events *********/ /// Raised when the player presses a button on the keyboard, controller, or mouse. - public static event EventHandler ButtonPressed; + public static event EventHandler ButtonPressed + { + add => InputEvents.EventManager.Input_ButtonPressed.Add(value); + remove => InputEvents.EventManager.Input_ButtonPressed.Remove(value); + } /// Raised when the player releases a keyboard key on the keyboard, controller, or mouse. - public static event EventHandler ButtonReleased; + public static event EventHandler ButtonReleased + { + add => InputEvents.EventManager.Input_ButtonReleased.Add(value); + remove => InputEvents.EventManager.Input_ButtonReleased.Remove(value); + } /********* - ** Internal methods + ** Public methods *********/ - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The button on the controller, keyboard, or mouse. - /// The cursor position. - /// Whether the input should trigger actions on the affected tile. - /// Whether the input should use tools on the affected tile. - internal static void InvokeButtonPressed(IMonitor monitor, SButton button, ICursorPosition cursor, bool isActionButton, bool isUseToolButton) - { - monitor.SafelyRaiseGenericEvent($"{nameof(InputEvents)}.{nameof(InputEvents.ButtonPressed)}", InputEvents.ButtonPressed?.GetInvocationList(), null, new EventArgsInput(button, cursor, isActionButton, isUseToolButton)); - } - - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The button on the controller, keyboard, or mouse. - /// The cursor position. - /// Whether the input should trigger actions on the affected tile. - /// Whether the input should use tools on the affected tile. - internal static void InvokeButtonReleased(IMonitor monitor, SButton button, ICursorPosition cursor, bool isActionButton, bool isUseToolButton) + /// Initialise the events. + /// The core event manager. + internal static void Init(EventManager eventManager) { - monitor.SafelyRaiseGenericEvent($"{nameof(InputEvents)}.{nameof(InputEvents.ButtonReleased)}", InputEvents.ButtonReleased?.GetInvocationList(), null, new EventArgsInput(button, cursor, isActionButton, isUseToolButton)); + InputEvents.EventManager = eventManager; } } } diff --git a/src/SMAPI/Events/LocationEvents.cs b/src/SMAPI/Events/LocationEvents.cs index b834bc1c..81d13e9f 100644 --- a/src/SMAPI/Events/LocationEvents.cs +++ b/src/SMAPI/Events/LocationEvents.cs @@ -1,9 +1,5 @@ -using System; -using System.Collections.Generic; -using Microsoft.Xna.Framework; -using StardewModdingAPI.Framework; -using StardewValley; -using Object = StardewValley.Object; +using System; +using StardewModdingAPI.Framework.Events; namespace StardewModdingAPI.Events { @@ -11,44 +7,45 @@ namespace StardewModdingAPI.Events public static class LocationEvents { /********* - ** Events + ** Properties *********/ - /// Raised after the player warps to a new location. - public static event EventHandler CurrentLocationChanged; - - /// Raised after a game location is added or removed. - public static event EventHandler LocationsChanged; - - /// Raised after the list of objects in the current location changes (e.g. an object is added or removed). - public static event EventHandler LocationObjectsChanged; + /// The core event manager. + private static EventManager EventManager; /********* - ** Internal methods + ** Events *********/ - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The player's previous location. - /// The player's current location. - internal static void InvokeCurrentLocationChanged(IMonitor monitor, GameLocation priorLocation, GameLocation newLocation) + /// Raised after the player warps to a new location. + public static event EventHandler CurrentLocationChanged { - monitor.SafelyRaiseGenericEvent($"{nameof(LocationEvents)}.{nameof(LocationEvents.CurrentLocationChanged)}", LocationEvents.CurrentLocationChanged?.GetInvocationList(), null, new EventArgsCurrentLocationChanged(priorLocation, newLocation)); + add => LocationEvents.EventManager.Location_CurrentLocationChanged.Add(value); + remove => LocationEvents.EventManager.Location_CurrentLocationChanged.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The current list of game locations. - internal static void InvokeLocationsChanged(IMonitor monitor, List newLocations) + /// Raised after a game location is added or removed. + public static event EventHandler LocationsChanged + { + add => LocationEvents.EventManager.Location_LocationsChanged.Add(value); + remove => LocationEvents.EventManager.Location_LocationsChanged.Remove(value); + } + + /// Raised after the list of objects in the current location changes (e.g. an object is added or removed). + public static event EventHandler LocationObjectsChanged { - monitor.SafelyRaiseGenericEvent($"{nameof(LocationEvents)}.{nameof(LocationEvents.LocationsChanged)}", LocationEvents.LocationsChanged?.GetInvocationList(), null, new EventArgsGameLocationsChanged(newLocations)); + add => LocationEvents.EventManager.Location_LocationObjectsChanged.Add(value); + remove => LocationEvents.EventManager.Location_LocationObjectsChanged.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The current list of objects in the current location. - internal static void InvokeOnNewLocationObject(IMonitor monitor, SerializableDictionary newObjects) + + /********* + ** Public methods + *********/ + /// Initialise the events. + /// The core event manager. + internal static void Init(EventManager eventManager) { - monitor.SafelyRaiseGenericEvent($"{nameof(LocationEvents)}.{nameof(LocationEvents.LocationObjectsChanged)}", LocationEvents.LocationObjectsChanged?.GetInvocationList(), null, new EventArgsLocationObjectsChanged(newObjects)); + LocationEvents.EventManager = eventManager; } } } diff --git a/src/SMAPI/Events/MenuEvents.cs b/src/SMAPI/Events/MenuEvents.cs index bd8d897e..7fcc3844 100644 --- a/src/SMAPI/Events/MenuEvents.cs +++ b/src/SMAPI/Events/MenuEvents.cs @@ -1,40 +1,44 @@ -using System; -using StardewModdingAPI.Framework; -using StardewValley.Menus; +using System; +using StardewModdingAPI.Framework.Events; namespace StardewModdingAPI.Events { /// Events raised when a game menu is opened or closed (including internal menus like the title screen). public static class MenuEvents { + /********* + ** Properties + *********/ + /// The core event manager. + private static EventManager EventManager; + + /********* ** Events *********/ /// Raised after a game menu is opened or replaced with another menu. This event is not invoked when a menu is closed. - public static event EventHandler MenuChanged; + public static event EventHandler MenuChanged + { + add => MenuEvents.EventManager.Menu_Changed.Add(value); + remove => MenuEvents.EventManager.Menu_Changed.Remove(value); + } /// Raised after a game menu is closed. - public static event EventHandler MenuClosed; + public static event EventHandler MenuClosed + { + add => MenuEvents.EventManager.Menu_Closed.Add(value); + remove => MenuEvents.EventManager.Menu_Closed.Remove(value); + } /********* - ** Internal methods + ** Public methods *********/ - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The previous menu. - /// The current menu. - internal static void InvokeMenuChanged(IMonitor monitor, IClickableMenu priorMenu, IClickableMenu newMenu) - { - monitor.SafelyRaiseGenericEvent($"{nameof(MenuEvents)}.{nameof(MenuEvents.MenuChanged)}", MenuEvents.MenuChanged?.GetInvocationList(), null, new EventArgsClickableMenuChanged(priorMenu, newMenu)); - } - - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The menu that was closed. - internal static void InvokeMenuClosed(IMonitor monitor, IClickableMenu priorMenu) + /// Initialise the events. + /// The core event manager. + internal static void Init(EventManager eventManager) { - monitor.SafelyRaiseGenericEvent($"{nameof(MenuEvents)}.{nameof(MenuEvents.MenuClosed)}", MenuEvents.MenuClosed?.GetInvocationList(), null, new EventArgsClickableMenuClosed(priorMenu)); + MenuEvents.EventManager = eventManager; } } } diff --git a/src/SMAPI/Events/MineEvents.cs b/src/SMAPI/Events/MineEvents.cs index 9cf7edac..5ee4001b 100644 --- a/src/SMAPI/Events/MineEvents.cs +++ b/src/SMAPI/Events/MineEvents.cs @@ -1,28 +1,37 @@ -using System; -using StardewModdingAPI.Framework; +using System; +using StardewModdingAPI.Framework.Events; namespace StardewModdingAPI.Events { /// Events raised when something happens in the mines. public static class MineEvents { + /********* + ** Properties + *********/ + /// The core event manager. + private static EventManager EventManager; + + /********* ** Events *********/ /// Raised after the player warps to a new level of the mine. - public static event EventHandler MineLevelChanged; + public static event EventHandler MineLevelChanged + { + add => MineEvents.EventManager.Mine_LevelChanged.Add(value); + remove => MineEvents.EventManager.Mine_LevelChanged.Remove(value); + } /********* - ** Internal methods + ** Public methods *********/ - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The previous mine level. - /// The current mine level. - internal static void InvokeMineLevelChanged(IMonitor monitor, int previousMineLevel, int currentMineLevel) + /// Initialise the events. + /// The core event manager. + internal static void Init(EventManager eventManager) { - monitor.SafelyRaiseGenericEvent($"{nameof(MineEvents)}.{nameof(MineEvents.MineLevelChanged)}", MineEvents.MineLevelChanged?.GetInvocationList(), null, new EventArgsMineLevelChanged(previousMineLevel, currentMineLevel)); + MineEvents.EventManager = eventManager; } } } diff --git a/src/SMAPI/Events/PlayerEvents.cs b/src/SMAPI/Events/PlayerEvents.cs index 5a9a9d5f..84a7ff63 100644 --- a/src/SMAPI/Events/PlayerEvents.cs +++ b/src/SMAPI/Events/PlayerEvents.cs @@ -1,43 +1,44 @@ using System; -using System.Collections.Generic; -using System.Linq; -using StardewModdingAPI.Framework; -using StardewValley; +using StardewModdingAPI.Framework.Events; namespace StardewModdingAPI.Events { /// Events raised when the player data changes. public static class PlayerEvents { + /********* + ** Properties + *********/ + /// The core event manager. + private static EventManager EventManager; + + /********* ** Events *********/ /// Raised after the player's inventory changes in any way (added or removed item, sorted, etc). - public static event EventHandler InventoryChanged; + public static event EventHandler InventoryChanged + { + add => PlayerEvents.EventManager.Player_InventoryChanged.Add(value); + remove => PlayerEvents.EventManager.Player_InventoryChanged.Remove(value); + } /// Raised after the player levels up a skill. This happens as soon as they level up, not when the game notifies the player after their character goes to bed. - public static event EventHandler LeveledUp; + public static event EventHandler LeveledUp + { + add => PlayerEvents.EventManager.Player_LeveledUp.Add(value); + remove => PlayerEvents.EventManager.Player_LeveledUp.Remove(value); + } /********* - ** Internal methods + ** Public methods *********/ - /// Raise an event. - /// Encapsulates monitoring and logging. - /// The player's inventory. - /// The inventory changes. - internal static void InvokeInventoryChanged(IMonitor monitor, List inventory, IEnumerable changedItems) - { - monitor.SafelyRaiseGenericEvent($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.InventoryChanged)}", PlayerEvents.InventoryChanged?.GetInvocationList(), null, new EventArgsInventoryChanged(inventory, changedItems.ToList())); - } - - /// Rase a event. - /// Encapsulates monitoring and logging. - /// The player skill that leveled up. - /// The new skill level. - internal static void InvokeLeveledUp(IMonitor monitor, EventArgsLevelUp.LevelType type, int newLevel) + /// Initialise the events. + /// The core event manager. + internal static void Init(EventManager eventManager) { - monitor.SafelyRaiseGenericEvent($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.LeveledUp)}", PlayerEvents.LeveledUp?.GetInvocationList(), null, new EventArgsLevelUp(type, newLevel)); + PlayerEvents.EventManager = eventManager; } } } diff --git a/src/SMAPI/Events/SaveEvents.cs b/src/SMAPI/Events/SaveEvents.cs index 99b6c8d2..62184282 100644 --- a/src/SMAPI/Events/SaveEvents.cs +++ b/src/SMAPI/Events/SaveEvents.cs @@ -1,5 +1,5 @@ using System; -using StardewModdingAPI.Framework; +using StardewModdingAPI.Framework.Events; namespace StardewModdingAPI.Events { @@ -7,70 +7,66 @@ namespace StardewModdingAPI.Events public static class SaveEvents { /********* - ** Events + ** Properties *********/ - /// Raised before the game creates the save file. - public static event EventHandler BeforeCreate; - - /// Raised after the game finishes creating the save file. - public static event EventHandler AfterCreate; - - /// Raised before the game begins writes data to the save file. - public static event EventHandler BeforeSave; - - /// Raised after the game finishes writing data to the save file. - public static event EventHandler AfterSave; - - /// Raised after the player loads a save slot. - public static event EventHandler AfterLoad; - - /// Raised after the game returns to the title screen. - public static event EventHandler AfterReturnToTitle; + /// The core event manager. + private static EventManager EventManager; /********* - ** Internal methods + ** Events *********/ - /// Raise a event. - /// Encapsulates monitoring and logging. - internal static void InvokeBeforeCreate(IMonitor monitor) + /// Raised before the game creates the save file. + public static event EventHandler BeforeCreate + { + add => SaveEvents.EventManager.Save_BeforeCreate.Add(value); + remove => SaveEvents.EventManager.Save_BeforeCreate.Remove(value); + } + + /// Raised after the game finishes creating the save file. + public static event EventHandler AfterCreate { - monitor.SafelyRaisePlainEvent($"{nameof(SaveEvents)}.{nameof(SaveEvents.BeforeCreate)}", SaveEvents.BeforeCreate?.GetInvocationList(), null, EventArgs.Empty); + add => SaveEvents.EventManager.Save_AfterCreate.Add(value); + remove => SaveEvents.EventManager.Save_AfterCreate.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - internal static void InvokeAfterCreated(IMonitor monitor) + /// Raised before the game begins writes data to the save file. + public static event EventHandler BeforeSave { - monitor.SafelyRaisePlainEvent($"{nameof(SaveEvents)}.{nameof(SaveEvents.AfterCreate)}", SaveEvents.AfterCreate?.GetInvocationList(), null, EventArgs.Empty); + add => SaveEvents.EventManager.Save_BeforeSave.Add(value); + remove => SaveEvents.EventManager.Save_BeforeSave.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - internal static void InvokeBeforeSave(IMonitor monitor) + /// Raised after the game finishes writing data to the save file. + public static event EventHandler AfterSave { - monitor.SafelyRaisePlainEvent($"{nameof(SaveEvents)}.{nameof(SaveEvents.BeforeSave)}", SaveEvents.BeforeSave?.GetInvocationList(), null, EventArgs.Empty); + add => SaveEvents.EventManager.Save_AfterSave.Add(value); + remove => SaveEvents.EventManager.Save_AfterSave.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - internal static void InvokeAfterSave(IMonitor monitor) + /// Raised after the player loads a save slot. + public static event EventHandler AfterLoad { - monitor.SafelyRaisePlainEvent($"{nameof(SaveEvents)}.{nameof(SaveEvents.AfterSave)}", SaveEvents.AfterSave?.GetInvocationList(), null, EventArgs.Empty); + add => SaveEvents.EventManager.Save_AfterLoad.Add(value); + remove => SaveEvents.EventManager.Save_AfterLoad.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - internal static void InvokeAfterLoad(IMonitor monitor) + /// Raised after the game returns to the title screen. + public static event EventHandler AfterReturnToTitle { - monitor.SafelyRaisePlainEvent($"{nameof(SaveEvents)}.{nameof(SaveEvents.AfterLoad)}", SaveEvents.AfterLoad?.GetInvocationList(), null, EventArgs.Empty); + add => SaveEvents.EventManager.Save_AfterReturnToTitle.Add(value); + remove => SaveEvents.EventManager.Save_AfterReturnToTitle.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - internal static void InvokeAfterReturnToTitle(IMonitor monitor) + + /********* + ** Public methods + *********/ + /// Initialise the events. + /// The core event manager. + internal static void Init(EventManager eventManager) { - monitor.SafelyRaisePlainEvent($"{nameof(SaveEvents)}.{nameof(SaveEvents.AfterReturnToTitle)}", SaveEvents.AfterReturnToTitle?.GetInvocationList(), null, EventArgs.Empty); + SaveEvents.EventManager = eventManager; } } } diff --git a/src/SMAPI/Events/SpecialisedEvents.cs b/src/SMAPI/Events/SpecialisedEvents.cs index 2a36e6e4..33ebf3b2 100644 --- a/src/SMAPI/Events/SpecialisedEvents.cs +++ b/src/SMAPI/Events/SpecialisedEvents.cs @@ -1,26 +1,37 @@ using System; -using StardewModdingAPI.Framework; +using StardewModdingAPI.Framework.Events; namespace StardewModdingAPI.Events { /// Events serving specialised edge cases that shouldn't be used by most mod. public static class SpecialisedEvents { + /********* + ** Properties + *********/ + /// The core event manager. + private static EventManager EventManager; + + /********* ** Events *********/ /// Raised when the game updates its state (≈60 times per second), regardless of normal SMAPI validation. This event is not thread-safe and may be invoked while game logic is running asynchronously. Changes to game state in this method may crash the game or corrupt an in-progress save. Do not use this event unless you're fully aware of the context in which your code will be run. Mods using this method will trigger a stability warning in the SMAPI console. - public static event EventHandler UnvalidatedUpdateTick; + public static event EventHandler UnvalidatedUpdateTick + { + add => SpecialisedEvents.EventManager.Specialised_UnvalidatedUpdateTick.Add(value); + remove => SpecialisedEvents.EventManager.Specialised_UnvalidatedUpdateTick.Remove(value); + } /********* - ** Internal methods + ** Public methods *********/ - /// Raise an event. - /// Encapsulates logging and monitoring. - internal static void InvokeUnvalidatedUpdateTick(IMonitor monitor) + /// Initialise the events. + /// The core event manager. + internal static void Init(EventManager eventManager) { - monitor.SafelyRaisePlainEvent($"{nameof(SpecialisedEvents)}.{nameof(SpecialisedEvents.UnvalidatedUpdateTick)}", SpecialisedEvents.UnvalidatedUpdateTick?.GetInvocationList()); + SpecialisedEvents.EventManager = eventManager; } } } diff --git a/src/SMAPI/Events/TimeEvents.cs b/src/SMAPI/Events/TimeEvents.cs index 9aea5e04..f769fd08 100644 --- a/src/SMAPI/Events/TimeEvents.cs +++ b/src/SMAPI/Events/TimeEvents.cs @@ -1,5 +1,5 @@ using System; -using StardewModdingAPI.Framework; +using StardewModdingAPI.Framework.Events; namespace StardewModdingAPI.Events { @@ -7,31 +7,38 @@ namespace StardewModdingAPI.Events public static class TimeEvents { /********* - ** Events + ** Properties *********/ - /// Raised after the game begins a new day, including when loading a save. - public static event EventHandler AfterDayStarted; + /// The core event manager. + private static EventManager EventManager; - /// Raised after the in-game clock changes. - public static event EventHandler TimeOfDayChanged; /********* - ** Internal methods + ** Events *********/ - /// Raise an event. - /// Encapsulates monitoring and logging. - internal static void InvokeAfterDayStarted(IMonitor monitor) + /// Raised after the game begins a new day, including when loading a save. + public static event EventHandler AfterDayStarted + { + add => TimeEvents.EventManager.Time_AfterDayStarted.Add(value); + remove => TimeEvents.EventManager.Time_AfterDayStarted.Remove(value); + } + + /// Raised after the in-game clock changes. + public static event EventHandler TimeOfDayChanged { - monitor.SafelyRaisePlainEvent($"{nameof(TimeEvents)}.{nameof(TimeEvents.AfterDayStarted)}", TimeEvents.AfterDayStarted?.GetInvocationList(), null, EventArgs.Empty); + add => TimeEvents.EventManager.Time_TimeOfDayChanged.Add(value); + remove => TimeEvents.EventManager.Time_TimeOfDayChanged.Remove(value); } - /// Raise a event. - /// Encapsulates monitoring and logging. - /// The previous time in military time format (e.g. 6:00pm is 1800). - /// The current time in military time format (e.g. 6:10pm is 1810). - internal static void InvokeTimeOfDayChanged(IMonitor monitor, int priorTime, int newTime) + + /********* + ** Public methods + *********/ + /// Initialise the events. + /// The core event manager. + internal static void Init(EventManager eventManager) { - monitor.SafelyRaiseGenericEvent($"{nameof(TimeEvents)}.{nameof(TimeEvents.TimeOfDayChanged)}", TimeEvents.TimeOfDayChanged?.GetInvocationList(), null, new EventArgsIntChanged(priorTime, newTime)); + TimeEvents.EventManager = eventManager; } } } diff --git a/src/SMAPI/Framework/Events/EventManager.cs b/src/SMAPI/Framework/Events/EventManager.cs new file mode 100644 index 00000000..d7c89a76 --- /dev/null +++ b/src/SMAPI/Framework/Events/EventManager.cs @@ -0,0 +1,249 @@ +using System.Diagnostics.CodeAnalysis; +using Microsoft.Xna.Framework.Input; +using StardewModdingAPI.Events; + +namespace StardewModdingAPI.Framework.Events +{ + /// Manages SMAPI events. + [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Private fields are deliberately named to simplify organisation.")] + internal class EventManager + { + /********* + ** Properties + *********/ + /**** + ** ContentEvents + ****/ + /// Raised after the content language changes. + public readonly ManagedEvent> Content_LocaleChanged; + + /**** + ** ControlEvents + ****/ + /// Raised when the changes. That happens when the player presses or releases a key. + public readonly ManagedEvent Control_KeyboardChanged; + + /// Raised when the player presses a keyboard key. + public readonly ManagedEvent Control_KeyPressed; + + /// Raised when the player releases a keyboard key. + public readonly ManagedEvent Control_KeyReleased; + + /// Raised when the changes. That happens when the player moves the mouse, scrolls the mouse wheel, or presses/releases a button. + public readonly ManagedEvent Control_MouseChanged; + + /// The player pressed a controller button. This event isn't raised for trigger buttons. + public readonly ManagedEvent Control_ControllerButtonPressed; + + /// The player released a controller button. This event isn't raised for trigger buttons. + public readonly ManagedEvent Control_ControllerButtonReleased; + + /// The player pressed a controller trigger button. + public readonly ManagedEvent Control_ControllerTriggerPressed; + + /// The player released a controller trigger button. + public readonly ManagedEvent Control_ControllerTriggerReleased; + + /**** + ** GameEvents + ****/ + /// Raised once after the game initialises and all methods have been called. + public readonly ManagedEvent Game_FirstUpdateTick; + + /// Raised when the game updates its state (≈60 times per second). + public readonly ManagedEvent Game_UpdateTick; + + /// Raised every other tick (≈30 times per second). + public readonly ManagedEvent Game_SecondUpdateTick; + + /// Raised every fourth tick (≈15 times per second). + public readonly ManagedEvent Game_FourthUpdateTick; + + /// Raised every eighth tick (≈8 times per second). + public readonly ManagedEvent Game_EighthUpdateTick; + + /// Raised every 15th tick (≈4 times per second). + public readonly ManagedEvent Game_QuarterSecondTick; + + /// Raised every 30th tick (≈twice per second). + public readonly ManagedEvent Game_HalfSecondTick; + + /// Raised every 60th tick (≈once per second). + public readonly ManagedEvent Game_OneSecondTick; + + /**** + ** GraphicsEvents + ****/ + /// Raised after the game window is resized. + public readonly ManagedEvent Graphics_Resize; + + /// Raised before drawing the world to the screen. + public readonly ManagedEvent Graphics_OnPreRenderEvent; + + /// Raised after drawing the world to the screen. + public readonly ManagedEvent Graphics_OnPostRenderEvent; + + /// Raised before drawing the HUD (item toolbar, clock, etc) to the screen. The HUD is available at this point, but not necessarily visible. (For example, the event is raised even if a menu is open.) + public readonly ManagedEvent Graphics_OnPreRenderHudEvent; + + /// Raised after drawing the HUD (item toolbar, clock, etc) to the screen. The HUD is available at this point, but not necessarily visible. (For example, the event is raised even if a menu is open.) + public readonly ManagedEvent Graphics_OnPostRenderHudEvent; + + /// Raised before drawing a menu to the screen during a draw loop. This includes the game's internal menus like the title screen. + public readonly ManagedEvent Graphics_OnPreRenderGuiEvent; + + /// Raised after drawing a menu to the screen during a draw loop. This includes the game's internal menus like the title screen. + public readonly ManagedEvent Graphics_OnPostRenderGuiEvent; + + /**** + ** InputEvents + ****/ + /// Raised when the player presses a button on the keyboard, controller, or mouse. + public readonly ManagedEvent Input_ButtonPressed; + + /// Raised when the player releases a keyboard key on the keyboard, controller, or mouse. + public readonly ManagedEvent Input_ButtonReleased; + + /**** + ** LocationEvents + ****/ + /// Raised after the player warps to a new location. + public readonly ManagedEvent Location_CurrentLocationChanged; + + /// Raised after a game location is added or removed. + public readonly ManagedEvent Location_LocationsChanged; + + /// Raised after the list of objects in the current location changes (e.g. an object is added or removed). + public readonly ManagedEvent Location_LocationObjectsChanged; + + /**** + ** MenuEvents + ****/ + /// Raised after a game menu is opened or replaced with another menu. This event is not invoked when a menu is closed. + public readonly ManagedEvent Menu_Changed; + + /// Raised after a game menu is closed. + public readonly ManagedEvent Menu_Closed; + + /**** + ** MineEvents + ****/ + /// Raised after the player warps to a new level of the mine. + public readonly ManagedEvent Mine_LevelChanged; + + /**** + ** PlayerEvents + ****/ + /// Raised after the player's inventory changes in any way (added or removed item, sorted, etc). + public readonly ManagedEvent Player_InventoryChanged; + + /// Raised after the player levels up a skill. This happens as soon as they level up, not when the game notifies the player after their character goes to bed. + public readonly ManagedEvent Player_LeveledUp; + + /**** + ** SaveEvents + ****/ + /// Raised before the game creates the save file. + public readonly ManagedEvent Save_BeforeCreate; + + /// Raised after the game finishes creating the save file. + public readonly ManagedEvent Save_AfterCreate; + + /// Raised before the game begins writes data to the save file. + public readonly ManagedEvent Save_BeforeSave; + + /// Raised after the game finishes writing data to the save file. + public readonly ManagedEvent Save_AfterSave; + + /// Raised after the player loads a save slot. + public readonly ManagedEvent Save_AfterLoad; + + /// Raised after the game returns to the title screen. + public readonly ManagedEvent Save_AfterReturnToTitle; + + /**** + ** SpecialisedEvents + ****/ + /// Raised when the game updates its state (≈60 times per second), regardless of normal SMAPI validation. This event is not thread-safe and may be invoked while game logic is running asynchronously. Changes to game state in this method may crash the game or corrupt an in-progress save. Do not use this event unless you're fully aware of the context in which your code will be run. Mods using this method will trigger a stability warning in the SMAPI console. + public readonly ManagedEvent Specialised_UnvalidatedUpdateTick; + + /**** + ** TimeEvents + ****/ + /// Raised after the game begins a new day, including when loading a save. + public readonly ManagedEvent Time_AfterDayStarted; + + /// Raised after the in-game clock changes. + public readonly ManagedEvent Time_TimeOfDayChanged; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// Writes messages to the log. + /// The mod registry with which to identify mods. + public EventManager(IMonitor monitor, ModRegistry modRegistry) + { + // create shortcut initialisers + ManagedEvent ManageEventOf(string typeName, string eventName) => new ManagedEvent($"{typeName}.{eventName}", monitor, modRegistry); + ManagedEvent ManageEvent(string typeName, string eventName) => new ManagedEvent($"{typeName}.{eventName}", monitor, modRegistry); + + // init events + this.Content_LocaleChanged = ManageEventOf>(nameof(ContentEvents), nameof(ContentEvents.AfterLocaleChanged)); + + this.Control_ControllerButtonPressed = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.ControllerButtonPressed)); + this.Control_ControllerButtonReleased = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.ControllerButtonReleased)); + this.Control_ControllerTriggerPressed = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.ControllerTriggerPressed)); + this.Control_ControllerTriggerReleased = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.ControllerTriggerReleased)); + this.Control_KeyboardChanged = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.KeyboardChanged)); + this.Control_KeyPressed = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.KeyPressed)); + this.Control_KeyReleased = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.KeyReleased)); + this.Control_MouseChanged = ManageEventOf(nameof(ControlEvents), nameof(ControlEvents.MouseChanged)); + + this.Game_FirstUpdateTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.FirstUpdateTick)); + this.Game_UpdateTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.UpdateTick)); + this.Game_SecondUpdateTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.SecondUpdateTick)); + this.Game_FourthUpdateTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.FourthUpdateTick)); + this.Game_EighthUpdateTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.EighthUpdateTick)); + this.Game_QuarterSecondTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.QuarterSecondTick)); + this.Game_HalfSecondTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.HalfSecondTick)); + this.Game_OneSecondTick = ManageEvent(nameof(GameEvents), nameof(GameEvents.OneSecondTick)); + + this.Graphics_Resize = ManageEvent(nameof(GraphicsEvents), nameof(GraphicsEvents.Resize)); + this.Graphics_OnPreRenderEvent = ManageEvent(nameof(GraphicsEvents), nameof(GraphicsEvents.OnPreRenderEvent)); + this.Graphics_OnPostRenderEvent = ManageEvent(nameof(GraphicsEvents), nameof(GraphicsEvents.OnPostRenderEvent)); + this.Graphics_OnPreRenderHudEvent = ManageEvent(nameof(GraphicsEvents), nameof(GraphicsEvents.OnPreRenderHudEvent)); + this.Graphics_OnPostRenderHudEvent = ManageEvent(nameof(GraphicsEvents), nameof(GraphicsEvents.OnPostRenderHudEvent)); + this.Graphics_OnPreRenderGuiEvent = ManageEvent(nameof(GraphicsEvents), nameof(GraphicsEvents.OnPreRenderGuiEvent)); + this.Graphics_OnPostRenderGuiEvent = ManageEvent(nameof(GraphicsEvents), nameof(GraphicsEvents.OnPostRenderGuiEvent)); + + this.Input_ButtonPressed = ManageEventOf(nameof(InputEvents), nameof(InputEvents.ButtonPressed)); + this.Input_ButtonReleased = ManageEventOf(nameof(InputEvents), nameof(InputEvents.ButtonReleased)); + + this.Location_CurrentLocationChanged = ManageEventOf(nameof(LocationEvents), nameof(LocationEvents.CurrentLocationChanged)); + this.Location_LocationsChanged = ManageEventOf(nameof(LocationEvents), nameof(LocationEvents.LocationsChanged)); + this.Location_LocationObjectsChanged = ManageEventOf(nameof(LocationEvents), nameof(LocationEvents.LocationObjectsChanged)); + + this.Menu_Changed = ManageEventOf(nameof(MenuEvents), nameof(MenuEvents.MenuChanged)); + this.Menu_Closed = ManageEventOf(nameof(MenuEvents), nameof(MenuEvents.MenuClosed)); + + this.Mine_LevelChanged = ManageEventOf(nameof(MineEvents), nameof(MineEvents.MineLevelChanged)); + + this.Player_InventoryChanged = ManageEventOf(nameof(PlayerEvents), nameof(PlayerEvents.InventoryChanged)); + this.Player_LeveledUp = ManageEventOf(nameof(PlayerEvents), nameof(PlayerEvents.LeveledUp)); + + this.Save_BeforeCreate = ManageEvent(nameof(SaveEvents), nameof(SaveEvents.BeforeCreate)); + this.Save_AfterCreate = ManageEvent(nameof(SaveEvents), nameof(SaveEvents.AfterCreate)); + this.Save_BeforeSave = ManageEvent(nameof(SaveEvents), nameof(SaveEvents.BeforeSave)); + this.Save_AfterSave = ManageEvent(nameof(SaveEvents), nameof(SaveEvents.AfterSave)); + this.Save_AfterLoad = ManageEvent(nameof(SaveEvents), nameof(SaveEvents.AfterLoad)); + this.Save_AfterReturnToTitle = ManageEvent(nameof(SaveEvents), nameof(SaveEvents.AfterReturnToTitle)); + + this.Specialised_UnvalidatedUpdateTick = ManageEvent(nameof(SpecialisedEvents), nameof(SpecialisedEvents.UnvalidatedUpdateTick)); + + this.Time_AfterDayStarted = ManageEvent(nameof(TimeEvents), nameof(TimeEvents.AfterDayStarted)); + this.Time_TimeOfDayChanged = ManageEventOf(nameof(TimeEvents), nameof(TimeEvents.TimeOfDayChanged)); + } + } +} diff --git a/src/SMAPI/Framework/Events/ManagedEvent.cs b/src/SMAPI/Framework/Events/ManagedEvent.cs new file mode 100644 index 00000000..e54a4fd3 --- /dev/null +++ b/src/SMAPI/Framework/Events/ManagedEvent.cs @@ -0,0 +1,119 @@ +using System; +using System.Linq; + +namespace StardewModdingAPI.Framework.Events +{ + /// An event wrapper which intercepts and logs errors in handler code. + /// The event arguments type. + internal class ManagedEvent : ManagedEventBase> + { + /********* + ** Properties + *********/ + /// The underlying event. + private event EventHandler Event; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// A human-readable name for the event. + /// Writes messages to the log. + /// The mod registry with which to identify mods. + public ManagedEvent(string eventName, IMonitor monitor, ModRegistry modRegistry) + : base(eventName, monitor, modRegistry) { } + + /// Add an event handler. + /// The event handler. + public void Add(EventHandler handler) + { + this.Event += handler; + this.AddTracking(handler, this.Event?.GetInvocationList().Cast>()); + } + + /// Remove an event handler. + /// The event handler. + public void Remove(EventHandler handler) + { + this.Event -= handler; + this.RemoveTracking(handler, this.Event?.GetInvocationList().Cast>()); + } + + /// Raise the event and notify all handlers. + /// The event arguments to pass. + public void Raise(TEventArgs args) + { + if (this.Event == null) + return; + + foreach (EventHandler handler in this.CachedInvocationList) + { + try + { + handler.Invoke(null, args); + } + catch (Exception ex) + { + this.LogError(handler, ex); + } + } + } + } + + /// An event wrapper which intercepts and logs errors in handler code. + internal class ManagedEvent : ManagedEventBase + { + /********* + ** Properties + *********/ + /// The underlying event. + private event EventHandler Event; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// A human-readable name for the event. + /// Writes messages to the log. + /// The mod registry with which to identify mods. + public ManagedEvent(string eventName, IMonitor monitor, ModRegistry modRegistry) + : base(eventName, monitor, modRegistry) { } + + /// Add an event handler. + /// The event handler. + public void Add(EventHandler handler) + { + this.Event += handler; + this.AddTracking(handler, this.Event?.GetInvocationList().Cast()); + } + + /// Remove an event handler. + /// The event handler. + public void Remove(EventHandler handler) + { + this.Event -= handler; + this.RemoveTracking(handler, this.Event?.GetInvocationList().Cast()); + } + + /// Raise the event and notify all handlers. + public void Raise() + { + if (this.Event == null) + return; + + foreach (EventHandler handler in this.CachedInvocationList) + { + try + { + handler.Invoke(null, EventArgs.Empty); + } + catch (Exception ex) + { + this.LogError(handler, ex); + } + } + } + } +} diff --git a/src/SMAPI/Framework/Events/ManagedEventBase.cs b/src/SMAPI/Framework/Events/ManagedEventBase.cs new file mode 100644 index 00000000..cc4d89ec --- /dev/null +++ b/src/SMAPI/Framework/Events/ManagedEventBase.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace StardewModdingAPI.Framework.Events +{ + /// The base implementation for an event wrapper which intercepts and logs errors in handler code. + internal abstract class ManagedEventBase + { + /********* + ** Properties + *********/ + /// A human-readable name for the event. + private readonly string EventName; + + /// Writes messages to the log. + private readonly IMonitor Monitor; + + /// The mod registry with which to identify mods. + private readonly ModRegistry ModRegistry; + + /// The display names for the mods which added each delegate. + private readonly IDictionary SourceMods = new Dictionary(); + + /// The cached invocation list. + protected TEventHandler[] CachedInvocationList { get; private set; } + + + /********* + ** Public methods + *********/ + /// Get whether anything is listening to the event. + public bool HasListeners() + { + return this.CachedInvocationList?.Length > 0; + } + + /********* + ** Protected methods + *********/ + /// Construct an instance. + /// A human-readable name for the event. + /// Writes messages to the log. + /// The mod registry with which to identify mods. + protected ManagedEventBase(string eventName, IMonitor monitor, ModRegistry modRegistry) + { + this.EventName = eventName; + this.Monitor = monitor; + this.ModRegistry = modRegistry; + } + + /// Track an event handler. + /// The event handler. + /// The updated event invocation list. + protected void AddTracking(TEventHandler handler, IEnumerable invocationList) + { + this.SourceMods[handler] = this.ModRegistry.GetFromStack(); + this.CachedInvocationList = invocationList.ToArray(); + } + + /// Remove tracking for an event handler. + /// The event handler. + /// The updated event invocation list. + protected void RemoveTracking(TEventHandler handler, IEnumerable invocationList) + { + this.SourceMods.Remove(handler); + this.CachedInvocationList = invocationList.ToArray(); + } + + /// Log an exception from an event handler. + /// The event handler instance. + /// The exception that was raised. + protected void LogError(TEventHandler handler, Exception ex) + { + if (this.SourceMods.TryGetValue(handler, out IModMetadata mod)) + mod.LogAsMod($"This mod failed in the {this.EventName} event. Technical details: \n{ex.GetLogSummary()}", LogLevel.Error); + else + this.Monitor.Log($"A mod failed in the {this.EventName} event. Technical details: \n{ex.GetLogSummary()}", LogLevel.Error); + } + } +} diff --git a/src/SMAPI/Framework/InternalExtensions.cs b/src/SMAPI/Framework/InternalExtensions.cs index ce67ae18..bff4807c 100644 --- a/src/SMAPI/Framework/InternalExtensions.cs +++ b/src/SMAPI/Framework/InternalExtensions.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Reflection; using Microsoft.Xna.Framework.Graphics; using Newtonsoft.Json.Linq; @@ -15,63 +14,6 @@ namespace StardewModdingAPI.Framework /**** ** IMonitor ****/ - /// Safely raise an event, and intercept any exceptions thrown by its handlers. - /// Encapsulates monitoring and logging. - /// The event name for error messages. - /// The event handlers. - /// The event sender. - /// The event arguments (or null to pass ). - public static void SafelyRaisePlainEvent(this IMonitor monitor, string name, IEnumerable handlers, object sender = null, EventArgs args = null) - { - if (handlers == null) - return; - - foreach (EventHandler handler in handlers.Cast()) - { - // handle SMAPI exiting - if (monitor.IsExiting) - { - monitor.Log($"SMAPI shutting down: aborting {name} event.", LogLevel.Warn); - return; - } - - // raise event - try - { - handler.Invoke(sender, args ?? EventArgs.Empty); - } - catch (Exception ex) - { - monitor.Log($"A mod failed handling the {name} event:\n{ex.GetLogSummary()}", LogLevel.Error); - } - } - } - - /// Safely raise an event, and intercept any exceptions thrown by its handlers. - /// The event argument object type. - /// Encapsulates monitoring and logging. - /// The event name for error messages. - /// The event handlers. - /// The event sender. - /// The event arguments. - public static void SafelyRaiseGenericEvent(this IMonitor monitor, string name, IEnumerable handlers, object sender, TEventArgs args) - { - if (handlers == null) - return; - - foreach (EventHandler handler in handlers.Cast>()) - { - try - { - handler.Invoke(sender, args); - } - catch (Exception ex) - { - monitor.Log($"A mod failed handling the {name} event:\n{ex.GetLogSummary()}", LogLevel.Error); - } - } - } - /// Log a message for the player or developer the first time it occurs. /// The monitor through which to log the message. /// The hash of logged messages. diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index 2d3bad55..5c45edca 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -10,6 +10,7 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using StardewModdingAPI.Events; +using StardewModdingAPI.Framework.Events; using StardewModdingAPI.Framework.Input; using StardewModdingAPI.Framework.Reflection; using StardewModdingAPI.Framework.Utilities; @@ -35,6 +36,9 @@ namespace StardewModdingAPI.Framework /// Encapsulates monitoring and logging. private readonly IMonitor Monitor; + /// Manages SMAPI events for mods. + private readonly EventManager Events; + /// The maximum number of consecutive attempts SMAPI should make to recover from a draw error. private readonly Countdown DrawCrashTimer = new Countdown(60); // 60 ticks = roughly one second @@ -117,6 +121,9 @@ namespace StardewModdingAPI.Framework /// The current game instance. private static SGame Instance; + /// A callback to invoke after the game finishes initialising. + private readonly Action OnGameInitialised; + /**** ** Private wrappers ****/ @@ -132,9 +139,9 @@ namespace StardewModdingAPI.Framework set => SGame.Reflection.GetField(typeof(Game1), nameof(_fps)).SetValue(value); } private static Task _newDayTask => SGame.Reflection.GetField(typeof(Game1), nameof(_newDayTask)).GetValue(); - private Color bgColor => SGame.Reflection.GetField(this, nameof(bgColor)).GetValue(); + private Color bgColor => SGame.Reflection.GetField(this, nameof(this.bgColor)).GetValue(); public RenderTarget2D screenWrapper => SGame.Reflection.GetProperty(this, "screen").GetValue(); // deliberately renamed to avoid an infinite loop - public BlendState lightingBlend => SGame.Reflection.GetField(this, nameof(lightingBlend)).GetValue(); + public BlendState lightingBlend => SGame.Reflection.GetField(this, nameof(this.lightingBlend)).GetValue(); private readonly Action drawFarmBuildings = () => SGame.Reflection.GetMethod(SGame.Instance, nameof(drawFarmBuildings)).Invoke(); private readonly Action drawHUD = () => SGame.Reflection.GetMethod(SGame.Instance, nameof(drawHUD)).Invoke(); private readonly Action drawDialogueBox = () => SGame.Reflection.GetMethod(SGame.Instance, nameof(drawDialogueBox)).Invoke(); @@ -158,13 +165,17 @@ namespace StardewModdingAPI.Framework /// Construct an instance. /// Encapsulates monitoring and logging. /// Simplifies access to private game code. - internal SGame(IMonitor monitor, Reflector reflection) + /// Manages SMAPI events for mods. + /// A callback to invoke after the game finishes initialising. + internal SGame(IMonitor monitor, Reflector reflection, EventManager eventManager, Action onGameInitialised) { // initialise this.Monitor = monitor; + this.Events = eventManager; this.FirstUpdate = true; SGame.Instance = this; SGame.Reflection = reflection; + this.OnGameInitialised = onGameInitialised; // set XNA option required by Stardew Valley Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef; @@ -229,7 +240,7 @@ namespace StardewModdingAPI.Framework if (SGame._newDayTask != null) { base.Update(gameTime); - SpecialisedEvents.InvokeUnvalidatedUpdateTick(this.Monitor); + this.Events.Specialised_UnvalidatedUpdateTick.Raise(); return; } @@ -237,7 +248,7 @@ namespace StardewModdingAPI.Framework if (Game1.gameMode == Game1.loadingMode) { base.Update(gameTime); - SpecialisedEvents.InvokeUnvalidatedUpdateTick(this.Monitor); + this.Events.Specialised_UnvalidatedUpdateTick.Raise(); return; } @@ -256,20 +267,20 @@ namespace StardewModdingAPI.Framework { this.IsBetweenCreateEvents = true; this.Monitor.Log("Context: before save creation.", LogLevel.Trace); - SaveEvents.InvokeBeforeCreate(this.Monitor); + this.Events.Save_BeforeCreate.Raise(); } - + // raise before-save if (Context.IsWorldReady && !this.IsBetweenSaveEvents) { this.IsBetweenSaveEvents = true; this.Monitor.Log("Context: before save.", LogLevel.Trace); - SaveEvents.InvokeBeforeSave(this.Monitor); + this.Events.Save_BeforeSave.Raise(); } // suppress non-save events base.Update(gameTime); - SpecialisedEvents.InvokeUnvalidatedUpdateTick(this.Monitor); + this.Events.Specialised_UnvalidatedUpdateTick.Raise(); return; } if (this.IsBetweenCreateEvents) @@ -277,22 +288,22 @@ namespace StardewModdingAPI.Framework // raise after-create this.IsBetweenCreateEvents = false; this.Monitor.Log($"Context: after save creation, starting {Game1.currentSeason} {Game1.dayOfMonth} Y{Game1.year}.", LogLevel.Trace); - SaveEvents.InvokeAfterCreated(this.Monitor); + this.Events.Save_AfterCreate.Raise(); } if (this.IsBetweenSaveEvents) { // raise after-save this.IsBetweenSaveEvents = false; this.Monitor.Log($"Context: after save, starting {Game1.currentSeason} {Game1.dayOfMonth} Y{Game1.year}.", LogLevel.Trace); - SaveEvents.InvokeAfterSave(this.Monitor); - TimeEvents.InvokeAfterDayStarted(this.Monitor); + this.Events.Save_AfterSave.Raise(); + this.Events.Time_AfterDayStarted.Raise(); } /********* - ** Game loaded events + ** Notify SMAPI that game is initialised *********/ if (this.FirstUpdate) - GameEvents.InvokeInitialize(this.Monitor); + this.OnGameInitialised(); /********* ** Locale changed events @@ -305,7 +316,8 @@ namespace StardewModdingAPI.Framework this.Monitor.Log($"Context: locale set to {newValue}.", LogLevel.Trace); if (oldValue != null) - ContentEvents.InvokeAfterLocaleChanged(this.Monitor, oldValue.ToString(), newValue.ToString()); + this.Events.Content_LocaleChanged.Raise(new EventArgsValueChanged(oldValue.ToString(), newValue.ToString())); + this.PreviousLocale = newValue; } @@ -322,8 +334,8 @@ namespace StardewModdingAPI.Framework this.Monitor.Log($"Context: loaded saved game '{Constants.SaveFolderName}', starting {Game1.currentSeason} {Game1.dayOfMonth} Y{Game1.year}.", LogLevel.Trace); Context.IsWorldReady = true; - SaveEvents.InvokeAfterLoad(this.Monitor); - TimeEvents.InvokeAfterDayStarted(this.Monitor); + this.Events.Save_AfterLoad.Raise(); + this.Events.Time_AfterDayStarted.Raise(); } } @@ -341,7 +353,7 @@ namespace StardewModdingAPI.Framework this.IsExitingToTitle = false; this.CleanupAfterReturnToTitle(); - SaveEvents.InvokeAfterReturnToTitle(this.Monitor); + this.Events.Save_AfterReturnToTitle.Raise(); } /********* @@ -354,7 +366,7 @@ namespace StardewModdingAPI.Framework if (Game1.viewport.Width != this.PreviousWindowSize.X || Game1.viewport.Height != this.PreviousWindowSize.Y) { Point size = new Point(Game1.viewport.Width, Game1.viewport.Height); - GraphicsEvents.InvokeResize(this.Monitor); + this.Events.Graphics_Resize.Raise(); this.PreviousWindowSize = size; } @@ -394,47 +406,47 @@ namespace StardewModdingAPI.Framework if (status == InputStatus.Pressed) { - InputEvents.InvokeButtonPressed(this.Monitor, button, cursor, button.IsActionButton(), button.IsUseToolButton()); + this.Events.Input_ButtonPressed.Raise(new EventArgsInput(button, cursor, button.IsActionButton(), button.IsUseToolButton())); // legacy events if (button.TryGetKeyboard(out Keys key)) { if (key != Keys.None) - ControlEvents.InvokeKeyPressed(this.Monitor, key); + this.Events.Control_KeyPressed.Raise(new EventArgsKeyPressed(key)); } else if (button.TryGetController(out Buttons controllerButton)) { if (controllerButton == Buttons.LeftTrigger || controllerButton == Buttons.RightTrigger) - ControlEvents.InvokeTriggerPressed(this.Monitor, controllerButton, controllerButton == Buttons.LeftTrigger ? inputState.ControllerState.Triggers.Left : inputState.ControllerState.Triggers.Right); + this.Events.Control_ControllerTriggerPressed.Raise(new EventArgsControllerTriggerPressed(PlayerIndex.One, controllerButton, controllerButton == Buttons.LeftTrigger ? inputState.ControllerState.Triggers.Left : inputState.ControllerState.Triggers.Right)); else - ControlEvents.InvokeButtonPressed(this.Monitor, controllerButton); + this.Events.Control_ControllerButtonPressed.Raise(new EventArgsControllerButtonPressed(PlayerIndex.One, controllerButton)); } } else if (status == InputStatus.Released) { - InputEvents.InvokeButtonReleased(this.Monitor, button, cursor, button.IsActionButton(), button.IsUseToolButton()); + this.Events.Input_ButtonReleased.Raise(new EventArgsInput(button, cursor, button.IsActionButton(), button.IsUseToolButton())); // legacy events if (button.TryGetKeyboard(out Keys key)) { if (key != Keys.None) - ControlEvents.InvokeKeyReleased(this.Monitor, key); + this.Events.Control_KeyReleased.Raise(new EventArgsKeyPressed(key)); } else if (button.TryGetController(out Buttons controllerButton)) { if (controllerButton == Buttons.LeftTrigger || controllerButton == Buttons.RightTrigger) - ControlEvents.InvokeTriggerReleased(this.Monitor, controllerButton, controllerButton == Buttons.LeftTrigger ? inputState.ControllerState.Triggers.Left : inputState.ControllerState.Triggers.Right); + this.Events.Control_ControllerTriggerReleased.Raise(new EventArgsControllerTriggerReleased(PlayerIndex.One, controllerButton, controllerButton == Buttons.LeftTrigger ? inputState.ControllerState.Triggers.Left : inputState.ControllerState.Triggers.Right)); else - ControlEvents.InvokeButtonReleased(this.Monitor, controllerButton); + this.Events.Control_ControllerButtonReleased.Raise(new EventArgsControllerButtonReleased(PlayerIndex.One, controllerButton)); } } } // raise legacy state-changed events if (inputState.KeyboardState != this.PreviousInput.KeyboardState) - ControlEvents.InvokeKeyboardChanged(this.Monitor, this.PreviousInput.KeyboardState, inputState.KeyboardState); + this.Events.Control_KeyboardChanged.Raise(new EventArgsKeyboardStateChanged(this.PreviousInput.KeyboardState, inputState.KeyboardState)); if (inputState.MouseState != this.PreviousInput.MouseState) - ControlEvents.InvokeMouseChanged(this.Monitor, this.PreviousInput.MouseState, inputState.MouseState, this.PreviousInput.MousePosition, inputState.MousePosition); + this.Events.Control_MouseChanged.Raise(new EventArgsMouseStateChanged(this.PreviousInput.MouseState, inputState.MouseState, this.PreviousInput.MousePosition, inputState.MousePosition)); // track state this.PreviousInput = inputState; @@ -461,9 +473,9 @@ namespace StardewModdingAPI.Framework // raise menu events if (newMenu != null) - MenuEvents.InvokeMenuChanged(this.Monitor, previousMenu, newMenu); + this.Events.Menu_Changed.Raise(new EventArgsClickableMenuChanged(previousMenu, newMenu)); else - MenuEvents.InvokeMenuClosed(this.Monitor, previousMenu); + this.Events.Menu_Closed.Raise(new EventArgsClickableMenuClosed(previousMenu)); // update previous menu // (if the menu was changed in one of the handlers, deliberately defer detection until the next update so mods can be notified of the new menu change) @@ -480,46 +492,46 @@ namespace StardewModdingAPI.Framework { if (this.VerboseLogging) this.Monitor.Log($"Context: set location to {Game1.currentLocation?.Name ?? "(none)"}.", LogLevel.Trace); - LocationEvents.InvokeCurrentLocationChanged(this.Monitor, this.PreviousGameLocation, Game1.currentLocation); + this.Events.Location_CurrentLocationChanged.Raise(new EventArgsCurrentLocationChanged(this.PreviousGameLocation, Game1.currentLocation)); } // raise location list changed if (this.GetHash(Game1.locations) != this.PreviousGameLocations) - LocationEvents.InvokeLocationsChanged(this.Monitor, Game1.locations); + this.Events.Location_LocationsChanged.Raise(new EventArgsGameLocationsChanged(Game1.locations)); // raise events that shouldn't be triggered on initial load if (Game1.uniqueIDForThisGame == this.PreviousSaveID) { // raise player leveled up a skill if (Game1.player.combatLevel != this.PreviousCombatLevel) - PlayerEvents.InvokeLeveledUp(this.Monitor, EventArgsLevelUp.LevelType.Combat, Game1.player.combatLevel); + this.Events.Player_LeveledUp.Raise(new EventArgsLevelUp(EventArgsLevelUp.LevelType.Combat, Game1.player.combatLevel)); if (Game1.player.farmingLevel != this.PreviousFarmingLevel) - PlayerEvents.InvokeLeveledUp(this.Monitor, EventArgsLevelUp.LevelType.Farming, Game1.player.farmingLevel); + this.Events.Player_LeveledUp.Raise(new EventArgsLevelUp(EventArgsLevelUp.LevelType.Farming, Game1.player.farmingLevel)); if (Game1.player.fishingLevel != this.PreviousFishingLevel) - PlayerEvents.InvokeLeveledUp(this.Monitor, EventArgsLevelUp.LevelType.Fishing, Game1.player.fishingLevel); + this.Events.Player_LeveledUp.Raise(new EventArgsLevelUp(EventArgsLevelUp.LevelType.Fishing, Game1.player.fishingLevel)); if (Game1.player.foragingLevel != this.PreviousForagingLevel) - PlayerEvents.InvokeLeveledUp(this.Monitor, EventArgsLevelUp.LevelType.Foraging, Game1.player.foragingLevel); + this.Events.Player_LeveledUp.Raise(new EventArgsLevelUp(EventArgsLevelUp.LevelType.Foraging, Game1.player.foragingLevel)); if (Game1.player.miningLevel != this.PreviousMiningLevel) - PlayerEvents.InvokeLeveledUp(this.Monitor, EventArgsLevelUp.LevelType.Mining, Game1.player.miningLevel); + this.Events.Player_LeveledUp.Raise(new EventArgsLevelUp(EventArgsLevelUp.LevelType.Mining, Game1.player.miningLevel)); if (Game1.player.luckLevel != this.PreviousLuckLevel) - PlayerEvents.InvokeLeveledUp(this.Monitor, EventArgsLevelUp.LevelType.Luck, Game1.player.luckLevel); + this.Events.Player_LeveledUp.Raise(new EventArgsLevelUp(EventArgsLevelUp.LevelType.Luck, Game1.player.luckLevel)); // raise player inventory changed ItemStackChange[] changedItems = this.GetInventoryChanges(Game1.player.items, this.PreviousItems).ToArray(); if (changedItems.Any()) - PlayerEvents.InvokeInventoryChanged(this.Monitor, Game1.player.items, changedItems); + this.Events.Player_InventoryChanged.Raise(new EventArgsInventoryChanged(Game1.player.items, changedItems.ToList())); // raise current location's object list changed if (this.GetHash(Game1.currentLocation.objects) != this.PreviousLocationObjects) - LocationEvents.InvokeOnNewLocationObject(this.Monitor, Game1.currentLocation.objects); + this.Events.Location_LocationObjectsChanged.Raise(new EventArgsLocationObjectsChanged(Game1.currentLocation.objects)); // raise time changed if (Game1.timeOfDay != this.PreviousTime) - TimeEvents.InvokeTimeOfDayChanged(this.Monitor, this.PreviousTime, Game1.timeOfDay); + this.Events.Time_TimeOfDayChanged.Raise(new EventArgsIntChanged(this.PreviousTime, Game1.timeOfDay)); // raise mine level changed if (Game1.mine != null && Game1.mine.mineLevel != this.PreviousMineLevel) - MineEvents.InvokeMineLevelChanged(this.Monitor, this.PreviousMineLevel, Game1.mine.mineLevel); + this.Events.Mine_LevelChanged.Raise(new EventArgsMineLevelChanged(this.PreviousMineLevel, Game1.mine.mineLevel)); } // update state @@ -553,25 +565,25 @@ namespace StardewModdingAPI.Framework /********* ** Update events *********/ - SpecialisedEvents.InvokeUnvalidatedUpdateTick(this.Monitor); + this.Events.Specialised_UnvalidatedUpdateTick.Raise(); if (this.FirstUpdate) { this.FirstUpdate = false; - GameEvents.InvokeFirstUpdateTick(this.Monitor); + this.Events.Game_FirstUpdateTick.Raise(); } - GameEvents.InvokeUpdateTick(this.Monitor); + this.Events.Game_UpdateTick.Raise(); if (this.CurrentUpdateTick % 2 == 0) - GameEvents.InvokeSecondUpdateTick(this.Monitor); + this.Events.Game_SecondUpdateTick.Raise(); if (this.CurrentUpdateTick % 4 == 0) - GameEvents.InvokeFourthUpdateTick(this.Monitor); + this.Events.Game_FourthUpdateTick.Raise(); if (this.CurrentUpdateTick % 8 == 0) - GameEvents.InvokeEighthUpdateTick(this.Monitor); + this.Events.Game_EighthUpdateTick.Raise(); if (this.CurrentUpdateTick % 15 == 0) - GameEvents.InvokeQuarterSecondTick(this.Monitor); + this.Events.Game_QuarterSecondTick.Raise(); if (this.CurrentUpdateTick % 30 == 0) - GameEvents.InvokeHalfSecondTick(this.Monitor); + this.Events.Game_HalfSecondTick.Raise(); if (this.CurrentUpdateTick % 60 == 0) - GameEvents.InvokeOneSecondTick(this.Monitor); + this.Events.Game_OneSecondTick.Raise(); this.CurrentUpdateTick += 1; if (this.CurrentUpdateTick >= 60) this.CurrentUpdateTick = 0; @@ -680,9 +692,9 @@ namespace StardewModdingAPI.Framework Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); try { - GraphicsEvents.InvokeOnPreRenderGuiEvent(this.Monitor); + this.Events.Graphics_OnPreRenderGuiEvent.Raise(); activeClickableMenu.draw(Game1.spriteBatch); - GraphicsEvents.InvokeOnPostRenderGuiEvent(this.Monitor); + this.Events.Graphics_OnPostRenderGuiEvent.Raise(); } catch (Exception ex) { @@ -704,9 +716,9 @@ namespace StardewModdingAPI.Framework try { Game1.activeClickableMenu.drawBackground(Game1.spriteBatch); - GraphicsEvents.InvokeOnPreRenderGuiEvent(this.Monitor); + this.Events.Graphics_OnPreRenderGuiEvent.Raise(); Game1.activeClickableMenu.draw(Game1.spriteBatch); - GraphicsEvents.InvokeOnPostRenderGuiEvent(this.Monitor); + this.Events.Graphics_OnPostRenderGuiEvent.Raise(); } catch (Exception ex) { @@ -771,9 +783,9 @@ namespace StardewModdingAPI.Framework { try { - GraphicsEvents.InvokeOnPreRenderGuiEvent(this.Monitor); + this.Events.Graphics_OnPreRenderGuiEvent.Raise(); Game1.activeClickableMenu.draw(Game1.spriteBatch); - GraphicsEvents.InvokeOnPostRenderGuiEvent(this.Monitor); + this.Events.Graphics_OnPostRenderGuiEvent.Raise(); } catch (Exception ex) { @@ -858,7 +870,7 @@ namespace StardewModdingAPI.Framework Game1.bloom.BeginDraw(); this.GraphicsDevice.Clear(this.bgColor); Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null); - GraphicsEvents.InvokeOnPreRenderEvent(this.Monitor); + this.Events.Graphics_OnPreRenderEvent.Raise(); if (Game1.background != null) Game1.background.draw(Game1.spriteBatch); Game1.mapDisplayDevice.BeginScene(Game1.spriteBatch); @@ -1129,9 +1141,9 @@ namespace StardewModdingAPI.Framework this.drawBillboard(); if ((Game1.displayHUD || Game1.eventUp) && (Game1.currentBillboard == 0 && (int)Game1.gameMode == 3) && (!Game1.freezeControls && !Game1.panMode)) { - GraphicsEvents.InvokeOnPreRenderHudEvent(this.Monitor); + this.Events.Graphics_OnPreRenderHudEvent.Raise(); this.drawHUD(); - GraphicsEvents.InvokeOnPostRenderHudEvent(this.Monitor); + this.Events.Graphics_OnPostRenderHudEvent.Raise(); } else if (Game1.activeClickableMenu == null && Game1.farmEvent == null) Game1.spriteBatch.Draw(Game1.mouseCursors, new Vector2((float)Game1.getOldMouseX(), (float)Game1.getOldMouseY()), new Microsoft.Xna.Framework.Rectangle?(Game1.getSourceRectForStandardTileSheet(Game1.mouseCursors, 0, 16, 16)), Color.White, 0.0f, Vector2.Zero, (float)(4.0 + (double)Game1.dialogueButtonScale / 150.0), SpriteEffects.None, 1f); @@ -1263,9 +1275,9 @@ namespace StardewModdingAPI.Framework { try { - GraphicsEvents.InvokeOnPreRenderGuiEvent(this.Monitor); + this.Events.Graphics_OnPreRenderGuiEvent.Raise(); Game1.activeClickableMenu.draw(Game1.spriteBatch); - GraphicsEvents.InvokeOnPostRenderGuiEvent(this.Monitor); + this.Events.Graphics_OnPostRenderGuiEvent.Raise(); } catch (Exception ex) { @@ -1350,11 +1362,11 @@ namespace StardewModdingAPI.Framework /// Whether to create a new sprite batch. private void RaisePostRender(bool needsNewBatch = false) { - if (GraphicsEvents.HasPostRenderListeners()) + if (this.Events.Graphics_OnPostRenderEvent.HasListeners()) { if (needsNewBatch) Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); - GraphicsEvents.InvokeOnPostRenderEvent(this.Monitor); + this.Events.Graphics_OnPostRenderEvent.Raise(); if (needsNewBatch) Game1.spriteBatch.End(); } diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index e9084b2d..47db8e86 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -17,6 +17,7 @@ using Newtonsoft.Json; using StardewModdingAPI.Common.Models; using StardewModdingAPI.Events; using StardewModdingAPI.Framework; +using StardewModdingAPI.Framework.Events; using StardewModdingAPI.Framework.Exceptions; using StardewModdingAPI.Framework.Logging; using StardewModdingAPI.Framework.ModData; @@ -65,7 +66,7 @@ namespace StardewModdingAPI /// Tracks the installed mods. /// This is initialised after the game starts. - private ModRegistry ModRegistry; + private readonly ModRegistry ModRegistry = new ModRegistry(); /// Manages deprecation warnings. /// This is initialised after the game starts. @@ -75,6 +76,9 @@ namespace StardewModdingAPI /// This is initialised after the game starts. private CommandManager CommandManager; + /// Manages SMAPI events for mods. + private readonly EventManager EventManager; + /// Whether the game is currently running. private bool IsGameRunning; @@ -128,8 +132,24 @@ namespace StardewModdingAPI /// The full file path to which to write log messages. public Program(bool writeToConsole, string logPath) { + // init basics this.LogFile = new LogFileManager(logPath); this.Monitor = new Monitor("SMAPI", this.ConsoleManager, this.LogFile, this.CancellationTokenSource) { WriteToConsole = writeToConsole }; + this.EventManager = new EventManager(this.Monitor, this.ModRegistry); + + // hook up events + ContentEvents.Init(this.EventManager); + ControlEvents.Init(this.EventManager); + GameEvents.Init(this.EventManager); + GraphicsEvents.Init(this.EventManager); + InputEvents.Init(this.EventManager); + LocationEvents.Init(this.EventManager); + MenuEvents.Init(this.EventManager); + MineEvents.Init(this.EventManager); + PlayerEvents.Init(this.EventManager); + SaveEvents.Init(this.EventManager); + SpecialisedEvents.Init(this.EventManager); + TimeEvents.Init(this.EventManager); } /// Launch SMAPI. @@ -170,7 +190,7 @@ namespace StardewModdingAPI AppDomain.CurrentDomain.UnhandledException += (sender, e) => this.Monitor.Log($"Critical app domain exception: {e.ExceptionObject}", LogLevel.Error); // override game - this.GameInstance = new SGame(this.Monitor, this.Reflection); + this.GameInstance = new SGame(this.Monitor, this.Reflection, this.EventManager, this.InitialiseAfterGameStart); StardewValley.Program.gamePtr = this.GameInstance; // add exit handler @@ -198,7 +218,6 @@ namespace StardewModdingAPI ((Form)Control.FromHandle(this.GameInstance.Window.Handle)).FormClosing += (sender, args) => this.Dispose(); #endif this.GameInstance.Exiting += (sender, e) => this.Dispose(); - GameEvents.InitializeInternal += (sender, e) => this.InitialiseAfterGameStart(); ContentEvents.AfterLocaleChanged += (sender, e) => this.OnLocaleChanged(); // set window titles @@ -326,7 +345,6 @@ namespace StardewModdingAPI this.GameInstance.VerboseLogging = this.Settings.VerboseLogging; // load core components - this.ModRegistry = new ModRegistry(); this.DeprecationManager = new DeprecationManager(this.Monitor, this.ModRegistry); this.CommandManager = new CommandManager(); diff --git a/src/SMAPI/StardewModdingAPI.csproj b/src/SMAPI/StardewModdingAPI.csproj index 14ed1531..8ef3022f 100644 --- a/src/SMAPI/StardewModdingAPI.csproj +++ b/src/SMAPI/StardewModdingAPI.csproj @@ -85,9 +85,12 @@ Properties\GlobalAssemblyInfo.cs + + + -- cgit