using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using StardewModdingAPI.AssemblyRewriters;
using StardewModdingAPI.Framework.Content;
using StardewModdingAPI.Framework.Reflection;
using StardewValley;
namespace StardewModdingAPI.Framework
{
/// SMAPI's implementation of the game's content manager which lets it raise content events.
internal class SContentManager : LocalizedContentManager
{
/*********
** Properties
*********/
/// The possible directory separator characters in an asset key.
private static readonly char[] PossiblePathSeparators = new[] { '/', '\\', Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }.Distinct().ToArray();
/// The preferred directory separator chaeacter in an asset key.
private static readonly string PreferredPathSeparator = Path.DirectorySeparatorChar.ToString();
/// Encapsulates monitoring and logging.
private readonly IMonitor Monitor;
/// The underlying content manager's asset cache.
private readonly IDictionary Cache;
/// Applies platform-specific asset key normalisation so it's consistent with the underlying cache.
private readonly Func NormaliseAssetNameForPlatform;
/// The private method which generates the locale portion of an asset name.
private readonly IPrivateMethod GetKeyLocale;
/// The language codes used in asset keys.
private IDictionary KeyLocales;
/// The game's static asset setters by normalised asset name.
private readonly IDictionary CoreAssetSetters;
/*********
** Accessors
*********/
/// Interceptors which provide the initial versions of matching assets.
internal IDictionary> Loaders { get; } = new Dictionary>();
/// Interceptors which edit matching assets after they're loaded.
internal IDictionary> Editors { get; } = new Dictionary>();
/// The absolute path to the .
public string FullRootDirectory => Path.Combine(Constants.ExecutionPath, this.RootDirectory);
/*********
** Public methods
*********/
/// Construct an instance.
/// The service provider to use to locate services.
/// The root directory to search for content.
/// The current culture for which to localise content.
/// The current language code for which to localise content.
/// Encapsulates monitoring and logging.
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;
// get underlying fields for interception
this.Cache = reflection.GetPrivateField>(this, "loadedAssets").GetValue();
this.GetKeyLocale = reflection.GetPrivateMethod(this, "languageCode");
// get asset key normalisation logic
if (Constants.TargetPlatform == Platform.Windows)
{
IPrivateMethod method = reflection.GetPrivateMethod(typeof(TitleContainer), "GetCleanPath");
this.NormaliseAssetNameForPlatform = path => method.Invoke(path);
}
else
this.NormaliseAssetNameForPlatform = key => key.Replace('\\', '/'); // based on MonoGame's ContentManager.Load logic
// get asset key locales
this.KeyLocales = this.GetKeyLocales(reflection);
this.CoreAssetSetters = this.GetCoreAssetSetters();
}
/// Get methods to reload core game assets by normalised key.
private IDictionary GetCoreAssetSetters()
{
return Constants.GetCoreAssetSetters()
.ToDictionary>, string, Action>(
p => this.NormaliseAssetName(p.Key),
p => () => p.Value(this, p.Key)
);
}
/// Get the locale codes (like ja-JP) used in asset keys.
/// Simplifies access to private game code.
private IDictionary GetKeyLocales(Reflector reflection)
{
// get the private code field directly to avoid changed-code logic
IPrivateField codeField = reflection.GetPrivateField(typeof(LocalizedContentManager), "_currentLangCode");
// remember previous settings
LanguageCode previousCode = codeField.GetValue();
string previousOverride = this.LanguageCodeOverride;
// create locale => code map
IDictionary map = new Dictionary(StringComparer.InvariantCultureIgnoreCase);
this.LanguageCodeOverride = null;
foreach (LanguageCode code in Enum.GetValues(typeof(LanguageCode)))
{
codeField.SetValue(code);
map[this.GetKeyLocale.Invoke()] = code;
}
// restore previous settings
codeField.SetValue(previousCode);
this.LanguageCodeOverride = previousOverride;
return map;
}
/// Normalise path separators in a file path. For asset keys, see instead.
/// The file path to normalise.
public string NormalisePathSeparators(string path)
{
string[] parts = path.Split(SContentManager.PossiblePathSeparators, StringSplitOptions.RemoveEmptyEntries);
string normalised = string.Join(SContentManager.PreferredPathSeparator, parts);
if (path.StartsWith(SContentManager.PreferredPathSeparator))
normalised = SContentManager.PreferredPathSeparator + normalised; // keep root slash
return normalised;
}
/// Normalise an asset name so it's consistent with the underlying cache.
/// The asset key.
public string NormaliseAssetName(string assetName)
{
assetName = this.NormalisePathSeparators(assetName);
if (assetName.EndsWith(".xnb", StringComparison.InvariantCultureIgnoreCase))
return assetName.Substring(0, assetName.Length - 4);
return this.NormaliseAssetNameForPlatform(assetName);
}
/// Get whether the content manager has already loaded and cached the given asset.
/// The asset path relative to the loader root directory, not including the .xnb extension.
public bool IsLoaded(string assetName)
{
assetName = this.NormaliseAssetName(assetName);
return this.IsNormalisedKeyLoaded(assetName);
}
/// Load an asset that has been processed by the content pipeline.
/// The type of asset to load.
/// The asset path relative to the loader root directory, not including the .xnb extension.
public override T Load(string assetName)
{
assetName = this.NormaliseAssetName(assetName);
// skip if already loaded
if (this.IsNormalisedKeyLoaded(assetName))
return base.Load(assetName);
// load asset
T data;
{
IAssetInfo info = new AssetInfo(this.GetLocale(), assetName, typeof(T), this.NormaliseAssetName);
IAssetData asset = this.ApplyLoader(info) ?? new AssetDataForObject(info, base.Load(assetName), this.NormaliseAssetName);
asset = this.ApplyEditors(info, asset);
data = (T)asset.Data;
}
// update cache & return data
this.Cache[assetName] = data;
return data;
}
/// Inject an asset into the cache.
/// The type of asset to inject.
/// The asset path relative to the loader root directory, not including the .xnb extension.
/// The asset value.
public void Inject(string assetName, T value)
{
assetName = this.NormaliseAssetName(assetName);
this.Cache[assetName] = value;
}
/// Get the current content locale.
public string GetLocale()
{
return this.GetKeyLocale.Invoke();
}
/// Get the cached asset keys.
public IEnumerable GetAssetKeys()
{
IEnumerable GetAllAssetKeys()
{
foreach (string cacheKey in this.Cache.Keys)
{
this.ParseCacheKey(cacheKey, out string assetKey, out string _);
yield return assetKey;
}
}
return GetAllAssetKeys().Distinct();
}
/// Reset the asset cache and reload the game's static assets.
/// Matches the asset keys to invalidate.
/// Returns whether any cache entries were invalidated.
/// This implementation is derived from .
public bool InvalidateCache(Func predicate)
{
// find matching asset keys
HashSet purgeCacheKeys = new HashSet(StringComparer.InvariantCultureIgnoreCase);
HashSet purgeAssetKeys = new HashSet(StringComparer.InvariantCultureIgnoreCase);
foreach (string cacheKey in this.Cache.Keys)
{
this.ParseCacheKey(cacheKey, out string assetKey, out string localeCode);
Type type = this.Cache[cacheKey].GetType();
if (predicate(assetKey, type))
{
purgeAssetKeys.Add(assetKey);
purgeCacheKeys.Add(cacheKey);
}
}
// purge from cache
foreach (string key in purgeCacheKeys)
this.Cache.Remove(key);
// reload core game assets
int reloaded = 0;
foreach (string key in purgeAssetKeys)
{
if (this.CoreAssetSetters.TryGetValue(key, out Action reloadAsset))
{
reloadAsset();
reloaded++;
}
}
// report result
if (purgeCacheKeys.Any())
{
this.Monitor.Log($"Invalidated {purgeCacheKeys.Count} cache entries for {purgeAssetKeys.Count} asset keys: {string.Join(", ", purgeCacheKeys.OrderBy(p => p, StringComparer.InvariantCultureIgnoreCase))}. Reloaded {reloaded} core assets.", LogLevel.Trace);
return true;
}
this.Monitor.Log("Invalidated 0 cache entries.", LogLevel.Trace);
return false;
}
/*********
** Private methods
*********/
/// Get whether an asset has already been loaded.
/// The normalised asset name.
private bool IsNormalisedKeyLoaded(string normalisedAssetName)
{
return this.Cache.ContainsKey(normalisedAssetName)
|| this.Cache.ContainsKey($"{normalisedAssetName}.{this.GetKeyLocale.Invoke()}"); // translated asset
}
/// Parse a cache key into its component parts.
/// The input cache key.
/// The original asset key.
/// The asset locale code (or null if not localised).
private void ParseCacheKey(string cacheKey, out string assetKey, out string localeCode)
{
// handle localised key
if (!string.IsNullOrWhiteSpace(cacheKey))
{
int lastSepIndex = cacheKey.LastIndexOf(".", StringComparison.InvariantCulture);
if (lastSepIndex >= 0)
{
string suffix = cacheKey.Substring(lastSepIndex + 1, cacheKey.Length - lastSepIndex - 1);
if (this.KeyLocales.ContainsKey(suffix))
{
assetKey = cacheKey.Substring(0, lastSepIndex);
localeCode = cacheKey.Substring(lastSepIndex + 1, cacheKey.Length - lastSepIndex - 1);
return;
}
}
}
// handle simple key
assetKey = cacheKey;
localeCode = null;
}
/// Load the initial asset from the registered .
/// The basic asset metadata.
/// Returns the loaded asset metadata, or null if no loader matched.
private IAssetData ApplyLoader(IAssetInfo info)
{
// find matching loaders
var loaders = this.GetInterceptors(this.Loaders)
.Where(entry =>
{
try
{
return entry.Value.CanLoad(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(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);
}
/// Apply any to a loaded asset.
/// The asset type.
/// The basic asset metadata.
/// The loaded asset.
private IAssetData ApplyEditors(IAssetInfo info, IAssetData asset)
{
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(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(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;
}
/// Get all registered interceptors from a list.
private IEnumerable> GetInterceptors(IDictionary> entries)
{
foreach (var entry in entries)
{
IModMetadata metadata = entry.Key;
IList interceptors = entry.Value;
// special case if mod is an interceptor
if (metadata.Mod is T modAsInterceptor)
yield return new KeyValuePair(metadata, modAsInterceptor);
// registered editors
foreach (T interceptor in interceptors)
yield return new KeyValuePair(metadata, interceptor);
}
}
/// Dispose all game resources.
/// Whether the content manager is disposing (rather than finalising).
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.Monitor.Log("Content manager disposed, resetting cache.", LogLevel.Trace);
this.InvalidateCache((key, type) => true);
}
}
}