1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
//! Plugin API for loading dynamic library files

use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs;
use std::hash::Hasher;
use std::path::Path;
use std::sync::Arc;
use dlopen::Error;
use crate::modules::{ModuleManager, PluginMetadata, SDModule, UniqueSDModule};
use dlopen::wrapper::{Container, WrapperApi};
use dlopen_derive::WrapperApi;
use image::DynamicImage;
use crate::core::button::Button;
use crate::core::manager::CoreManager;
use crate::core::{check_feature_list_for_feature, CoreHandle, UniqueButton, warn_for_feature};
use crate::modules::components::{ComponentDefinition, UIValue};
use crate::modules::events::{SDCoreEvent, SDGlobalEvent};
use crate::RenderingManager;
use crate::socket::SocketManager;
use crate::versions::SUPPORTED_FEATURES;

#[derive(WrapperApi)]
struct PluginApi {
    get_metadata: extern fn() -> PluginMetadata,
    register: extern fn(socket_manager: Arc<SocketManager>, render_manager: Arc<RenderingManager>, module_manager: Arc<PluginModuleManager>),
}

#[allow(dead_code)]
struct PluginProxy {
    pub wrapper: Arc<Container<PluginApi>>,
    pub metadata: PluginMetadata,
    pub plugin: UniqueSDModule
}

impl SDModule for PluginProxy {
    fn name(&self) -> String {
        self.plugin.name()
    }

    fn components(&self) -> HashMap<String, ComponentDefinition> {
        self.plugin.components()
    }

    fn add_component(&self, core: CoreHandle, button: &mut Button, name: &str) {
        self.plugin.add_component(core, button, name)
    }

    fn remove_component(&self, core: CoreHandle, button: &mut Button, name: &str) {
        self.plugin.remove_component(core, button, name)
    }

    fn paste_component(&self, core: CoreHandle, reference_button: &Button, new_button: &mut Button) {
        self.plugin.paste_component(core, reference_button, new_button)
    }

    fn component_values(&self, core: CoreHandle, button: &Button, name: &str) -> Vec<UIValue> {
        self.plugin.component_values(core, button, name)
    }

    fn set_component_value(&self, core: CoreHandle, button: &mut Button, name: &str, value: Vec<UIValue>) {
        self.plugin.set_component_value(core, button, name, value)
    }

    fn listening_for(&self) -> Vec<String> {
        self.plugin.listening_for()
    }

    fn settings(&self, core: Arc<CoreManager>) -> Vec<UIValue> {
        self.plugin.settings(core)
    }

    fn set_setting(&self, core: Arc<CoreManager>, value: Vec<UIValue>) {
        self.plugin.set_setting(core, value)
    }

    fn global_event(&self, event: SDGlobalEvent) {
        if check_feature_list_for_feature(&self.metadata.used_features, "global_events") {
            self.plugin.global_event(event)
        }
    }

    fn event(&self, core: CoreHandle, event: SDCoreEvent) {
        if core.check_for_feature("core_events") {
            self.plugin.event(core, event)
        }
    }

    fn render(&self, core: CoreHandle, button: &UniqueButton, frame: &mut DynamicImage) {
        if core.check_for_feature("rendering") {
            self.plugin.render(core, button, frame)
        }
    }

    fn render_hash(&self, core: CoreHandle, button: &UniqueButton, hash: &mut Box<dyn Hasher>) {
        if core.check_for_feature("rendering") {
            self.plugin.render_hash(core, button, hash)
        }
    }

    fn metadata(&self) -> PluginMetadata {
        self.metadata.clone()
    }
}

/// Wrapper of module manager for plugin initialization to use
pub struct PluginModuleManager {
    module_manager: Arc<ModuleManager>,
    metadata: PluginMetadata,
    wrapper: Arc<Container<PluginApi>>,
}

impl PluginModuleManager {
    pub fn add_module(&self, module: UniqueSDModule) -> Result<(), PluginError> {
        for component in module.components().keys() {
            if self.module_manager.get_component(component).is_some() {
                return Err(PluginError::ComponentConflict(module.name(), component.to_string()))
            }
        }

        self.module_manager.add_module(Arc::new(PluginProxy {
            wrapper: self.wrapper.clone(),
            metadata: self.metadata.clone(),
            plugin: module
        }));

        Ok(())
    }
}

