Skip to main content

egui_pop_api/bus/
owners.rs

1//! A window's owner on the bus: the `pop.window.open` an owner asks, and the
2//! windows a plugin leaves when it goes (ADR 0029, slice 3).
3
4use bus_contract::{Bus, ListenOpts};
5use serde_json::json;
6
7use super::{OWNER, PluginDisconnect, Reason, WindowKind, WindowOpen, WindowRequest, asking, emit};
8use crate::app::AppHandle;
9
10/// Closes the application windows a disconnected plugin owned, before
11/// `plugin.disconnected` is said: each a `pop.window.close` (`owner-gone`),
12/// counted as `windows_closed`.
13pub const OWNER_GONE: &str = "pop.window.owner-gone";
14
15/// Registers egui-pop's listeners of a window's owner.
16pub(super) fn install(kernel: &dyn Bus) {
17    let listened = kernel.listen::<PluginDisconnect>(
18        OWNER_GONE,
19        ListenOpts::new().owner(OWNER),
20        |change, counts| {
21            let Some(app) = asking() else { return Ok(()) };
22            let left: Vec<WindowRequest> = app
23                .windows_list()
24                .into_iter()
25                .filter(|w| w.kind == WindowKind::App)
26                .filter(|w| w.owner == change.plugin || w.owner == change.owner)
27                .map(|w| WindowRequest::new(w.id, w.kind, w.owner, Reason::OwnerGone))
28                .collect();
29            let mut closed = 0;
30            for req in left {
31                if app.request_window_close(req) {
32                    closed += 1;
33                }
34            }
35            if closed > 0 {
36                counts.insert("windows_closed".into(), json!(closed));
37            }
38            Ok(())
39        },
40    );
41    debug_assert!(listened.is_ok(), "{listened:?}");
42}
43
44impl AppHandle {
45    /// Runs `pop.window.open`'s listeners for a window its owner asks: what
46    /// they did, one line each.
47    pub(crate) fn ask_window_open(&self, req: WindowRequest) -> Vec<String> {
48        emit::<WindowOpen>(self, req)
49    }
50}