2018-05-13 19:49:26 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.IO;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Reflection;
|
|
|
|
|
|
|
|
|
|
namespace PKHeX.WinForms
|
|
|
|
|
{
|
|
|
|
|
public static class PluginLoader
|
|
|
|
|
{
|
|
|
|
|
public static IEnumerable<T> LoadPlugins<T>(string pluginPath)
|
|
|
|
|
{
|
|
|
|
|
var dllFileNames = Directory.EnumerateFiles(pluginPath, "*.dll", SearchOption.AllDirectories);
|
|
|
|
|
var assemblies = GetAssemblies(dllFileNames);
|
|
|
|
|
var pluginTypes = GetPluginsOfType<T>(assemblies);
|
|
|
|
|
return LoadPlugins<T>(pluginTypes);
|
|
|
|
|
}
|
|
|
|
|
private static IEnumerable<T> LoadPlugins<T>(IEnumerable<Type> pluginTypes)
|
|
|
|
|
{
|
|
|
|
|
return pluginTypes.Select(type => (T)Activator.CreateInstance(type));
|
|
|
|
|
}
|
|
|
|
|
private static IEnumerable<Assembly> GetAssemblies(IEnumerable<string> dllFileNames)
|
|
|
|
|
{
|
2018-05-16 03:16:57 +00:00
|
|
|
|
#if UNSAFEDLL
|
|
|
|
|
return dllFileNames.Select(Assembly.UnsafeLoadFrom);
|
|
|
|
|
#else
|
|
|
|
|
return dllFileNames.Select(Assembly.LoadFrom);
|
|
|
|
|
#endif
|
2018-05-13 19:49:26 +00:00
|
|
|
|
}
|
|
|
|
|
private static IEnumerable<Type> GetPluginsOfType<T>(IEnumerable<Assembly> assemblies)
|
|
|
|
|
{
|
|
|
|
|
var pluginType = typeof(T);
|
2018-05-15 00:30:56 +00:00
|
|
|
|
foreach (var z in assemblies.Where(z => z != null))
|
2018-05-13 19:49:26 +00:00
|
|
|
|
{
|
2018-05-15 00:30:56 +00:00
|
|
|
|
Type[] types; try { types = z.GetTypes(); }
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
Console.WriteLine($"Unable to load plugin [{pluginType.Name}]: {z.FullName}", ex.Message);
|
2018-05-13 19:49:26 +00:00
|
|
|
|
continue;
|
2018-05-15 00:30:56 +00:00
|
|
|
|
}
|
|
|
|
|
foreach (Type type in types)
|
|
|
|
|
{
|
|
|
|
|
if (type.IsInterface || type.IsAbstract)
|
|
|
|
|
continue;
|
|
|
|
|
if (type.GetInterface(pluginType.FullName) == null)
|
|
|
|
|
continue;
|
|
|
|
|
yield return type;
|
|
|
|
|
}
|
2018-05-13 19:49:26 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|