1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
//! The [`Presenter`] trait: what a renderer crate implements to rasterize a grid and present it
//! to a window surface.
//!
//! `Presenter` is an [`Output`](retroglyph_core::backend::Output) supertrait plus window-surface
//! operations, with no input methods: the event loop owns input, and
//! [`WindowBackend`](crate::WindowBackend) forwards translated events into its own queue instead.
//!
//! | Presenter | `present()` | `init_surface()` |
//! |---|---|---|
//! | `SoftwareRenderer` (retroglyph-software) | Copies pixel buffer to softbuffer surface | Creates `softbuffer::Context` + `Surface` |
//! | `GlRenderer` (retroglyph-gl) | Instanced draw + swaps buffers | Creates a GL context (glutin native / WebGL2 wasm) from the window |
//! | `WgpuRenderer` (future) | Submits render pass + presents swap chain | Creates `wgpu::Surface` + `Device` |
//!
//! See the crate-level docs (`crate` root, "DPI, scale, and the resize contract" and
//! "Threading model" sections) for the physical-pixel/no-auto-scaling contract on
//! [`cell_size`](Presenter::cell_size), the sub-cell-remainder behavior on
//! [`resize_surface`](Presenter::resize_surface), and the single-threaded execution model
//! every `Presenter` implementation runs under.
use ;
use Output;
use fmt;
use Arc;
/// A window/display handle pair, as one trait.
///
/// Presenters receive [`raw-window-handle`](raw_window_handle) types, not a concrete
/// `winit::window::Window`: softbuffer, wgpu, and glutin all accept these handles directly, so
/// any windowing library that produces them can drive the same presenter, and only this crate
/// depends on winit itself.
///
/// `raw-window-handle` has no combined trait, and surface libraries need to *own* the handle
/// (softbuffer stores it for the surface's lifetime), so presenters receive `Arc<dyn
/// WindowHandle>`: rwh implements the handle traits for `Arc<H: ?Sized>`, so the trait object
/// passes straight into `softbuffer::Surface::new` / `wgpu::Instance::create_surface`.
///
/// # Examples
///
/// Blanket-implemented for any type implementing both `raw-window-handle` traits; there is
/// nothing to implement directly on `WindowHandle` itself.
///
/// ```
/// use raw_window_handle::{
/// DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle,
/// WindowHandle as RawWindowHandle,
/// };
/// use retroglyph_window::WindowHandle;
///
/// struct NoWindow;
///
/// impl HasWindowHandle for NoWindow {
/// fn window_handle(&self) -> Result<RawWindowHandle<'_>, HandleError> {
/// Err(HandleError::NotSupported)
/// }
/// }
///
/// impl HasDisplayHandle for NoWindow {
/// fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
/// Err(HandleError::NotSupported)
/// }
/// }
///
/// fn assert_is_window_handle<T: WindowHandle>(_handle: &T) {}
/// assert_is_window_handle(&NoWindow);
/// ```
/// A surface-lifecycle error that can optionally signal whether it's worth retrying.
///
/// [`Presenter::SurfaceError`] is a per-implementation associated type: softbuffer's error enum
/// has no `Lost`/`Outdated`/`Timeout` discrimination the way `wgpu::SurfaceError` does, so today's
/// only backend (`SoftwareRenderer`) has no structured way to say "this specific failure is
/// fatal, don't bother retrying." [`is_recoverable`](Self::is_recoverable) is that hook: a
/// presenter with real error categories can override it to return `false` for a truly fatal
/// failure, while every presenter that doesn't need the distinction (including every backend that
/// exists in this crate today) can implement this trait with an empty body and inherit the
/// default `true`.
///
/// Deliberately not blanket-implemented for every `Debug + Display` type: that would make it
/// impossible for any concrete error type to override [`is_recoverable`](Self::is_recoverable) at
/// all (a specific `impl` would conflict with the blanket one), defeating the point of the trait.
/// Instead, each `SurfaceError` type needs one explicit (and usually empty) `impl
/// RecoverableError for ...` block: see `retroglyph_software`'s `SurfaceError` for the minimal
/// case that just inherits the default.
///
/// # Examples
///
/// ```
/// use core::fmt;
/// use retroglyph_window::RecoverableError;
///
/// #[derive(Debug)]
/// enum MySurfaceError {
/// Init,
/// Lost,
/// }
///
/// impl fmt::Display for MySurfaceError {
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// match self {
/// Self::Init => write!(f, "surface init failed"),
/// Self::Lost => write!(f, "surface lost"),
/// }
/// }
/// }
///
/// impl RecoverableError for MySurfaceError {
/// fn is_recoverable(&self) -> bool {
/// // Init failures are fatal; a lost surface may come back.
/// matches!(self, Self::Lost)
/// }
/// }
///
/// assert!(!MySurfaceError::Init.is_recoverable());
/// assert!(MySurfaceError::Lost.is_recoverable());
/// ```
// `Infallible` is uninhabited: no value of it can ever exist, so `is_recoverable` can never
// actually be called on one, but a presenter that can't fail (e.g. a test mock) still needs
// `type SurfaceError = core::convert::Infallible` to satisfy the `RecoverableError` bound, so
// this impl exists purely for that convenience.
/// A ready-made, string-backed [`SurfaceError`](Presenter::SurfaceError) for presenters whose
/// underlying surface library reports failures as opaque strings rather than a structured error
/// enum.
///
/// Several presenter backends (e.g. `retroglyph-gl`'s native/wasm split, or a future softbuffer
/// backend) need only two buckets ("surface/context creation failed" (fatal) and "presenting a
/// frame failed" (potentially recoverable)) and would otherwise each hand-roll the same `enum {
/// Init(String), Present(String) }` plus [`RecoverableError`] impl. This type is that common
/// shape, provided once here so backends can reuse it directly instead of duplicating it.
/// A renderer that rasterizes grid content and presents it to a window surface.
///
/// A supertrait of [`Output`], adding the surface lifecycle (`init_surface`, `resize_surface`,
/// `present`, `cell_size`) that the event loop drives. Every `Presenter` implementation is an
/// `Output` implementation for free: [`WindowBackend`](crate::WindowBackend) delegates its own
/// `Output` impl straight through to `P: Presenter`, with no duplicated method bodies.
///
/// # Sub-cell offsets and spill
///
/// A [`Tile`](retroglyph_core::tile::Tile)'s `dx`/`dy` shift its glyph within, and past, its cell.
/// This is a cross-backend rendering contract: the CPU rasterizer (`retroglyph-software`) and the
/// GPU one (`retroglyph-gl`) must produce the same pixels, so it is specified here once instead of
/// in mirrored per-backend comments that reference each other (and drift when only one is
/// touched). A `Presenter` that honors sub-cell offsets must obey all four points:
///
/// - `dx`/`dy` are in **unscaled font pixels** (a presenter multiplies by its own integer scale);
/// negative `dx` shifts the glyph left, negative `dy` up.
/// - The cell's **background fill is always the full, unshifted cell** rectangle. An offset moves
/// only the glyph, never the background.
/// - An offset glyph **may spill past its cell edge into neighboring cells**, and that spill is
/// **uniform in all four directions**: a glyph pushed right/down onto a later neighbor spills
/// the same way as one pushed left/up onto an earlier neighbor.
/// - The mechanism that guarantees that uniformity is a **two-pass draw**: lay down *every* cell's
/// background first, then draw *every* cell's (offset) glyph over the result. Interleaving the
/// two per cell would let a later cell's background overwrite an earlier neighbor's spilled
/// glyph, breaking spill in the right/down directions only.
///
/// The offset *application* is deliberately not shared code: `retroglyph-gl` shifts a quad's vertex
/// position in its vertex shader, `retroglyph-software` shifts `origin_x`/`origin_y` in a CPU blit:
/// irreducibly different mechanics that must nonetheless agree on the four points above.
///
/// # Examples
///
/// ```
/// use retroglyph_core::backend::{DrawCell, Output};
/// use retroglyph_core::grid::Size;
/// use retroglyph_window::{Presenter, WindowHandle};
/// use std::sync::Arc;
///
/// struct NullPresenter;
///
/// impl Output for NullPresenter {
/// type Error = core::convert::Infallible;
///
/// fn draw_layers<'a, I>(&mut self, _content: I) -> Result<(), Self::Error>
/// where
/// I: Iterator<Item = DrawCell<'a>>,
/// {
/// Ok(())
/// }
///
/// fn flush(&mut self) -> Result<(), Self::Error> {
/// Ok(())
/// }
///
/// fn size(&self) -> Size {
/// Size::new(4, 2)
/// }
///
/// fn clear(&mut self) -> Result<(), Self::Error> {
/// Ok(())
/// }
/// }
///
/// impl Presenter for NullPresenter {
/// type SurfaceError = core::convert::Infallible;
///
/// fn init_surface(&mut self, _window: Arc<dyn WindowHandle>) -> Result<(), Self::SurfaceError> {
/// Ok(())
/// }
///
/// fn resize_surface(&mut self, _width: u32, _height: u32) {}
///
/// fn present(&mut self) -> Result<(), Self::SurfaceError> {
/// Ok(())
/// }
///
/// fn cell_size(&self) -> (u32, u32) {
/// (8, 16)
/// }
/// }
/// ```