From 306427786b9ae349e3f33ca2e4be6a79b63cf6ce Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 1 Jul 2017 19:55:08 -0400 Subject: let mods implement IAssetEditor for simple cases (#255) --- src/StardewModdingAPI/Framework/SContentManager.cs | 46 +++++++++++++++------- 1 file changed, 32 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/StardewModdingAPI/Framework/SContentManager.cs b/src/StardewModdingAPI/Framework/SContentManager.cs index 24585963..1ee1eae6 100644 --- a/src/StardewModdingAPI/Framework/SContentManager.cs +++ b/src/StardewModdingAPI/Framework/SContentManager.cs @@ -224,25 +224,43 @@ namespace StardewModdingAPI.Framework // edit asset IAssetData data = new AssetDataForObject(info.Locale, info.AssetName, asset, this.NormaliseAssetName); - foreach (var modEditors in this.Editors) + foreach (var entry in this.GetAssetEditors()) { - IModMetadata mod = modEditors.Key; - foreach (IAssetEditor editor in modEditors.Value) - { - if (!editor.CanEdit(info)) - continue; - - this.Monitor.Log($"{mod.DisplayName} intercepted {info.AssetName}.", LogLevel.Trace); - editor.Edit(data); - if (data.Data == null) - throw new InvalidOperationException($"{mod.DisplayName} incorrectly set asset '{normalisedKey}' to a null value."); - if (!(data.Data is T)) - throw new InvalidOperationException($"{mod.DisplayName} incorrectly set asset '{normalisedKey}' to incompatible type '{data.Data.GetType()}', expected '{typeof(T)}'."); - } + IModMetadata mod = entry.Mod; + IAssetEditor editor = entry.Editor; + + if (!editor.CanEdit(info)) + continue; + + this.Monitor.Log($"{mod.DisplayName} intercepted {info.AssetName}.", LogLevel.Trace); + editor.Edit(data); + if (data.Data == null) + throw new InvalidOperationException($"{mod.DisplayName} incorrectly set asset '{normalisedKey}' to a null value."); + if (!(data.Data is T)) + throw new InvalidOperationException($"{mod.DisplayName} incorrectly set asset '{normalisedKey}' to incompatible type '{data.Data.GetType()}', expected '{typeof(T)}'."); } // return result return (T)data.Data; } + + /// Get all registered asset editors. + private IEnumerable<(IModMetadata Mod, IAssetEditor Editor)> GetAssetEditors() + { + foreach (var entry in this.Editors) + { + IModMetadata metadata = entry.Key; + IList editors = entry.Value; + + // special case if mod implements interface + // ReSharper disable once SuspiciousTypeConversion.Global + if (metadata.Mod is IAssetEditor modAsEditor) + yield return (metadata, modAsEditor); + + // registered editors + foreach (IAssetEditor editor in editors) + yield return (metadata, editor); + } + } } } -- cgit