summaryrefslogtreecommitdiff
path: root/src/StardewModdingAPI/Framework/ModHelpers
diff options
context:
space:
mode:
Diffstat (limited to 'src/StardewModdingAPI/Framework/ModHelpers')
-rw-r--r--src/StardewModdingAPI/Framework/ModHelpers/CommandHelper.cs52
-rw-r--r--src/StardewModdingAPI/Framework/ModHelpers/ContentHelper.cs351
-rw-r--r--src/StardewModdingAPI/Framework/ModHelpers/ModHelper.cs131
-rw-r--r--src/StardewModdingAPI/Framework/ModHelpers/ReflectionHelper.cs158
-rw-r--r--src/StardewModdingAPI/Framework/ModHelpers/TranslationHelper.cs138
5 files changed, 830 insertions, 0 deletions
diff --git a/src/StardewModdingAPI/Framework/ModHelpers/CommandHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/CommandHelper.cs
new file mode 100644
index 00000000..5fd56fdf
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/ModHelpers/CommandHelper.cs
@@ -0,0 +1,52 @@
+using System;
+
+namespace StardewModdingAPI.Framework.ModHelpers
+{
+ /// <summary>Provides an API for managing console commands.</summary>
+ internal class CommandHelper : ICommandHelper
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The friendly mod name for this instance.</summary>
+ private readonly string ModName;
+
+ /// <summary>Manages console commands.</summary>
+ private readonly CommandManager CommandManager;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="modName">The friendly mod name for this instance.</param>
+ /// <param name="commandManager">Manages console commands.</param>
+ public CommandHelper(string modName, CommandManager commandManager)
+ {
+ this.ModName = modName;
+ this.CommandManager = commandManager;
+ }
+
+ /// <summary>Add a console command.</summary>
+ /// <param name="name">The command name, which the user must type to trigger it.</param>
+ /// <param name="documentation">The human-readable documentation shown when the player runs the built-in 'help' command.</param>
+ /// <param name="callback">The method to invoke when the command is triggered. This method is passed the command name and arguments submitted by the user.</param>
+ /// <exception cref="ArgumentNullException">The <paramref name="name"/> or <paramref name="callback"/> is null or empty.</exception>
+ /// <exception cref="FormatException">The <paramref name="name"/> is not a valid format.</exception>
+ /// <exception cref="ArgumentException">There's already a command with that name.</exception>
+ public ICommandHelper Add(string name, string documentation, Action<string, string[]> callback)
+ {
+ this.CommandManager.Add(this.ModName, name, documentation, callback);
+ return this;
+ }
+
+ /// <summary>Trigger a command.</summary>
+ /// <param name="name">The command name.</param>
+ /// <param name="arguments">The command arguments.</param>
+ /// <returns>Returns whether a matching command was triggered.</returns>
+ public bool Trigger(string name, string[] arguments)
+ {
+ return this.CommandManager.Trigger(name, arguments);
+ }
+ }
+}
diff --git a/src/StardewModdingAPI/Framework/ModHelpers/ContentHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/ContentHelper.cs
new file mode 100644
index 00000000..4fc46dd0
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/ModHelpers/ContentHelper.cs
@@ -0,0 +1,351 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Linq;
+using Microsoft.Xna.Framework;
+using Microsoft.Xna.Framework.Content;
+using Microsoft.Xna.Framework.Graphics;
+using StardewModdingAPI.Framework.Exceptions;
+using StardewValley;
+using xTile;
+using xTile.Format;
+using xTile.Tiles;
+
+namespace StardewModdingAPI.Framework.ModHelpers
+{
+ /// <summary>Provides an API for loading content assets.</summary>
+ internal class ContentHelper : IContentHelper
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>SMAPI's underlying content manager.</summary>
+ private readonly SContentManager ContentManager;
+
+ /// <summary>The absolute path to the mod folder.</summary>
+ private readonly string ModFolderPath;
+
+ /// <summary>The path to the mod's folder, relative to the game's content folder (e.g. "../Mods/ModName").</summary>
+ private readonly string ModFolderPathFromContent;
+
+ /// <summary>The friendly mod name for use in errors.</summary>
+ private readonly string ModName;
+
+
+ /*********
+ ** 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="modName">The friendly mod name for use in errors.</param>
+ public ContentHelper(SContentManager contentManager, string modFolderPath, string modName)
+ {
+ this.ContentManager = contentManager;
+ this.ModFolderPath = modFolderPath;
+ this.ModName = modName;
+ this.ModFolderPathFromContent = this.GetRelativePath(contentManager.FullRootDirectory, modFolderPath);
+ }
+
+ /// <summary>Load content from the game folder or mod folder (if not already cached), and return it. When loading a <c>.png</c> file, this must be called outside the game's draw loop.</summary>
+ /// <typeparam name="T">The expected data type. The main supported types are <see cref="Texture2D"/> and dictionaries; other types may be supported by the game's content pipeline.</typeparam>
+ /// <param name="key">The asset key to fetch (if the <paramref name="source"/> is <see cref="ContentSource.GameContent"/>), or the local path to a content file relative to the mod folder.</param>
+ /// <param name="source">Where to search for a matching content asset.</param>
+ /// <exception cref="ArgumentException">The <paramref name="key"/> is empty or contains invalid characters.</exception>
+ /// <exception cref="ContentLoadException">The content asset couldn't be loaded (e.g. because it doesn't exist).</exception>
+ public T Load<T>(string key, ContentSource source = ContentSource.ModFolder)
+ {
+ SContentLoadException GetContentError(string reasonPhrase) => new SContentLoadException($"{this.ModName} failed loading content asset '{key}' from {source}: {reasonPhrase}.");
+
+ this.AssertValidAssetKeyFormat(key);
+ try
+ {
+ switch (source)
+ {
+ case ContentSource.GameContent:
+ return this.ContentManager.Load<T>(key);
+
+ case ContentSource.ModFolder:
+ // get file
+ FileInfo file = this.GetModFile(key);
+ if (!file.Exists)
+ throw GetContentError($"there's no matching file at path '{file.FullName}'.");
+
+ // get asset path
+ string assetPath = this.GetModAssetPath(key, file.FullName);
+
+ // try cache
+ if (this.ContentManager.IsLoaded(assetPath))
+ return this.ContentManager.Load<T>(assetPath);
+
+ // load content
+ switch (file.Extension.ToLower())
+ {
+ // XNB file
+ case ".xnb":
+ {
+ T asset = this.ContentManager.Load<T>(assetPath);
+ if (asset is Map)
+ this.FixLocalMapTilesheets(asset as Map, key);
+ return asset;
+ }
+
+ // unpacked map
+ case ".tbin":
+ {
+ // validate
+ if (typeof(T) != typeof(Map))
+ throw GetContentError($"can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Map)}'.");
+
+ // fetch & cache
+ FormatManager formatManager = FormatManager.Instance;
+ Map map = formatManager.LoadMap(file.FullName);
+ this.FixLocalMapTilesheets(map, key);
+
+ // inject map
+ this.ContentManager.Inject(assetPath, map);
+ return (T)(object)map;
+ }
+
+ // unpacked image
+ case ".png":
+ // validate
+ if (typeof(T) != typeof(Texture2D))
+ throw GetContentError($"can't read file with extension '{file.Extension}' as type '{typeof(T)}'; must be type '{typeof(Texture2D)}'.");
+
+ // fetch & cache
+ using (FileStream stream = File.OpenRead(file.FullName))
+ {
+ Texture2D texture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, stream);
+ texture = this.PremultiplyTransparency(texture);
+ this.ContentManager.Inject(assetPath, texture);
+ return (T)(object)texture;
+ }
+
+ default:
+ throw GetContentError($"unknown file extension '{file.Extension}'; must be one of '.png', '.tbin', or '.xnb'.");
+ }
+
+ default:
+ throw GetContentError($"unknown content source '{source}'.");
+ }
+ }
+ catch (Exception ex) when (!(ex is SContentLoadException))
+ {
+ throw new SContentLoadException($"{this.ModName} failed loading content asset '{key}' from {source}.", ex);
+ }
+ }
+
+ /// <summary>Get the underlying key in the game's content cache for an asset. This can be used to load custom map tilesheets, but should be avoided when you can use the content API instead. This does not validate whether the asset exists.</summary>
+ /// <param name="key">The asset key to fetch (if the <paramref name="source"/> is <see cref="ContentSource.GameContent"/>), or the local path to a content file relative to the mod folder.</param>
+ /// <param name="source">Where to search for a matching content asset.</param>
+ /// <exception cref="ArgumentException">The <paramref name="key"/> is empty or contains invalid characters.</exception>
+ public string GetActualAssetKey(string key, ContentSource source = ContentSource.ModFolder)
+ {
+ switch (source)
+ {
+ case ContentSource.GameContent:
+ return this.ContentManager.NormaliseAssetName(key);
+
+ case ContentSource.ModFolder:
+ FileInfo file = this.GetModFile(key);
+ return this.ContentManager.NormaliseAssetName(this.GetModAssetPath(key, file.FullName));
+
+ default:
+ throw new NotSupportedException($"Unknown content source '{source}'.");
+ }
+ }
+
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Fix the tilesheets for a map loaded from the mod folder.</summary>
+ /// <param name="map">The map whose tilesheets to fix.</param>
+ /// <param name="mapKey">The map asset key within the mod folder.</param>
+ /// <exception cref="ContentLoadException">The map tilesheets could not be loaded.</exception>
+ private void FixLocalMapTilesheets(Map map, string mapKey)
+ {
+ if (!map.TileSheets.Any())
+ return;
+
+ string relativeMapFolder = Path.GetDirectoryName(mapKey) ?? ""; // folder path containing the map, relative to the mod folder
+ foreach (TileSheet tilesheet in map.TileSheets)
+ {
+ // check for tilesheet relative to map
+ {
+ string localKey = Path.Combine(relativeMapFolder, tilesheet.ImageSource);
+ FileInfo localFile = this.GetModFile(localKey);
+ if (localFile.Exists)
+ {
+ try
+ {
+ this.Load<Texture2D>(localKey);
+ }
+ catch (Exception ex)
+ {
+ throw new ContentLoadException($"The local '{tilesheet.ImageSource}' tilesheet couldn't be loaded.", ex);
+ }
+ tilesheet.ImageSource = this.GetActualAssetKey(localKey);
+ continue;
+ }
+ }
+
+ // fallback to game content
+ {
+ string contentKey = tilesheet.ImageSource;
+ if (contentKey.EndsWith(".png"))
+ contentKey = contentKey.Substring(0, contentKey.Length - 4);
+ try
+ {
+ this.ContentManager.Load<Texture2D>(contentKey);
+ }
+ catch (Exception ex)
+ {
+ throw new ContentLoadException($"The '{tilesheet.ImageSource}' tilesheet couldn't be loaded relative to either map file or the game's content folder.", ex);
+ }
+ tilesheet.ImageSource = contentKey;
+ }
+ }
+ }
+
+ /// <summary>Assert that the given key has a valid format.</summary>
+ /// <param name="key">The asset key to check.</param>
+ /// <exception cref="ArgumentException">The asset key is empty or contains invalid characters.</exception>
+ [SuppressMessage("ReSharper", "UnusedParameter.Local", Justification = "Parameter is only used for assertion checks by design.")]
+ private void AssertValidAssetKeyFormat(string key)
+ {
+ if (string.IsNullOrWhiteSpace(key))
+ throw new ArgumentException("The asset key or local path is empty.");
+ if (key.Intersect(Path.GetInvalidPathChars()).Any())
+ throw new ArgumentException("The asset key or local path contains invalid characters.");
+ }
+
+ /// <summary>Get a file from the mod folder.</summary>
+ /// <param name="path">The asset path relative to the mod folder.</param>
+ private FileInfo GetModFile(string path)
+ {
+ // try exact match
+ path = Path.Combine(this.ModFolderPath, this.ContentManager.NormalisePathSeparators(path));
+ FileInfo file = new FileInfo(path);
+
+ // try with default extension
+ if (!file.Exists && file.Extension.ToLower() != ".xnb")
+ {
+ FileInfo result = new FileInfo(path + ".xnb");
+ if (result.Exists)
+ file = result;
+ }
+
+ return file;
+ }
+
+ /// <summary>Get the asset path which loads a mod folder through a content manager.</summary>
+ /// <param name="localPath">The file path relative to the mod's folder.</param>
+ /// <param name="absolutePath">The absolute file path.</param>
+ private string GetModAssetPath(string localPath, string absolutePath)
+ {
+#if SMAPI_FOR_WINDOWS
+ // XNA doesn't allow absolute asset paths, so get a path relative to the content folder
+ return Path.Combine(this.ModFolderPathFromContent, localPath);
+#else
+ // MonoGame is weird about relative paths on Mac, but allows absolute paths
+ return absolutePath;
+#endif
+ }
+
+ /// <summary>Get a directory path relative to a given root.</summary>
+ /// <param name="rootPath">The root path from which the path should be relative.</param>
+ /// <param name="targetPath">The target file path.</param>
+ private string GetRelativePath(string rootPath, string targetPath)
+ {
+ // convert to URIs
+ Uri from = new Uri(rootPath + "/");
+ Uri to = new Uri(targetPath + "/");
+ if (from.Scheme != to.Scheme)
+ throw new InvalidOperationException($"Can't get path for '{targetPath}' relative to '{rootPath}'.");
+
+ // get relative path
+ return Uri.UnescapeDataString(from.MakeRelativeUri(to).ToString())
+ .Replace(Path.DirectorySeparatorChar == '/' ? '\\' : '/', Path.DirectorySeparatorChar); // use correct separator for platform
+ }
+
+ /// <summary>Premultiply a texture's alpha values to avoid transparency issues in the game. This is only possible if the game isn't currently drawing.</summary>
+ /// <param name="texture">The texture to premultiply.</param>
+ /// <returns>Returns a premultiplied texture.</returns>
+ /// <remarks>Based on <a href="https://gist.github.com/Layoric/6255384">code by Layoric</a>.</remarks>
+ private Texture2D PremultiplyTransparency(Texture2D texture)
+ {
+ // validate
+ if (Context.IsInDrawLoop)
+ throw new NotSupportedException("Can't load a PNG file while the game is drawing to the screen. Make sure you load content outside the draw loop.");
+
+ // process texture
+ SpriteBatch spriteBatch = Game1.spriteBatch;
+ GraphicsDevice gpu = Game1.graphics.GraphicsDevice;
+ using (RenderTarget2D renderTarget = new RenderTarget2D(Game1.graphics.GraphicsDevice, texture.Width, texture.Height))
+ {
+ // create blank render target to premultiply
+ gpu.SetRenderTarget(renderTarget);
+ gpu.Clear(Color.Black);
+
+ // multiply each color by the source alpha, and write just the color values into the final texture
+ spriteBatch.Begin(SpriteSortMode.Immediate, new BlendState
+ {
+ ColorDestinationBlend = Blend.Zero,
+ ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue,
+ AlphaDestinationBlend = Blend.Zero,
+ AlphaSourceBlend = Blend.SourceAlpha,
+ ColorSourceBlend = Blend.SourceAlpha
+ });
+ spriteBatch.Draw(texture, texture.Bounds, Color.White);
+ spriteBatch.End();
+
+ // copy the alpha values from the source texture into the final one without multiplying them
+ spriteBatch.Begin(SpriteSortMode.Immediate, new BlendState
+ {
+ ColorWriteChannels = ColorWriteChannels.Alpha,
+ AlphaDestinationBlend = Blend.Zero,
+ ColorDestinationBlend = Blend.Zero,
+ AlphaSourceBlend = Blend.One,
+ ColorSourceBlend = Blend.One
+ });
+ spriteBatch.Draw(texture, texture.Bounds, Color.White);
+ spriteBatch.End();
+
+ // release GPU
+ gpu.SetRenderTarget(null);
+
+ // extract premultiplied data
+ Color[] data = new Color[texture.Width * texture.Height];
+ renderTarget.GetData(data);
+
+ // unset texture from GPU to regain control
+ gpu.Textures[0] = null;
+
+ // update texture with premultiplied data
+ texture.SetData(data);
+ }
+
+ return texture;
+ }
+ }
+}
diff --git a/src/StardewModdingAPI/Framework/ModHelpers/ModHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/ModHelper.cs
new file mode 100644
index 00000000..965a940a
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/ModHelpers/ModHelper.cs
@@ -0,0 +1,131 @@
+using System;
+using System.IO;
+using StardewModdingAPI.Framework.Serialisation;
+
+namespace StardewModdingAPI.Framework.ModHelpers
+{
+ /// <summary>Provides simplified APIs for writing mods.</summary>
+ internal class ModHelper : IModHelper, IDisposable
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>Encapsulates SMAPI's JSON file parsing.</summary>
+ private readonly JsonHelper JsonHelper;
+
+
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The full path to the mod's folder.</summary>
+ public string DirectoryPath { get; }
+
+ /// <summary>An API for loading content assets.</summary>
+ public IContentHelper Content { get; }
+
+ /// <summary>Simplifies access to private game code.</summary>
+ public IReflectionHelper Reflection { get; }
+
+ /// <summary>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> &lt; <c>pt.json</c> &lt; <c>default.json</c>).</summary>
+ public ITranslationHelper Translation { get; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="displayName">The mod's display name.</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>
+ /// <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)
+ {
+ // validate
+ 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());
+ }
+
+ /****
+ ** Mod config file
+ ****/
+ /// <summary>Read the mod's configuration file (and create it if needed).</summary>
+ /// <typeparam name="TConfig">The config class type. This should be a plain class that has public properties for the settings you want. These can be complex types.</typeparam>
+ public TConfig ReadConfig<TConfig>()
+ where TConfig : class, new()
+ {
+ TConfig config = this.ReadJsonFile<TConfig>("config.json") ?? new TConfig();
+ this.WriteConfig(config); // create file or fill in missing fields
+ return config;
+ }
+
+ /// <summary>Save to the mod's configuration file.</summary>
+ /// <typeparam name="TConfig">The config class type.</typeparam>
+ /// <param name="config">The config settings to save.</param>
+ public void WriteConfig<TConfig>(TConfig config)
+ where TConfig : class, new()
+ {
+ this.WriteJsonFile("config.json", config);
+ }
+
+ /****
+ ** Generic JSON files
+ ****/
+ /// <summary>Read a JSON file.</summary>
+ /// <typeparam name="TModel">The model type.</typeparam>
+ /// <param name="path">The file path relative to the mod directory.</param>
+ /// <returns>Returns the deserialised model, or <c>null</c> if the file doesn't exist or is empty.</returns>
+ public TModel ReadJsonFile<TModel>(string path)
+ where TModel : class
+ {
+ path = Path.Combine(this.DirectoryPath, path);
+ return this.JsonHelper.ReadJsonFile<TModel>(path);
+ }
+
+ /// <summary>Save to a JSON file.</summary>
+ /// <typeparam name="TModel">The model type.</typeparam>
+ /// <param name="path">The file path relative to the mod directory.</param>
+ /// <param name="model">The model to save.</param>
+ public void WriteJsonFile<TModel>(string path, TModel model)
+ where TModel : class
+ {
+ path = Path.Combine(this.DirectoryPath, path);
+ this.JsonHelper.WriteJsonFile(path, model);
+ }
+
+
+ /****
+ ** Disposal
+ ****/
+ /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
+ public void Dispose()
+ {
+ // nothing to dispose yet
+ }
+ }
+}
diff --git a/src/StardewModdingAPI/Framework/ModHelpers/ReflectionHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/ReflectionHelper.cs
new file mode 100644
index 00000000..5a21d999
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/ModHelpers/ReflectionHelper.cs
@@ -0,0 +1,158 @@
+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 : IReflectionHelper
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The underlying reflection helper.</summary>
+ private readonly Reflector Reflector;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="reflector">The underlying reflection helper.</param>
+ public ReflectionHelper(Reflector reflector)
+ {
+ 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/ModHelpers/TranslationHelper.cs b/src/StardewModdingAPI/Framework/ModHelpers/TranslationHelper.cs
new file mode 100644
index 00000000..86737f85
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/ModHelpers/TranslationHelper.cs
@@ -0,0 +1,138 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using StardewValley;
+
+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> &lt; <c>pt.json</c> &lt; <c>default.json</c>).</summary>
+ internal class TranslationHelper : ITranslationHelper
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The name of the relevant mod for error messages.</summary>
+ private readonly string ModName;
+
+ /// <summary>The translations for each locale.</summary>
+ private readonly IDictionary<string, IDictionary<string, string>> All = new Dictionary<string, IDictionary<string, string>>(StringComparer.InvariantCultureIgnoreCase);
+
+ /// <summary>The translations for the current locale, with locale fallback taken into account.</summary>
+ private IDictionary<string, Translation> ForLocale;
+
+
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The current locale.</summary>
+ public string Locale { get; private set; }
+
+ /// <summary>The game's current language code.</summary>
+ public LocalizedContentManager.LanguageCode LocaleEnum { get; private set; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <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)
+ {
+ // save data
+ this.ModName = modName;
+
+ // set locale
+ this.SetLocale(locale, languageCode);
+ }
+
+ /// <summary>Get all translations for the current locale.</summary>
+ public IEnumerable<Translation> GetTranslations()
+ {
+ return this.ForLocale.Values.ToArray();
+ }
+
+ /// <summary>Get a translation for the current locale.</summary>
+ /// <param name="key">The translation key.</param>
+ public Translation Get(string key)
+ {
+ this.ForLocale.TryGetValue(key, out Translation translation);
+ return translation ?? new Translation(this.ModName, this.Locale, key, null);
+ }
+
+ /// <summary>Get a translation for the current locale.</summary>
+ /// <param name="key">The translation key.</param>
+ /// <param name="tokens">An object containing token key/value pairs. This can be an anonymous object (like <c>new { value = 42, name = "Cranberries" }</c>), a dictionary, or a class instance.</param>
+ public Translation Get(string key, object tokens)
+ {
+ return this.Get(key).Tokens(tokens);
+ }
+
+ /// <summary>Set the translations to use.</summary>
+ /// <param name="translations">The translations to use.</param>
+ internal TranslationHelper SetTranslations(IDictionary<string, IDictionary<string, string>> translations)
+ {
+ // reset translations
+ this.All.Clear();
+ foreach (var pair in translations)
+ this.All[pair.Key] = new Dictionary<string, string>(pair.Value, StringComparer.InvariantCultureIgnoreCase);
+
+ // rebuild cache
+ this.SetLocale(this.Locale, this.LocaleEnum);
+
+ return this;
+ }
+
+ /// <summary>Set the current locale and precache translations.</summary>
+ /// <param name="locale">The current locale.</param>
+ /// <param name="localeEnum">The game's current language code.</param>
+ internal void SetLocale(string locale, LocalizedContentManager.LanguageCode localeEnum)
+ {
+ this.Locale = locale.ToLower().Trim();
+ this.LocaleEnum = localeEnum;
+
+ this.ForLocale = new Dictionary<string, Translation>(StringComparer.InvariantCultureIgnoreCase);
+ foreach (string next in this.GetRelevantLocales(this.Locale))
+ {
+ // skip if locale not defined
+ if (!this.All.TryGetValue(next, out IDictionary<string, string> translations))
+ continue;
+
+ // add missing translations
+ foreach (var pair in translations)
+ {
+ if (!this.ForLocale.ContainsKey(pair.Key))
+ this.ForLocale.Add(pair.Key, new Translation(this.ModName, this.Locale, pair.Key, pair.Value));
+ }
+ }
+ }
+
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Get the locales which can provide translations for the given locale, in precedence order.</summary>
+ /// <param name="locale">The locale for which to find valid locales.</param>
+ private IEnumerable<string> GetRelevantLocales(string locale)
+ {
+ // given locale
+ yield return locale;
+
+ // broader locales (like pt-BR => pt)
+ while (true)
+ {
+ int dashIndex = locale.LastIndexOf('-');
+ if (dashIndex <= 0)
+ break;
+
+ locale = locale.Substring(0, dashIndex);
+ yield return locale;
+ }
+
+ // default
+ if (locale != "default")
+ yield return "default";
+ }
+ }
+}