Skip to main content

egui_pop_api/runner/
host.rs

1//! What pairs each window with its viewport, for egui-pop's own runner
2//! and for a host running the event loop itself.
3//!
4//! egui-pop's runner (`create-native`) calls these itself. A host that
5//! builds the winit event loop and drives eframe through
6//! `eframe::create_native` and `run_app_on_demand` (feature `host-loop`)
7//! calls them from its own `ApplicationHandler`, so [`super::window`]
8//! answers for every window there too, detached panels' windows
9//! included:
10//!
11//! ```ignore
12//! // In the application's creator, first:
13//! egui_pop::api::runner::host::created(cc);
14//!
15//! impl ApplicationHandler<eframe::UserEvent> for HostLoop<'_> {
16//!     fn resumed(&mut self, event_loop: &ActiveEventLoop) {
17//!         egui_pop::api::runner::host::resumed(event_loop);
18//!         self.eframe.resumed(event_loop);
19//!     }
20//!     fn window_event(&mut self, el: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
21//!         egui_pop::api::runner::host::window_event(id, &event);
22//!         if matches!(event, WindowEvent::RedrawRequested) {
23//!             let eframe = &mut self.eframe;
24//!             egui_pop::api::runner::host::redraw(id, || eframe.window_event(el, id, event));
25//!         } else {
26//!             self.eframe.window_event(el, id, event);
27//!         }
28//!     }
29//!     // ... the other callbacks to eframe as before.
30//! }
31//! // After run_app_on_demand returns:
32//! egui_pop::api::runner::host::detach();
33//! ```
34//!
35//! [`redraw`] notes which window eframe paints: the pass that begins in
36//! it is that window's viewport (a deferred viewport, the main window).
37//! An immediate viewport is painted in a pass nested in its parent's,
38//! and its own window's redraw runs no pass: the two are paired in the
39//! order seen (see `pairs`). The handles come from the window's winit id
40//! (`egui_pop_winit`), used only once the main window's id was seen to be
41//! its native window ([`super::ids_verified`]).
42
43use std::cell::{Cell, RefCell};
44use std::sync::Arc;
45
46use egui::ViewportId;
47use egui_pop_winit::{Display, WindowHandles};
48use raw_window_handle::{HasWindowHandle, RawDisplayHandle, RawWindowHandle};
49use winit::event::WindowEvent;
50use winit::event_loop::ActiveEventLoop;
51use winit::window::WindowId;
52
53use super::pairs::Pairs;
54use crate::window::Windowing;
55
56thread_local! {
57    /// The window eframe is painting (set in its `RedrawRequested`, taken
58    /// by the first pass that begins in it).
59    static PAINTING: Cell<Option<WindowId>> = const { Cell::new(None) };
60    /// Passes begun and not ended: more than one is a nested pass.
61    static DEPTH: Cell<usize> = const { Cell::new(0) };
62    static DISPLAY: Cell<Option<Display>> = const { Cell::new(None) };
63    static PAIRS: RefCell<Pairs> = RefCell::new(Pairs::default());
64    /// The main window's handle as eframe gives it.
65    static ROOT: Cell<Option<RawWindowHandle>> = const { Cell::new(None) };
66    static VERIFIED: Cell<Option<bool>> = const { Cell::new(None) };
67    /// The main window, as eframe gives it at creation.
68    static ROOT_WINDOW: RefCell<Option<super::Window>> = const { RefCell::new(None) };
69    /// The application's context, to forget a destroyed window's handles.
70    static CTX: RefCell<Option<egui::Context>> = const { RefCell::new(None) };
71    /// The main window's winit id.
72    static ROOT_ID: Cell<Option<WindowId>> = const { Cell::new(None) };
73}
74
75/// In the application's creator (`eframe::AppCreator`), before anything
76/// else: the main window (its handles and winit id) and the context
77/// whose passes pair the other windows ([`attach`]).
78pub fn created(cc: &eframe::CreationContext<'_>) {
79    if let Ok(h) = cc.window_handle() {
80        ROOT.set(Some(h.as_raw()));
81    }
82    if let Some(w) = cc.winit_window() {
83        ROOT_ID.set(Some(w.id()));
84        let w: Arc<dyn crate::files::ParentWindow> = w.clone();
85        ROOT_WINDOW.set(Some(super::Window::new(w)));
86    }
87    attach(&cc.egui_ctx);
88}
89
90/// The main window, when [`created`] cannot give it (a host making its
91/// own creation context, a test): its winit id and its handles.
92pub fn set_main_window(id: WindowId, window: Arc<dyn crate::files::ParentWindow>) {
93    ROOT.set(window.window_handle().ok().map(|h| h.as_raw()));
94    ROOT_ID.set(Some(id));
95    ROOT_WINDOW.set(Some(super::Window::new(window)));
96}
97
98/// Pairs the windows painted for `ctx`'s passes: hooks on its passes'
99/// begin and end, once per context.
100pub fn attach(ctx: &egui::Context) {
101    let same = CTX.with_borrow(|c| c.as_ref().is_some_and(|c| c == ctx));
102    if same {
103        return;
104    }
105    CTX.set(Some(ctx.clone()));
106    DEPTH.set(0);
107    ctx.on_begin_pass("egui_pop::runner", Arc::new(begin_pass));
108    ctx.on_end_pass(
109        "egui_pop::runner",
110        Arc::new(|_| DEPTH.set(DEPTH.get().saturating_sub(1))),
111    );
112}
113
114/// When the event loop resumes, before eframe's `resumed`: the display
115/// the windows' ids are read against ([`set_display`]).
116pub fn resumed(event_loop: &ActiveEventLoop) {
117    if let Some(d) = Display::of(event_loop) {
118        DISPLAY.set(Some(d));
119    }
120}
121
122/// The display the windows' ids are read against, when [`resumed`]
123/// cannot give it (a test).
124pub fn set_display(display: RawDisplayHandle) {
125    DISPLAY.set(Some(Display::from_raw(display)));
126}
127
128/// Around eframe's handling of `window`'s `RedrawRequested`: the pass
129/// that begins in it is that window's viewport; no pass at all, an
130/// immediate viewport's window (eframe repaints its parent instead).
131pub fn redraw<R>(window: WindowId, paint: impl FnOnce() -> R) -> R {
132    let previous = PAINTING.replace(Some(window));
133    let out = paint();
134    let untaken = PAINTING.get() == Some(window);
135    PAINTING.set(previous);
136    if untaken && ROOT_ID.get() != Some(window) {
137        let new = PAIRS.with_borrow_mut(|p| p.redraw_without_pass(u64::from(window)));
138        if new {
139            record_paired();
140        }
141    }
142    out
143}
144
145/// Each window event, before eframe gets it: a destroyed window's
146/// handles go.
147pub fn window_event(window: WindowId, event: &WindowEvent) {
148    if matches!(event, WindowEvent::Destroyed) {
149        forget(window);
150    }
151}
152
153/// After the loop returned: everything forgotten, for a next run.
154pub fn detach() {
155    PAINTING.set(None);
156    DEPTH.set(0);
157    CTX.set(None);
158    ROOT_ID.set(None);
159    ROOT_WINDOW.set(None);
160    ROOT.set(None);
161    VERIFIED.set(None);
162    PAIRS.with_borrow_mut(Pairs::clear);
163}
164
165/// The main window's id, for `native`'s runner (feature `create-native`).
166#[cfg(feature = "create-native")]
167pub(super) fn main_window_id() -> Option<WindowId> {
168    ROOT_ID.get()
169}
170
171pub(super) fn ids_verified() -> Option<bool> {
172    VERIFIED.get()
173}
174
175pub(super) fn windowing() -> Windowing {
176    match DISPLAY.get().map(|d| d.raw()) {
177        None => Windowing::Unknown,
178        Some(RawDisplayHandle::Wayland(_)) => Windowing::Wayland,
179        Some(RawDisplayHandle::Xlib(_) | RawDisplayHandle::Xcb(_)) => Windowing::X11,
180        Some(RawDisplayHandle::Windows(_)) => Windowing::Windows,
181        Some(RawDisplayHandle::AppKit(_)) => Windowing::MacOs,
182        Some(_) => Windowing::Other,
183    }
184}
185
186fn handles(viewport: ViewportId) -> Option<WindowHandles> {
187    if VERIFIED.get() != Some(true) {
188        return None;
189    }
190    let window = PAIRS.with_borrow(|p| p.window_of(viewport))?;
191    DISPLAY.get()?.window(WindowId::from(window))
192}
193
194pub(super) fn window_handle(viewport: ViewportId) -> Option<RawWindowHandle> {
195    if viewport == ViewportId::ROOT
196        && let Some(h) = ROOT.get()
197    {
198        return Some(h);
199    }
200    handles(viewport).map(|h| h.raw_window())
201}
202
203pub(super) fn window(viewport: ViewportId) -> Option<super::Window> {
204    if viewport == ViewportId::ROOT {
205        return ROOT_WINDOW.with_borrow(Clone::clone);
206    }
207    handles(viewport).map(|h| super::Window::new(Arc::new(h)))
208}
209
210pub(super) fn windows() -> Vec<ViewportId> {
211    let mut known = Vec::new();
212    if ROOT_WINDOW.with_borrow(Option::is_some) {
213        known.push(ViewportId::ROOT);
214    }
215    if VERIFIED.get() == Some(true) && DISPLAY.get().is_some() {
216        PAIRS.with_borrow(|p| {
217            known.extend(p.viewports().filter(|v| *v != ViewportId::ROOT));
218        });
219    }
220    known
221}
222
223/// The `on_begin_pass` hook: pairs the window being painted with the
224/// pass's viewport (or, nested, notes an immediate viewport), verifies
225/// the ids on the main window, and records the handles of every paired
226/// window once they are verified.
227fn begin_pass(ui: &mut egui::Ui) {
228    let depth = DEPTH.get() + 1;
229    DEPTH.set(depth);
230    let ctx = ui.ctx().clone();
231    let viewport = ctx.viewport_id();
232    let new = if depth > 1 {
233        PAIRS.with_borrow_mut(|p| p.nested(viewport))
234    } else {
235        let Some(window) = PAINTING.take() else {
236            return;
237        };
238        let open: Vec<ViewportId> = ctx.input(|i| i.raw.viewports.keys().copied().collect());
239        let new = PAIRS.with_borrow_mut(|p| {
240            if viewport == ViewportId::ROOT && !open.is_empty() {
241                p.retain_viewports(&open);
242            }
243            p.painted(u64::from(window), viewport)
244        });
245        if new {
246            log::debug!(
247                target: "egui_pop::runner",
248                "viewport {viewport:?} is window {:#x}",
249                u64::from(window)
250            );
251        }
252        if new && viewport == ViewportId::ROOT && VERIFIED.get().is_none() {
253            verify(window);
254        }
255        new
256    };
257    if new {
258        record_paired();
259    }
260}
261
262/// Whether winit's ids are the native windows: the main window's id read
263/// as a handle against the handle eframe gave.
264fn verify(window: WindowId) {
265    let Some(display) = DISPLAY.get() else {
266        return;
267    };
268    let from_id = display.window_handle(window);
269    let ok = match (from_id, ROOT.get()) {
270        (Some(a), Some(b)) => egui_pop_winit::same_window(&a, &b),
271        _ => false,
272    };
273    VERIFIED.set(Some(ok));
274    if ok {
275        log::debug!(target: "egui_pop::runner", "window ids are the native windows");
276    } else {
277        log::info!(
278            target: "egui_pop::runner",
279            "window ids are not the native windows here ({from_id:?} against {:?}): only the main window's handles are known",
280            ROOT.get()
281        );
282    }
283}
284
285/// Records the handles of the paired windows not recorded yet, once the
286/// ids are verified. The main window's are eframe's own.
287fn record_paired() {
288    if VERIFIED.get() != Some(true) {
289        return;
290    }
291    let (Some(display), Some(ctx)) = (DISPLAY.get(), CTX.with_borrow(Clone::clone)) else {
292        return;
293    };
294    let todo = PAIRS.with_borrow_mut(Pairs::take_unrecorded);
295    for pair in todo {
296        if pair.viewport == ViewportId::ROOT {
297            continue;
298        }
299        let Some(h) = display.window(WindowId::from(pair.window)) else {
300            continue;
301        };
302        log::debug!(
303            target: "egui_pop::runner",
304            "viewport {:?} is window {:#x}{}",
305            pair.viewport,
306            pair.window,
307            if pair.guessed { " (immediate)" } else { "" }
308        );
309        if let RawWindowHandle::Win32(w) = h.raw_window() {
310            crate::frame::set_native_window(&ctx, pair.viewport, w.hwnd.get());
311        }
312        let parent: Arc<dyn crate::files::ParentWindow> = Arc::new(h);
313        crate::files::set_parent_window(&ctx, pair.viewport, parent);
314        ctx.request_repaint_of(pair.viewport);
315    }
316}
317
318/// A destroyed window's handles go.
319fn forget(window: WindowId) {
320    let gone = PAIRS.with_borrow_mut(|p| p.forget(u64::from(window)));
321    CTX.with_borrow(|ctx| {
322        let Some(ctx) = ctx else { return };
323        for p in gone
324            .iter()
325            .filter(|p| p.recorded && p.viewport != ViewportId::ROOT)
326        {
327            crate::files::forget_parent_window(ctx, p.viewport);
328            crate::frame::forget_native_window(ctx, p.viewport);
329        }
330    });
331}