egui_pop_api/runner/
host.rs1use 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 static PAINTING: Cell<Option<WindowId>> = const { Cell::new(None) };
60 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 static ROOT: Cell<Option<RawWindowHandle>> = const { Cell::new(None) };
66 static VERIFIED: Cell<Option<bool>> = const { Cell::new(None) };
67 static ROOT_WINDOW: RefCell<Option<super::Window>> = const { RefCell::new(None) };
69 static CTX: RefCell<Option<egui::Context>> = const { RefCell::new(None) };
71 static ROOT_ID: Cell<Option<WindowId>> = const { Cell::new(None) };
73}
74
75pub 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
90pub 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
98pub 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
114pub fn resumed(event_loop: &ActiveEventLoop) {
117 if let Some(d) = Display::of(event_loop) {
118 DISPLAY.set(Some(d));
119 }
120}
121
122pub fn set_display(display: RawDisplayHandle) {
125 DISPLAY.set(Some(Display::from_raw(display)));
126}
127
128pub 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
145pub fn window_event(window: WindowId, event: &WindowEvent) {
148 if matches!(event, WindowEvent::Destroyed) {
149 forget(window);
150 }
151}
152
153pub 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#[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
223fn 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
262fn 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
285fn 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
318fn 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}