diff options
Diffstat (limited to 'src/StardewModdingAPI/Framework')
29 files changed, 1064 insertions, 385 deletions
diff --git a/src/StardewModdingAPI/Framework/Content/AssetData.cs b/src/StardewModdingAPI/Framework/Content/AssetData.cs new file mode 100644 index 00000000..1ab9eebd --- /dev/null +++ b/src/StardewModdingAPI/Framework/Content/AssetData.cs @@ -0,0 +1,44 @@ +using System; + +namespace StardewModdingAPI.Framework.Content +{ + /// <summary>Base implementation for a content helper which encapsulates access and changes to content being read from a data file.</summary> + /// <typeparam name="TValue">The interface value type.</typeparam> + internal class AssetData<TValue> : AssetInfo, IAssetData<TValue> + { + /********* + ** Accessors + *********/ + /// <summary>The content data being read.</summary> + public TValue Data { get; protected set; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="locale">The content's locale code, if the content is localised.</param> + /// <param name="assetName">The normalised asset name being read.</param> + /// <param name="data">The content data being read.</param> + /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param> + public AssetData(string locale, string assetName, TValue data, Func<string, string> getNormalisedPath) + : base(locale, assetName, data.GetType(), getNormalisedPath) + { + this.Data = data; + } + + /// <summary>Replace the entire content value with the given value. This is generally not recommended, since it may break compatibility with other mods or different versions of the game.</summary> + /// <param name="value">The new content value.</param> + /// <exception cref="ArgumentNullException">The <paramref name="value"/> is null.</exception> + /// <exception cref="InvalidCastException">The <paramref name="value"/>'s type is not compatible with the loaded asset's type.</exception> + public void ReplaceWith(TValue value) + { + if (value == null) + throw new ArgumentNullException(nameof(value), "Can't set a loaded asset to a null value."); + if (!this.DataType.IsInstanceOfType(value)) + throw new InvalidCastException($"Can't replace loaded asset of type {this.GetFriendlyTypeName(this.DataType)} with value of type {this.GetFriendlyTypeName(value.GetType())}. The new type must be compatible to prevent game errors."); + + this.Data = value; + } + } +} diff --git a/src/StardewModdingAPI/Framework/Content/ContentEventHelperForDictionary.cs b/src/StardewModdingAPI/Framework/Content/AssetDataForDictionary.cs index 26f059e4..e9b29b12 100644 --- a/src/StardewModdingAPI/Framework/Content/ContentEventHelperForDictionary.cs +++ b/src/StardewModdingAPI/Framework/Content/AssetDataForDictionary.cs @@ -5,7 +5,7 @@ using System.Linq; namespace StardewModdingAPI.Framework.Content { /// <summary>Encapsulates access and changes to dictionary content being read from a data file.</summary> - internal class ContentEventHelperForDictionary<TKey, TValue> : ContentEventData<IDictionary<TKey, TValue>>, IContentEventHelperForDictionary<TKey, TValue> + internal class AssetDataForDictionary<TKey, TValue> : AssetData<IDictionary<TKey, TValue>>, IAssetDataForDictionary<TKey, TValue> { /********* ** Public methods @@ -15,7 +15,7 @@ namespace StardewModdingAPI.Framework.Content /// <param name="assetName">The normalised asset name being read.</param> /// <param name="data">The content data being read.</param> /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param> - public ContentEventHelperForDictionary(string locale, string assetName, IDictionary<TKey, TValue> data, Func<string, string> getNormalisedPath) + public AssetDataForDictionary(string locale, string assetName, IDictionary<TKey, TValue> data, Func<string, string> getNormalisedPath) : base(locale, assetName, data, getNormalisedPath) { } /// <summary>Add or replace an entry in the dictionary.</summary> diff --git a/src/StardewModdingAPI/Framework/Content/ContentEventHelperForImage.cs b/src/StardewModdingAPI/Framework/Content/AssetDataForImage.cs index da30590b..45c5588b 100644 --- a/src/StardewModdingAPI/Framework/Content/ContentEventHelperForImage.cs +++ b/src/StardewModdingAPI/Framework/Content/AssetDataForImage.cs @@ -5,7 +5,7 @@ using Microsoft.Xna.Framework.Graphics; namespace StardewModdingAPI.Framework.Content { /// <summary>Encapsulates access and changes to dictionary content being read from a data file.</summary> - internal class ContentEventHelperForImage : ContentEventData<Texture2D>, IContentEventHelperForImage + internal class AssetDataForImage : AssetData<Texture2D>, IAssetDataForImage { /********* ** Public methods @@ -15,7 +15,7 @@ namespace StardewModdingAPI.Framework.Content /// <param name="assetName">The normalised asset name being read.</param> /// <param name="data">The content data being read.</param> /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param> - public ContentEventHelperForImage(string locale, string assetName, Texture2D data, Func<string, string> getNormalisedPath) + public AssetDataForImage(string locale, string assetName, Texture2D data, Func<string, string> getNormalisedPath) : base(locale, assetName, data, getNormalisedPath) { } /// <summary>Overwrite part of the image.</summary> diff --git a/src/StardewModdingAPI/Framework/Content/ContentEventHelper.cs b/src/StardewModdingAPI/Framework/Content/AssetDataForObject.cs index 9bf1ea17..f30003e4 100644 --- a/src/StardewModdingAPI/Framework/Content/ContentEventHelper.cs +++ b/src/StardewModdingAPI/Framework/Content/AssetDataForObject.cs @@ -5,7 +5,7 @@ using Microsoft.Xna.Framework.Graphics; namespace StardewModdingAPI.Framework.Content { /// <summary>Encapsulates access and changes to content being read from a data file.</summary> - internal class ContentEventHelper : ContentEventData<object>, IContentEventHelper + internal class AssetDataForObject : AssetData<object>, IAssetData { /********* ** Public methods @@ -15,23 +15,30 @@ namespace StardewModdingAPI.Framework.Content /// <param name="assetName">The normalised asset name being read.</param> /// <param name="data">The content data being read.</param> /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param> - public ContentEventHelper(string locale, string assetName, object data, Func<string, string> getNormalisedPath) + public AssetDataForObject(string locale, string assetName, object data, Func<string, string> getNormalisedPath) : base(locale, assetName, data, getNormalisedPath) { } + /// <summary>Construct an instance.</summary> + /// <param name="info">The asset metadata.</param> + /// <param name="data">The content data being read.</param> + /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param> + public AssetDataForObject(IAssetInfo info, object data, Func<string, string> getNormalisedPath) + : this(info.Locale, info.AssetName, data, getNormalisedPath) { } + /// <summary>Get a helper to manipulate the data as a dictionary.</summary> /// <typeparam name="TKey">The expected dictionary key.</typeparam> /// <typeparam name="TValue">The expected dictionary balue.</typeparam> /// <exception cref="InvalidOperationException">The content being read isn't a dictionary.</exception> - public IContentEventHelperForDictionary<TKey, TValue> AsDictionary<TKey, TValue>() + public IAssetDataForDictionary<TKey, TValue> AsDictionary<TKey, TValue>() { - return new ContentEventHelperForDictionary<TKey, TValue>(this.Locale, this.AssetName, this.GetData<IDictionary<TKey, TValue>>(), this.GetNormalisedPath); + return new AssetDataForDictionary<TKey, TValue>(this.Locale, this.AssetName, this.GetData<IDictionary<TKey, TValue>>(), this.GetNormalisedPath); } /// <summary>Get a helper to manipulate the data as an image.</summary> /// <exception cref="InvalidOperationException">The content being read isn't an image.</exception> - public IContentEventHelperForImage AsImage() + public IAssetDataForImage AsImage() { - return new ContentEventHelperForImage(this.Locale, this.AssetName, this.GetData<Texture2D>(), this.GetNormalisedPath); + return new AssetDataForImage(this.Locale, this.AssetName, this.GetData<Texture2D>(), this.GetNormalisedPath); } /// <summary>Get the data as a given type.</summary> diff --git a/src/StardewModdingAPI/Framework/Content/ContentEventData.cs b/src/StardewModdingAPI/Framework/Content/AssetInfo.cs index 1a1779d4..d580dc06 100644 --- a/src/StardewModdingAPI/Framework/Content/ContentEventData.cs +++ b/src/StardewModdingAPI/Framework/Content/AssetInfo.cs @@ -4,9 +4,7 @@ using Microsoft.Xna.Framework.Graphics; namespace StardewModdingAPI.Framework.Content { - /// <summary>Base implementation for a content helper which encapsulates access and changes to content being read from a data file.</summary> - /// <typeparam name="TValue">The interface value type.</typeparam> - internal class ContentEventData<TValue> : EventArgs, IContentEventData<TValue> + internal class AssetInfo : IAssetInfo { /********* ** Properties @@ -21,12 +19,9 @@ namespace StardewModdingAPI.Framework.Content /// <summary>The content's locale code, if the content is localised.</summary> public string Locale { get; } - /// <summary>The normalised asset name being read. The format may change between platforms; see <see cref="IsAssetName"/> to compare with a known path.</summary> + /// <summary>The normalised asset name being read. The format may change between platforms; see <see cref="AssetNameEquals"/> to compare with a known path.</summary> public string AssetName { get; } - /// <summary>The content data being read.</summary> - public TValue Data { get; protected set; } - /// <summary>The content data type.</summary> public Type DataType { get; } @@ -37,48 +32,24 @@ namespace StardewModdingAPI.Framework.Content /// <summary>Construct an instance.</summary> /// <param name="locale">The content's locale code, if the content is localised.</param> /// <param name="assetName">The normalised asset name being read.</param> - /// <param name="data">The content data being read.</param> - /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param> - public ContentEventData(string locale, string assetName, TValue data, Func<string, string> getNormalisedPath) - : this(locale, assetName, data, data.GetType(), getNormalisedPath) { } - - /// <summary>Construct an instance.</summary> - /// <param name="locale">The content's locale code, if the content is localised.</param> - /// <param name="assetName">The normalised asset name being read.</param> - /// <param name="data">The content data being read.</param> - /// <param name="dataType">The content data type being read.</param> + /// <param name="type">The content type being read.</param> /// <param name="getNormalisedPath">Normalises an asset key to match the cache key.</param> - public ContentEventData(string locale, string assetName, TValue data, Type dataType, Func<string, string> getNormalisedPath) + public AssetInfo(string locale, string assetName, Type type, Func<string, string> getNormalisedPath) { this.Locale = locale; this.AssetName = assetName; - this.Data = data; - this.DataType = dataType; + this.DataType = type; this.GetNormalisedPath = getNormalisedPath; } /// <summary>Get whether the asset name being loaded matches a given name after normalisation.</summary> /// <param name="path">The expected asset path, relative to the game's content folder and without the .xnb extension or locale suffix (like 'Data\ObjectInformation').</param> - public bool IsAssetName(string path) + public bool AssetNameEquals(string path) { path = this.GetNormalisedPath(path); return this.AssetName.Equals(path, StringComparison.InvariantCultureIgnoreCase); } - /// <summary>Replace the entire content value with the given value. This is generally not recommended, since it may break compatibility with other mods or different versions of the game.</summary> - /// <param name="value">The new content value.</param> - /// <exception cref="ArgumentNullException">The <paramref name="value"/> is null.</exception> - /// <exception cref="InvalidCastException">The <paramref name="value"/>'s type is not compatible with the loaded asset's type.</exception> - public void ReplaceWith(TValue value) - { - if (value == null) - throw new ArgumentNullException(nameof(value), "Can't set a loaded asset to a null value."); - if (!this.DataType.IsInstanceOfType(value)) - throw new InvalidCastException($"Can't replace loaded asset of type {this.GetFriendlyTypeName(this.DataType)} with value of type {this.GetFriendlyTypeName(value.GetType())}. The new type must be compatible to prevent game errors."); - - this.Data = value; - } - /********* ** Protected methods diff --git a/src/StardewModdingAPI/Framework/CursorPosition.cs b/src/StardewModdingAPI/Framework/CursorPosition.cs new file mode 100644 index 00000000..4f256da5 --- /dev/null +++ b/src/StardewModdingAPI/Framework/CursorPosition.cs @@ -0,0 +1,37 @@ +#if SMAPI_2_0 +using Microsoft.Xna.Framework; + +namespace StardewModdingAPI.Framework +{ + /// <summary>Defines a position on a given map at different reference points.</summary> + internal class CursorPosition : ICursorPosition + { + /********* + ** Accessors + *********/ + /// <summary>The pixel position relative to the top-left corner of the visible screen.</summary> + public Vector2 ScreenPixels { get; } + + /// <summary>The tile position under the cursor relative to the top-left corner of the map.</summary> + public Vector2 Tile { get; } + + /// <summary>The tile position that the game considers under the cursor for purposes of clicking actions. This may be different than <see cref="Tile"/> if that's too far from the player.</summary> + public Vector2 GrabTile { get; } + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="screenPixels">The pixel position relative to the top-left corner of the visible screen.</param> + /// <param name="tile">The tile position relative to the top-left corner of the map.</param> + /// <param name="grabTile">The tile position that the game considers under the cursor for purposes of clicking actions.</param> + public CursorPosition(Vector2 screenPixels, Vector2 tile, Vector2 grabTile) + { + this.ScreenPixels = screenPixels; + this.Tile = tile; + this.GrabTile = grabTile; + } + } +} +#endif diff --git a/src/StardewModdingAPI/Framework/DeprecationManager.cs b/src/StardewModdingAPI/Framework/DeprecationManager.cs index 6b95960b..153d8829 100644 --- a/src/StardewModdingAPI/Framework/DeprecationManager.cs +++ b/src/StardewModdingAPI/Framework/DeprecationManager.cs @@ -52,13 +52,12 @@ namespace StardewModdingAPI.Framework if (!this.MarkWarned(source ?? "<unknown>", nounPhrase, version)) return; + // show SMAPI 2.0 meta-warning + if(this.MarkWarned("SMAPI", "SMAPI 2.0 meta-warning", "2.0")) + this.Monitor.Log("Some mods may stop working in SMAPI 2.0 (but they'll work fine for now). Try updating mods with 'deprecated code' warnings; if that doesn't remove the warnings, let the mod authors know about this message or see http://community.playstarbound.com/threads/135000 for details.", LogLevel.Warn); + // build message - string message = source != null - ? $"{source} used {nounPhrase}, which is deprecated since SMAPI {version}." - : $"An unknown mod used {nounPhrase}, which is deprecated since SMAPI {version}."; - message += severity != DeprecationLevel.PendingRemoval - ? " This will break in a future version of SMAPI." - : " It will be removed soon, so the mod will break if it's not updated."; + string message = $"{source ?? "An unknown mod"} uses deprecated code ({nounPhrase})."; if (source == null) message += $"{Environment.NewLine}{Environment.StackTrace}"; @@ -70,7 +69,7 @@ namespace StardewModdingAPI.Framework break; case DeprecationLevel.Info: - this.Monitor.Log(message, LogLevel.Warn); + this.Monitor.Log(message, LogLevel.Debug); break; case DeprecationLevel.PendingRemoval: diff --git a/src/StardewModdingAPI/Framework/Exceptions/SParseException.cs b/src/StardewModdingAPI/Framework/Exceptions/SParseException.cs new file mode 100644 index 00000000..f7133ee7 --- /dev/null +++ b/src/StardewModdingAPI/Framework/Exceptions/SParseException.cs @@ -0,0 +1,17 @@ +using System; + +namespace StardewModdingAPI.Framework.Exceptions +{ + /// <summary>A format exception which provides a user-facing error message.</summary> + internal class SParseException : FormatException + { + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="message">The error message.</param> + /// <param name="ex">The underlying exception, if any.</param> + public SParseException(string message, Exception ex = null) + : base(message, ex) { } + } +} diff --git a/src/StardewModdingAPI/Framework/InternalExtensions.cs b/src/StardewModdingAPI/Framework/InternalExtensions.cs index b99d3798..2842bc83 100644 --- a/src/StardewModdingAPI/Framework/InternalExtensions.cs +++ b/src/StardewModdingAPI/Framework/InternalExtensions.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.Xna.Framework.Graphics; +using StardewModdingAPI.Framework.Reflection; using StardewValley; namespace StardewModdingAPI.Framework @@ -99,7 +100,7 @@ namespace StardewModdingAPI.Framework /// <summary>Get whether the sprite batch is between a begin and end pair.</summary> /// <param name="spriteBatch">The sprite batch to check.</param> /// <param name="reflection">The reflection helper with which to access private fields.</param> - public static bool IsOpen(this SpriteBatch spriteBatch, IReflectionHelper reflection) + public static bool IsOpen(this SpriteBatch spriteBatch, Reflector reflection) { // get field name const string fieldName = @@ -110,7 +111,7 @@ namespace StardewModdingAPI.Framework #endif // get result - return reflection.GetPrivateValue<bool>(Game1.spriteBatch, fieldName); + return reflection.GetPrivateField<bool>(Game1.spriteBatch, fieldName).GetValue(); } } } diff --git a/src/StardewModdingAPI/Framework/ModHelpers/BaseHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/BaseHelper.cs new file mode 100644 index 00000000..16032da1 --- /dev/null +++ b/src/StardewModdingAPI/Framework/ModHelpers/BaseHelper.cs @@ -0,0 +1,23 @@ +namespace StardewModdingAPI.Framework.ModHelpers +{ + /// <summary>The common base class for mod helpers.</summary> + internal abstract class BaseHelper : IModLinked + { + /********* + ** Accessors + *********/ + /// <summary>The unique ID of the mod for which the helper was created.</summary> + public string ModID { get; } + + + /********* + ** Protected methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="modID">The unique ID of the relevant mod.</param> + protected BaseHelper(string modID) + { + this.ModID = modID; + } + } +} diff --git a/src/StardewModdingAPI/Framework/CommandHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/CommandHelper.cs index 86734fc5..bdedb07c 100644 --- a/src/StardewModdingAPI/Framework/CommandHelper.cs +++ b/src/StardewModdingAPI/Framework/ModHelpers/CommandHelper.cs @@ -1,9 +1,9 @@ using System; -namespace StardewModdingAPI.Framework +namespace StardewModdingAPI.Framework.ModHelpers { /// <summary>Provides an API for managing console commands.</summary> - internal class CommandHelper : ICommandHelper + internal class CommandHelper : BaseHelper, ICommandHelper { /********* ** Accessors @@ -15,14 +15,15 @@ namespace StardewModdingAPI.Framework private readonly CommandManager CommandManager; - /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> + /// <param name="modID">The unique ID of the relevant mod.</param> /// <param name="modName">The friendly mod name for this instance.</param> /// <param name="commandManager">Manages console commands.</param> - public CommandHelper(string modName, CommandManager commandManager) + public CommandHelper(string modID, string modName, CommandManager commandManager) + : base(modID) { this.ModName = modName; this.CommandManager = commandManager; diff --git a/src/StardewModdingAPI/Framework/ContentHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/ContentHelper.cs index 7fd5e803..5f72176e 100644 --- a/src/StardewModdingAPI/Framework/ContentHelper.cs +++ b/src/StardewModdingAPI/Framework/ModHelpers/ContentHelper.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; @@ -11,10 +13,10 @@ using xTile; using xTile.Format; using xTile.Tiles; -namespace StardewModdingAPI.Framework +namespace StardewModdingAPI.Framework.ModHelpers { /// <summary>Provides an API for loading content assets.</summary> - internal class ContentHelper : IContentHelper + internal class ContentHelper : BaseHelper, IContentHelper { /********* ** Properties @@ -33,13 +35,31 @@ namespace StardewModdingAPI.Framework /********* + ** Accessors + *********/ + /// <summary>The observable implementation of <see cref="AssetEditors"/>.</summary> + internal ObservableCollection<IAssetEditor> ObservableAssetEditors { get; } = new ObservableCollection<IAssetEditor>(); + + /// <summary>The observable implementation of <see cref="AssetLoaders"/>.</summary> + internal ObservableCollection<IAssetLoader> ObservableAssetLoaders { get; } = new ObservableCollection<IAssetLoader>(); + + /// <summary>Interceptors which provide the initial versions of matching content assets.</summary> + internal IList<IAssetLoader> AssetLoaders => this.ObservableAssetLoaders; + + /// <summary>Interceptors which edit matching content assets after they're loaded.</summary> + internal IList<IAssetEditor> AssetEditors => this.ObservableAssetEditors; + + + /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="contentManager">SMAPI's underlying content manager.</param> /// <param name="modFolderPath">The absolute path to the mod folder.</param> + /// <param name="modID">The unique ID of the relevant mod.</param> /// <param name="modName">The friendly mod name for use in errors.</param> - public ContentHelper(SContentManager contentManager, string modFolderPath, string modName) + public ContentHelper(SContentManager contentManager, string modFolderPath, string modID, string modName) + : base(modID) { this.ContentManager = contentManager; this.ModFolderPath = modFolderPath; diff --git a/src/StardewModdingAPI/Framework/ModHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/ModHelper.cs index 5a8ce459..665b9cf4 100644 --- a/src/StardewModdingAPI/Framework/ModHelper.cs +++ b/src/StardewModdingAPI/Framework/ModHelpers/ModHelper.cs @@ -2,10 +2,10 @@ using System.IO; using StardewModdingAPI.Framework.Serialisation; -namespace StardewModdingAPI.Framework +namespace StardewModdingAPI.Framework.ModHelpers { /// <summary>Provides simplified APIs for writing mods.</summary> - internal class ModHelper : IModHelper, IDisposable + internal class ModHelper : BaseHelper, IModHelper, IDisposable { /********* ** Properties @@ -23,16 +23,16 @@ namespace StardewModdingAPI.Framework /// <summary>An API for loading content assets.</summary> public IContentHelper Content { get; } - /// <summary>Simplifies access to private game code.</summary> + /// <summary>An API for accessing private game code.</summary> public IReflectionHelper Reflection { get; } - /// <summary>Metadata about loaded mods.</summary> + /// <summary>an API for fetching metadata about loaded mods.</summary> public IModRegistry ModRegistry { get; } /// <summary>An API for managing console commands.</summary> public ICommandHelper ConsoleCommands { get; } - /// <summary>Provides translations stored in the mod's <c>i18n</c> folder, with one file per locale (like <c>en.json</c>) containing a flat key => value structure. Translations are fetched with locale fallback, so missing translations are filled in from broader locales (like <c>pt-BR.json</c> < <c>pt.json</c> < <c>default.json</c>).</summary> + /// <summary>An API for reading translations stored in the mod's <c>i18n</c> folder, with one file per locale (like <c>en.json</c>) containing a flat key => value structure. Translations are fetched with locale fallback, so missing translations are filled in from broader locales (like <c>pt-BR.json</c> < <c>pt.json</c> < <c>default.json</c>).</summary> public ITranslationHelper Translation { get; } @@ -40,35 +40,33 @@ namespace StardewModdingAPI.Framework ** Public methods *********/ /// <summary>Construct an instance.</summary> - /// <param name="displayName">The mod's display name.</param> + /// <param name="modID">The mod's unique ID.</param> /// <param name="modDirectory">The full path to the mod's folder.</param> /// <param name="jsonHelper">Encapsulate SMAPI's JSON parsing.</param> - /// <param name="modRegistry">Metadata about loaded mods.</param> - /// <param name="commandManager">Manages console commands.</param> - /// <param name="contentManager">The content manager which loads content assets.</param> - /// <param name="reflection">Simplifies access to private game code.</param> + /// <param name="contentHelper">An API for loading content assets.</param> + /// <param name="commandHelper">An API for managing console commands.</param> + /// <param name="modRegistry">an API for fetching metadata about loaded mods.</param> + /// <param name="reflectionHelper">An API for accessing private game code.</param> + /// <param name="translationHelper">An API for reading translations stored in the mod's <c>i18n</c> folder.</param> /// <exception cref="ArgumentNullException">An argument is null or empty.</exception> /// <exception cref="InvalidOperationException">The <paramref name="modDirectory"/> path does not exist on disk.</exception> - public ModHelper(string displayName, string modDirectory, JsonHelper jsonHelper, IModRegistry modRegistry, CommandManager commandManager, SContentManager contentManager, IReflectionHelper reflection) + public ModHelper(string modID, string modDirectory, JsonHelper jsonHelper, IContentHelper contentHelper, ICommandHelper commandHelper, IModRegistry modRegistry, IReflectionHelper reflectionHelper, ITranslationHelper translationHelper) + : base(modID) { - // validate + // validate directory if (string.IsNullOrWhiteSpace(modDirectory)) throw new ArgumentNullException(nameof(modDirectory)); - if (jsonHelper == null) - throw new ArgumentNullException(nameof(jsonHelper)); - if (modRegistry == null) - throw new ArgumentNullException(nameof(modRegistry)); if (!Directory.Exists(modDirectory)) throw new InvalidOperationException("The specified mod directory does not exist."); // initialise this.DirectoryPath = modDirectory; - this.JsonHelper = jsonHelper; - this.Content = new ContentHelper(contentManager, modDirectory, displayName); - this.ModRegistry = modRegistry; - this.ConsoleCommands = new CommandHelper(displayName, commandManager); - this.Reflection = reflection; - this.Translation = new TranslationHelper(displayName, contentManager.GetLocale(), contentManager.GetCurrentLanguage()); + this.JsonHelper = jsonHelper ?? throw new ArgumentNullException(nameof(jsonHelper)); + this.Content = contentHelper ?? throw new ArgumentNullException(nameof(contentHelper)); + this.ModRegistry = modRegistry ?? throw new ArgumentNullException(nameof(modRegistry)); + this.ConsoleCommands = commandHelper ?? throw new ArgumentNullException(nameof(commandHelper)); + this.Reflection = reflectionHelper ?? throw new ArgumentNullException(nameof(reflectionHelper)); + this.Translation = translationHelper ?? throw new ArgumentNullException(nameof(translationHelper)); } /**** diff --git a/src/StardewModdingAPI/Framework/ModHelpers/ModRegistryHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/ModRegistryHelper.cs new file mode 100644 index 00000000..9e824694 --- /dev/null +++ b/src/StardewModdingAPI/Framework/ModHelpers/ModRegistryHelper.cs @@ -0,0 +1,48 @@ +using System.Collections.Generic; + +namespace StardewModdingAPI.Framework.ModHelpers +{ + /// <summary>Provides metadata about installed mods.</summary> + internal class ModRegistryHelper : BaseHelper, IModRegistry + { + /********* + ** Properties + *********/ + /// <summary>The underlying mod registry.</summary> + private readonly ModRegistry Registry; + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="modID">The unique ID of the relevant mod.</param> + /// <param name="registry">The underlying mod registry.</param> + public ModRegistryHelper(string modID, ModRegistry registry) + : base(modID) + { + this.Registry = registry; + } + + /// <summary>Get metadata for all loaded mods.</summary> + public IEnumerable<IManifest> GetAll() + { + return this.Registry.GetAll(); + } + + /// <summary>Get metadata for a loaded mod.</summary> + /// <param name="uniqueID">The mod's unique ID.</param> + /// <returns>Returns the matching mod's metadata, or <c>null</c> if not found.</returns> + public IManifest Get(string uniqueID) + { + return this.Registry.Get(uniqueID); + } + + /// <summary>Get whether a mod has been loaded.</summary> + /// <param name="uniqueID">The mod's unique ID.</param> + public bool IsLoaded(string uniqueID) + { + return this.Registry.IsLoaded(uniqueID); + } + } +} diff --git a/src/StardewModdingAPI/Framework/ModHelpers/ReflectionHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/ReflectionHelper.cs new file mode 100644 index 00000000..9411a97a --- /dev/null +++ b/src/StardewModdingAPI/Framework/ModHelpers/ReflectionHelper.cs @@ -0,0 +1,160 @@ +using System; +using StardewModdingAPI.Framework.Reflection; + +namespace StardewModdingAPI.Framework.ModHelpers +{ + /// <summary>Provides helper methods for accessing private game code.</summary> + /// <remarks>This implementation searches up the type hierarchy, and caches the reflected fields and methods with a sliding expiry (to optimise performance without unnecessary memory usage).</remarks> + internal class ReflectionHelper : BaseHelper, IReflectionHelper + { + /********* + ** Properties + *********/ + /// <summary>The underlying reflection helper.</summary> + private readonly Reflector Reflector; + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="modID">The unique ID of the relevant mod.</param> + /// <param name="reflector">The underlying reflection helper.</param> + public ReflectionHelper(string modID, Reflector reflector) + : base(modID) + { + this.Reflector = reflector; + } + + /**** + ** Fields + ****/ + /// <summary>Get a private instance field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="obj">The object which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + /// <returns>Returns the field wrapper, or <c>null</c> if the field doesn't exist and <paramref name="required"/> is <c>false</c>.</returns> + public IPrivateField<TValue> GetPrivateField<TValue>(object obj, string name, bool required = true) + { + return this.Reflector.GetPrivateField<TValue>(obj, name, required); + } + + /// <summary>Get a private static field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="type">The type which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + public IPrivateField<TValue> GetPrivateField<TValue>(Type type, string name, bool required = true) + { + return this.Reflector.GetPrivateField<TValue>(type, name, required); + } + + /**** + ** Properties + ****/ + /// <summary>Get a private instance property.</summary> + /// <typeparam name="TValue">The property type.</typeparam> + /// <param name="obj">The object which has the property.</param> + /// <param name="name">The property name.</param> + /// <param name="required">Whether to throw an exception if the private property is not found.</param> + public IPrivateProperty<TValue> GetPrivateProperty<TValue>(object obj, string name, bool required = true) + { + return this.Reflector.GetPrivateProperty<TValue>(obj, name, required); + } + + /// <summary>Get a private static property.</summary> + /// <typeparam name="TValue">The property type.</typeparam> + /// <param name="type">The type which has the property.</param> + /// <param name="name">The property name.</param> + /// <param name="required">Whether to throw an exception if the private property is not found.</param> + public IPrivateProperty<TValue> GetPrivateProperty<TValue>(Type type, string name, bool required = true) + { + return this.Reflector.GetPrivateProperty<TValue>(type, name, required); + } + + /**** + ** Field values + ** (shorthand since this is the most common case) + ****/ + /// <summary>Get the value of a private instance field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="obj">The object which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + /// <returns>Returns the field value, or the default value for <typeparamref name="TValue"/> if the field wasn't found and <paramref name="required"/> is false.</returns> + /// <remarks> + /// This is a shortcut for <see cref="GetPrivateField{TValue}(object,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>. + /// When <paramref name="required" /> is false, this will return the default value if reflection fails. If you need to check whether the field exists, use <see cref="GetPrivateField{TValue}(object,string,bool)" /> instead. + /// </remarks> + public TValue GetPrivateValue<TValue>(object obj, string name, bool required = true) + { + IPrivateField<TValue> field = this.GetPrivateField<TValue>(obj, name, required); + return field != null + ? field.GetValue() + : default(TValue); + } + + /// <summary>Get the value of a private static field.</summary> + /// <typeparam name="TValue">The field type.</typeparam> + /// <param name="type">The type which has the field.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + /// <returns>Returns the field value, or the default value for <typeparamref name="TValue"/> if the field wasn't found and <paramref name="required"/> is false.</returns> + /// <remarks> + /// This is a shortcut for <see cref="GetPrivateField{TValue}(Type,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>. + /// When <paramref name="required" /> is false, this will return the default value if reflection fails. If you need to check whether the field exists, use <see cref="GetPrivateField{TValue}(Type,string,bool)" /> instead. + /// </remarks> + public TValue GetPrivateValue<TValue>(Type type, string name, bool required = true) + { + IPrivateField<TValue> field = this.GetPrivateField<TValue>(type, name, required); + return field != null + ? field.GetValue() + : default(TValue); + } + + /**** + ** Methods + ****/ + /// <summary>Get a private instance method.</summary> + /// <param name="obj">The object which has the method.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + public IPrivateMethod GetPrivateMethod(object obj, string name, bool required = true) + { + return this.Reflector.GetPrivateMethod(obj, name, required); + } + + /// <summary>Get a private static method.</summary> + /// <param name="type">The type which has the method.</param> + /// <param name="name">The field name.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + public IPrivateMethod GetPrivateMethod(Type type, string name, bool required = true) + { + return this.Reflector.GetPrivateMethod(type, name, required); + } + + /**** + ** Methods by signature + ****/ + /// <summary>Get a private instance method.</summary> + /// <param name="obj">The object which has the method.</param> + /// <param name="name">The field name.</param> + /// <param name="argumentTypes">The argument types of the method signature to find.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + public IPrivateMethod GetPrivateMethod(object obj, string name, Type[] argumentTypes, bool required = true) + { + return this.Reflector.GetPrivateMethod(obj, name, argumentTypes, required); + } + + /// <summary>Get a private static method.</summary> + /// <param name="type">The type which has the method.</param> + /// <param name="name">The field name.</param> + /// <param name="argumentTypes">The argument types of the method signature to find.</param> + /// <param name="required">Whether to throw an exception if the private field is not found.</param> + public IPrivateMethod GetPrivateMethod(Type type, string name, Type[] argumentTypes, bool required = true) + { + return this.Reflector.GetPrivateMethod(type, name, argumentTypes, required); + } + } +} diff --git a/src/StardewModdingAPI/Framework/TranslationHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/TranslationHelper.cs index fe387789..bbe3a81a 100644 --- a/src/StardewModdingAPI/Framework/TranslationHelper.cs +++ b/src/StardewModdingAPI/Framework/ModHelpers/TranslationHelper.cs @@ -3,10 +3,10 @@ using System.Collections.Generic; using System.Linq; using StardewValley; -namespace StardewModdingAPI.Framework +namespace StardewModdingAPI.Framework.ModHelpers { /// <summary>Provides translations stored in the mod's <c>i18n</c> folder, with one file per locale (like <c>en.json</c>) containing a flat key => value structure. Translations are fetched with locale fallback, so missing translations are filled in from broader locales (like <c>pt-BR.json</c> < <c>pt.json</c> < <c>default.json</c>).</summary> - internal class TranslationHelper : ITranslationHelper + internal class TranslationHelper : BaseHelper, ITranslationHelper { /********* ** Properties @@ -35,10 +35,12 @@ namespace StardewModdingAPI.Framework ** Public methods *********/ /// <summary>Construct an instance.</summary> + /// <param name="modID">The unique ID of the relevant mod.</param> /// <param name="modName">The name of the relevant mod for error messages.</param> /// <param name="locale">The initial locale.</param> /// <param name="languageCode">The game's current language code.</param> - public TranslationHelper(string modName, string locale, LocalizedContentManager.LanguageCode languageCode) + public TranslationHelper(string modID, string modName, string locale, LocalizedContentManager.LanguageCode languageCode) + : base(modID) { // save data this.ModName = modName; diff --git a/src/StardewModdingAPI/Framework/ModLoading/AssemblyLoader.cs b/src/StardewModdingAPI/Framework/ModLoading/AssemblyLoader.cs index 42bd7bfb..406d49e1 100644 --- a/src/StardewModdingAPI/Framework/ModLoading/AssemblyLoader.cs +++ b/src/StardewModdingAPI/Framework/ModLoading/AssemblyLoader.cs @@ -71,13 +71,15 @@ namespace StardewModdingAPI.Framework.ModLoading } // rewrite & load assemblies in leaf-to-root order + bool oneAssembly = assemblies.Length == 1; Assembly lastAssembly = null; foreach (AssemblyParseResult assembly in assemblies) { - bool changed = this.RewriteAssembly(assembly.Definition, assumeCompatible); + bool changed = this.RewriteAssembly(assembly.Definition, assumeCompatible, logPrefix: " "); if (changed) { - this.Monitor.Log($"Loading {assembly.File.Name} (rewritten in memory)...", LogLevel.Trace); + if (!oneAssembly) + this.Monitor.Log($" Loading {assembly.File.Name}.dll (rewritten in memory)...", LogLevel.Trace); using (MemoryStream outStream = new MemoryStream()) { assembly.Definition.Write(outStream); @@ -87,7 +89,8 @@ namespace StardewModdingAPI.Framework.ModLoading } else { - this.Monitor.Log($"Loading {assembly.File.Name}...", LogLevel.Trace); + if (!oneAssembly) + this.Monitor.Log($" Loading {assembly.File.Name}.dll...", LogLevel.Trace); lastAssembly = Assembly.UnsafeLoadFrom(assembly.File.FullName); } } @@ -161,12 +164,14 @@ namespace StardewModdingAPI.Framework.ModLoading /// <summary>Rewrite the types referenced by an assembly.</summary> /// <param name="assembly">The assembly to rewrite.</param> /// <param name="assumeCompatible">Assume the mod is compatible, even if incompatible code is detected.</param> + /// <param name="logPrefix">A string to prefix to log messages.</param> /// <returns>Returns whether the assembly was modified.</returns> /// <exception cref="IncompatibleInstructionException">An incompatible CIL instruction was found while rewriting the assembly.</exception> - private bool RewriteAssembly(AssemblyDefinition assembly, bool assumeCompatible) + private bool RewriteAssembly(AssemblyDefinition assembly, bool assumeCompatible, string logPrefix) { ModuleDefinition module = assembly.MainModule; HashSet<string> loggedMessages = new HashSet<string>(); + string filename = $"{assembly.Name.Name}.dll"; // swap assembly references if needed (e.g. XNA => MonoGame) bool platformChanged = false; @@ -175,7 +180,7 @@ namespace StardewModdingAPI.Framework.ModLoading // remove old assembly reference if (this.AssemblyMap.RemoveNames.Any(name => module.AssemblyReferences[i].Name == name)) { - this.LogOnce(this.Monitor, loggedMessages, $"Rewriting {assembly.Name.Name} for OS..."); + this.LogOnce(this.Monitor, loggedMessages, $"{logPrefix}Rewriting {filename} for OS..."); platformChanged = true; module.AssemblyReferences.RemoveAt(i); i--; @@ -205,15 +210,15 @@ namespace StardewModdingAPI.Framework.ModLoading { if (rewriter.Rewrite(module, method, this.AssemblyMap, platformChanged)) { - this.LogOnce(this.Monitor, loggedMessages, $"Rewrote {assembly.Name.Name} to fix {rewriter.NounPhrase}..."); + this.LogOnce(this.Monitor, loggedMessages, $"{logPrefix}Rewrote {filename} to fix {rewriter.NounPhrase}..."); anyRewritten = true; } } catch (IncompatibleInstructionException) { if (!assumeCompatible) - throw new IncompatibleInstructionException(rewriter.NounPhrase, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {assembly.Name.Name}."); - this.LogOnce(this.Monitor, loggedMessages, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {assembly.Name.Name}, but SMAPI is configured to allow it anyway. The mod may crash or behave unexpectedly.", LogLevel.Warn); + throw new IncompatibleInstructionException(rewriter.NounPhrase, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {filename}."); + this.LogOnce(this.Monitor, loggedMessages, $"{logPrefix}Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {filename}, but SMAPI is configured to allow it anyway. The mod may crash or behave unexpectedly.", LogLevel.Warn); } } @@ -227,15 +232,15 @@ namespace StardewModdingAPI.Framework.ModLoading { if (rewriter.Rewrite(module, cil, instruction, this.AssemblyMap, platformChanged)) { - this.LogOnce(this.Monitor, loggedMessages, $"Rewrote {assembly.Name.Name} to fix {rewriter.NounPhrase}..."); + this.LogOnce(this.Monitor, loggedMessages, $"{logPrefix}Rewrote {filename} to fix {rewriter.NounPhrase}..."); anyRewritten = true; } } catch (IncompatibleInstructionException) { if (!assumeCompatible) - throw new IncompatibleInstructionException(rewriter.NounPhrase, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {assembly.Name.Name}."); - this.LogOnce(this.Monitor, loggedMessages, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {assembly.Name.Name}, but SMAPI is configured to allow it anyway. The mod may crash or behave unexpectedly.", LogLevel.Warn); + throw new IncompatibleInstructionException(rewriter.NounPhrase, $"Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {filename}."); + this.LogOnce(this.Monitor, loggedMessages, $"{logPrefix}Found an incompatible CIL instruction ({rewriter.NounPhrase}) while loading assembly {filename}, but SMAPI is configured to allow it anyway. The mod may crash or behave unexpectedly.", LogLevel.Warn); } } } diff --git a/src/StardewModdingAPI/Framework/ModLoading/ModResolver.cs b/src/StardewModdingAPI/Framework/ModLoading/ModResolver.cs index f5139ce5..38dddce7 100644 --- a/src/StardewModdingAPI/Framework/ModLoading/ModResolver.cs +++ b/src/StardewModdingAPI/Framework/ModLoading/ModResolver.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using StardewModdingAPI.Framework.Exceptions; using StardewModdingAPI.Framework.Models; using StardewModdingAPI.Framework.Serialisation; @@ -17,10 +18,13 @@ namespace StardewModdingAPI.Framework.ModLoading /// <param name="rootPath">The root path to search for mods.</param> /// <param name="jsonHelper">The JSON helper with which to read manifests.</param> /// <param name="compatibilityRecords">Metadata about mods that SMAPI should assume is compatible or broken, regardless of whether it detects incompatible code.</param> + /// <param name="disabledMods">Metadata about mods that SMAPI should consider obsolete and not load.</param> /// <returns>Returns the manifests by relative folder.</returns> - public IEnumerable<IModMetadata> ReadManifests(string rootPath, JsonHelper jsonHelper, IEnumerable<ModCompatibility> compatibilityRecords) + public IEnumerable<IModMetadata> ReadManifests(string rootPath, JsonHelper jsonHelper, IEnumerable<ModCompatibility> compatibilityRecords, IEnumerable<DisabledMod> disabledMods) { compatibilityRecords = compatibilityRecords.ToArray(); + disabledMods = disabledMods.ToArray(); + foreach (DirectoryInfo modDir in this.GetModFolders(rootPath)) { // read file @@ -42,25 +46,38 @@ namespace StardewModdingAPI.Framework.ModLoading else if (string.IsNullOrWhiteSpace(manifest.EntryDll)) error = "its manifest doesn't set an entry DLL."; } + catch (SParseException ex) + { + error = $"parsing its manifest failed: {ex.Message}"; + } catch (Exception ex) { error = $"parsing its manifest failed:\n{ex.GetLogSummary()}"; } - // get compatibility record + // validate metadata ModCompatibility compatibility = null; if (manifest != null) { + // get unique key for lookups string key = !string.IsNullOrWhiteSpace(manifest.UniqueID) ? manifest.UniqueID : manifest.EntryDll; + + // check if mod should be disabled + DisabledMod disabledMod = disabledMods.FirstOrDefault(mod => mod.ID.Contains(key, StringComparer.InvariantCultureIgnoreCase)); + if (disabledMod != null) + error = $"it's obsolete: {disabledMod.ReasonPhrase}"; + + // get compatibility record compatibility = ( from mod in compatibilityRecords where - mod.ID.Contains(key, StringComparer.InvariantCultureIgnoreCase) - && (mod.LowerSemanticVersion == null || !manifest.Version.IsOlderThan(mod.LowerSemanticVersion)) - && !manifest.Version.IsNewerThan(mod.UpperSemanticVersion) + mod.ID.Contains(key, StringComparer.InvariantCultureIgnoreCase) + && (mod.LowerSemanticVersion == null || !manifest.Version.IsOlderThan(mod.LowerSemanticVersion)) + && !manifest.Version.IsNewerThan(mod.UpperSemanticVersion) select mod ).FirstOrDefault(); } + // build metadata string displayName = !string.IsNullOrWhiteSpace(manifest?.Name) ? manifest.Name @@ -92,7 +109,7 @@ namespace StardewModdingAPI.Framework.ModLoading bool hasOfficialUrl = !string.IsNullOrWhiteSpace(mod.Compatibility.UpdateUrl); bool hasUnofficialUrl = !string.IsNullOrWhiteSpace(mod.Compatibility.UnofficialUpdateUrl); - string reasonPhrase = compatibility.ReasonPhrase ?? "it's not compatible with the latest version of the game"; + string reasonPhrase = compatibility.ReasonPhrase ?? "it's not compatible with the latest version of the game or SMAPI"; string error = $"{reasonPhrase}. Please check for a version newer than {compatibility.UpperVersionLabel ?? compatibility.UpperVersion} here:"; if (hasOfficialUrl) error += !hasUnofficialUrl ? $" {compatibility.UpdateUrl}" : $"{Environment.NewLine}- official mod: {compatibility.UpdateUrl}"; @@ -105,24 +122,36 @@ namespace StardewModdingAPI.Framework.ModLoading } // validate SMAPI version - if (!string.IsNullOrWhiteSpace(mod.Manifest.MinimumApiVersion)) + if (mod.Manifest.MinimumApiVersion?.IsNewerThan(apiVersion) == true) { - if (!SemanticVersion.TryParse(mod.Manifest.MinimumApiVersion, out ISemanticVersion minVersion)) - { - mod.SetStatus(ModMetadataStatus.Failed, $"it has an invalid minimum SMAPI version '{mod.Manifest.MinimumApiVersion}'. This should be a semantic version number like {apiVersion}."); - continue; - } - if (minVersion.IsNewerThan(apiVersion)) - { - mod.SetStatus(ModMetadataStatus.Failed, $"it needs SMAPI {minVersion} or later. Please update SMAPI to the latest version to use this mod."); - continue; - } + mod.SetStatus(ModMetadataStatus.Failed, $"it needs SMAPI {mod.Manifest.MinimumApiVersion} or later. Please update SMAPI to the latest version to use this mod."); + continue; } // validate DLL path string assemblyPath = Path.Combine(mod.DirectoryPath, mod.Manifest.EntryDll); if (!File.Exists(assemblyPath)) + { mod.SetStatus(ModMetadataStatus.Failed, $"its DLL '{mod.Manifest.EntryDll}' doesn't exist."); + continue; + } + + // validate required fields +#if SMAPI_2_0 + { + List<string> missingFields = new List<string>(3); + + if (string.IsNullOrWhiteSpace(mod.Manifest.Name)) + missingFields.Add(nameof(IManifest.Name)); + if (mod.Manifest.Version == null || mod.Manifest.Version.ToString() == "0.0") + missingFields.Add(nameof(IManifest.Version)); + if (string.IsNullOrWhiteSpace(mod.Manifest.UniqueID)) + missingFields.Add(nameof(IManifest.UniqueID)); + + if (missingFields.Any()) + mod.SetStatus(ModMetadataStatus.Failed, $"its manifest is missing required fields ({string.Join(", ", missingFields)})."); + } +#endif } } @@ -193,20 +222,51 @@ namespace StardewModdingAPI.Framework.ModLoading return states[mod] = ModDependencyStatus.Sorted; } + // get dependencies + var dependencies = + ( + from entry in mod.Manifest.Dependencies + let dependencyMod = mods.FirstOrDefault(m => string.Equals(m.Manifest?.UniqueID, entry.UniqueID, StringComparison.InvariantCultureIgnoreCase)) + orderby entry.UniqueID + select new + { + ID = entry.UniqueID, + MinVersion = entry.MinimumVersion, + Mod = dependencyMod, + IsRequired = +#if SMAPI_2_0 + entry.IsRequired +#else + true +#endif + } + ) + .ToArray(); + // missing required dependencies, mark failed { - string[] missingModIDs = + string[] failedIDs = (from entry in dependencies where entry.IsRequired && entry.Mod == null select entry.ID).ToArray(); + if (failedIDs.Any()) + { + sortedMods.Push(mod); + mod.SetStatus(ModMetadataStatus.Failed, $"it requires mods which aren't installed ({string.Join(", ", failedIDs)})."); + return states[mod] = ModDependencyStatus.Failed; + } + } + + // dependency min version not met, mark failed + { + string[] failedLabels = ( - from dependency in mod.Manifest.Dependencies - where mods.All(m => m.Manifest?.UniqueID != dependency.UniqueID) - orderby dependency.UniqueID - select dependency.UniqueID + from entry in dependencies + where entry.Mod != null && entry.MinVersion != null && entry.MinVersion.IsNewerThan(entry.Mod.Manifest.Version) + select $"{entry.Mod.DisplayName} (needs {entry.MinVersion} or later)" ) .ToArray(); - if (missingModIDs.Any()) + if (failedLabels.Any()) { sortedMods.Push(mod); - mod.SetStatus(ModMetadataStatus.Failed, $"it requires mods which aren't installed ({string.Join(", ", missingModIDs)})."); + mod.SetStatus(ModMetadataStatus.Failed, $"it needs newer versions of some mods: {string.Join(", ", failedLabels)}."); return states[mod] = ModDependencyStatus.Failed; } } @@ -215,20 +275,16 @@ namespace StardewModdingAPI.Framework.ModLoading { states[mod] = ModDependencyStatus.Checking; - // get mods to load first - IModMetadata[] modsToLoadFirst = - ( - from other in mods - where mod.Manifest.Dependencies.Any(required => required.UniqueID == other.Manifest?.UniqueID) - select other - ) - .ToArray(); - // recursively sort dependencies - foreach (IModMetadata requiredMod in modsToLoadFirst) + foreach (var dependency in dependencies) { + IModMetadata requiredMod = dependency.Mod; var subchain = new List<IModMetadata>(currentChain) { mod }; + // ignore missing optional dependency + if (!dependency.IsRequired && requiredMod == null) + continue; + // detect dependency loop if (states[requiredMod] == ModDependencyStatus.Checking) { diff --git a/src/StardewModdingAPI/Framework/ModRegistry.cs b/src/StardewModdingAPI/Framework/ModRegistry.cs index f9d3cfbf..a427bdb7 100644 --- a/src/StardewModdingAPI/Framework/ModRegistry.cs +++ b/src/StardewModdingAPI/Framework/ModRegistry.cs @@ -7,7 +7,7 @@ using System.Reflection; namespace StardewModdingAPI.Framework { /// <summary>Tracks the installed mods.</summary> - internal class ModRegistry : IModRegistry + internal class ModRegistry { /********* ** Properties @@ -23,7 +23,7 @@ namespace StardewModdingAPI.Framework ** Public methods *********/ /**** - ** IModRegistry + ** Basic metadata ****/ /// <summary>Get metadata for all loaded mods.</summary> public IEnumerable<IManifest> GetAll() @@ -47,7 +47,7 @@ namespace StardewModdingAPI.Framework } /**** - ** Internal methods + ** Mod data ****/ /// <summary>Register a mod as a possible source of deprecation warnings.</summary> /// <param name="metadata">The mod metadata.</param> diff --git a/src/StardewModdingAPI/Framework/Models/DisabledMod.cs b/src/StardewModdingAPI/Framework/Models/DisabledMod.cs new file mode 100644 index 00000000..170fa760 --- /dev/null +++ b/src/StardewModdingAPI/Framework/Models/DisabledMod.cs @@ -0,0 +1,22 @@ +namespace StardewModdingAPI.Framework.Models +{ + /// <summary>Metadata about for a mod that should never be loaded.</summary> + internal class DisabledMod + { + /********* + ** Accessors + *********/ + /**** + ** From config + ****/ + /// <summary>The unique mod IDs.</summary> + public string[] ID { get; set; } + + /// <summary>The mod name.</summary> + public string Name { get; set; } + + /// <summary>The reason phrase to show in the warning, or <c>null</c> to use the default value.</summary> + /// <example>"this mod is no longer supported or used"</example> + public string ReasonPhrase { get; set; } + } +} diff --git a/src/StardewModdingAPI/Framework/Models/Manifest.cs b/src/StardewModdingAPI/Framework/Models/Manifest.cs index be781585..08b88025 100644 --- a/src/StardewModdingAPI/Framework/Models/Manifest.cs +++ b/src/StardewModdingAPI/Framework/Models/Manifest.cs @@ -25,7 +25,8 @@ namespace StardewModdingAPI.Framework.Models public ISemanticVersion Version { get; set; } /// <summary>The minimum SMAPI version required by this mod, if any.</summary> - public string MinimumApiVersion { get; set; } + [JsonConverter(typeof(ManifestFieldConverter))] + public ISemanticVersion MinimumApiVersion { get; set; } /// <summary>The name of the DLL in the directory that has the <see cref="Mod.Entry"/> method.</summary> public string EntryDll { get; set; } @@ -37,9 +38,11 @@ namespace StardewModdingAPI.Framework.Models /// <summary>The unique mod ID.</summary> public string UniqueID { get; set; } +#if !SMAPI_2_0 /// <summary>Whether the mod uses per-save config files.</summary> [Obsolete("Use " + nameof(Mod) + "." + nameof(Mod.Helper) + "." + nameof(IModHelper.ReadConfig) + " instead")] public bool PerSaveConfigs { get; set; } +#endif /// <summary>Any manifest fields which didn't match a valid field.</summary> [JsonExtensionData] diff --git a/src/StardewModdingAPI/Framework/Models/ManifestDependency.cs b/src/StardewModdingAPI/Framework/Models/ManifestDependency.cs index 2f580c1d..25d92a29 100644 --- a/src/StardewModdingAPI/Framework/Models/ManifestDependency.cs +++ b/src/StardewModdingAPI/Framework/Models/ManifestDependency.cs @@ -9,15 +9,34 @@ /// <summary>The unique mod ID to require.</summary> public string UniqueID { get; set; } + /// <summary>The minimum required version (if any).</summary> + public ISemanticVersion MinimumVersion { get; set; } + +#if SMAPI_2_0 + /// <summary>Whether the dependency must be installed to use the mod.</summary> + public bool IsRequired { get; set; } +#endif /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="uniqueID">The unique mod ID to require.</param> - public ManifestDependency(string uniqueID) + /// <param name="minimumVersion">The minimum required version (if any).</param> + /// <param name="required">Whether the dependency must be installed to use the mod.</param> + public ManifestDependency(string uniqueID, string minimumVersion +#if SMAPI_2_0 + , bool required = true +#endif + ) { this.UniqueID = uniqueID; + this.MinimumVersion = !string.IsNullOrWhiteSpace(minimumVersion) + ? new SemanticVersion(minimumVersion) + : null; +#if SMAPI_2_0 + this.IsRequired = required; +#endif } } } diff --git a/src/StardewModdingAPI/Framework/Models/SConfig.cs b/src/StardewModdingAPI/Framework/Models/SConfig.cs index c3f0816e..b2ca4113 100644 --- a/src/StardewModdingAPI/Framework/Models/SConfig.cs +++ b/src/StardewModdingAPI/Framework/Models/SConfig.cs @@ -17,5 +17,8 @@ /// <summary>A list of mod versions which should be considered compatible or incompatible regardless of whether SMAPI detects incompatible code.</summary> public ModCompatibility[] ModCompatibility { get; set; } + + /// <summary>A list of mods which should be considered obsolete and not loaded.</summary> + public DisabledMod[] DisabledMods { get; set; } } } diff --git a/src/StardewModdingAPI/Framework/Monitor.cs b/src/StardewModdingAPI/Framework/Monitor.cs index 925efc33..6359b454 100644 --- a/src/StardewModdingAPI/Framework/Monitor.cs +++ b/src/StardewModdingAPI/Framework/Monitor.cs @@ -45,6 +45,11 @@ namespace StardewModdingAPI.Framework /// <summary>Whether SMAPI is aborting. Mods don't need to worry about this unless they have background tasks.</summary> public bool IsExiting => this.ExitTokenSource.IsCancellationRequested; +#if SMAPI_2_0 + /// <summary>Whether to show the full log stamps (with time/level/logger) in the console. If false, shows a simplified stamp with only the logger.</summary> + internal bool ShowFullStampInConsole { get; set; } +#endif + /// <summary>Whether to show trace messages in the console.</summary> internal bool ShowTraceInConsole { get; set; } @@ -92,6 +97,18 @@ namespace StardewModdingAPI.Framework this.ExitTokenSource.Cancel(); } +#if SMAPI_2_0 + /// <summary>Write a newline to the console and log file.</summary> + internal void Newline() + { + if (this.WriteToConsole) + this.ConsoleManager.ExclusiveWriteWithoutInterception(Console.WriteLine); + if (this.WriteToFile) + this.LogFile.WriteLine(""); + } +#endif + +#if !SMAPI_2_0 /// <summary>Log a message for the player or developer, using the specified console color.</summary> /// <param name="source">The name of the mod logging the message.</param> /// <param name="message">The message to log.</param> @@ -102,6 +119,7 @@ namespace StardewModdingAPI.Framework { this.LogImpl(source, message, level, color); } +#endif /********* @@ -124,7 +142,13 @@ namespace StardewModdingAPI.Framework { // generate message string levelStr = level.ToString().ToUpper().PadRight(Monitor.MaxLevelLength); - message = $"[{DateTime.Now:HH:mm:ss} {levelStr} {source}] {message}"; + + string fullMessage = $"[{DateTime.Now:HH:mm:ss} {levelStr} {source}] {message}"; +#if SMAPI_2_0 + string consoleMessage = this.ShowFullStampInConsole ? fullMessage : $"[{source}] {message}"; +#else + string consoleMessage = fullMessage; +#endif // write to console if (this.WriteToConsole && (this.ShowTraceInConsole || level != LogLevel.Trace)) @@ -136,17 +160,17 @@ namespace StardewModdingAPI.Framework if (background.HasValue) Console.BackgroundColor = background.Value; Console.ForegroundColor = color; - Console.WriteLine(message); + Console.WriteLine(consoleMessage); Console.ResetColor(); } else - Console.WriteLine(message); + Console.WriteLine(consoleMessage); }); } // write to log file if (this.WriteToFile) - this.LogFile.WriteLine(message); + this.LogFile.WriteLine(fullMessage); } } } diff --git a/src/StardewModdingAPI/Framework/Reflection/ReflectionHelper.cs b/src/StardewModdingAPI/Framework/Reflection/Reflector.cs index 7a5789dc..5c2d90fa 100644 --- a/src/StardewModdingAPI/Framework/Reflection/ReflectionHelper.cs +++ b/src/StardewModdingAPI/Framework/Reflection/Reflector.cs @@ -7,13 +7,13 @@ namespace StardewModdingAPI.Framework.Reflection { /// <summary>Provides helper methods for accessing private game code.</summary> /// <remarks>This implementation searches up the type hierarchy, and caches the reflected fields and methods with a sliding expiry (to optimise performance without unnecessary memory usage).</remarks> - internal class ReflectionHelper : IReflectionHelper + internal class Reflector { /********* ** Properties *********/ /// <summary>The cached fields and methods found via reflection.</summary> - private readonly MemoryCache Cache = new MemoryCache(typeof(ReflectionHelper).FullName); + private readonly MemoryCache Cache = new MemoryCache(typeof(Reflector).FullName); /// <summary>The sliding cache expiration time.</summary> private readonly TimeSpan SlidingCacheExpiry = TimeSpan.FromMinutes(5); @@ -94,46 +94,6 @@ namespace StardewModdingAPI.Framework.Reflection } /**** - ** Field values - ** (shorthand since this is the most common case) - ****/ - /// <summary>Get the value of a private instance field.</summary> - /// <typeparam name="TValue">The field type.</typeparam> - /// <param name="obj">The object which has the field.</param> - /// <param name="name">The field name.</param> - /// <param name="required">Whether to throw an exception if the private field is not found.</param> - /// <returns>Returns the field value, or the default value for <typeparamref name="TValue"/> if the field wasn't found and <paramref name="required"/> is false.</returns> - /// <remarks> - /// This is a shortcut for <see cref="GetPrivateField{TValue}(object,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>. - /// When <paramref name="required" /> is false, this will return the default value if reflection fails. If you need to check whether the field exists, use <see cref="GetPrivateField{TValue}(object,string,bool)" /> instead. - /// </remarks> - public TValue GetPrivateValue<TValue>(object obj, string name, bool required = true) - { - IPrivateField<TValue> field = this.GetPrivateField<TValue>(obj, name, required); - return field != null - ? field.GetValue() - : default(TValue); - } - - /// <summary>Get the value of a private static field.</summary> - /// <typeparam name="TValue">The field type.</typeparam> - /// <param name="type">The type which has the field.</param> - /// <param name="name">The field name.</param> - /// <param name="required">Whether to throw an exception if the private field is not found.</param> - /// <returns>Returns the field value, or the default value for <typeparamref name="TValue"/> if the field wasn't found and <paramref name="required"/> is false.</returns> - /// <remarks> - /// This is a shortcut for <see cref="GetPrivateField{TValue}(Type,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>. - /// When <paramref name="required" /> is false, this will return the default value if reflection fails. If you need to check whether the field exists, use <see cref="GetPrivateField{TValue}(Type,string,bool)" /> instead. - /// </remarks> - public TValue GetPrivateValue<TValue>(Type type, string name, bool required = true) - { - IPrivateField<TValue> field = this.GetPrivateField<TValue>(type, name, required); - return field != null - ? field.GetValue() - : default(TValue); - } - - /**** ** Methods ****/ /// <summary>Get a private instance method.</summary> diff --git a/src/StardewModdingAPI/Framework/SContentManager.cs b/src/StardewModdingAPI/Framework/SContentManager.cs index acd3e108..669b0e7a 100644 --- a/src/StardewModdingAPI/Framework/SContentManager.cs +++ b/src/StardewModdingAPI/Framework/SContentManager.cs @@ -3,14 +3,16 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; -using System.Threading; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.AssemblyRewriters; -using StardewModdingAPI.Events; using StardewModdingAPI.Framework.Content; using StardewModdingAPI.Framework.Reflection; using StardewValley; +using StardewValley.BellsAndWhistles; +using StardewValley.Objects; +using StardewValley.Projectiles; namespace StardewModdingAPI.Framework { @@ -42,6 +44,12 @@ namespace StardewModdingAPI.Framework /********* ** Accessors *********/ + /// <summary>Interceptors which provide the initial versions of matching assets.</summary> + internal IDictionary<IModMetadata, IList<IAssetLoader>> Loaders { get; } = new Dictionary<IModMetadata, IList<IAssetLoader>>(); + + /// <summary>Interceptors which edit matching assets after they're loaded.</summary> + internal IDictionary<IModMetadata, IList<IAssetEditor>> Editors { get; } = new Dictionary<IModMetadata, IList<IAssetEditor>>(); + /// <summary>The absolute path to the <see cref="ContentManager.RootDirectory"/>.</summary> public string FullRootDirectory => Path.Combine(Constants.ExecutionPath, this.RootDirectory); @@ -52,22 +60,19 @@ namespace StardewModdingAPI.Framework /// <summary>Construct an instance.</summary> /// <param name="serviceProvider">The service provider to use to locate services.</param> /// <param name="rootDirectory">The root directory to search for content.</param> - /// <param name="monitor">Encapsulates monitoring and logging.</param> - public SContentManager(IServiceProvider serviceProvider, string rootDirectory, IMonitor monitor) - : this(serviceProvider, rootDirectory, Thread.CurrentThread.CurrentUICulture, null, monitor) { } - - /// <summary>Construct an instance.</summary> - /// <param name="serviceProvider">The service provider to use to locate services.</param> - /// <param name="rootDirectory">The root directory to search for content.</param> /// <param name="currentCulture">The current culture for which to localise content.</param> /// <param name="languageCodeOverride">The current language code for which to localise content.</param> /// <param name="monitor">Encapsulates monitoring and logging.</param> public SContentManager(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, string languageCodeOverride, IMonitor monitor) : base(serviceProvider, rootDirectory, currentCulture, languageCodeOverride) { + // validate + if (monitor == null) + throw new ArgumentNullException(nameof(monitor)); + // initialise + var reflection = new Reflector(); this.Monitor = monitor; - IReflectionHelper reflection = new ReflectionHelper(); // get underlying fields for interception this.Cache = reflection.GetPrivateField<Dictionary<string, object>>(this, "loadedAssets").GetValue(); @@ -117,22 +122,24 @@ namespace StardewModdingAPI.Framework /// <param name="assetName">The asset path relative to the loader root directory, not including the <c>.xnb</c> extension.</param> public override T Load<T>(string assetName) { - // get normalised metadata assetName = this.NormaliseAssetName(assetName); - string cacheLocale = this.GetCacheLocale(assetName); // skip if already loaded if (this.IsNormalisedKeyLoaded(assetName)) return base.Load<T>(assetName); - // load data - T data = base.Load<T>(assetName); + // load asset + T data; + { + IAssetInfo info = new AssetInfo(this.GetLocale(), assetName, typeof(T), this.NormaliseAssetName); + IAssetData asset = this.ApplyLoader<T>(info) ?? new AssetDataForObject(info, base.Load<T>(assetName), this.NormaliseAssetName); + asset = this.ApplyEditors<T>(info, asset); + data = (T)asset.Data; + } - // let mods intercept content - IContentEventHelper helper = new ContentEventHelper(cacheLocale, assetName, data, this.NormaliseAssetName); - ContentEvents.InvokeAfterAssetLoaded(this.Monitor, helper); - this.Cache[assetName] = helper.Data; - return (T)helper.Data; + // update cache & return data + this.Cache[assetName] = data; + return data; } /// <summary>Inject an asset into the cache.</summary> @@ -142,6 +149,7 @@ namespace StardewModdingAPI.Framework public void Inject<T>(string assetName, T value) { assetName = this.NormaliseAssetName(assetName); + this.Cache[assetName] = value; } @@ -151,6 +159,57 @@ namespace StardewModdingAPI.Framework return this.GetKeyLocale.Invoke<string>(); } + /// <summary>Reset the asset cache and reload the game's static assets.</summary> + /// <remarks>This implementation is derived from <see cref="Game1.LoadContent"/>.</remarks> + public void Reset() + { + this.Monitor.Log("Resetting asset cache...", LogLevel.Trace); + this.Cache.Clear(); + + // from Game1.LoadContent + Game1.daybg = this.Load<Texture2D>("LooseSprites\\daybg"); + Game1.nightbg = this.Load<Texture2D>("LooseSprites\\nightbg"); + Game1.menuTexture = this.Load<Texture2D>("Maps\\MenuTiles"); + Game1.lantern = this.Load<Texture2D>("LooseSprites\\Lighting\\lantern"); + Game1.windowLight = this.Load<Texture2D>("LooseSprites\\Lighting\\windowLight"); + Game1.sconceLight = this.Load<Texture2D>("LooseSprites\\Lighting\\sconceLight"); + Game1.cauldronLight = this.Load<Texture2D>("LooseSprites\\Lighting\\greenLight"); + Game1.indoorWindowLight = this.Load<Texture2D>("LooseSprites\\Lighting\\indoorWindowLight"); + Game1.shadowTexture = this.Load<Texture2D>("LooseSprites\\shadow"); + Game1.mouseCursors = this.Load<Texture2D>("LooseSprites\\Cursors"); + Game1.controllerMaps = this.Load<Texture2D>("LooseSprites\\ControllerMaps"); + Game1.animations = this.Load<Texture2D>("TileSheets\\animations"); + Game1.achievements = this.Load<Dictionary<int, string>>("Data\\Achievements"); + Game1.NPCGiftTastes = this.Load<Dictionary<string, string>>("Data\\NPCGiftTastes"); + Game1.dialogueFont = this.Load<SpriteFont>("Fonts\\SpriteFont1"); + Game1.smallFont = this.Load<SpriteFont>("Fonts\\SmallFont"); + Game1.tinyFont = this.Load<SpriteFont>("Fonts\\tinyFont"); + Game1.tinyFontBorder = this.Load<SpriteFont>("Fonts\\tinyFontBorder"); + Game1.objectSpriteSheet = this.Load<Texture2D>("Maps\\springobjects"); + Game1.cropSpriteSheet = this.Load<Texture2D>("TileSheets\\crops"); + Game1.emoteSpriteSheet = this.Load<Texture2D>("TileSheets\\emotes"); + Game1.debrisSpriteSheet = this.Load<Texture2D>("TileSheets\\debris"); + Game1.bigCraftableSpriteSheet = this.Load<Texture2D>("TileSheets\\Craftables"); + Game1.rainTexture = this.Load<Texture2D>("TileSheets\\rain"); + Game1.buffsIcons = this.Load<Texture2D>("TileSheets\\BuffsIcons"); + Game1.objectInformation = this.Load<Dictionary<int, string>>("Data\\ObjectInformation"); + Game1.bigCraftablesInformation = this.Load<Dictionary<int, string>>("Data\\BigCraftablesInformation"); + FarmerRenderer.hairStylesTexture = this.Load<Texture2D>("Characters\\Farmer\\hairstyles"); + FarmerRenderer.shirtsTexture = this.Load<Texture2D>("Characters\\Farmer\\shirts"); + FarmerRenderer.hatsTexture = this.Load<Texture2D>("Characters\\Farmer\\hats"); + FarmerRenderer.accessoriesTexture = this.Load<Texture2D>("Characters\\Farmer\\accessories"); + Furniture.furnitureTexture = this.Load<Texture2D>("TileSheets\\furniture"); + SpriteText.spriteTexture = this.Load<Texture2D>("LooseSprites\\font_bold"); + SpriteText.coloredTexture = this.Load<Texture2D>("LooseSprites\\font_colored"); + Tool.weaponsTexture = this.Load<Texture2D>("TileSheets\\weapons"); + Projectile.projectileSheet = this.Load<Texture2D>("TileSheets\\Projectiles"); + + // from Farmer constructor + if (Game1.player != null) + Game1.player.FarmerRenderer = new FarmerRenderer(this.Load<Texture2D>("Characters\\Farmer\\farmer_" + (Game1.player.isMale ? "" : "girl_") + "base")); + } + + /********* ** Private methods *********/ @@ -162,14 +221,151 @@ namespace StardewModdingAPI.Framework || this.Cache.ContainsKey($"{normalisedAssetName}.{this.GetKeyLocale.Invoke<string>()}"); // translated asset } - /// <summary>Get the locale for which the asset name was saved, if any.</summary> - /// <param name="normalisedAssetName">The normalised asset name.</param> - private string GetCacheLocale(string normalisedAssetName) + /// <summary>Load the initial asset from the registered <see cref="Loaders"/>.</summary> + /// <param name="info">The basic asset metadata.</param> + /// <returns>Returns the loaded asset metadata, or <c>null</c> if no loader matched.</returns> + private IAssetData ApplyLoader<T>(IAssetInfo info) + { + // find matching loaders + var loaders = this.GetInterceptors(this.Loaders) + .Where(entry => + { + try + { + return entry.Value.CanLoad<T>(info); + } + catch (Exception ex) + { + this.Monitor.Log($"{entry.Key.DisplayName} crashed when checking whether it could load asset '{info.AssetName}', and will be ignored. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); + return false; + } + }) + .ToArray(); + + // validate loaders + if (!loaders.Any()) + return null; + if (loaders.Length > 1) + { + string[] loaderNames = loaders.Select(p => p.Key.DisplayName).ToArray(); + this.Monitor.Log($"Multiple mods want to provide the '{info.AssetName}' asset ({string.Join(", ", loaderNames)}), but an asset can't be loaded multiple times. SMAPI will use the default asset instead; uninstall one of the mods to fix this. (Message for modders: you should usually use {typeof(IAssetEditor)} instead to avoid conflicts.)", LogLevel.Warn); + return null; + } + + // fetch asset from loader + IModMetadata mod = loaders[0].Key; + IAssetLoader loader = loaders[0].Value; + T data; + try + { + data = loader.Load<T>(info); + this.Monitor.Log($"{mod.DisplayName} loaded asset '{info.AssetName}'.", LogLevel.Trace); + } + catch (Exception ex) + { + this.Monitor.Log($"{mod.DisplayName} crashed when loading asset '{info.AssetName}'. SMAPI will use the default asset instead. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); + return null; + } + + // validate asset + if (data == null) + { + this.Monitor.Log($"{mod.DisplayName} incorrectly set asset '{info.AssetName}' to a null value; ignoring override.", LogLevel.Error); + return null; + } + + // return matched asset + return new AssetDataForObject(info, data, this.NormaliseAssetName); + } + + /// <summary>Apply any <see cref="Editors"/> to a loaded asset.</summary> + /// <typeparam name="T">The asset type.</typeparam> + /// <param name="info">The basic asset metadata.</param> + /// <param name="asset">The loaded asset.</param> + private IAssetData ApplyEditors<T>(IAssetInfo info, IAssetData asset) { - string locale = this.GetKeyLocale.Invoke<string>(); - return this.Cache.ContainsKey($"{normalisedAssetName}.{locale}") - ? locale - : null; + IAssetData GetNewData(object data) => new AssetDataForObject(info, data, this.NormaliseAssetName); + + // edit asset + foreach (var entry in this.GetInterceptors(this.Editors)) + { + // check for match + IModMetadata mod = entry.Key; + IAssetEditor editor = entry.Value; + try + { + if (!editor.CanEdit<T>(info)) + continue; + } + catch (Exception ex) + { + this.Monitor.Log($"{mod.DisplayName} crashed when checking whether it could edit asset '{info.AssetName}', and will be ignored. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); + continue; + } + + // try edit + object prevAsset = asset.Data; + try + { + editor.Edit<T>(asset); + this.Monitor.Log($"{mod.DisplayName} intercepted {info.AssetName}.", LogLevel.Trace); + } + catch (Exception ex) + { + this.Monitor.Log($"{mod.DisplayName} crashed when editing asset '{info.AssetName}', which may cause errors in-game. Error details:\n{ex.GetLogSummary()}", LogLevel.Error); + } + + // validate edit + if (asset.Data == null) + { + this.Monitor.Log($"{mod.DisplayName} incorrectly set asset '{info.AssetName}' to a null value; ignoring override.", LogLevel.Warn); + asset = GetNewData(prevAsset); + } + else if (!(asset.Data is T)) + { + this.Monitor.Log($"{mod.DisplayName} incorrectly set asset '{asset.AssetName}' to incompatible type '{asset.Data.GetType()}', expected '{typeof(T)}'; ignoring override.", LogLevel.Warn); + asset = GetNewData(prevAsset); + } + } + + // return result + return asset; + } + + /// <summary>Get all registered interceptors from a list.</summary> + private IEnumerable<KeyValuePair<IModMetadata, T>> GetInterceptors<T>(IDictionary<IModMetadata, IList<T>> entries) + { + foreach (var entry in entries) + { + IModMetadata metadata = entry.Key; + IList<T> interceptors = entry.Value; + + // special case if mod is an interceptor + if (metadata.Mod is T modAsInterceptor) + yield return new KeyValuePair<IModMetadata, T>(metadata, modAsInterceptor); + + // registered editors + foreach (T interceptor in interceptors) + yield return new KeyValuePair<IModMetadata, T>(metadata, interceptor); + } + } + + /// <summary>Dispose all game resources.</summary> + /// <param name="disposing">Whether the content manager is disposing (rather than finalising).</param> + protected override void Dispose(bool disposing) + { + if (!disposing) + return; + + // Clear cache & reload all assets. While that may seem perverse during disposal, it's + // necessary due to limitations in the way SMAPI currently intercepts content assets. + // + // The game uses multiple content managers while SMAPI needs one and only one. The game + // only disposes some of its content managers when returning to title, which means SMAPI + // can't know which assets are meant to be disposed. Here we remove current assets from + // the cache, but don't dispose them to avoid crashing any code that still references + // them. The garbage collector will eventually clean up any unused assets. + this.Reset(); } } } diff --git a/src/StardewModdingAPI/Framework/SGame.cs b/src/StardewModdingAPI/Framework/SGame.cs index 602a522b..c7784c60 100644 --- a/src/StardewModdingAPI/Framework/SGame.cs +++ b/src/StardewModdingAPI/Framework/SGame.cs @@ -4,11 +4,14 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Threading; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using StardewModdingAPI.Events; +using StardewModdingAPI.Framework.Reflection; +using StardewModdingAPI.Utilities; using StardewValley; using StardewValley.BellsAndWhistles; using StardewValley.Locations; @@ -29,6 +32,12 @@ namespace StardewModdingAPI.Framework /**** ** SMAPI state ****/ + /// <summary>Encapsulates monitoring and logging.</summary> + private readonly IMonitor Monitor; + + /// <summary>SMAPI's content manager.</summary> + private readonly SContentManager SContentManager; + /// <summary>The maximum number of consecutive attempts SMAPI should make to recover from a draw error.</summary> private readonly Countdown DrawCrashTimer = new Countdown(60); // 60 ticks = roughly one second @@ -48,18 +57,19 @@ namespace StardewModdingAPI.Framework /// <summary>Whether the game's zoom level is at 100% (i.e. nothing should be scaled).</summary> public bool ZoomLevelIsOne => Game1.options.zoomLevel.Equals(1.0f); - /// <summary>Encapsulates monitoring and logging.</summary> - private readonly IMonitor Monitor; /**** ** Game state ****/ - /// <summary>Arrays of pressed controller buttons indexed by <see cref="PlayerIndex"/>.</summary> - private Buttons[] PreviousPressedButtons = new Buttons[0]; + /// <summary>A record of the buttons pressed as of the previous tick.</summary> + private SButton[] PreviousPressedButtons = new SButton[0]; /// <summary>A record of the keyboard state (i.e. the up/down state for each button) as of the previous tick.</summary> private KeyboardState PreviousKeyState; + /// <summary>A record of the controller state (i.e. the up/down state for each button) as of the previous tick.</summary> + private GamePadState PreviousControllerState; + /// <summary>A record of the mouse state (i.e. the cursor position, scroll amount, and the up/down state for each button) as of the previous tick.</summary> private MouseState PreviousMouseState; @@ -108,6 +118,7 @@ namespace StardewModdingAPI.Framework /// <summary>The time of day (in 24-hour military format) at last check.</summary> private int PreviousTime; +#if !SMAPI_2_0 /// <summary>The day of month (1–28) at last check.</summary> private int PreviousDay; @@ -122,6 +133,7 @@ namespace StardewModdingAPI.Framework /// <summary>The player character at last check.</summary> private SFarmer PreviousFarmer; +#endif /// <summary>The previous content locale.</summary> private LocalizedContentManager.LanguageCode? PreviousLocale; @@ -139,7 +151,7 @@ namespace StardewModdingAPI.Framework ** Private wrappers ****/ /// <summary>Simplifies access to private game code.</summary> - private static IReflectionHelper Reflection; + private static Reflector Reflection; // ReSharper disable ArrangeStaticMemberQualifier, ArrangeThisQualifier, InconsistentNaming /// <summary>Used to access private fields and methods.</summary> @@ -173,23 +185,22 @@ namespace StardewModdingAPI.Framework /// <summary>Construct an instance.</summary> /// <param name="monitor">Encapsulates monitoring and logging.</param> /// <param name="reflection">Simplifies access to private game code.</param> - internal SGame(IMonitor monitor, IReflectionHelper reflection) + internal SGame(IMonitor monitor, Reflector reflection) { + // initialise this.Monitor = monitor; this.FirstUpdate = true; SGame.Instance = this; SGame.Reflection = reflection; - Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef; // required by Stardew Valley + // set XNA option required by Stardew Valley + Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef; - // The game uses the default content manager instead of Game1.CreateContentManager in - // several cases (See http://community.playstarbound.com/threads/130058/page-27#post-3159274). - // The workaround is... - // 1. Override the default content manager. - // 2. Since Game1.content isn't initialised yet, and we need one main instance to - // support custom map tilesheets, detect when Game1.content is being initialised - // and use the same instance. - this.Content = new SContentManager(this.Content.ServiceProvider, this.Content.RootDirectory, this.Monitor); + // override content manager + this.Monitor?.Log("Overriding content manager...", LogLevel.Trace); + this.SContentManager = new SContentManager(this.Content.ServiceProvider, this.Content.RootDirectory, Thread.CurrentThread.CurrentUICulture, null, this.Monitor); + this.Content = this.SContentManager; + Game1.content = this.SContentManager; } /**** @@ -200,13 +211,19 @@ namespace StardewModdingAPI.Framework /// <param name="rootDirectory">The root directory to search for content.</param> protected override LocalizedContentManager CreateContentManager(IServiceProvider serviceProvider, string rootDirectory) { - // When Game1.content is being initialised, use SMAPI's main content manager instance. - // See comment in SGame constructor. - if (Game1.content == null && this.Content is SContentManager mainContentManager) - return mainContentManager; + // return default if SMAPI's content manager isn't initialised yet + if (this.SContentManager == null) + { + this.Monitor?.Log("SMAPI's content manager isn't initialised; skipping content manager interception.", LogLevel.Trace); + return base.CreateContentManager(serviceProvider, rootDirectory); + } - // build new instance - return new SContentManager(this.Content.ServiceProvider, this.Content.RootDirectory, this.Monitor); + // return single instance if valid + if (serviceProvider != this.Content.ServiceProvider) + throw new InvalidOperationException("SMAPI uses a single content manager internally. You can't get a new content manager with a different service provider."); + if (rootDirectory != this.Content.RootDirectory) + throw new InvalidOperationException($"SMAPI uses a single content manager internally. You can't get a new content manager with a different root directory (current is {this.Content.RootDirectory}, requested {rootDirectory})."); + return this.SContentManager; } /// <summary>The method called when the game is updating its state. This happens roughly 60 times per second.</summary> @@ -275,7 +292,9 @@ namespace StardewModdingAPI.Framework if (this.FirstUpdate) { GameEvents.InvokeInitialize(this.Monitor); +#if !SMAPI_2_0 GameEvents.InvokeLoadContent(this.Monitor); +#endif GameEvents.InvokeGameLoaded(this.Monitor); } @@ -305,7 +324,9 @@ namespace StardewModdingAPI.Framework Context.IsWorldReady = true; SaveEvents.InvokeAfterLoad(this.Monitor); +#if !SMAPI_2_0 PlayerEvents.InvokeLoadedGame(this.Monitor, new EventArgsLoadedGameChanged(Game1.hasLoadedGame)); +#endif TimeEvents.InvokeAfterDayStarted(this.Monitor); } this.AfterLoadTimer--; @@ -334,53 +355,96 @@ namespace StardewModdingAPI.Framework if (Game1.game1.IsActive) { // get latest state - KeyboardState keyState = Keyboard.GetState(); - MouseState mouseState = Mouse.GetState(); - Point mousePosition = new Point(Game1.getMouseX(), Game1.getMouseY()); + KeyboardState keyState; + GamePadState controllerState; + MouseState mouseState; + Point mousePosition; + try + { + keyState = Keyboard.GetState(); + controllerState = GamePad.GetState(PlayerIndex.One); + mouseState = Mouse.GetState(); + mousePosition = new Point(Game1.getMouseX(), Game1.getMouseY()); + } + catch (InvalidOperationException) // GetState() may crash for some players if window doesn't have focus but game1.IsActive == true + { + keyState = this.PreviousKeyState; + controllerState = this.PreviousControllerState; + mouseState = this.PreviousMouseState; + mousePosition = this.PreviousMousePosition; + } // analyse state - Keys[] currentlyPressedKeys = keyState.GetPressedKeys(); - Keys[] previousPressedKeys = this.PreviousKeyState.GetPressedKeys(); - Keys[] framePressedKeys = currentlyPressedKeys.Except(previousPressedKeys).ToArray(); - Keys[] frameReleasedKeys = previousPressedKeys.Except(currentlyPressedKeys).ToArray(); - - // raise key pressed - foreach (Keys key in framePressedKeys) - ControlEvents.InvokeKeyPressed(this.Monitor, key); - - // raise key released - foreach (Keys key in frameReleasedKeys) - ControlEvents.InvokeKeyReleased(this.Monitor, key); + SButton[] currentlyPressedKeys = this.GetPressedButtons(keyState, mouseState, controllerState).ToArray(); + SButton[] previousPressedKeys = this.PreviousPressedButtons; + SButton[] framePressedKeys = currentlyPressedKeys.Except(previousPressedKeys).ToArray(); + SButton[] frameReleasedKeys = previousPressedKeys.Except(currentlyPressedKeys).ToArray(); + bool isClick = framePressedKeys.Contains(SButton.MouseLeft) || (framePressedKeys.Contains(SButton.ControllerA) && !currentlyPressedKeys.Contains(SButton.ControllerX)); + + // get cursor position +#if SMAPI_2_0 + ICursorPosition cursor; + { + // cursor position + Vector2 screenPixels = new Vector2(Game1.getMouseX(), Game1.getMouseY()); + Vector2 tile = new Vector2((Game1.viewport.X + screenPixels.X) / Game1.tileSize, (Game1.viewport.Y + screenPixels.Y) / Game1.tileSize); + Vector2 grabTile = (Game1.mouseCursorTransparency > 0 && Utility.tileWithinRadiusOfPlayer((int)tile.X, (int)tile.Y, 1, Game1.player)) // derived from Game1.pressActionButton + ? tile + : Game1.player.GetGrabTile(); + cursor = new CursorPosition(screenPixels, tile, grabTile); + } +#endif - // raise controller button pressed - foreach (Buttons button in this.GetFramePressedButtons()) + // raise button pressed + foreach (SButton button in framePressedKeys) { - if (button == Buttons.LeftTrigger || button == Buttons.RightTrigger) +#if SMAPI_2_0 + InputEvents.InvokeButtonPressed(this.Monitor, button, cursor, isClick); +#endif + + // legacy events + if (button.TryGetKeyboard(out Keys key)) { - var triggers = GamePad.GetState(PlayerIndex.One).Triggers; - ControlEvents.InvokeTriggerPressed(this.Monitor, button, button == Buttons.LeftTrigger ? triggers.Left : triggers.Right); + if (key != Keys.None) + ControlEvents.InvokeKeyPressed(this.Monitor, key); + } + else if (button.TryGetController(out Buttons controllerButton)) + { + if (controllerButton == Buttons.LeftTrigger || controllerButton == Buttons.RightTrigger) + ControlEvents.InvokeTriggerPressed(this.Monitor, controllerButton, controllerButton == Buttons.LeftTrigger ? controllerState.Triggers.Left : controllerState.Triggers.Right); + else + ControlEvents.InvokeButtonPressed(this.Monitor, controllerButton); } - else - ControlEvents.InvokeButtonPressed(this.Monitor, button); } - // raise controller button released - foreach (Buttons button in this.GetFrameReleasedButtons()) + // raise button released + foreach (SButton button in frameReleasedKeys) { - if (button == Buttons.LeftTrigger || button == Buttons.RightTrigger) +#if SMAPI_2_0 + bool wasClick = + (button == SButton.MouseLeft && previousPressedKeys.Contains(SButton.MouseLeft)) // released left click + || (button == SButton.ControllerA && previousPressedKeys.Contains(SButton.ControllerA) && !previousPressedKeys.Contains(SButton.ControllerX)); + InputEvents.InvokeButtonReleased(this.Monitor, button, cursor, wasClick); +#endif + + // legacy events + if (button.TryGetKeyboard(out Keys key)) { - var triggers = GamePad.GetState(PlayerIndex.One).Triggers; - ControlEvents.InvokeTriggerReleased(this.Monitor, button, button == Buttons.LeftTrigger ? triggers.Left : triggers.Right); + if (key != Keys.None) + ControlEvents.InvokeKeyReleased(this.Monitor, key); + } + else if (button.TryGetController(out Buttons controllerButton)) + { + if (controllerButton == Buttons.LeftTrigger || controllerButton == Buttons.RightTrigger) + ControlEvents.InvokeTriggerReleased(this.Monitor, controllerButton, controllerButton == Buttons.LeftTrigger ? controllerState.Triggers.Left : controllerState.Triggers.Right); + else + ControlEvents.InvokeButtonReleased(this.Monitor, controllerButton); } - else - ControlEvents.InvokeButtonReleased(this.Monitor, button); } - // raise keyboard state changed + // raise legacy state-changed events if (keyState != this.PreviousKeyState) ControlEvents.InvokeKeyboardChanged(this.Monitor, this.PreviousKeyState, keyState); - - // raise mouse state changed if (mouseState != this.PreviousMouseState) ControlEvents.InvokeMouseChanged(this.Monitor, this.PreviousMouseState, mouseState, this.PreviousMousePosition, mousePosition); @@ -388,7 +452,8 @@ namespace StardewModdingAPI.Framework this.PreviousMouseState = mouseState; this.PreviousMousePosition = mousePosition; this.PreviousKeyState = keyState; - this.PreviousPressedButtons = this.GetButtonsDown(); + this.PreviousControllerState = controllerState; + this.PreviousPressedButtons = currentlyPressedKeys; } /********* @@ -438,9 +503,11 @@ namespace StardewModdingAPI.Framework if (this.GetHash(Game1.locations) != this.PreviousGameLocations) LocationEvents.InvokeLocationsChanged(this.Monitor, Game1.locations); +#if !SMAPI_2_0 // raise player changed if (Game1.player != this.PreviousFarmer) PlayerEvents.InvokeFarmerChanged(this.Monitor, this.PreviousFarmer, Game1.player); +#endif // raise events that shouldn't be triggered on initial load if (Game1.uniqueIDForThisGame == this.PreviousSaveID) @@ -471,12 +538,14 @@ namespace StardewModdingAPI.Framework // raise time changed if (Game1.timeOfDay != this.PreviousTime) TimeEvents.InvokeTimeOfDayChanged(this.Monitor, this.PreviousTime, Game1.timeOfDay); +#if !SMAPI_2_0 if (Game1.dayOfMonth != this.PreviousDay) TimeEvents.InvokeDayOfMonthChanged(this.Monitor, this.PreviousDay, Game1.dayOfMonth); if (Game1.currentSeason != this.PreviousSeason) TimeEvents.InvokeSeasonOfYearChanged(this.Monitor, this.PreviousSeason, Game1.currentSeason); if (Game1.year != this.PreviousYear) TimeEvents.InvokeYearOfGameChanged(this.Monitor, this.PreviousYear, Game1.year); +#endif // raise mine level changed if (Game1.mine != null && Game1.mine.mineLevel != this.PreviousMineLevel) @@ -486,7 +555,6 @@ namespace StardewModdingAPI.Framework // update state this.PreviousGameLocations = this.GetHash(Game1.locations); this.PreviousGameLocation = Game1.currentLocation; - this.PreviousFarmer = Game1.player; this.PreviousCombatLevel = Game1.player.combatLevel; this.PreviousFarmingLevel = Game1.player.farmingLevel; this.PreviousFishingLevel = Game1.player.fishingLevel; @@ -496,21 +564,26 @@ namespace StardewModdingAPI.Framework this.PreviousItems = Game1.player.items.Where(n => n != null).ToDictionary(n => n, n => n.Stack); this.PreviousLocationObjects = this.GetHash(Game1.currentLocation.objects); this.PreviousTime = Game1.timeOfDay; + this.PreviousMineLevel = Game1.mine?.mineLevel ?? 0; + this.PreviousSaveID = Game1.uniqueIDForThisGame; +#if !SMAPI_2_0 + this.PreviousFarmer = Game1.player; this.PreviousDay = Game1.dayOfMonth; this.PreviousSeason = Game1.currentSeason; this.PreviousYear = Game1.year; - this.PreviousMineLevel = Game1.mine?.mineLevel ?? 0; - this.PreviousSaveID = Game1.uniqueIDForThisGame; +#endif } /********* ** Game day transition event (obsolete) *********/ +#if !SMAPI_2_0 if (Game1.newDay != this.PreviousIsNewDay) { TimeEvents.InvokeOnNewDay(this.Monitor, this.PreviousDay, Game1.dayOfMonth, Game1.newDay); this.PreviousIsNewDay = Game1.newDay; } +#endif /********* ** Game update @@ -530,7 +603,9 @@ namespace StardewModdingAPI.Framework GameEvents.InvokeUpdateTick(this.Monitor); if (this.FirstUpdate) { +#if !SMAPI_2_0 GameEvents.InvokeFirstUpdateTick(this.Monitor); +#endif this.FirstUpdate = false; } if (this.CurrentUpdateTick % 2 == 0) @@ -1270,120 +1345,66 @@ namespace StardewModdingAPI.Framework this.PreviousSaveID = 0; } - /// <summary>Get the controller buttons which are currently pressed.</summary> - private Buttons[] GetButtonsDown() - { - var state = GamePad.GetState(PlayerIndex.One); - var buttons = new List<Buttons>(); - if (state.IsConnected) - { - if (state.Buttons.A == ButtonState.Pressed) buttons.Add(Buttons.A); - if (state.Buttons.B == ButtonState.Pressed) buttons.Add(Buttons.B); - if (state.Buttons.Back == ButtonState.Pressed) buttons.Add(Buttons.Back); - if (state.Buttons.BigButton == ButtonState.Pressed) buttons.Add(Buttons.BigButton); - if (state.Buttons.LeftShoulder == ButtonState.Pressed) buttons.Add(Buttons.LeftShoulder); - if (state.Buttons.LeftStick == ButtonState.Pressed) buttons.Add(Buttons.LeftStick); - if (state.Buttons.RightShoulder == ButtonState.Pressed) buttons.Add(Buttons.RightShoulder); - if (state.Buttons.RightStick == ButtonState.Pressed) buttons.Add(Buttons.RightStick); - if (state.Buttons.Start == ButtonState.Pressed) buttons.Add(Buttons.Start); - if (state.Buttons.X == ButtonState.Pressed) buttons.Add(Buttons.X); - if (state.Buttons.Y == ButtonState.Pressed) buttons.Add(Buttons.Y); - if (state.DPad.Up == ButtonState.Pressed) buttons.Add(Buttons.DPadUp); - if (state.DPad.Down == ButtonState.Pressed) buttons.Add(Buttons.DPadDown); - if (state.DPad.Left == ButtonState.Pressed) buttons.Add(Buttons.DPadLeft); - if (state.DPad.Right == ButtonState.Pressed) buttons.Add(Buttons.DPadRight); - if (state.Triggers.Left > 0.2f) buttons.Add(Buttons.LeftTrigger); - if (state.Triggers.Right > 0.2f) buttons.Add(Buttons.RightTrigger); - } - return buttons.ToArray(); - } - - /// <summary>Get the controller buttons which were pressed after the last update.</summary> - private Buttons[] GetFramePressedButtons() + /// <summary>Get the buttons pressed in the given stats.</summary> + /// <param name="keyboard">The keyboard state.</param> + /// <param name="mouse">The mouse state.</param> + /// <param name="controller">The controller state.</param> + private IEnumerable<SButton> GetPressedButtons(KeyboardState keyboard, MouseState mouse, GamePadState controller) { - var state = GamePad.GetState(PlayerIndex.One); - var buttons = new List<Buttons>(); - if (state.IsConnected) + // keyboard + foreach (Keys key in keyboard.GetPressedKeys()) + yield return key.ToSButton(); + + // mouse + if (mouse.LeftButton == ButtonState.Pressed) + yield return SButton.MouseLeft; + if (mouse.RightButton == ButtonState.Pressed) + yield return SButton.MouseRight; + if (mouse.MiddleButton == ButtonState.Pressed) + yield return SButton.MouseMiddle; + if (mouse.XButton1 == ButtonState.Pressed) + yield return SButton.MouseX1; + if (mouse.XButton2 == ButtonState.Pressed) + yield return SButton.MouseX2; + + // controller + if (controller.IsConnected) { - if (this.WasButtonJustPressed(Buttons.A, state.Buttons.A)) buttons.Add(Buttons.A); - if (this.WasButtonJustPressed(Buttons.B, state.Buttons.B)) buttons.Add(Buttons.B); - if (this.WasButtonJustPressed(Buttons.Back, state.Buttons.Back)) buttons.Add(Buttons.Back); - if (this.WasButtonJustPressed(Buttons.BigButton, state.Buttons.BigButton)) buttons.Add(Buttons.BigButton); - if (this.WasButtonJustPressed(Buttons.LeftShoulder, state.Buttons.LeftShoulder)) buttons.Add(Buttons.LeftShoulder); - if (this.WasButtonJustPressed(Buttons.LeftStick, state.Buttons.LeftStick)) buttons.Add(Buttons.LeftStick); - if (this.WasButtonJustPressed(Buttons.RightShoulder, state.Buttons.RightShoulder)) buttons.Add(Buttons.RightShoulder); - if (this.WasButtonJustPressed(Buttons.RightStick, state.Buttons.RightStick)) buttons.Add(Buttons.RightStick); - if (this.WasButtonJustPressed(Buttons.Start, state.Buttons.Start)) buttons.Add(Buttons.Start); - if (this.WasButtonJustPressed(Buttons.X, state.Buttons.X)) buttons.Add(Buttons.X); - if (this.WasButtonJustPressed(Buttons.Y, state.Buttons.Y)) buttons.Add(Buttons.Y); - if (this.WasButtonJustPressed(Buttons.DPadUp, state.DPad.Up)) buttons.Add(Buttons.DPadUp); - if (this.WasButtonJustPressed(Buttons.DPadDown, state.DPad.Down)) buttons.Add(Buttons.DPadDown); - if (this.WasButtonJustPressed(Buttons.DPadLeft, state.DPad.Left)) buttons.Add(Buttons.DPadLeft); - if (this.WasButtonJustPressed(Buttons.DPadRight, state.DPad.Right)) buttons.Add(Buttons.DPadRight); - if (this.WasButtonJustPressed(Buttons.LeftTrigger, state.Triggers.Left)) buttons.Add(Buttons.LeftTrigger); - if (this.WasButtonJustPressed(Buttons.RightTrigger, state.Triggers.Right)) buttons.Add(Buttons.RightTrigger); + if (controller.Buttons.A == ButtonState.Pressed) + yield return SButton.ControllerA; + if (controller.Buttons.B == ButtonState.Pressed) + yield return SButton.ControllerB; + if (controller.Buttons.Back == ButtonState.Pressed) + yield return SButton.ControllerBack; + if (controller.Buttons.BigButton == ButtonState.Pressed) + yield return SButton.BigButton; + if (controller.Buttons.LeftShoulder == ButtonState.Pressed) + yield return SButton.LeftShoulder; + if (controller.Buttons.LeftStick == ButtonState.Pressed) + yield return SButton.LeftStick; + if (controller.Buttons.RightShoulder == ButtonState.Pressed) + yield return SButton.RightShoulder; + if (controller.Buttons.RightStick == ButtonState.Pressed) + yield return SButton.RightStick; + if (controller.Buttons.Start == ButtonState.Pressed) + yield return SButton.ControllerStart; + if (controller.Buttons.X == ButtonState.Pressed) + yield return SButton.ControllerX; + if (controller.Buttons.Y == ButtonState.Pressed) + yield return SButton.ControllerY; + if (controller.DPad.Up == ButtonState.Pressed) + yield return SButton.DPadUp; + if (controller.DPad.Down == ButtonState.Pressed) + yield return SButton.DPadDown; + if (controller.DPad.Left == ButtonState.Pressed) + yield return SButton.DPadLeft; + if (controller.DPad.Right == ButtonState.Pressed) + yield return SButton.DPadRight; + if (controller.Triggers.Left > 0.2f) + yield return SButton.LeftTrigger; + if (controller.Triggers.Right > 0.2f) + yield return SButton.RightTrigger; } - return buttons.ToArray(); - } - - /// <summary>Get the controller buttons which were released after the last update.</summary> - private Buttons[] GetFrameReleasedButtons() - { - var state = GamePad.GetState(PlayerIndex.One); - var buttons = new List<Buttons>(); - if (state.IsConnected) - { - if (this.WasButtonJustReleased(Buttons.A, state.Buttons.A)) buttons.Add(Buttons.A); - if (this.WasButtonJustReleased(Buttons.B, state.Buttons.B)) buttons.Add(Buttons.B); - if (this.WasButtonJustReleased(Buttons.Back, state.Buttons.Back)) buttons.Add(Buttons.Back); - if (this.WasButtonJustReleased(Buttons.BigButton, state.Buttons.BigButton)) buttons.Add(Buttons.BigButton); - if (this.WasButtonJustReleased(Buttons.LeftShoulder, state.Buttons.LeftShoulder)) buttons.Add(Buttons.LeftShoulder); - if (this.WasButtonJustReleased(Buttons.LeftStick, state.Buttons.LeftStick)) buttons.Add(Buttons.LeftStick); - if (this.WasButtonJustReleased(Buttons.RightShoulder, state.Buttons.RightShoulder)) buttons.Add(Buttons.RightShoulder); - if (this.WasButtonJustReleased(Buttons.RightStick, state.Buttons.RightStick)) buttons.Add(Buttons.RightStick); - if (this.WasButtonJustReleased(Buttons.Start, state.Buttons.Start)) buttons.Add(Buttons.Start); - if (this.WasButtonJustReleased(Buttons.X, state.Buttons.X)) buttons.Add(Buttons.X); - if (this.WasButtonJustReleased(Buttons.Y, state.Buttons.Y)) buttons.Add(Buttons.Y); - if (this.WasButtonJustReleased(Buttons.DPadUp, state.DPad.Up)) buttons.Add(Buttons.DPadUp); - if (this.WasButtonJustReleased(Buttons.DPadDown, state.DPad.Down)) buttons.Add(Buttons.DPadDown); - if (this.WasButtonJustReleased(Buttons.DPadLeft, state.DPad.Left)) buttons.Add(Buttons.DPadLeft); - if (this.WasButtonJustReleased(Buttons.DPadRight, state.DPad.Right)) buttons.Add(Buttons.DPadRight); - if (this.WasButtonJustReleased(Buttons.LeftTrigger, state.Triggers.Left)) buttons.Add(Buttons.LeftTrigger); - if (this.WasButtonJustReleased(Buttons.RightTrigger, state.Triggers.Right)) buttons.Add(Buttons.RightTrigger); - } - return buttons.ToArray(); - } - - /// <summary>Get whether a controller button was pressed since the last check.</summary> - /// <param name="button">The controller button to check.</param> - /// <param name="buttonState">The last known state.</param> - private bool WasButtonJustPressed(Buttons button, ButtonState buttonState) - { - return buttonState == ButtonState.Pressed && !this.PreviousPressedButtons.Contains(button); - } - - /// <summary>Get whether a controller button was released since the last check.</summary> - /// <param name="button">The controller button to check.</param> - /// <param name="buttonState">The last known state.</param> - private bool WasButtonJustReleased(Buttons button, ButtonState buttonState) - { - return buttonState == ButtonState.Released && this.PreviousPressedButtons.Contains(button); - } - - /// <summary>Get whether an analogue controller button was pressed since the last check.</summary> - /// <param name="button">The controller button to check.</param> - /// <param name="value">The last known value.</param> - private bool WasButtonJustPressed(Buttons button, float value) - { - return this.WasButtonJustPressed(button, value > 0.2f ? ButtonState.Pressed : ButtonState.Released); - } - - /// <summary>Get whether an analogue controller button was released since the last check.</summary> - /// <param name="button">The controller button to check.</param> - /// <param name="value">The last known value.</param> - private bool WasButtonJustReleased(Buttons button, float value) - { - return this.WasButtonJustReleased(button, value > 0.2f ? ButtonState.Pressed : ButtonState.Released); } /// <summary>Get the player inventory changes between two states.</summary> diff --git a/src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs b/src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs index 64d8738e..3193aa3c 100644 --- a/src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs +++ b/src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; using Microsoft.Xna.Framework.Input; using Newtonsoft.Json; +using StardewModdingAPI.Utilities; namespace StardewModdingAPI.Framework.Serialisation { @@ -19,7 +20,7 @@ namespace StardewModdingAPI.Framework.Serialisation ObjectCreationHandling = ObjectCreationHandling.Replace, // avoid issue where default ICollection<T> values are duplicated each time the config is loaded Converters = new List<JsonConverter> { - new SelectiveStringEnumConverter(typeof(Buttons), typeof(Keys)) + new SelectiveStringEnumConverter(typeof(Buttons), typeof(Keys), typeof(SButton)) } }; @@ -51,7 +52,21 @@ namespace StardewModdingAPI.Framework.Serialisation } // deserialise model - return JsonConvert.DeserializeObject<TModel>(json, this.JsonSettings); + try + { + return JsonConvert.DeserializeObject<TModel>(json, this.JsonSettings); + } + catch (JsonReaderException ex) + { + string message = $"The file at {fullPath} doesn't seem to be valid JSON."; + + string text = File.ReadAllText(fullPath); + if (text.Contains("“") || text.Contains("”")) + message += " Found curly quotes in the text; note that only straight quotes are allowed in JSON."; + + message += $"\nTechnical details: {ex.Message}"; + throw new JsonReaderException(message); + } } /// <summary>Save to a JSON file.</summary> diff --git a/src/StardewModdingAPI/Framework/Serialisation/ManifestFieldConverter.cs b/src/StardewModdingAPI/Framework/Serialisation/ManifestFieldConverter.cs index 6b5a6aaa..5be0f0b6 100644 --- a/src/StardewModdingAPI/Framework/Serialisation/ManifestFieldConverter.cs +++ b/src/StardewModdingAPI/Framework/Serialisation/ManifestFieldConverter.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using StardewModdingAPI.Framework.Exceptions; using StardewModdingAPI.Framework.Models; namespace StardewModdingAPI.Framework.Serialisation @@ -36,12 +37,32 @@ namespace StardewModdingAPI.Framework.Serialisation // semantic version if (objectType == typeof(ISemanticVersion)) { - JObject obj = JObject.Load(reader); - int major = obj.Value<int>(nameof(ISemanticVersion.MajorVersion)); - int minor = obj.Value<int>(nameof(ISemanticVersion.MinorVersion)); - int patch = obj.Value<int>(nameof(ISemanticVersion.PatchVersion)); - string build = obj.Value<string>(nameof(ISemanticVersion.Build)); - return new SemanticVersion(major, minor, patch, build); + JToken token = JToken.Load(reader); + switch (token.Type) + { + case JTokenType.Object: + { + JObject obj = (JObject)token; + int major = obj.Value<int>(nameof(ISemanticVersion.MajorVersion)); + int minor = obj.Value<int>(nameof(ISemanticVersion.MinorVersion)); + int patch = obj.Value<int>(nameof(ISemanticVersion.PatchVersion)); + string build = obj.Value<string>(nameof(ISemanticVersion.Build)); + return new SemanticVersion(major, minor, patch, build); + } + + case JTokenType.String: + { + string str = token.Value<string>(); + if (string.IsNullOrWhiteSpace(str)) + return null; + if (!SemanticVersion.TryParse(str, out ISemanticVersion version)) + throw new SParseException($"Can't parse semantic version from invalid value '{str}', should be formatted like 1.2, 1.2.30, or 1.2.30-beta."); + return version; + } + + default: + throw new SParseException($"Can't parse semantic version from {token.Type}, must be an object or string."); + } } // manifest dependency @@ -51,7 +72,13 @@ namespace StardewModdingAPI.Framework.Serialisation foreach (JObject obj in JArray.Load(reader).Children<JObject>()) { string uniqueID = obj.Value<string>(nameof(IManifestDependency.UniqueID)); - result.Add(new ManifestDependency(uniqueID)); + string minVersion = obj.Value<string>(nameof(IManifestDependency.MinimumVersion)); +#if SMAPI_2_0 + bool required = obj.Value<bool?>(nameof(IManifestDependency.IsRequired)) ?? true; + result.Add(new ManifestDependency(uniqueID, minVersion, required)); +#else + result.Add(new ManifestDependency(uniqueID, minVersion)); +#endif } return result.ToArray(); } |