freya_core/
plugins.rs

1use freya_engine::prelude::{
2    Canvas,
3    FontCollection,
4};
5use freya_native_core::NodeId;
6use torin::torin::Torin;
7use winit::{
8    event_loop::EventLoopProxy,
9    window::Window,
10};
11
12use crate::{
13    dom::FreyaDOM,
14    event_loop_messages::EventLoopMessage,
15    events::PlatformEvent,
16};
17
18#[derive(Clone)]
19pub struct PluginHandle {
20    pub proxy: EventLoopProxy<EventLoopMessage>,
21}
22
23impl PluginHandle {
24    pub fn new(proxy: &EventLoopProxy<EventLoopMessage>) -> Self {
25        Self {
26            proxy: proxy.clone(),
27        }
28    }
29
30    /// Emit a [PlatformEvent]. Useful to simulate certain events.
31    pub fn send_platform_event(&self, event: PlatformEvent) {
32        self.proxy
33            .send_event(EventLoopMessage::PlatformEvent(event))
34            .ok();
35    }
36
37    /// Emit a [EventLoopMessage].
38    pub fn send_event_loop_event(&self, event: EventLoopMessage) {
39        self.proxy.send_event(event).ok();
40    }
41}
42
43/// Manages all loaded plugins.
44#[derive(Default)]
45pub struct PluginsManager {
46    plugins: Vec<Box<dyn FreyaPlugin>>,
47}
48
49impl PluginsManager {
50    pub fn add_plugin(&mut self, plugin: impl FreyaPlugin + 'static) {
51        self.plugins.push(Box::new(plugin))
52    }
53
54    pub fn send(&mut self, event: PluginEvent, handle: PluginHandle) {
55        for plugin in &mut self.plugins {
56            plugin.on_event(&event, handle.clone())
57        }
58    }
59}
60
61/// Event emitted to Plugins.
62pub enum PluginEvent<'a> {
63    /// The Window just got created.
64    WindowCreated(&'a Window),
65
66    /// Before starting to render the app to the Canvas.
67    BeforeRender {
68        canvas: &'a Canvas,
69        font_collection: &'a FontCollection,
70        freya_dom: &'a FreyaDOM,
71    },
72
73    /// After rendering the app to the Canvas.
74    AfterRender {
75        canvas: &'a Canvas,
76        font_collection: &'a FontCollection,
77        freya_dom: &'a FreyaDOM,
78    },
79
80    /// Before starting to measure the layout.
81    StartedMeasuringLayout(&'a Torin<NodeId>),
82
83    /// After measuring the layout.
84    FinishedMeasuringLayout(&'a Torin<NodeId>),
85
86    /// Before starting to process the queued events.
87    StartedMeasuringEvents,
88
89    /// After processing the queued events.
90    FinishedMeasuringEvents,
91
92    StartedUpdatingDOM,
93
94    FinishedUpdatingDOM,
95}
96
97/// Skeleton for Freya plugins.
98pub trait FreyaPlugin {
99    /// React on events emitted by Freya.
100    fn on_event(&mut self, event: &PluginEvent, handle: PluginHandle);
101}