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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! 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` (retroglyph-wgpu) | Submits a render pass + presents the swap chain | Creates a `wgpu::Surface`, `Device`, and `Queue` |
//!
//! 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 Tile;
use fmt;
use Arc;
use crateCellGeometry;
/// 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`.
///
/// `Send + Sync` is part of the trait rather than left to each implementation because a trait
/// object erases auto traits its trait doesn't name, and `wgpu::Instance::create_surface` requires
/// them: its safe entry point takes ownership of a `Send + Sync` handle, and the alternative that
/// doesn't is `unsafe`. Declaring them here is what makes `Arc<dyn WindowHandle>` usable with it.
/// Every windowing library that produces `raw-window-handle` types satisfies this already
/// (`winit::window::Window` does on every platform).
///
/// # 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`.
///
/// 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`]'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 ones (`retroglyph-gl`, `retroglyph-wgpu`) 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.
///
/// See <https://main.retroglyph.dev/book/explanation/coordinates.html> for why the offset
/// *application* itself is not shared code across backends.
///
/// # 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)
/// }
/// }
/// ```
/// The glyph a `Presenter` should paint art (a bitmap-font glyph or a tileset sprite) for, or
/// `None` when this cell draws none.
///
/// Both pixel backends (`retroglyph-software`, `retroglyph-gl`) ask this same question at
/// several points in their draw path (sprite-vs-font dispatch, font fallback, whether a cell
/// counts as "occupied" for compositing), and used to each answer it independently, which let
/// them drift (retroglyph#762). This is the one place that decides it:
///
/// - A [`TileFlags::SPAN_COVERED`](retroglyph_core::tile::TileFlags::SPAN_COVERED) cell (see
/// [`Tile::span_offset`]) draws no art of its own: the span's anchor already drew one piece of
/// artwork across the whole footprint, and this cell's glyph is only that artwork's text
/// fallback for backends that can't draw it.
/// - An [`is_empty`](Tile::is_empty) tile draws no art: nothing has been written to it, so it is
/// transparent when compositing layers. This is the canonical blank rule, matching
/// [`Grid::flatten_into`](retroglyph_core::grid::Grid::flatten_into) and the cell backends;
/// comparing the glyph itself against `' '` is both slower (it can't be decided without the
/// glyph) and wrong for a font whose space glyph isn't blank.
///
/// Neither check depends on whether a sprite exists for the glyph: that dispatch (sprite vs.
/// bitmap font) is a separate, backend-specific decision made *after* this one, once a caller
/// knows a cell draws art at all.
pub const