egui_pop_api/runner.rs
1//! The native runner: eframe on an event loop egui-pop owns.
2//!
3//! <div class="warning">Experimental: may change in any release
4//! (docs/stability.md).</div>
5//!
6//! With the `create-native` feature (on by default), `AppBuilder::run_native`
7//! and `run_native_with` do not call `eframe::run_native`: they build the
8//! winit event loop, hand eframe to it through `eframe::create_native`, and
9//! run it with a handler of their own, which sees every winit callback
10//! before eframe does. eframe still creates and paints every window and
11//! runs the application as before; what owning the loop adds:
12//!
13//! - **The screens before the main window.** The handler reads the
14//! monitors in `resumed`, before eframe's own `resumed` creates the main
15//! window, and tells them (`window::set_screens`, the way a host running
16//! its own loop tells them); eframe calls the window's `window_builder`
17//! hook inside it, so the place restored from the last run is repaired
18//! against real screens (`window::repair_builder`), not only bounded.
19//! They are read again when a window's scale factor changes or a window
20//! moves (onto another monitor, maybe). [`screens`] gives them.
21//! - **Every window's handles.** eframe hands out the main window's only.
22//! It paints a window synchronously in that window's `RedrawRequested`,
23//! so the handler notes which window is being painted, and a
24//! `Context::on_begin_pass` hook pairs it with the pass's viewport. The
25//! handles come from the window's winit id (`egui_pop_winit`, where the
26//! `unsafe` lives), checked first against the main window's handles from
27//! eframe: they are used only once both agree ([`ids_verified`]). Each
28//! window's handles are recorded where egui-pop keeps them per viewport
29//! (`files::set_parent_window`, `frame::set_native_window`) and forgotten
30//! when winit destroys the window. [`window`] gives a viewport's
31//! window by its id, [`windows`] the viewports whose window is known,
32//! [`window_handle`] the raw handle alone.
33//! - **Paced paints.** A window paints at most once per interval, a
34//! little under the fastest screen's refresh period (read in `resumed`,
35//! 60 Hz when no screen tells): a `RedrawRequested` that comes sooner
36//! is held and painted at its time. Vsync and Wayland's frame callbacks
37//! pace a window already; this holds where the present does not wait
38//! (an X server without DRI3, Mesa's software rendering), where an
39//! animating window would otherwise draw as fast as the CPU goes.
40//!
41//! - **Immediate viewports' windows too** (a detached panel's window):
42//! painted inside their parent's pass, their own window's redraw runs no
43//! pass; the nested pass and that redraw are paired in the order seen.
44//!
45//! A host that runs the event loop itself (feature `host-loop`, without
46//! `create-native`) gets the same pairing by calling [`host`]'s hooks
47//! from its own handler. On the web, and without either feature, eframe
48//! runs as before and this module's functions answer nothing.
49
50#[cfg(all(
51 feature = "create-native",
52 not(any(target_os = "ios", target_os = "android"))
53))]
54mod native;
55
56#[cfg(all(
57 feature = "host-loop",
58 not(any(target_os = "ios", target_os = "android"))
59))]
60pub mod host;
61#[cfg(all(
62 feature = "host-loop",
63 not(any(target_os = "ios", target_os = "android"))
64))]
65mod pairs;
66
67/// Without the feature (or on iOS and Android): eframe's own runner, and
68/// nothing seen.
69#[cfg(not(all(
70 feature = "host-loop",
71 not(any(target_os = "ios", target_os = "android"))
72)))]
73mod host {
74 use egui::ViewportId;
75 use raw_window_handle::RawWindowHandle;
76
77 pub(super) fn window_handle(_: ViewportId) -> Option<RawWindowHandle> {
78 None
79 }
80
81 pub(super) fn window(_: ViewportId) -> Option<super::Window> {
82 None
83 }
84
85 pub(super) fn windows() -> Vec<ViewportId> {
86 Vec::new()
87 }
88
89 pub(super) fn ids_verified() -> Option<bool> {
90 None
91 }
92
93 pub(super) fn windowing() -> crate::window::Windowing {
94 crate::window::Windowing::Unknown
95 }
96}
97
98#[cfg(not(all(
99 feature = "create-native",
100 not(any(target_os = "ios", target_os = "android"))
101)))]
102mod native {
103 pub(super) fn run(
104 title: &str,
105 options: eframe::NativeOptions,
106 creator: eframe::AppCreator<'_>,
107 ) -> eframe::Result {
108 eframe::run_native(title, options, creator)
109 }
110}
111
112use std::sync::Arc;
113
114use egui::{Rect, ViewportId};
115use raw_window_handle::{
116 DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawWindowHandle, WindowHandle,
117};
118
119use crate::files::ParentWindow;
120
121/// The handle traits [`Window`] implements.
122pub use raw_window_handle;
123
124/// The native window showing a viewport ([`window`]): what takes a window
125/// through `HasWindowHandle` and `HasDisplayHandle` (a file chooser's
126/// parent, a Wayland subsurface, a Win32 subclass) is given it.
127///
128/// The main window's is eframe's own window; another window's handles
129/// are read from its winit id. They name a window winit keeps: use them
130/// on the thread that runs the event loop (the one running the
131/// application's frames), and keep them no longer than the viewport is
132/// open; once it closes, [`window`] answers none for it.
133#[derive(Clone)]
134pub struct Window(Arc<dyn ParentWindow>);
135
136impl Window {
137 #[cfg_attr(
138 not(all(
139 feature = "host-loop",
140 not(any(target_os = "ios", target_os = "android"))
141 )),
142 allow(dead_code)
143 )]
144 pub(crate) fn new(window: Arc<dyn ParentWindow>) -> Window {
145 Window(window)
146 }
147
148 /// The raw window handle; none if the window refuses it.
149 pub fn raw_window(&self) -> Option<RawWindowHandle> {
150 self.0.window_handle().ok().map(|h| h.as_raw())
151 }
152
153 /// The same window as what a file chooser is attached to
154 /// (`files::set_parent_window` takes it).
155 pub fn as_parent(&self) -> Arc<dyn ParentWindow> {
156 self.0.clone()
157 }
158}
159
160impl std::fmt::Debug for Window {
161 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162 f.debug_tuple("Window").field(&self.raw_window()).finish()
163 }
164}
165
166impl HasWindowHandle for Window {
167 fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
168 self.0.window_handle()
169 }
170}
171
172impl HasDisplayHandle for Window {
173 fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
174 self.0.display_handle()
175 }
176}
177
178/// The native window showing `viewport`, reached by its id: the main
179/// window ([`ViewportId::ROOT`]) as soon as eframe created it, on every
180/// system; another deferred viewport's once it was painted for a redraw
181/// request, an immediate viewport's (a detached panel's window) once its
182/// window's redraw came, and the window ids were verified
183/// ([`ids_verified`]). None for a viewport not open (or closed since),
184/// when called off the event loop's thread, or when neither egui-pop nor
185/// the host (`host`, feature `host-loop`) pairs the windows.
186pub fn window(viewport: ViewportId) -> Option<Window> {
187 host::window(viewport)
188}
189
190/// The viewports whose native window is known ([`window`]), the main
191/// window first.
192pub fn windows() -> Vec<ViewportId> {
193 host::windows()
194}
195
196/// The screens, in points (each monitor's physical rectangle over its
197/// scale factor): those told to egui-pop (`window::screens`), by this
198/// runner before the main window is created and again when they change,
199/// or by a host running the event loop itself (`window::set_screens`);
200/// empty until told.
201pub fn screens() -> Vec<Rect> {
202 crate::window::screens()
203}
204
205/// The raw handle of the window showing `viewport` ([`window`]): the main
206/// window's as eframe gives it, another window's once it was painted for
207/// a redraw request (eframe paints a window still hidden at start
208/// outside of one) and the window ids were verified ([`ids_verified`]);
209/// none when neither egui-pop nor the host pairs the windows.
210pub fn window_handle(viewport: ViewportId) -> Option<RawWindowHandle> {
211 host::window_handle(viewport)
212}
213
214/// Whether winit's window ids were seen to be the native windows: the
215/// main window's id read as a handle, compared with the handle eframe
216/// gives for it. `None` until the main window is painted, or when
217/// egui-pop does not own the event loop; `Some(false)` on a system where
218/// they differ (macOS, or a winit that changed), where no window's
219/// handles are recorded beyond the main window's.
220pub fn ids_verified() -> Option<bool> {
221 host::ids_verified()
222}
223
224/// The windowing system the event loop's display is on: told when the
225/// loop resumes (egui-pop's runner, or a host's `host::resumed`);
226/// `Windowing::Unknown` before, or when nobody told.
227pub fn windowing() -> crate::window::Windowing {
228 host::windowing()
229}
230
231/// `eframe::run_native`, or eframe on egui-pop's own event loop.
232pub(crate) fn run(
233 title: &str,
234 options: eframe::NativeOptions,
235 creator: eframe::AppCreator<'_>,
236) -> eframe::Result {
237 native::run(title, options, creator)
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243 use crate::window::{Screen, repair_place};
244
245 #[test]
246 fn no_window_before_the_loop_runs() {
247 assert!(window(ViewportId::ROOT).is_none());
248 assert!(window(ViewportId::from_hash_of("secondary")).is_none());
249 assert!(windows().is_empty());
250 assert!(window_handle(ViewportId::ROOT).is_none());
251 }
252
253 #[test]
254 fn a_monitor_in_points() {
255 let s = Screen::from_physical(Some("DP-1".into()), (2560, 0), (2560, 1440), 2.0);
256 assert_eq!(
257 s.rect,
258 Rect::from_min_size(egui::pos2(1280.0, 0.0), egui::vec2(1280.0, 720.0))
259 );
260 assert_eq!(s.name.as_deref(), Some("DP-1"));
261 assert_eq!(s.scale, 2.0);
262 let s = Screen::from_physical(None, (0, 0), (800, 600), 0.0);
263 assert_eq!(s.rect.size(), egui::vec2(800.0, 600.0));
264 }
265
266 #[test]
267 fn a_place_off_every_screen_comes_back() {
268 let screen = Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(1280.0, 800.0));
269 let vb = egui::ViewportBuilder::default()
270 .with_position([5000.0, 4000.0])
271 .with_inner_size([800.0, 600.0]);
272 let vb = repair_place(vb, &[screen]);
273 let p = vb.position.expect("a position");
274 assert!(screen.contains(p), "{p:?} is on the screen");
275 assert_eq!(vb.inner_size, Some(egui::vec2(800.0, 600.0)));
276 }
277
278 #[test]
279 fn a_size_larger_than_its_screen_shrinks() {
280 let screen = Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(1280.0, 800.0));
281 let vb = egui::ViewportBuilder::default()
282 .with_position([10.0, 10.0])
283 .with_inner_size([3000.0, 2000.0]);
284 let vb = repair_place(vb, &[screen]);
285 assert_eq!(vb.inner_size, Some(egui::vec2(1280.0, 800.0)));
286 assert_eq!(vb.position, Some(egui::pos2(10.0, 10.0)));
287 }
288
289 #[test]
290 fn no_screens_no_change() {
291 let vb = egui::ViewportBuilder::default()
292 .with_position([5000.0, 4000.0])
293 .with_inner_size([800.0, 600.0]);
294 let vb = repair_place(vb, &[]);
295 assert_eq!(vb.position, Some(egui::pos2(5000.0, 4000.0)));
296 }
297}