1 /**
2 Copyright: Copyright (c) 2015-2016 Andrey Penechko.
3 License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
4 Authors: Andrey Penechko.
5 */
6 
7 module pluginlib.pluginmanager;
8 
9 import std.experimental.logger;
10 import std.string : format;
11 import pluginlib;
12 
13 class PluginManager : IPluginManager, IResourceManagerRegistry
14 {
15 	IPlugin[TypeInfo] plugins;
16 	IPlugin[string] pluginsById;
17 	IResourceManager[TypeInfo] resourceManagers;
18 
19 	void registerPlugin(IPlugin pluginInstance)
20 	{
21 		assert(pluginInstance);
22 		assert(
23 			typeid(pluginInstance) !in plugins &&
24 			pluginInstance.id !in pluginsById,
25 			format("Duplicate plugin registered: id=\"%s\" type=\"%s\"",
26 				pluginInstance.id, pluginInstance));
27 		plugins[typeid(pluginInstance)] = pluginInstance;
28 		pluginsById[pluginInstance.id] = pluginInstance;
29 	}
30 
31 	void registerResourceManager(IResourceManager rmInstance)
32 	{
33 		assert(rmInstance);
34 		assert(typeid(rmInstance) !in resourceManagers,
35 			format("Duplicate resource manager registered: id=\"%s\" type=\"%s\"",
36 				rmInstance.id, rmInstance));
37 		resourceManagers[typeid(rmInstance)] = rmInstance;
38 	}
39 
40 	// IPluginManager
41 	IPlugin findPlugin(TypeInfo pluginType)
42 	{
43 		return plugins.get(pluginType, null);
44 	}
45 
46 	IPlugin findPluginById(string pluginId)
47 	{
48 		return pluginsById.get(pluginId, null);
49 	}
50 
51 
52 	// IResourceManagerRegistry
53 	IResourceManager findResourceManager(TypeInfo rmType)
54 	{
55 		return resourceManagers.get(rmType, null);
56 	}
57 
58 	void initPlugins()
59 	{
60 		// Register resources
61 		foreach(IPlugin p; plugins)
62 		{
63 			p.registerResourceManagers(&registerResourceManager);
64 		}
65 
66 		foreach(IResourceManager rm; resourceManagers)
67 		{
68 			rm.preInit();
69 		}
70 		foreach(IResourceManager rm; resourceManagers)
71 		{
72 			rm.init(this);
73 		}
74 
75 		foreach(IPlugin p; plugins)
76 		{
77 			p.registerResources(this);
78 		}
79 
80 		// Load resources
81 		foreach(IResourceManager rm; resourceManagers)
82 		{
83 			rm.loadResources();
84 		}
85 		foreach(IResourceManager rm; resourceManagers)
86 		{
87 			rm.postInit();
88 		}
89 
90 		// Load plugins
91 		foreach(IPlugin p; plugins)
92 		{
93 			p.preInit();
94 		}
95 		foreach(IPlugin p; plugins)
96 		{
97 			p.init(this);
98 		}
99 
100 		foreach(IPlugin p; plugins)
101 		{
102 			p.postInit();
103 		}
104 
105 		size_t i = 1;
106 		infof("Loaded %s plugins", plugins.length);
107 		foreach(IPlugin p; plugins)
108 		{
109 			infof("Loaded #%s %s %s", i, p.id, p.semver);
110 			++i;
111 		}
112 	}
113 }