budnhead/org.budnhead/tools/ResourceLibrary.cs

90 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using org.hwo.contracts;
namespace org.budnhead.tools
{
public static class ResourceLibrary
{
static Dictionary<Type,Dictionary<string,object>>
resourceTypes = new Dictionary<Type, Dictionary<string, object>>();
static List<string>
resourcePaths = new List<string>(new string[]{"."});
static Dictionary<Type,string> prefixes = new Dictionary<Type, string>();
static Dictionary<Type,string> suffixes = new Dictionary<Type, string>();
internal static bool initializeResourceType(Type t,string prefix,string suffix,bool initializeBases){
ConstructorInfo ci = null;
new BooleanConditional()
.requiresValid(ref ci,delegate { return t.GetConstructor(new Type[]{ typeof(Stream) }); })
.does( delegate { initializeResourceType(t,prefix,suffix); } );
if (initializeBases && (t.BaseType != null)){
initializeResourceType(t.BaseType,prefix,suffix,true);
}
return true;
}
internal static bool initializeResourceType(Type t,string prefix,string suffix){
if (prefix != null)
prefixes.Add(t,prefix);
if (suffix != null)
suffixes.Add(t,suffix);
return true;
}
static T findLoadedInstance<T>(string name){
if (resourceTypes.ContainsKey(typeof(T))){
if (resourceTypes[typeof(T)].ContainsKey(name)){
return (T)resourceTypes[typeof(T)][name];
}
}
throw new KeyNotFoundException("");
}
public static void cacheInstance<T>(string name,T instance){
if (!resourceTypes.ContainsKey(typeof(T))){
resourceTypes.Add(typeof(T),new Dictionary<string, object>());
}
resourceTypes[typeof(T)].Add(name,instance);
}
public static T getResource<T>(string name){
try {
return findLoadedInstance<T>(name);
} catch (KeyNotFoundException){
string p="",s="";
if (prefixes.ContainsKey(typeof(T))){
p = prefixes[typeof(T)];
}
if (suffixes.ContainsKey(typeof(T))){
s = suffixes[typeof(T)];
}
string resFileName = FileHelper.findFile(String.Format("{0}{1}{2}",p,name,s),resourcePaths.ToArray());
if (resFileName != null){
Stream resStream = new FileStream(resFileName,FileMode.Open);
ConstructorInfo ci = typeof(T).GetConstructor(new Type[]{ typeof(Stream) });
T o = (T)ci.Invoke(new object[]{ resStream });
cacheInstance(name,o);
return o;
}
throw new KeyNotFoundException(String.Format("ResourceLibrary[{0}:{1}]",typeof(T).ToString(),name));
}
}
}
}