Skip to main content

agg_gui_shell/
lib.rs

1//! Turn-key native shell for an [`agg_gui::App`] — winit window, wgpu present,
2//! input forwarding, redraw scheduling, window-bounds persistence, and
3//! device-loss recovery.
4//!
5//! Every native agg-gui app used to hand-roll the same several hundred lines
6//! of event loop, and every copy drifted: one had key-up dispatch and surface
7//! recovery, another had touch input and the anti-flash first-paint ordering,
8//! a third had the DPI-safe window restore. This crate is the union of them.
9//!
10//! ```no_run
11//! use agg_gui_shell::{run, NoHost, ShellConfig};
12//!
13//! # fn build_my_app() -> agg_gui::App { unimplemented!() }
14//! fn main() -> Result<(), agg_gui_shell::ShellError> {
15//!     run(
16//!         ShellConfig::new("My App").with_logical_size(1280.0, 720.0),
17//!         |_init| Ok((build_my_app(), NoHost)),
18//!     )
19//! }
20//! ```
21//!
22//! # What the shell owns
23//!
24//! - Window creation with DPI-safe restore of a saved size (see
25//!   [`WindowBoundsStore`]) and the paint-first-then-show ordering that avoids
26//!   a white flash on start-up.
27//! - Mouse, wheel (including the shift→horizontal remap), keyboard **down and
28//!   up**, touch, cursor-leave, modifiers, and the OS cursor icon.
29//! - Reactive redraw scheduling: `Poll` while the app wants frames,
30//!   `WaitUntil` for a scheduled deadline, `Wait` otherwise — or
31//!   [`RedrawPolicy::Continuous`] when the app wants every frame.
32//! - The agg-gui host waker, so a background thread's
33//!   `animation::signal_async_state_change` wakes a parked loop; installed
34//!   only after the window and GPU came up and cleared on every exit path.
35//! - Surface-acquire recovery, swap-chain resize coalescing, and rebuilding
36//!   the device after a **device loss** (TDR, driver reset, GPU removal, RDP
37//!   session change) — see [`ShellHost::on_gpu_rebuilt`].
38//! - Optional deterministic screenshot capture, and fullscreen toggles
39//!   requested through `agg_gui::fullscreen`.
40//!
41//! # What the app owns
42//!
43//! Everything else, through [`ShellHost`]: per-frame state ticks, a custom
44//! frame body, GPU read-back after the render is submitted, geometry change
45//! notifications, idle-time work, exit and relaunch. Every method has a
46//! default, so [`NoHost`] is a complete implementation for an app that just
47//! wants a window.
48//!
49//! # Public API surface
50//!
51//! `winit` and `wgpu` types appear in this crate's API ([`ShellConfig`]'s
52//! present mode, [`ShellHost::paint`]'s render context, the window handed to a
53//! builder closure). Their major versions are therefore part of *this* crate's
54//! public API: a `winit` 0.31 or `wgpu` 30 will be a breaking release here,
55//! and an app must depend on the same majors this crate does.
56//!
57//! The browser equivalent of this crate does not live here — a wasm app drives
58//! its own `requestAnimationFrame` loop against `agg-gui-wgpu`.
59
60mod bounds;
61mod config;
62mod host;
63mod input;
64mod paint;
65mod run;
66mod screenshot;
67mod shell_loop;
68mod tooltip;
69mod waker;
70
71pub use bounds::{sanitize_restored_window_size, SavedBounds, WindowBoundsStore};
72pub use config::{RedrawPolicy, ScreenshotConfig, ShellConfig, WindowIcon, WindowSize};
73pub use host::{default_paint, Frame, NoHost, ShellControl, ShellHost, WindowGeometry};
74pub use run::run;
75pub use shell_loop::ShellInit;
76
77// Re-exported so a consumer can build a `ShellHost` without naming the
78// renderer crate, and so the versions can never disagree.
79pub use agg_gui_wgpu::{CopySrc, Gpu, WgpuGfxCtx};
80
81/// The `wgpu` this shell was built against.
82///
83/// Its major version is part of this crate's public API (present modes, the
84/// render context, the device behind [`Gpu`]), so an app that names `wgpu`
85/// types itself should reach them through here rather than adding its own
86/// `wgpu` dependency, where a mismatched major would silently produce two
87/// incompatible sets of types.
88pub use wgpu;
89
90/// The `winit` this shell was built against.
91///
92/// Its major version is part of this crate's public API (the window handed to
93/// the builder closure, fullscreen and monitor types), so an app that names
94/// `winit` types itself should reach them through here rather than adding its
95/// own `winit` dependency.
96pub use winit;
97
98/// Why the shell could not start, or could not finish.
99#[derive(Debug)]
100#[non_exhaustive]
101pub enum ShellError {
102    /// Creating or running the winit event loop failed.
103    EventLoop(winit::error::EventLoopError),
104    /// The OS refused to create the window.
105    CreateWindow(winit::error::OsError),
106    /// wgpu could not produce a usable device or surface — at start-up, or
107    /// when rebuilding after a device loss.
108    Gpu(agg_gui_wgpu::GpuInitError),
109    /// A configured deterministic capture could not be produced.
110    Screenshot(String),
111    /// [`ShellControl::request_relaunch`] could not start the new process.
112    Relaunch(std::io::Error),
113    /// The app's builder closure failed. Build one with [`ShellError::app`].
114    App(Box<dyn std::error::Error + Send + Sync>),
115}
116
117impl ShellError {
118    /// Wrap an app-side start-up failure so a builder closure can use `?`.
119    pub fn app(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
120        Self::App(error.into())
121    }
122}
123
124impl std::fmt::Display for ShellError {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        match self {
127            Self::EventLoop(e) => write!(f, "winit event loop: {e}"),
128            Self::CreateWindow(e) => write!(f, "create window: {e}"),
129            Self::Gpu(e) => write!(f, "wgpu init: {e}"),
130            Self::Screenshot(msg) => write!(f, "screenshot: {msg}"),
131            Self::Relaunch(e) => write!(f, "relaunch: {e}"),
132            Self::App(e) => write!(f, "app start-up: {e}"),
133        }
134    }
135}
136
137impl std::error::Error for ShellError {
138    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
139        match self {
140            Self::EventLoop(e) => Some(e),
141            Self::CreateWindow(e) => Some(e),
142            Self::Gpu(e) => Some(e),
143            Self::Relaunch(e) => Some(e),
144            Self::App(e) => Some(e.as_ref()),
145            Self::Screenshot(_) => None,
146        }
147    }
148}