/// Returns error if plugin is incompatible
pub fn compare_plugin_versions(versions: &Vec<(String, String)>) -> Result<(), PluginError> {
    let core_versions = SUPPORTED_FEATURES.clone().into_iter()
        .map(|(n, v)| (*n, *v))
        .collect::<HashMap<&str, &str>>();

    for (name, version) in versions {
        if let Some(software_version) = core_versions.get(name.as_str()) {
            if software_version != version {
                return Err(PluginError::WrongVersion(format!("{} {}", name, version), format!("{} {}", name, software_version)))
            }
        } else {
            return Err(PluginError::TooNew(format!("{} {}", name, version)))
        }
    }

    Ok(())
}

/// Warns about essential features
fn warn_about_essential_features(meta: &PluginMetadata) {
    let name = &meta.name;
    let features = &meta.used_features;

    warn_for_feature(name, &features, "plugin_api");
    warn_for_feature(name, &features, "sdmodule_trait");
}

/// Loads a plugin into module manager
pub fn load_plugin<T: AsRef<OsStr>>(module_manager: Arc<ModuleManager>, socket_manager: Arc<SocketManager>, render_manager: Arc<RenderingManager>, path: T) -> Result<(), PluginError> {
    // Loading file as a library, error if cannot load
    let wrapper: Container<PluginApi> = unsafe { Container::load(path) }?;

    let wrapper = Arc::new(wrapper);

    // Retrieving metadata and comparing versions
    let metadata = wrapper.get_metadata();
    compare_plugin_versions(&metadata.used_features)?;

    // Warn plugin if metadata doesn't contain essential plugins
    warn_about_essential_features(&metadata);

    // Adding module if it wasn't defined before
    if module_manager.get_module(&metadata.name).is_none() {
        let plugin_manager = Arc::new(PluginModuleManager {
            module_manager,
            metadata: metadata.clone(),
            wrapper
        });

        // Calling register after all checks were done
        plugin_manager.wrapper.register(socket_manager, render_manager, plugin_manager.clone());

        Ok(())
    } else {
        Err(PluginError::AlreadyExists(metadata.name))
    }
}

/// Loads plugins into module manager from path
pub fn load_plugins_from_folder<T: AsRef<OsStr>>(module_manager: Arc<ModuleManager>, socket_manager: Arc<SocketManager>, render_manager: Arc<RenderingManager>, path: T) {
    let path = Path::new(&path);
    match fs::read_dir(path) {
        Ok(read_dir) => {
            for item in read_dir {
                match item {
                    Ok(entry) => {
                        if entry.path().is_file() {
                            if let Some(file_name) = entry.path().file_name() {
                                log::info!("Loading plugin {:?}", file_name);
                                match load_plugin(module_manager.clone(), socket_manager.clone(), render_manager.clone(), entry.path()) {
                                    Err(err) => match err {
                                        PluginError::LoadError(err) => log::error!("Failed to load plugin: {}", err),
                                        PluginError::WrongVersion(plugin, software) => log::error!("Failed to load plugin: Plugin is using unsupported version of '{}', software's using '{}'", plugin, software),
                                        PluginError::TooNew(version) => log::error!("Failed to load plugin: Software doesn't support '{}', try updating the software", version),
                                        PluginError::AlreadyExists(name) => log::error!("Failed to load plugin: Module '{}' was already defined", name),
                                        PluginError::ComponentConflict(name, component_name) => log::error!("Failed to load plugin: Module '{}' is declaring '{}' component, but it was already previously declared by other module", name, component_name),
                                    },
                                    _ => {}
                                }
                            }
                        }
                    }
                    Err(err) => log::error!("Failed to reach entry. {}", err),
                }
            }
        }
        Err(e) => {
            if let std::io::ErrorKind::NotFound = e.kind() {
                log::info!("Loaded no plugins, missing plugins folder")
            } else {
                log::error!("Plugins folder is unreachable: {:?}", path);
            }
        }
    }
}

/// Enum for anything wrong that might happen during plugin loading
#[derive(Debug)]
pub enum PluginError {
    LoadError(dlopen::Error),
    WrongVersion(String, String),
    TooNew(String),
    AlreadyExists(String),
    ComponentConflict(String, String),
}

impl From<dlopen::Error> for PluginError {
    fn from(err: Error) -> Self {
        PluginError::LoadError(err)
    }
}