konnektoren_core/controller/plugins/
plugin_manager.rs1use crate::controller::game_controller::GameControllerTrait;
2use crate::controller::{ControllerPlugin, ControllerPluginError};
3use std::collections::HashMap;
4use std::sync::Arc;
5
6pub struct PluginManager {
7 plugins: HashMap<String, Arc<dyn ControllerPlugin>>,
8}
9
10impl Default for PluginManager {
11 fn default() -> Self {
12 Self::new()
13 }
14}
15
16impl PluginManager {
17 pub fn new() -> Self {
18 Self {
19 plugins: HashMap::new(),
20 }
21 }
22
23 pub fn add_plugin(&mut self, plugin: Arc<dyn ControllerPlugin>) {
24 self.plugins.insert(plugin.name().to_string(), plugin);
25 }
26
27 pub fn init_plugins(&mut self) -> Result<(), ControllerPluginError> {
28 for (_, plugin) in self.plugins.iter() {
29 plugin.init()?;
30 }
31 Ok(())
32 }
33
34 pub fn load_plugins(
35 &self,
36 game_controller: &Arc<dyn GameControllerTrait>,
37 ) -> Result<(), ControllerPluginError> {
38 for plugin in self.plugins.values() {
39 plugin.load(game_controller.clone())?;
40 }
41 Ok(())
42 }
43
44 pub fn unload_plugins(
45 &self,
46 game_controller: &Arc<dyn GameControllerTrait>,
47 ) -> Result<(), ControllerPluginError> {
48 for (_, plugin) in self.plugins.iter() {
49 plugin.unload(game_controller.clone())?;
50 }
51 Ok(())
52 }
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58 use crate::controller::GameController;
59 use crate::controller::GameControllerTrait;
60 use crate::controller::plugins::controller_plugin::MockControllerPlugin;
61 use crate::game::Game;
62 use crate::persistence::MemoryPersistence;
63
64 #[test]
65 fn test_plugin_manager() {
66 let game = Game::default();
67 let persistence = Arc::new(MemoryPersistence::default());
68 let controller = GameController::new(game, persistence).init();
69
70 let mut plugin_manager = PluginManager::new();
71 let mut mocked_plugin = MockControllerPlugin::new();
72 mocked_plugin
73 .expect_name()
74 .return_const("MockedPlugin".to_string());
75 mocked_plugin.expect_init().returning(|| Ok(()));
76 mocked_plugin.expect_load().returning(|_| Ok(()));
77 mocked_plugin.expect_unload().returning(|_| Ok(()));
78 let plugin = Arc::new(mocked_plugin);
79 plugin_manager.add_plugin(plugin);
80
81 let game_controller = controller as Arc<dyn GameControllerTrait>;
82
83 assert!(plugin_manager.init_plugins().is_ok());
84 assert!(plugin_manager.load_plugins(&game_controller).is_ok());
85 assert!(plugin_manager.unload_plugins(&game_controller).is_ok());
86 }
87}