Skip to main content

egui_pop_api/
hooks.rs

1//! Hooks: synchronous `alter` hooks over declarations (menus, the palette,
2//! settings), run when the application is built or a plugin comes or
3//! goes, never per frame; and lifecycle events.
4
5use std::fmt;
6
7use egui_pop_model::ids::{CommandId, HookId, MenuId, OwnerId, SettingId};
8use egui_pop_model::menus::MenuItem;
9use egui_pop_model::values::Descriptor;
10use serde::Serialize;
11
12use crate::app::AppHandle;
13
14/// A palette entry, derived from a command.
15#[derive(Clone, Debug, PartialEq, Serialize)]
16pub struct PaletteEntry {
17    pub command: CommandId,
18    pub title: String,
19    pub category: String,
20    /// Its keys as shown (`Ctrl+K Ctrl+S`).
21    pub keys: Vec<String>,
22}
23
24/// A setting as the settings form shows it.
25#[derive(Clone, Debug, PartialEq, Serialize)]
26pub struct SettingEntry {
27    pub id: SettingId,
28    /// Its path in the value store (`settings/<id>`).
29    pub path: String,
30    pub owner: OwnerId,
31    /// A section title (the owner's, unless a hook changes it).
32    pub section: String,
33    pub descriptor: Descriptor,
34}
35
36/// A function altering a list of declarations.
37pub type AlterFn<T> = Box<dyn Fn(&mut Vec<T>)>;
38
39/// What a hook alters.
40pub enum Alter {
41    Menu(MenuId, AlterFn<MenuItem>),
42    Palette(AlterFn<PaletteEntry>),
43    Settings(AlterFn<SettingEntry>),
44}
45
46impl fmt::Debug for Alter {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        match self {
49            Alter::Menu(m, _) => write!(f, "Menu({m})"),
50            Alter::Palette(_) => write!(f, "Palette"),
51            Alter::Settings(_) => write!(f, "Settings"),
52        }
53    }
54}
55
56/// An alter hook: an id, what it alters, a priority (higher first) and
57/// the hooks it must run after.
58#[derive(Debug)]
59pub struct Hook {
60    pub id: HookId,
61    pub alter: Alter,
62    pub priority: i32,
63    pub after: Vec<HookId>,
64}
65
66impl Hook {
67    /// Alters a menu's items (order, removal, additions).
68    pub fn menu(id: HookId, menu: MenuId, f: impl Fn(&mut Vec<MenuItem>) + 'static) -> Hook {
69        Hook {
70            id,
71            alter: Alter::Menu(menu, Box::new(f)),
72            priority: 0,
73            after: Vec::new(),
74        }
75    }
76
77    /// Alters the palette's entries.
78    pub fn palette(id: HookId, f: impl Fn(&mut Vec<PaletteEntry>) + 'static) -> Hook {
79        Hook {
80            id,
81            alter: Alter::Palette(Box::new(f)),
82            priority: 0,
83            after: Vec::new(),
84        }
85    }
86
87    /// Alters the settings form's entries.
88    pub fn settings(id: HookId, f: impl Fn(&mut Vec<SettingEntry>) + 'static) -> Hook {
89        Hook {
90            id,
91            alter: Alter::Settings(Box::new(f)),
92            priority: 0,
93            after: Vec::new(),
94        }
95    }
96
97    pub fn priority(mut self, priority: i32) -> Hook {
98        self.priority = priority;
99        self
100    }
101
102    /// Runs after another hook (a missing one is reported, and ignored).
103    pub fn after(mut self, hook: HookId) -> Hook {
104        self.after.push(hook);
105        self
106    }
107}
108
109/// Moments of an application's life.
110#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
111#[serde(tag = "event", content = "plugin", rename_all = "snake_case")]
112pub enum Lifecycle {
113    /// Every plugin is connected; the first frame comes next.
114    Started,
115    /// A plugin was connected after start-up.
116    Connected(egui_pop_model::ids::PluginId),
117    /// A plugin was disconnected.
118    Disconnected(egui_pop_model::ids::PluginId),
119    /// The declarations were rebuilt (menus, palette, settings, zones).
120    Rebuilt,
121    /// A pass of the application's logic (`App::logic`): before each
122    /// frame, and also while the window is hidden or minimized when
123    /// something asked for a repaint (`egui::Context::request_repaint`,
124    /// from any thread). What a background thread hands over is taken
125    /// here; nothing may be drawn.
126    Pass,
127}
128
129impl Lifecycle {
130    /// The kind, ignoring the plugin: what handlers subscribe to.
131    pub fn kind(&self) -> &'static str {
132        match self {
133            Lifecycle::Started => "started",
134            Lifecycle::Connected(_) => "connected",
135            Lifecycle::Disconnected(_) => "disconnected",
136            Lifecycle::Rebuilt => "rebuilt",
137            Lifecycle::Pass => "pass",
138        }
139    }
140}
141
142/// Which lifecycle events a handler wants.
143#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
144#[serde(rename_all = "snake_case")]
145pub enum On {
146    Started,
147    Connected,
148    Disconnected,
149    Rebuilt,
150    /// Every pass of the logic, even while the window is hidden
151    /// ([`Lifecycle::Pass`]).
152    Pass,
153}
154
155impl On {
156    pub(crate) fn matches(self, e: &Lifecycle) -> bool {
157        matches!(
158            (self, e),
159            (On::Started, Lifecycle::Started)
160                | (On::Connected, Lifecycle::Connected(_))
161                | (On::Disconnected, Lifecycle::Disconnected(_))
162                | (On::Rebuilt, Lifecycle::Rebuilt)
163                | (On::Pass, Lifecycle::Pass)
164        )
165    }
166}
167
168/// A lifecycle handler.
169pub type LifecycleFn = Box<dyn FnMut(&AppHandle, &Lifecycle)>;