using System; using System.Diagnostics.CodeAnalysis; using HarmonyLib; using StardewModdingAPI.Internal; using StardewModdingAPI.Internal.Patching; using StardewValley; namespace StardewModdingAPI.Mods.ErrorHandler.Patches { /// Harmony patches for which intercept invalid dialogue lines and logs an error instead of crashing. /// Patch methods must be static for Harmony to work correctly. See the Harmony documentation before renaming patch arguments. [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony and methods are named for clarity.")] [SuppressMessage("ReSharper", "IdentifierTypo", Justification = "Argument names are defined by Harmony and methods are named for clarity.")] internal class DialoguePatcher : BasePatcher { /********* ** Fields *********/ /// Writes messages to the console and log file on behalf of the game. private static IMonitor MonitorForGame = null!; /// Simplifies access to private code. private static IReflectionHelper Reflection = null!; /********* ** Public methods *********/ /// Construct an instance. /// Writes messages to the console and log file on behalf of the game. /// Simplifies access to private code. public DialoguePatcher(IMonitor monitorForGame, IReflectionHelper reflector) { DialoguePatcher.MonitorForGame = monitorForGame; DialoguePatcher.Reflection = reflector; } /// public override void Apply(Harmony harmony, IMonitor monitor) { harmony.Patch( original: this.RequireConstructor(typeof(string), typeof(NPC)), finalizer: this.GetHarmonyMethod(nameof(DialoguePatcher.Finalize_Constructor)) ); } /********* ** Private methods *********/ /// The method to call when the Dialogue constructor throws an exception. /// The instance being patched. /// The dialogue being parsed. /// The NPC for which the dialogue is being parsed. /// The exception thrown by the wrapped method, if any. /// Returns the exception to throw, if any. private static Exception? Finalize_Constructor(Dialogue __instance, string masterDialogue, NPC? speaker, Exception? __exception) { if (__exception != null) { // log message string? name = !string.IsNullOrWhiteSpace(speaker?.Name) ? speaker.Name : null; DialoguePatcher.MonitorForGame.Log($"Failed parsing dialogue string{(name != null ? $" for {name}" : "")}:\n{masterDialogue}\n{__exception.GetLogSummary()}", LogLevel.Error); // set default dialogue IReflectedMethod parseDialogueString = DialoguePatcher.Reflection.GetMethod(__instance, "parseDialogueString"); IReflectedMethod checkForSpecialDialogueAttributes = DialoguePatcher.Reflection.GetMethod(__instance, "checkForSpecialDialogueAttributes"); parseDialogueString.Invoke("..."); checkForSpecialDialogueAttributes.Invoke(); } return null; } } }