Skip to main content

agg_gui_shell/
run.rs

1//! Startup: restore the window bounds, open the window, bring up wgpu, build
2//! the app, paint the first frame into the still-hidden window, and hand
3//! control to [`crate::shell_loop::ShellLoop`].
4//!
5//! The ordering here is deliberate and load-bearing; see [`run`].
6
7#![allow(deprecated)] // winit 0.30 `EventLoop::run` idiom
8
9use std::cell::{Cell, RefCell};
10use std::rc::Rc;
11use std::sync::Arc;
12use std::time::Instant;
13
14use agg_gui::{App, Modifiers};
15use agg_gui_wgpu::{CopySrc, Gpu, GpuConfig};
16use winit::event_loop::EventLoop;
17use winit::window::{Icon, Window, WindowAttributes};
18
19use crate::bounds::{
20    sanitize_restored_window_size, BoundsAutoSave, SavedBounds, WindowedSizeTracker,
21};
22use crate::config::{ShellConfig, WindowIcon, WindowSize};
23use crate::host::{ExitAction, ShellHost};
24use crate::paint::{PaintRequest, Painter};
25use crate::shell_loop::{ShellInit, ShellLoop};
26use crate::waker::HostWakerGuard;
27use crate::ShellError;
28
29/// Open a window, bring up wgpu, build the app, and run the event loop until
30/// the window closes.
31///
32/// `build` is called once the window and the GPU exist — the device scale,
33/// input profile and surface size are already in place, which is what a widget
34/// tree wants to see while it is being built. It returns the [`App`] and the
35/// [`ShellHost`] that carries the app's own per-frame plumbing; a host with
36/// nothing to add is [`crate::NoHost`].
37///
38/// ```no_run
39/// # fn demo(app: agg_gui::App) -> Result<(), agg_gui_shell::ShellError> {
40/// use agg_gui_shell::{run, NoHost, ShellConfig};
41///
42/// run(ShellConfig::new("My App"), move |_init| Ok((app, NoHost)))
43/// # }
44/// ```
45///
46/// # Ordering
47///
48/// 1. Restore and sanitise the saved window size, then refine it against the
49///    real monitor once the window exists (winit 0.30 only exposes monitors
50///    through a live `Window`).
51/// 2. Create the window **hidden**, finish wgpu setup, build the app, and
52///    paint the first real frame before showing it — otherwise the user sees
53///    an unstyled OS-default background and a black border around the
54///    not-yet-configured surface.
55/// 3. Install the agg-gui host waker only after the window and GPU came up,
56///    and clear it on every exit path (`HostWakerGuard`).
57pub fn run<H, B>(config: ShellConfig, build: B) -> Result<(), ShellError>
58where
59    H: ShellHost + 'static,
60    B: FnOnce(&ShellInit<'_>) -> Result<(App, H), ShellError>,
61{
62    let event_loop = EventLoop::new().map_err(ShellError::EventLoop)?;
63
64    let restored_bounds = config.bounds_store.as_ref().and_then(|s| s.load());
65    let (window, restored_size) = create_window(&event_loop, &config, restored_bounds)?;
66    agg_gui::set_device_scale(window.scale_factor());
67    if config.os_tooltip_timings {
68        if let Some(timings) = crate::tooltip::os_tooltip_timings() {
69            agg_gui::set_tooltip_timings(timings);
70        }
71    }
72
73    // Configure at the window's REAL inner size rather than the size that was
74    // requested: `request_inner_size` may be applied asynchronously, and the
75    // `Resized` event that follows drives the surface reconfigure anyway.
76    let init_size = window.inner_size();
77    let gpu_config = GpuConfig::new(config.device_label)
78        .with_present_mode(config.present_mode)
79        .with_optional_features(config.optional_features)
80        // A capture run that silently produced nothing would be worse than a
81        // hard failure, so a configured screenshot *requires* read-back.
82        .with_copy_src(if config.screenshot.is_some() {
83            CopySrc::Required
84        } else {
85            config.copy_src
86        });
87    let gpu = Gpu::new(
88        Arc::clone(&window),
89        (init_size.width.max(1), init_size.height.max(1)),
90        gpu_config,
91    )
92    .map_err(ShellError::Gpu)?;
93
94    let (app, host) = build(&ShellInit {
95        window: &window,
96        gpu: &gpu,
97        restored_bounds,
98    })?;
99
100    // Only now: window up, GPU up, app built. Cleared on every exit path by
101    // the guard, which the loop owns from here on.
102    let waker_guard = HostWakerGuard::install(event_loop.create_proxy());
103
104    let painter = Painter::new(&gpu);
105    let maximized = window.is_maximized();
106    // Seeded from the restored size, NOT from the live surface: a window
107    // created maximized reports the work-area rect, which must never become
108    // the persisted windowed size. See `WindowedSizeTracker::new`.
109    let windowed_size =
110        WindowedSizeTracker::new(restored_size, (gpu.config().width, gpu.config().height));
111    let mut bounds_auto = BoundsAutoSave::default();
112    bounds_auto.seed(restored_bounds);
113
114    let exit = Rc::new(Cell::new(None::<ExitAction>));
115    let error = Rc::new(RefCell::new(None::<ShellError>));
116
117    let mut shell = ShellLoop {
118        window: Arc::clone(&window),
119        gpu: Some(gpu),
120        gpu_config,
121        painter,
122        app,
123        host,
124        policy: config.redraw_policy,
125        screenshot: config.screenshot.clone(),
126        screenshot_done: false,
127        screenshot_last_paint: Instant::now(),
128        cursor: (0.0, 0.0),
129        mods: Modifiers::default(),
130        mouse_buttons_down: 0,
131        input_since_frame: false,
132        pending_resize: None,
133        bounds_store: config.bounds_store,
134        bounds_auto,
135        windowed_size,
136        maximized,
137        exit: Rc::clone(&exit),
138        error: Rc::clone(&error),
139        finished: false,
140        _waker_guard: waker_guard,
141    };
142
143    // First frame into the hidden window: after this the surface holds the
144    // fully-styled first frame, so `set_visible(true)` never flashes an
145    // OS-default background. The screenshot path is deliberately not armed
146    // here — a capture counts settle frames from the visible window.
147    if let Some(gpu) = shell.gpu.as_mut() {
148        shell.painter.paint(
149            gpu,
150            &window,
151            &mut shell.app,
152            &mut shell.host,
153            PaintRequest {
154                pending_resize: &mut None,
155                input_since_last_frame: false,
156                capture: None,
157            },
158        )?;
159    }
160    window.set_visible(true);
161
162    event_loop
163        .run(move |event, elwt| shell.handle(event, elwt))
164        .map_err(ShellError::EventLoop)?;
165
166    if let Some(e) = error.borrow_mut().take() {
167        return Err(e);
168    }
169    if exit.get() == Some(ExitAction::Relaunch) {
170        relaunch()?;
171    }
172    Ok(())
173}
174
175/// Start a fresh copy of this executable. Called after the loop has exited and
176/// every store has been flushed, so the child reads the state this run wrote.
177fn relaunch() -> Result<(), ShellError> {
178    let exe = std::env::current_exe().map_err(ShellError::Relaunch)?;
179    std::process::Command::new(exe)
180        .spawn()
181        .map(|_| ())
182        .map_err(ShellError::Relaunch)
183}
184
185/// Create the window, returning it alongside the sanitised restored size that
186/// was applied (`None` when nothing was restored). The caller needs that size
187/// to seed [`WindowedSizeTracker`]: it is the last *windowed* size, which the
188/// live surface does not report when the window came up maximized.
189fn create_window(
190    event_loop: &EventLoop<()>,
191    config: &ShellConfig,
192    restored: Option<SavedBounds>,
193) -> Result<(Arc<Window>, Option<(u32, u32)>), ShellError> {
194    // A restored size is physical px and may be corrupt (an old DPI-ratchet
195    // bug, a zeroed file), so it is sanitised before winit ever sees it. This
196    // first pass has no monitor information: winit 0.30 exposes monitors on
197    // the `Window`, not the pre-run `EventLoop`, so the real display size is
198    // not available until the window exists. The fallback ceiling already
199    // floors tiny values and caps an over-large size below the GPU max; the
200    // refinement against the actual monitor happens right after creation.
201    let saved = restored.map(|b| (b.width, b.height));
202    let mut restored_size = saved.map(|_| sanitize_restored_window_size(saved, None));
203    let size = match restored_size {
204        Some((w, h)) => WindowSize::Physical(w, h),
205        None => config.size,
206    };
207
208    let mut attributes = WindowAttributes::default()
209        .with_title(config.title.clone())
210        .with_inner_size(size.to_winit())
211        .with_maximized(restored.map(|b| b.maximized).unwrap_or(config.maximized))
212        // Shown after the first frame is painted, to avoid a white flash.
213        .with_visible(false);
214    if let Some(min) = config.min_size {
215        attributes = attributes.with_min_inner_size(min.to_winit());
216    }
217    if let Some(icon) = config.icon.as_ref() {
218        attributes = attributes.with_window_icon(window_icon(icon));
219    }
220    if config.fullscreen {
221        attributes = attributes.with_fullscreen(Some(winit::window::Fullscreen::Borderless(None)));
222        agg_gui::fullscreen::set_active(true);
223    }
224
225    let window = Arc::new(
226        event_loop
227            .create_window(attributes)
228            .map_err(ShellError::CreateWindow)?,
229    );
230
231    // Refine a restored size against the window's real monitor now that it
232    // exists: this shrinks a size larger than the display back onto it before
233    // the window is shown. The window is still hidden, so the resize is
234    // invisible.
235    if saved.is_some() {
236        if let Some(monitor) = window
237            .primary_monitor()
238            .or_else(|| window.current_monitor())
239        {
240            let m = monitor.size();
241            let refined = sanitize_restored_window_size(saved, Some((m.width, m.height)));
242            restored_size = Some(refined);
243            if WindowSize::Physical(refined.0, refined.1) != size {
244                let _ =
245                    window.request_inner_size(winit::dpi::PhysicalSize::new(refined.0, refined.1));
246            }
247        }
248    }
249    Ok((window, restored_size))
250}
251
252/// Build a winit icon, logging and dropping one the platform rejects — a bad
253/// icon must not stop the app from opening.
254fn window_icon(icon: &WindowIcon) -> Option<Icon> {
255    match Icon::from_rgba(icon.rgba.clone(), icon.width, icon.height) {
256        Ok(icon) => Some(icon),
257        Err(err) => {
258            log::warn!("agg-gui-shell: ignoring invalid window icon: {err}");
259            None
260        }
261    }
262}