using System; using System.Collections.Generic; using System.Reflection; using System.Resources; using System.Windows.Media; using System.Windows.Media.Imaging; namespace RainmeterStudio.Resources { /// /// Manages and provides resources /// public static class ResourceProvider { /// /// Holds information about a resource manager /// private struct ResourceManagerInfo { public ResourceManager Manager; public Assembly Assembly; } private static List _resourceManagers = new List(); private static Dictionary _cacheStrings = new Dictionary(); private static Dictionary _cacheImages = new Dictionary(); /// /// Registers a resource manager /// /// The resource manager /// The assembly which will contain the non-string resources public static void RegisterManager(ResourceManager manager, Assembly ownerAssembly) { _resourceManagers.Add(new ResourceManagerInfo() { Manager = manager, Assembly = ownerAssembly }); } /// /// Gets a string from the resource managers /// /// Identifier of the resource /// By default, strings are cached. Setting this to true will bypass the cache. /// If this parameter is set to true, the obtained string will be cached. /// The string, or null if not found public static string GetString(string key, bool bypassCache = false, bool keepInCache = true) { string value = null; // Look up in cache if (bypassCache || !_cacheStrings.TryGetValue(key, out value)) { // Not found, query resource managers foreach (var info in _resourceManagers) { // Try to get resource var str = info.Manager.GetString(key); // Found? if (str != null) { value = str; if (keepInCache) _cacheStrings[key] = str; break; } } } // Resource not found return value; } /// /// Gets an image from the resource manager. /// /// Identifier of the resource /// By default, images are cached. Setting this to true will bypass the cache. /// If this parameter is set to true, the obtained image will be cached. /// The image source, or null if not found public static ImageSource GetImage(string key, bool bypassCache = false, bool keepInCache = true) { ImageSource image = null; // Look up in cache if (bypassCache || !_cacheImages.TryGetValue(key, out image)) { // Not found, query resource managers foreach (var info in _resourceManagers) { // Try to get resource var path = info.Manager.GetString(key); // Found if (path != null) { Uri fullPath = new Uri("/" + info.Assembly.GetName().Name + ";component" + path, UriKind.Relative); image = new BitmapImage(fullPath); if (keepInCache) _cacheImages[key] = image; break; } } } // Resource not found return image; } /// /// Clears the cache /// public static void ClearCache() { _cacheImages.Clear(); _cacheStrings.Clear(); } } }