using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using StardewModdingAPI.Framework.Content; using StardewModdingAPI.Framework.ModLoading; using StardewModdingAPI.Framework.Reflection; using StardewModdingAPI.Framework.Utilities; using StardewModdingAPI.Metadata; 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 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 readonly IDictionary KeyLocales; /// Provides metadata for core game assets. private readonly CoreAssets CoreAssets; /// The assets currently being intercepted by instances. This is used to prevent infinite loops when a loader loads a new asset. private readonly ContextHash AssetsBeingLoaded = new ContextHash(); /// A lookup of the content managers which loaded each asset. private readonly IDictionary> AssetLoaders = new Dictionary>(); /// An object locked to prevent concurrent changes to the underlying assets. private readonly object Lock = new object(); /********* ** 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 possible directory separator characters in an asset key. internal static readonly char[] PossiblePathSeparators = new[] { '/', '\\', Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }.Distinct().ToArray(); /// The absolute path to the . internal 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 data this.CoreAssets = new CoreAssets(this.NormaliseAssetName); this.KeyLocales = this.GetKeyLocales(reflection); } /// 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) { lock (this.Lock) { 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) { return this.LoadFor(assetName, this); } /// 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. /// The content manager instance for which to load the asset. public T LoadFor(string assetName, ContentManager instance) { lock (this.Lock) { assetName = this.NormaliseAssetName(assetName); // skip if already loaded if (this.IsNormalisedKeyLoaded(assetName)) { this.TrackAssetLoader(assetName, instance); return base.Load(assetName); } // load asset T data; if (this.AssetsBeingLoaded.Contains(assetName)) { this.Monitor.Log($"Broke loop while loading asset '{assetName}'.", LogLevel.Warn); this.Monitor.Log($"Bypassing mod loaders for this asset. Stack trace:\n{Environment.StackTrace}", LogLevel.Trace); data = base.Load(assetName); } else { data = this.AssetsBeingLoaded.Track(assetName, () => { 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); return (T)asset.Data; }); } // update cache & return data this.Cache[assetName] = data; this.TrackAssetLoader(assetName, instance); 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) { lock (this.Lock) { assetName = this.NormaliseAssetName(assetName); this.Cache[assetName] = value; this.TrackAssetLoader(assetName, this); } } /// Get the current content locale. public string GetLocale() { return this.GetKeyLocale.Invoke(); } /// Get the cached asset keys. public IEnumerable GetAssetKeys() { lock (this.Lock) { IEnumerable GetAllAssetKeys() { foreach (string cacheKey in this.Cache.Keys) { this.ParseCacheKey(cacheKey, out string assetKey, out string _); yield return assetKey; } } return GetAllAssetKeys().Distinct(); } } /// Purge assets from the cache that match one of the interceptors. /// The asset editors for which to purge matching assets. /// The asset loaders for which to purge matching assets. /// Returns whether any cache entries were invalidated. public bool InvalidateCacheFor(IAssetEditor[] editors, IAssetLoader[] loaders) { if (!editors.Any() && !loaders.Any()) return false; // get CanEdit/Load methods MethodInfo canEdit = typeof(IAssetEditor).GetMethod(nameof(IAssetEditor.CanEdit)); MethodInfo canLoad = typeof(IAssetLoader).GetMethod(nameof(IAssetLoader.CanLoad)); // invalidate matching keys return this.InvalidateCache((assetName, assetType) => { // get asset metadata IAssetInfo info = new AssetInfo(this.GetLocale(), assetName, assetType, this.NormaliseAssetName); // check loaders MethodInfo canLoadGeneric = canLoad.MakeGenericMethod(assetType); if (loaders.Any(loader => (bool)canLoadGeneric.Invoke(loader, new object[] { info }))) return true; // check editors MethodInfo canEditGeneric = canEdit.MakeGenericMethod(assetType); return editors.Any(editor => (bool)canEditGeneric.Invoke(editor, new object[] { info })); }); } /// Purge matched assets from the cache. /// Matches the asset keys to invalidate. /// Whether to dispose invalidated assets. This should only be true when they're being invalidated as part of a dispose, to avoid crashing the game. /// Returns whether any cache entries were invalidated. public bool InvalidateCache(Func predicate, bool dispose = false) { lock (this.Lock) { // 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 _); Type type = this.Cache[cacheKey].GetType(); if (predicate(assetKey, type)) { purgeAssetKeys.Add(assetKey); purgeCacheKeys.Add(cacheKey); } } // purge assets foreach (string key in purgeCacheKeys) { if (dispose && this.Cache[key] is IDisposable disposable) disposable.Dispose(); this.Cache.Remove(key); this.AssetLoaders.Remove(key); } // reload core game assets int reloaded = 0; foreach (string key in purgeAssetKeys) { if (this.CoreAssets.ReloadForKey(this, key)) 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; } } /// Dispose assets for the given content manager shim. /// The content manager whose assets to dispose. internal void DisposeFor(ContentManagerShim shim) { this.Monitor.Log($"Content manager '{shim.Name}' disposed, disposing assets that aren't needed by any other asset loader.", LogLevel.Trace); foreach (var entry in this.AssetLoaders) entry.Value.Remove(shim); this.InvalidateCache((key, type) => !this.AssetLoaders[key].Any(), dispose: true); } /********* ** 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 } /// Track that a content manager loaded an asset. /// The asset key that was loaded. /// The content manager that loaded the asset. private void TrackAssetLoader(string key, ContentManager manager) { if (!this.AssetLoaders.TryGetValue(key, out HashSet hash)) hash = this.AssetLoaders[key] = new HashSet(); hash.Add(manager); } /// 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; } /// 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 held resources. /// Whether the content manager is disposing (rather than finalising). protected override void Dispose(bool disposing) { this.Monitor.Log("Disposing SMAPI's main content manager. It will no longer be usable after this point.", LogLevel.Trace); base.Dispose(disposing); } } }