Skip to main content

retroglyph_window/
presenter.rs

1//! The [`Presenter`] trait: what a renderer crate implements to rasterize a grid and present it
2//! to a window surface.
3//!
4//! `Presenter` is an [`Output`](retroglyph_core::backend::Output) supertrait plus window-surface
5//! operations, with no input methods: the event loop owns input, and
6//! [`WindowBackend`](crate::WindowBackend) forwards translated events into its own queue instead.
7//!
8//! | Presenter | `present()` | `init_surface()` |
9//! |---|---|---|
10//! | `SoftwareRenderer` (retroglyph-software) | Copies pixel buffer to softbuffer surface | Creates `softbuffer::Context` + `Surface` |
11//! | `GlRenderer` (retroglyph-gl) | Instanced draw + swaps buffers | Creates a GL context (glutin native / WebGL2 wasm) from the window |
12//! | `WgpuRenderer` (future) | Submits render pass + presents swap chain | Creates `wgpu::Surface` + `Device` |
13//!
14//! See the crate-level docs (`crate` root, "DPI, scale, and the resize contract" and
15//! "Threading model" sections) for the physical-pixel/no-auto-scaling contract on
16//! [`cell_size`](Presenter::cell_size), the sub-cell-remainder behavior on
17//! [`resize_surface`](Presenter::resize_surface), and the single-threaded execution model
18//! every `Presenter` implementation runs under.
19
20use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
21use retroglyph_core::backend::Output;
22use std::fmt;
23use std::sync::Arc;
24
25/// A window/display handle pair, as one trait.
26///
27/// Presenters receive [`raw-window-handle`](raw_window_handle) types, not a concrete
28/// `winit::window::Window`: softbuffer, wgpu, and glutin all accept these handles directly, so
29/// any windowing library that produces them can drive the same presenter, and only this crate
30/// depends on winit itself.
31///
32/// `raw-window-handle` has no combined trait, and surface libraries need to *own* the handle
33/// (softbuffer stores it for the surface's lifetime), so presenters receive `Arc<dyn
34/// WindowHandle>` -- rwh implements the handle traits for `Arc<H: ?Sized>`, so the trait object
35/// passes straight into `softbuffer::Surface::new` / `wgpu::Instance::create_surface`.
36pub trait WindowHandle: HasWindowHandle + HasDisplayHandle {}
37
38impl<T: HasWindowHandle + HasDisplayHandle + ?Sized> WindowHandle for T {}
39
40/// A surface-lifecycle error that can optionally signal whether it's worth retrying.
41///
42/// [`Presenter::SurfaceError`] is a per-implementation associated type: softbuffer's error enum
43/// has no `Lost`/`Outdated`/`Timeout` discrimination the way `wgpu::SurfaceError` does, so today's
44/// only backend (`SoftwareRenderer`) has no structured way to say "this specific failure is
45/// fatal, don't bother retrying." [`is_recoverable`](Self::is_recoverable) is that hook: a
46/// presenter with real error categories can override it to return `false` for a truly fatal
47/// failure, while every presenter that doesn't need the distinction (including every backend that
48/// exists in this crate today) can implement this trait with an empty body and inherit the
49/// default `true`.
50///
51/// Deliberately not blanket-implemented for every `Debug + Display` type: that would make it
52/// impossible for any concrete error type to override [`is_recoverable`](Self::is_recoverable) at
53/// all (a specific `impl` would conflict with the blanket one), defeating the point of the trait.
54/// Instead, each `SurfaceError` type needs one explicit (and usually empty) `impl
55/// RecoverableError for ...` block -- see `retroglyph_software`'s `SurfaceError` for the minimal
56/// case that just inherits the default.
57pub trait RecoverableError: core::fmt::Debug + core::fmt::Display {
58    /// Whether this error represents a transient failure worth retrying, as opposed to a fatal
59    /// one.
60    ///
61    /// Defaults to `true`: absent any structured error categorization, every failure is treated
62    /// as potentially transient, matching the generic consecutive-failure recovery heuristic
63    /// `winit::run::present_failure_action` already applies. Override to return `false` only for
64    /// an error variant known to be unrecoverable regardless of retries (e.g. a `wgpu::SurfaceError
65    /// ::Lost` variant that persists until the surface is fully rebuilt from a different code
66    /// path than a simple retry).
67    #[must_use]
68    fn is_recoverable(&self) -> bool {
69        true
70    }
71}
72
73// `Infallible` is uninhabited -- no value of it can ever exist, so `is_recoverable` can never
74// actually be called on one -- but a presenter that can't fail (e.g. a test mock) still needs
75// `type SurfaceError = core::convert::Infallible` to satisfy the `RecoverableError` bound, so
76// this impl exists purely for that convenience.
77impl RecoverableError for core::convert::Infallible {}
78
79/// A ready-made, string-backed [`SurfaceError`](Presenter::SurfaceError) for presenters whose
80/// underlying surface library reports failures as opaque strings rather than a structured error
81/// enum.
82///
83/// Several presenter backends (e.g. `retroglyph-gl`'s native/wasm split, or a future softbuffer
84/// backend) need only two buckets -- "surface/context creation failed" (fatal) and "presenting a
85/// frame failed" (potentially recoverable) -- and would otherwise each hand-roll the same `enum {
86/// Init(String), Present(String) }` plus [`RecoverableError`] impl. This type is that common
87/// shape, provided once here so backends can reuse it directly instead of duplicating it.
88#[derive(Debug)]
89pub enum GenericSurfaceError {
90    /// Creating the surface or its underlying context failed. Treated as fatal (not
91    /// recoverable): a presenter cannot proceed without a surface, and retrying the same
92    /// creation path is very unlikely to succeed.
93    Init(String),
94    /// Presenting a frame failed. Treated as potentially recoverable so the event loop's
95    /// consecutive-failure heuristic can retry before giving up.
96    Present(String),
97}
98
99impl fmt::Display for GenericSurfaceError {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        match self {
102            Self::Init(msg) => write!(f, "surface init: {msg}"),
103            Self::Present(msg) => write!(f, "surface present: {msg}"),
104        }
105    }
106}
107
108impl std::error::Error for GenericSurfaceError {}
109
110impl RecoverableError for GenericSurfaceError {
111    fn is_recoverable(&self) -> bool {
112        // Init failures are fatal (nothing to retry into); present failures may be transient.
113        matches!(self, Self::Present(_))
114    }
115}
116
117/// A renderer that rasterizes grid content and presents it to a window surface.
118///
119/// A supertrait of [`Output`], adding the surface lifecycle (`init_surface`, `resize_surface`,
120/// `present`, `cell_size`) that the event loop drives. Every `Presenter` implementation is an
121/// `Output` implementation for free: [`WindowBackend`](crate::WindowBackend) delegates its own
122/// `Output` impl straight through to `P: Presenter`, with no duplicated method bodies.
123///
124/// # Sub-cell offsets and spill
125///
126/// A [`Tile`](retroglyph_core::tile::Tile)'s `dx`/`dy` shift its glyph within, and past, its cell.
127/// This is a cross-backend rendering contract: the CPU rasterizer (`retroglyph-software`) and the
128/// GPU one (`retroglyph-gl`) must produce the same pixels, so it is specified here once instead of
129/// in mirrored per-backend comments that reference each other (and drift when only one is
130/// touched). A `Presenter` that honors sub-cell offsets must obey all four points:
131///
132/// - `dx`/`dy` are in **unscaled font pixels** (a presenter multiplies by its own integer scale);
133///   negative `dx` shifts the glyph left, negative `dy` up.
134/// - The cell's **background fill is always the full, unshifted cell** rectangle. An offset moves
135///   only the glyph, never the background.
136/// - An offset glyph **may spill past its cell edge into neighboring cells**, and that spill is
137///   **uniform in all four directions** -- a glyph pushed right/down onto a later neighbor spills
138///   the same way as one pushed left/up onto an earlier neighbor.
139/// - The mechanism that guarantees that uniformity is a **two-pass draw**: lay down *every* cell's
140///   background first, then draw *every* cell's (offset) glyph over the result. Interleaving the
141///   two per cell would let a later cell's background overwrite an earlier neighbor's spilled
142///   glyph, breaking spill in the right/down directions only.
143///
144/// The offset *application* is deliberately not shared code: `retroglyph-gl` shifts a quad's vertex
145/// position in its vertex shader, `retroglyph-software` shifts `origin_x`/`origin_y` in a CPU blit
146/// -- irreducibly different mechanics that must nonetheless agree on the four points above.
147pub trait Presenter: Output {
148    /// Surface lifecycle error (context creation, buffer acquisition,
149    /// present).
150    type SurfaceError: RecoverableError;
151
152    /// Initialize the window surface.
153    ///
154    /// Called once from the loop's `resumed` handler. The presenter creates
155    /// its platform surface (softbuffer surface, wgpu device+surface, GL
156    /// context) from the raw window/display handles.
157    ///
158    /// # Errors
159    ///
160    /// Returns [`Self::SurfaceError`] if surface or context creation fails.
161    fn init_surface(&mut self, window: Arc<dyn WindowHandle>) -> Result<(), Self::SurfaceError>;
162
163    /// Resize the window surface to a new physical pixel size.
164    ///
165    /// Called on every window resize event with `width`/`height` already resolved by the
166    /// caller -- for the `winit` driver (see `winit::run::WindowApp::resize_to`), that means
167    /// `cols * cell_w` x `rows * cell_h`, where `cols`/`rows` are the window's physical size
168    /// divided down to whole cells. Any sub-cell remainder is truncated, not centered or
169    /// cleared: when the window's physical size isn't an exact multiple of the cell size,
170    /// `width`/`height` here are the largest whole-cell-multiple that fits, which can be
171    /// smaller than the window's actual physical size. The OS window itself is never resized
172    /// to compensate, so a non-exact-multiple resize leaves a thin strip at the window's
173    /// trailing edge outside the surface -- retroglyph does not paint or clear that strip;
174    /// whatever the OS/windowing backend leaves there remains visible until a subsequent
175    /// resize covers it.
176    fn resize_surface(&mut self, width: u32, height: u32);
177
178    /// Notify the presenter that the window's scale factor (DPI) changed.
179    ///
180    /// Called when the window moves to a display with a different pixel density, or the
181    /// system DPI setting changes. The event loop follows this with
182    /// [`resize_surface`](Self::resize_surface) for the window's new physical size, so
183    /// this hook only needs to handle DPI-dependent state that isn't a plain buffer
184    /// resize (e.g. regenerating a font atlas rasterized for a particular scale).
185    ///
186    /// Defaults to a no-op: presenters whose rasterization doesn't depend on DPI (like
187    /// `SoftwareRenderer`'s integer `scale` config, set once at construction) need no
188    /// action here.
189    fn scale_factor_changed(&mut self, _scale_factor: f64) {}
190
191    /// Present the rasterized frame to the window surface.
192    ///
193    /// Called after each app tick. A lost frame is not fatal; the caller
194    /// logs the error and continues.
195    ///
196    /// # Errors
197    ///
198    /// Returns [`Self::SurfaceError`] if the surface buffer can't be acquired
199    /// or presented (e.g. context lost on wasm, page flip pending on
200    /// DRI/KMS).
201    fn present(&mut self) -> Result<(), Self::SurfaceError>;
202
203    /// Cell size in physical pixels `(width, height)`.
204    ///
205    /// Physical pixels, not logical/DPI-scaled pixels, and never auto-scaled by this crate for
206    /// display DPI -- see the crate-level "DPI, scale, and the resize contract" docs. A presenter
207    /// whose cells should grow on a `HiDPI` display must change what this returns itself (from
208    /// [`resize`](Output::resize) or [`scale_factor_changed`](Self::scale_factor_changed)); absent
209    /// that, it stays constant for the presenter's lifetime.
210    ///
211    /// `(u32, u32)` rather than [`Size`](retroglyph_core::grid::Size) because grid coordinates
212    /// are `u16` but pixel arithmetic uses `u32` (winit `PhysicalSize`).
213    #[must_use]
214    fn cell_size(&self) -> (u32, u32);
215}
216
217#[cfg(test)]
218mod generic_surface_error_tests {
219    use super::{GenericSurfaceError, RecoverableError};
220
221    #[test]
222    fn init_is_not_recoverable() {
223        let err = GenericSurfaceError::Init("boom".to_string());
224        assert!(!err.is_recoverable());
225    }
226
227    #[test]
228    fn present_is_recoverable() {
229        let err = GenericSurfaceError::Present("boom".to_string());
230        assert!(err.is_recoverable());
231    }
232
233    #[test]
234    fn display_includes_message() {
235        let init = GenericSurfaceError::Init("init failed".to_string());
236        assert!(init.to_string().contains("init failed"));
237
238        let present = GenericSurfaceError::Present("present failed".to_string());
239        assert!(present.to_string().contains("present failed"));
240    }
241}