Skip to main content

brep_app/
desktop_loop.rs

1//! The desktop event loop.
2//!
3//! `eframe::run_native` runs the app only under winit's `RedrawRequested`.
4//! On Wayland winit withholds that event while the surface's frame callback
5//! is outstanding (winit 0.30 `wayland/event_loop/mod.rs`, which skips a window
6//! whose callback is `Requested`, with no timeout), and a compositor sends no
7//! callbacks to a window it is not showing (another workspace, a hidden
8//! scratchpad, a covered window under some compositors). An automation command
9//! queued then waited until the user focused the window: the 2026-10-31
10//! desktop report's 29 s initial read. eframe's fallback for invisible windows
11//! does not apply, because Wayland reports neither visibility nor minimisation
12//! (`is_visible`/`is_minimized` return `None`). And once a repaint is
13//! outstanding with no pass run, egui stops calling its repaint callback, so a
14//! later submit did not even wake the loop.
15//!
16//! `run` owns the winit loop instead (`eframe::create_native`) and wraps
17//! eframe's handler in `DesktopLoop`. The automation queue's waker sends the
18//! loop its own event (never forwarded to eframe), and after every batch of
19//! events the loop runs `BrepApp::service_automation` on this, the app's
20//! thread, whenever the queue's head can be dispatched without a frame. Frames
21//! still drain the queue exactly as before; this path draws nothing.
22//!
23//! A command that needs more than app state (input egui must apply, a layout
24//! read, a capture) does not wait for a frame either: the loop runs an egui
25//! pass itself, on demand (`run_pass`). It is the same pass eframe runs
26//! (`raw_input_hook`, then `logic` and `ui` inside `Context::run_ui`), on the
27//! window's last known size and clock, and it is never presented: a capture
28//! asked for in it is drawn into an offscreen texture (`crate::offscreen`).
29//! Everything else the pass hands back goes where eframe would have put it:
30//! its textures to the shared renderer, its viewport and platform commands
31//! back onto the context for eframe's next real frame, and a capture's
32//! `Event::Screenshot` into the next pass's input, as eframe delivers one.
33//!
34//! The loop also keeps an undrawn window idle. eframe arms
35//! `ControlFlow::Poll` whenever it requests a redraw (`check_redraw_requests`)
36//! and disarms it only in the pass that redraw runs, so a redraw the
37//! compositor never delivers leaves the loop polling, a core spinning while
38//! idle. winit wakes the loop itself when a requested redraw is delivered, so
39//! after one polled iteration without a `RedrawRequested`, the loop waits.
40use crate::app::BrepApp;
41use eframe::UserEvent;
42use std::cell::RefCell;
43use std::rc::Rc;
44use std::sync::{Arc, Mutex};
45use std::time::{Duration, Instant};
46use winit::application::ApplicationHandler;
47use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy};
48
49/// Wakes the loop thread (the automation queue's waker).
50pub type Waker = Arc<dyn Fn() + Send + Sync>;
51
52/// The pass number the wake event carries. It is never a real pass, and the
53/// event is never forwarded to eframe, so egui's repaint bookkeeping cannot
54/// see or swallow it.
55const WAKE: u64 = u64::MAX;
56
57/// While work a frame-free dispatch started is still in flight (a background
58/// history run, a store write) and no frame comes, it is serviced at the frame
59/// cadence: the rate a drawn window pumps it. Background runs report
60/// completion only by being polled (`Documents::pump_all`). This paces
61/// completion of accepted work only; dispatch itself is event-driven.
62const SERVICE_PACE: Duration = Duration::from_millis(16);
63
64/// The app, shared on the loop thread between eframe (through [`Shell`]) and
65/// the loop's service step. The two never run at once: winit delivers events
66/// to one handler, sequentially, on this thread.
67#[derive(Clone, Default)]
68pub struct Slot(Rc<RefCell<Option<Installed>>>);
69
70#[derive(Clone)]
71struct Installed {
72    app: Rc<RefCell<BrepApp>>,
73    ctx: egui::Context,
74    /// The window's renderer (shared with eframe's painter): an on-demand
75    /// pass uploads its textures there and draws its captures with it.
76    render: Option<eframe::egui_wgpu::RenderState>,
77    pass: Rc<RefCell<PassInput>>,
78}
79
80/// What an on-demand pass needs to stand in for eframe's input: the clock
81/// eframe's passes run on, the window's size and scale, and the events a
82/// capture delivers to the pass after it.
83struct PassInput {
84    /// `(egui time, when)` of the last real pass, to continue its clock.
85    clock: Option<(f64, Instant)>,
86    /// When the app was installed: the clock's origin before any real pass.
87    started: Instant,
88    /// The window's inner size in physical pixels, from `Resized`.
89    size: Option<winit::dpi::PhysicalSize<u32>>,
90    /// The window's scale factor, from `ScaleFactorChanged`.
91    scale: Option<f64>,
92    /// Events for the next pass, real or on demand (`Event::Screenshot`).
93    events: Vec<egui::Event>,
94}
95
96impl PassInput {
97    fn new() -> Self {
98        PassInput { clock: None, started: Instant::now(), size: None, scale: None, events: Vec::new() }
99    }
100
101    fn now(&self) -> f64 {
102        match self.clock {
103            Some((time, at)) => time + at.elapsed().as_secs_f64(),
104            None => self.started.elapsed().as_secs_f64(),
105        }
106    }
107}
108
109impl Slot {
110    /// Install the app from the eframe creation closure; returns eframe's
111    /// handle to it.
112    pub fn install(&self, app: BrepApp, ctx: &egui::Context, render: Option<eframe::egui_wgpu::RenderState>) -> Shell {
113        // This loop draws scaled captures (`run_pass`), when it can draw at all.
114        #[cfg(feature = "automation")]
115        app.automation().set_scaled_capture(render.is_some());
116        let app = Rc::new(RefCell::new(app));
117        let pass = Rc::new(RefCell::new(PassInput::new()));
118        *self.0.borrow_mut() = Some(Installed { app: app.clone(), ctx: ctx.clone(), render, pass: pass.clone() });
119        Shell(app, pass)
120    }
121
122    fn get(&self) -> Option<Installed> {
123        self.0.borrow().clone()
124    }
125}
126
127/// eframe's view of the shared app: every [`eframe::App`] method forwards.
128pub struct Shell(Rc<RefCell<BrepApp>>, Rc<RefCell<PassInput>>);
129
130impl eframe::App for Shell {
131    fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
132        eframe::App::logic(&mut *self.0.borrow_mut(), ctx, frame)
133    }
134    fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
135        eframe::App::ui(&mut *self.0.borrow_mut(), ui, frame)
136    }
137    fn save(&mut self, storage: &mut dyn eframe::Storage) {
138        eframe::App::save(&mut *self.0.borrow_mut(), storage)
139    }
140    fn on_exit(&mut self) {
141        eframe::App::on_exit(&mut *self.0.borrow_mut())
142    }
143    fn auto_save_interval(&self) -> Duration {
144        eframe::App::auto_save_interval(&*self.0.borrow())
145    }
146    fn clear_color(&self, visuals: &egui::Visuals) -> [f32; 4] {
147        eframe::App::clear_color(&*self.0.borrow(), visuals)
148    }
149    fn persist_egui_memory(&self) -> bool {
150        eframe::App::persist_egui_memory(&*self.0.borrow())
151    }
152    fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
153        {
154            // A real pass: an on-demand one continues its clock, and the
155            // events an on-demand capture left for "the next pass" are this one's.
156            let mut pass = self.1.borrow_mut();
157            if let Some(time) = raw_input.time {
158                pass.clock = Some((time, Instant::now()));
159            }
160            raw_input.events.append(&mut pass.events);
161        }
162        eframe::App::raw_input_hook(&mut *self.0.borrow_mut(), ctx, raw_input)
163    }
164}
165
166/// How many passes the loop has run on demand (never presented).
167static ON_DEMAND_PASSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
168
169/// How many passes the loop has run on demand in this process.
170pub fn on_demand_passes() -> u64 {
171    ON_DEMAND_PASSES.load(std::sync::atomic::Ordering::SeqCst)
172}
173
174/// On-demand passes run at most at the frame cadence. The egui clock is wall
175/// time in them as in a drawn frame, so what counts time in frames (a click's
176/// timing, a dwell, `wait_frames`) sees what a drawn window would; and the
177/// loop goes back to the window's own events between two of them.
178const PASS_PACE: Duration = SERVICE_PACE;
179
180/// The surface an on-demand pass lays out on before the window has reported
181/// any size (in points; winit's default window size, which eframe keeps).
182const FALLBACK_SIZE: egui::Vec2 = egui::vec2(800.0, 600.0);
183
184/// Run one egui pass of the app now, as eframe's `run_ui_and_paint` would,
185/// but without presenting it. See the module doc.
186#[cfg(feature = "automation")]
187fn run_pass(app: &mut BrepApp, installed: &Installed) {
188    let ctx = &installed.ctx;
189    // A scaled capture is one pass drawn at `scale` x the window's density:
190    // the same surface in points (so the same layout, camera and overlay
191    // positions), more pixels. Nothing is resized, and the next pass is the
192    // window's own density again.
193    let scaled = app.automation().take_scaled_capture();
194    let raw = {
195        let mut pass = installed.pass.borrow_mut();
196        let mut raw = ctx.input(|i| i.raw.clone());
197        // The last pass's input stands for the window (its size, scale,
198        // focus, texture limit); its events are spent.
199        raw.events = std::mem::take(&mut pass.events);
200        raw.hovered_files.clear();
201        raw.dropped_files.clear();
202        raw.time = Some(pass.now());
203        let root = raw.viewports.entry(egui::ViewportId::ROOT).or_default();
204        root.events.clear();
205        if let Some(scale) = pass.scale {
206            root.native_pixels_per_point = Some(scale as f32);
207        }
208        // egui-winit's rule: points = physical pixels / (native scale x zoom).
209        let pixels_per_point = root.native_pixels_per_point.unwrap_or(1.0) * ctx.zoom_factor();
210        if let Some((_, scale)) = scaled {
211            // The window's density stays what the next pass starts from (a
212            // pass inherits the last one's input), and this pass draws at
213            // `scale` times it.
214            let native = root.native_pixels_per_point.unwrap_or(1.0);
215            pass.scale.get_or_insert(f64::from(native));
216            root.native_pixels_per_point = Some(native * scale);
217        }
218        if let Some(size) = pass.size.filter(|s| s.width > 0 && s.height > 0) {
219            raw.screen_rect = Some(egui::Rect::from_min_size(
220                egui::Pos2::ZERO,
221                egui::vec2(size.width as f32, size.height as f32) / pixels_per_point,
222            ));
223        }
224        if raw.screen_rect.is_none() {
225            // No pass and no `Resized` yet: the size eframe opened the window
226            // at, rather than egui's unbounded default.
227            raw.screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, FALLBACK_SIZE));
228        }
229        if raw.max_texture_side.is_none() {
230            raw.max_texture_side = installed.render.as_ref().map(|r| r.device.limits().max_texture_dimension_2d as usize);
231        }
232        raw
233    };
234    // Counted as it begins: the pass answers commands from inside it.
235    ON_DEMAND_PASSES.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
236    let render = installed.render.as_ref();
237    let queue = app.automation().clone();
238    queue.set_pass_scale(scaled.map(|(_, scale)| scale));
239    let mut pass = crate::on_demand::run(app, ctx, render, raw);
240    queue.set_pass_scale(None);
241    if let Some((token, _)) = scaled {
242        // A window-density capture asked for in this pass waits for the next
243        // one: this pass's pixels are not the window's.
244        for user_data in std::mem::take(&mut pass.captures) {
245            ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(user_data));
246        }
247        let (size_px, clear) = crate::on_demand::capture_target(app, ctx, pass.pixels_per_point);
248        let shapes = std::mem::take(&mut pass.shapes);
249        let image = match render {
250            Some(render) => crate::offscreen::capture(render, ctx, shapes, pass.pixels_per_point, size_px, clear),
251            None => Err("scaled capture: the window has no wgpu render state".to_string()),
252        };
253        match image {
254            Ok(image) => installed.pass.borrow_mut().events.extend(crate::on_demand::screenshot_events(vec![egui::UserData::new(token)], image)),
255            Err(error) => {
256                log::error!("{error}");
257                queue.fail_capture(token, &error);
258            }
259        }
260    }
261    // A capture is drawn here, waiting for the GPU (nothing is presented),
262    // and lands in the next pass's input as eframe delivers one.
263    if !pass.captures.is_empty() {
264        let (size_px, clear) = crate::on_demand::capture_target(app, ctx, pass.pixels_per_point);
265        let image = match render {
266            Some(render) => crate::offscreen::capture(render, ctx, pass.shapes, pass.pixels_per_point, size_px, clear),
267            None => Err("offscreen capture: the window has no wgpu render state".to_string()),
268        };
269        match image {
270            Ok(image) => installed.pass.borrow_mut().events.extend(crate::on_demand::screenshot_events(pass.captures, image)),
271            Err(error) => {
272                log::error!("{error}");
273                app.automation().fail_captures(&error);
274            }
275        }
276    }
277    if let Some(render) = render {
278        crate::offscreen::apply_texture_frees(render, &pass.textures_delta);
279    }
280}
281
282/// A waker that sends the loop its wake event. Safe from any thread; a closed
283/// loop ignores it.
284pub fn waker(proxy: EventLoopProxy<UserEvent>) -> Waker {
285    let proxy = Mutex::new(proxy);
286    Arc::new(move || {
287        let event = UserEvent::RequestRepaint { viewport_id: egui::ViewportId::ROOT, when: Instant::now(), cumulative_pass_nr: WAKE };
288        let _ = proxy.lock().unwrap_or_else(|p| p.into_inner()).send_event(event);
289    })
290}
291
292fn is_wake(event: &UserEvent) -> bool {
293    matches!(event, UserEvent::RequestRepaint { cumulative_pass_nr: WAKE, .. })
294}
295
296/// eframe's winit handler plus the frame-free service step.
297pub struct DesktopLoop<H> {
298    inner: H,
299    slot: Slot,
300    /// Work the last service step started is still in flight.
301    busy: bool,
302    /// The `WaitUntil` deadline the service step armed to pace that work.
303    paced: Option<Instant>,
304    /// The last iteration ended polling (eframe requested a redraw).
305    polled: bool,
306    /// A `RedrawRequested` arrived since the last `about_to_wait`.
307    redrawn: bool,
308    /// When the loop last ran a pass on demand ([`PASS_PACE`]).
309    last_pass: Option<Instant>,
310}
311
312impl<H: ApplicationHandler<UserEvent>> DesktopLoop<H> {
313    pub fn new(inner: H, slot: Slot) -> Self {
314        DesktopLoop { inner, slot, busy: false, paced: None, polled: false, redrawn: false, last_pass: None }
315    }
316
317    fn with_pass(&self, f: impl FnOnce(&mut PassInput)) {
318        if let Some(installed) = self.slot.get() {
319            f(&mut installed.pass.borrow_mut());
320        }
321    }
322
323    /// End eframe's poll for a redraw that did not come within one polled
324    /// iteration (a hidden Wayland window gets none). Stock behaviour while
325    /// redraws are delivered: each one disarms the poll in its own pass.
326    fn unstick_poll(&mut self, event_loop: &ActiveEventLoop) {
327        if event_loop.control_flow() == ControlFlow::Poll {
328            if self.polled && !self.redrawn {
329                event_loop.set_control_flow(ControlFlow::Wait);
330                self.polled = false;
331            } else {
332                self.polled = true;
333            }
334        } else {
335            self.polled = false;
336        }
337        self.redrawn = false;
338    }
339
340    /// One frame-free service step, when the queue's head needs no frame or
341    /// work it started is still in flight.
342    fn service(&mut self, event_loop: &ActiveEventLoop) {
343        #[cfg(feature = "automation")]
344        self.step();
345        #[cfg(not(feature = "automation"))]
346        let _ = &self.slot;
347        // The deadline this step armed last time, if the loop still holds it
348        // (eframe replaces it with its own when it schedules a repaint).
349        let ours = self.paced.take().filter(|at| event_loop.control_flow() == ControlFlow::WaitUntil(*at));
350        if self.busy {
351            let next = Instant::now() + SERVICE_PACE;
352            match event_loop.control_flow() {
353                ControlFlow::Poll => {}
354                // eframe's own earlier wake stands; ours is renewed.
355                ControlFlow::WaitUntil(at) if at <= next && ours.is_none() => {}
356                _ => {
357                    event_loop.set_control_flow(ControlFlow::WaitUntil(next));
358                    self.paced = Some(next);
359                }
360            }
361        } else if ours.is_some() {
362            // Work done: a deadline left in the past would wake the loop at
363            // once, every iteration.
364            event_loop.set_control_flow(ControlFlow::Wait);
365        }
366    }
367
368    /// Dispatch what needs no pass, and run the pass the queue's head needs
369    /// ([`PASS_PACE`] after the last one; until then the step stays busy, so
370    /// the loop comes back for it).
371    #[cfg(feature = "automation")]
372    fn step(&mut self) {
373        let Some(installed) = self.slot.get() else { return };
374        // Only eframe holds this borrow, and never across a loop callback.
375        let Ok(mut app) = installed.app.try_borrow_mut() else { return };
376        let queue = app.automation().clone();
377        let owed = loop {
378            if self.busy || queue.has_frameless_work() {
379                self.busy = app.service_automation(&installed.ctx);
380            }
381            let events = !installed.pass.borrow().events.is_empty();
382            // A measured spin advances one step per pass.
383            let owed = queue.needs_pass() || events || app.spinning() || queue.wants_scaled_capture();
384            if !owed || self.last_pass.is_some_and(|at| at.elapsed() < PASS_PACE) {
385                break owed;
386            }
387            run_pass(&mut app, &installed);
388            self.last_pass = Some(Instant::now());
389        };
390        self.busy |= owed;
391    }
392}
393
394impl<H: ApplicationHandler<UserEvent>> ApplicationHandler<UserEvent> for DesktopLoop<H> {
395    fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: winit::event::StartCause) {
396        self.inner.new_events(event_loop, cause);
397    }
398
399    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
400        self.inner.resumed(event_loop);
401    }
402
403    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) {
404        // The wake is ours alone; `about_to_wait`, which always follows the
405        // batch it arrived in, services the queue.
406        if !is_wake(&event) {
407            self.inner.user_event(event_loop, event);
408        }
409    }
410
411    fn window_event(&mut self, event_loop: &ActiveEventLoop, window_id: winit::window::WindowId, event: winit::event::WindowEvent) {
412        self.redrawn |= matches!(event, winit::event::WindowEvent::RedrawRequested);
413        // The window's size and scale, for an on-demand pass (eframe keeps
414        // its own copy where the loop cannot read it).
415        let resized = match &event {
416            winit::event::WindowEvent::Resized(size) => {
417                self.with_pass(|pass| pass.size = Some(*size));
418                true
419            }
420            winit::event::WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
421                let scale = *scale_factor;
422                self.with_pass(|pass| pass.scale = Some(scale));
423                true
424            }
425            _ => false,
426        };
427        self.inner.window_event(event_loop, window_id, event);
428        #[cfg(feature = "automation")]
429        if resized {
430            if let Some(installed) = self.slot.get() {
431                if let Ok(app) = installed.app.try_borrow() {
432                    app.automation().mark_layout_dirty();
433                }
434            }
435        }
436        #[cfg(not(feature = "automation"))]
437        let _ = resized;
438    }
439
440    fn device_event(&mut self, event_loop: &ActiveEventLoop, device_id: winit::event::DeviceId, event: winit::event::DeviceEvent) {
441        self.inner.device_event(event_loop, device_id, event);
442    }
443
444    /// After every batch of events, including the batch a wake arrived in
445    /// and the one in which eframe created the app: a command queued before
446    /// the app existed, or before the waker was installed, is found here.
447    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
448        self.inner.about_to_wait(event_loop);
449        self.unstick_poll(event_loop);
450        if !event_loop.exiting() {
451            self.service(event_loop);
452        }
453    }
454
455    fn suspended(&mut self, event_loop: &ActiveEventLoop) {
456        self.inner.suspended(event_loop);
457    }
458
459    fn exiting(&mut self, event_loop: &ActiveEventLoop) {
460        self.inner.exiting(event_loop);
461    }
462
463    fn memory_warning(&mut self, event_loop: &ActiveEventLoop) {
464        self.inner.memory_warning(event_loop);
465    }
466}
467
468/// What the creation closure is given: eframe's context and the waker to
469/// install on the app's automation queue before anything can submit to it.
470pub type Create<'a> = Box<dyn 'a + FnOnce(&eframe::CreationContext<'_>, Waker) -> Result<BrepApp, String>>;
471
472/// Run the app on a new event loop.
473pub fn run(app_name: &str, options: eframe::NativeOptions, create: Create<'_>) -> Result<(), String> {
474    let event_loop = EventLoop::<UserEvent>::with_user_event().build().map_err(|e| format!("event loop: {e}"))?;
475    run_on(event_loop, app_name, options, create, |eframe| eframe)
476}
477
478/// Run the app on `event_loop`. `wrap` sits between [`DesktopLoop`] and
479/// eframe's handler: the identity in production; a test interposes there to
480/// play a compositor that withholds frames.
481pub fn run_on<'a, H: ApplicationHandler<UserEvent>>(
482    event_loop: EventLoop<UserEvent>,
483    app_name: &str,
484    options: eframe::NativeOptions,
485    create: Create<'a>,
486    wrap: impl FnOnce(eframe::EframeWinitApplication<'a>) -> H,
487) -> Result<(), String> {
488    let slot = Slot::default();
489    let failure: Rc<RefCell<Option<String>>> = Rc::default();
490    let waker = waker(event_loop.create_proxy());
491    let (installer, failed) = (slot.clone(), failure.clone());
492    // A history run (or any runner reply) landing wakes the loop to collect
493    // it, rather than waiting for the service step's next timed check.
494    brep_render::runner::set_reply_waker(Some(waker.clone()));
495    let creator: eframe::AppCreator<'a> = Box::new(move |cc| match create(cc, waker) {
496        Ok(app) => Ok(Box::new(installer.install(app, &cc.egui_ctx, cc.wgpu_render_state.clone())) as Box<dyn eframe::App>),
497        Err(error) => {
498            *failed.borrow_mut() = Some(error.clone());
499            Err(error.into())
500        }
501    });
502    let eframe = eframe::create_native(app_name, options, creator, &event_loop);
503    let mut handler = DesktopLoop::new(wrap(eframe), slot);
504    event_loop.run_app(&mut handler).map_err(|e| format!("event loop: {e}"))?;
505    let failed = failure.borrow_mut().take();
506    match failed {
507        Some(error) => Err(error),
508        None => Ok(()),
509    }
510}