Skip to main content

egui_pop_api/bus/
drawing.rs

1//! The panel being drawn: a scope egui-pop holds around each panel's
2//! draw, so what runs inside it (an emit, a listener, an ask, a sink of
3//! the bus's trace tap) knows which panel, window and topology it runs
4//! for.
5//!
6//! The scope is a thread-local stack, as [`super::asking`] is: a panel
7//! drawn inside another's draw (a palette's preview) is the innermost.
8//! An observer of the bus reads it from its sink, which the kernel calls
9//! on the emitting thread ([`trace`](super::trace)):
10//!
11//! ```ignore
12//! use egui_pop_api::bus::BusTrace;
13//! let guard = app.bus().trace().unwrap().observe(|event| {
14//!     if let Some(drawing) = egui_pop_api::bus::drawing_panel() {
15//!         // `event` was made while `drawing.panel` was drawn.
16//!     }
17//! });
18//! ```
19//!
20//! <div class="warning">Experimental: may change in any release
21//! (docs/stability.md).</div>
22
23use std::cell::RefCell;
24use std::fmt;
25use std::rc::Rc;
26
27use egui::ViewportId;
28use egui_pop_model::ids::PanelId;
29
30use crate::app::{AppHandle, WeakApp};
31
32/// Says which topology an application puts a panel in
33/// ([`AppHandle::set_panel_topology`]): the panel, the window holding it
34/// ([`DrawingPanel::window`]).
35pub type TopologyOf = dyn Fn(&AppHandle, &PanelId, Option<&PanelId>) -> Option<String>;
36
37/// The application's [`TopologyOf`], kept in its locals.
38#[derive(Default)]
39pub(crate) struct Topologies(RefCell<Option<Rc<TopologyOf>>>);
40
41thread_local! {
42    /// The panels being drawn on this thread, innermost last.
43    static DRAWING: RefCell<Vec<DrawingPanel>> = const { RefCell::new(Vec::new()) };
44}
45
46/// A panel being drawn ([`drawing_panel`]).
47///
48/// <div class="warning">Experimental: may change in any release
49/// (docs/stability.md).</div>
50#[derive(Clone)]
51pub struct DrawingPanel {
52    panel: PanelId,
53    window: Option<PanelId>,
54    viewport: ViewportId,
55    app: WeakApp,
56}
57
58impl fmt::Debug for DrawingPanel {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        f.debug_struct("DrawingPanel")
61            .field("panel", &self.panel)
62            .field("window", &self.window)
63            .field("viewport", &self.viewport)
64            .finish_non_exhaustive()
65    }
66}
67
68impl DrawingPanel {
69    /// The panel: an instance with its number (`kind#2`).
70    pub fn panel(&self) -> &PanelId {
71        &self.panel
72    }
73
74    /// The window of the layout holding it, named by its first panel;
75    /// `None` for the main window.
76    pub fn window(&self) -> Option<&PanelId> {
77        self.window.as_ref()
78    }
79
80    /// The egui viewport drawing it.
81    pub fn viewport(&self) -> ViewportId {
82        self.viewport
83    }
84
85    /// The topology the application puts it in
86    /// ([`AppHandle::set_panel_topology`]); `None` when the application
87    /// says none, or has no topologies. Asked when read, not while drawing.
88    pub fn topology(&self) -> Option<String> {
89        let app = self.app.get().ok()?;
90        let of = app.local::<Topologies>().0.borrow().clone()?;
91        of(&app, &self.panel, self.window.as_ref())
92    }
93
94    /// The application drawing it, while it lives.
95    pub fn app(&self) -> Option<AppHandle> {
96        self.app.get().ok()
97    }
98}
99
100/// The panel being drawn on this thread now, innermost first; `None`
101/// outside a panel's draw.
102///
103/// <div class="warning">Experimental: may change in any release
104/// (docs/stability.md).</div>
105pub fn drawing_panel() -> Option<DrawingPanel> {
106    DRAWING.with_borrow(|d| d.last().cloned())
107}
108
109/// Holds a panel as [`drawing_panel`] until dropped, even by a panic.
110pub(crate) struct Drawing(());
111
112impl Drawing {
113    pub(crate) fn enter(
114        app: &AppHandle,
115        panel: &PanelId,
116        window: Option<PanelId>,
117        viewport: ViewportId,
118    ) -> Drawing {
119        DRAWING.with_borrow_mut(|d| {
120            d.push(DrawingPanel {
121                panel: panel.clone(),
122                window,
123                viewport,
124                app: app.downgrade(),
125            })
126        });
127        Drawing(())
128    }
129}
130
131impl Drop for Drawing {
132    fn drop(&mut self) {
133        DRAWING.with_borrow_mut(|d| d.pop());
134    }
135}
136
137impl AppHandle {
138    /// Says which topology the application puts a panel in, for
139    /// [`DrawingPanel::topology`]: given the panel and the window holding
140    /// it, a name of the application's (a group of panels working
141    /// together), or `None`. Called only when a reader asks.
142    ///
143    /// <div class="warning">Experimental: may change in any release
144    /// (docs/stability.md).</div>
145    pub fn set_panel_topology(
146        &self,
147        of: impl Fn(&AppHandle, &PanelId, Option<&PanelId>) -> Option<String> + 'static,
148    ) {
149        *self.local::<Topologies>().0.borrow_mut() = Some(Rc::new(of));
150    }
151}