retroglyph_core/backend/mod.rs
1//! Pluggable rendering backends.
2//!
3//! The [`Output`], [`Input`], and [`Cursor`] traits (plus the [`Backend`] bundle that ties them
4//! together) and the dependency-free [`Headless`] test backend live here. Platform backends
5//! (crossterm, software/winit) are separate crates (`retroglyph-crossterm`, `retroglyph-software`)
6//! that depend on this one and implement these traits.
7
8pub mod headless;
9
10pub use headless::Headless;
11
12use crate::event::Event;
13use crate::grid::{Pos, Size};
14use crate::tile::Tile;
15use crate::tint::Tint;
16use core::time::Duration;
17
18/// Associated error type used by all fallible backend methods.
19///
20/// Backends that are infallible (e.g. `Headless`, `SoftwareRenderer`) use
21/// [`core::convert::Infallible`]. Fallible backends (e.g. `Crossterm`) use
22/// [`std::io::Error`].
23///
24/// Requiring [`core::error::Error`] rather than just [`Display`](core::fmt::Display) +
25/// [`Debug`](core::fmt::Debug) lets generic code convert `B::Error` into `Box<dyn Error>` or any
26/// error-trait-based caller error with a plain `?`, and exposes `source()` chains for concrete
27/// error types that wrap an inner error.
28///
29/// # Examples
30///
31/// ```
32/// use retroglyph_core::backend::BackendError;
33/// use core::fmt;
34///
35/// #[derive(Debug)]
36/// struct MyBackendError;
37///
38/// impl fmt::Display for MyBackendError {
39/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40/// write!(f, "my backend failed")
41/// }
42/// }
43///
44/// impl core::error::Error for MyBackendError {}
45/// impl BackendError for MyBackendError {}
46/// ```
47pub trait BackendError: core::error::Error {}
48
49impl BackendError for core::convert::Infallible {}
50#[cfg(feature = "std")]
51impl BackendError for std::io::Error {}
52
53/// One cell handed to a backend at draw time: the tile, plus the state that does not fit in one.
54///
55/// [`Tile`] is deliberately compact (20 bytes, no padding to spare), so a cell's rarer members
56/// live in a sparse side table on [`Grid`](crate::grid::Grid) instead. A backend cannot reach
57/// that table, so they are delivered here.
58///
59/// This is a struct rather than a tuple because it has grown twice and will grow again. Each
60/// addition would otherwise break every backend's `draw` signature and leave the meaning of a
61/// fourth or fifth unnamed element to the reader.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63#[non_exhaustive]
64pub struct DrawCell<'a> {
65 /// Which layer this cell belongs to. Always `0` for cells arriving through
66 /// [`Output::draw`].
67 pub layer: u8,
68 /// Where the cell sits in the grid.
69 pub pos: Pos,
70 /// The tile itself.
71 pub tile: &'a Tile,
72 /// The tile's full grapheme cluster, or `None` to render [`Tile::glyph`] alone.
73 ///
74 /// `Some` only for multi-codepoint clusters (combining marks, ZWJ sequences), and **only
75 /// ever `Some` when the `egc` feature is enabled**: without it `Grid` never populates the
76 /// side table, so a backend that does not support `egc` can ignore this entirely and render
77 /// from [`Tile::glyph`].
78 pub grapheme: Option<&'a str>,
79 /// How a pixel backend recolours this cell's sprite.
80 ///
81 /// [`Tint::None`] for the overwhelming majority of cells. Cell backends have no sprite to
82 /// recolour and ignore it; see [`Tint`].
83 pub tint: Tint,
84}
85
86impl<'a> DrawCell<'a> {
87 /// A cell on layer 0 with no grapheme text and no tint: the shape almost every test and
88 /// cell backend wants.
89 #[must_use]
90 pub const fn new(pos: Pos, tile: &'a Tile) -> Self {
91 Self {
92 layer: 0,
93 pos,
94 tile,
95 grapheme: None,
96 tint: Tint::None,
97 }
98 }
99
100 /// [`new`](Self::new) on an explicit layer.
101 #[must_use]
102 pub const fn on_layer(layer: u8, pos: Pos, tile: &'a Tile) -> Self {
103 Self {
104 layer,
105 pos,
106 tile,
107 grapheme: None,
108 tint: Tint::None,
109 }
110 }
111
112 /// This cell with `grapheme` as its full cluster text.
113 #[must_use]
114 pub const fn with_grapheme(mut self, grapheme: Option<&'a str>) -> Self {
115 self.grapheme = grapheme;
116 self
117 }
118
119 /// This cell with `tint` applied to its sprite.
120 #[must_use]
121 pub const fn with_tint(mut self, tint: Tint) -> Self {
122 self.tint = tint;
123 self
124 }
125}
126
127/// Draws grid content to a display and reports its dimensions.
128///
129/// This is the only one of the three backend facets ([`Output`], [`Input`], [`Cursor`]) that's
130/// fallible: writing to a real display can fail (a broken pipe, a closed terminal, a lost
131/// surface), so every mutating method here returns `Result<(), Self::Error>`.
132///
133/// # Examples
134///
135/// ```
136/// use retroglyph_core::backend::{DrawCell, Output};
137/// use retroglyph_core::grid::Size;
138///
139/// struct NullOutput;
140///
141/// impl Output for NullOutput {
142/// type Error = core::convert::Infallible;
143///
144/// fn draw_layers<'a, I>(&mut self, _content: I) -> Result<(), Self::Error>
145/// where
146/// I: Iterator<Item = DrawCell<'a>>,
147/// {
148/// Ok(())
149/// }
150///
151/// fn flush(&mut self) -> Result<(), Self::Error> {
152/// Ok(())
153/// }
154///
155/// fn size(&self) -> Size {
156/// Size::new(4, 2)
157/// }
158///
159/// fn clear(&mut self) -> Result<(), Self::Error> {
160/// Ok(())
161/// }
162/// }
163/// ```
164pub trait Output {
165 /// Error type returned by fallible operations.
166 type Error: BackendError;
167
168 /// Draw changed cells to the output surface, layer 0 only.
169 ///
170 /// Every cell arrives as a [`DrawCell`], which carries the out-of-line state a [`Tile`]
171 /// cannot: its full grapheme cluster and its tint. Both live in a side table on
172 /// [`Grid`](crate::grid::Grid)
173 /// rather than in the tile, so a backend that needs either must read it from here.
174 ///
175 /// The default implementation forwards to [`draw_layers`](Self::draw_layers), which every
176 /// backend implements. [`crate::Terminal::present`] never calls this method directly (it
177 /// always goes through `draw_layers`, pre-flattened onto layer 0 for a backend that doesn't
178 /// composite; see [`composites_layers`](Self::composites_layers)), so overriding this is
179 /// only worthwhile if a backend has a cheaper direct path for the known-single-layer case
180 /// than its own `draw_layers` would take.
181 ///
182 /// # Errors
183 ///
184 /// See [`draw_layers`](Self::draw_layers), which this forwards to by default and shares
185 /// its error contract with.
186 fn draw<'a, I>(&mut self, content: I) -> Result<(), Self::Error>
187 where
188 I: Iterator<Item = DrawCell<'a>>,
189 {
190 self.draw_layers(content)
191 }
192
193 /// Draw changed cells across all layers.
194 ///
195 /// [`crate::Terminal::present`] always calls this method, never [`draw`](Self::draw)
196 /// directly, for every backend. A backend that renders one glyph per cell and returns
197 /// `false` from [`composites_layers`](Self::composites_layers) (the default) receives a
198 /// stream `present` has already pre-flattened onto layer 0 (all allocated layers
199 /// composited into one frame first, so layers 1+ still appear on every backend, not only
200 /// pixel ones); implementing this is no different from what implementing single-layer
201 /// `draw` used to mean. A pixel/GPU backend that returns `true` from `composites_layers`
202 /// receives the real, multi-layer stream here and does its own compositing (per-pixel or
203 /// per-quad, plus sub-cell offsets and transparency as needed).
204 ///
205 /// When [`needs_full_frame`](Self::needs_full_frame) returns `true`, this
206 /// receives **all** cells from every allocated layer, and the backend
207 /// should clear its output surface before drawing.
208 ///
209 /// Items are the same [`DrawCell`] [`draw`](Self::draw) receives, read through
210 /// [`DrawCell::layer`] rather than a separate element.
211 ///
212 /// # Errors
213 ///
214 /// `Self::Error` is implementation-defined (a broken pipe or closed terminal for a
215 /// process-backed display, a lost surface for a windowed one); implementations do not
216 /// roll back cells already written before the failure. Because
217 /// [`crate::Terminal::present`] only swaps its diff buffers into `previous` after the
218 /// call that reached this method succeeds, a failed draw leaves the same cells marked
219 /// dirty, so they are resent on the next successful present rather than silently
220 /// dropped.
221 fn draw_layers<'a, I>(&mut self, content: I) -> Result<(), Self::Error>
222 where
223 I: Iterator<Item = DrawCell<'a>>;
224
225 /// Returns `true` if the backend needs the **entire** frame (all cells on
226 /// all layers) on every call to [`draw_layers`](Self::draw_layers), rather
227 /// than just the changed cells.
228 ///
229 /// Pixel-based backends (e.g. `SoftwareRenderer`) need this because
230 /// sub-cell offsets can spill glyph pixels into adjacent cells — without
231 /// a full redraw, orphaned pixels from the previous frame linger.
232 ///
233 /// The default implementation returns `false`.
234 fn needs_full_frame(&self) -> bool {
235 false
236 }
237
238 /// Whether this backend composites layers itself (per pixel or quad),
239 /// receiving the raw layered stream from [`draw_layers`](Self::draw_layers).
240 ///
241 /// Backends that render one glyph per cell return `false` (the default) and
242 /// receive a pre-flattened, single-layer stream: [`crate::Terminal::present`]
243 /// composites all allocated layers into one frame first. This makes layers
244 /// 1+ appear on every backend, not only pixel backends. Pixel/GPU backends
245 /// return `true` and composite the layers themselves.
246 fn composites_layers(&self) -> bool {
247 false
248 }
249
250 /// Flush buffered output to the display.
251 ///
252 /// # Errors
253 ///
254 /// `Self::Error` is implementation-defined (a broken pipe, a closed terminal, a lost
255 /// surface). [`crate::Terminal::present`] calls this only after
256 /// [`draw`](Self::draw)/[`draw_layers`](Self::draw_layers) succeed, and swaps its diff
257 /// buffers only after `flush` also succeeds; a failed flush therefore leaves the
258 /// current frame's cells buffered but unconfirmed, and they are resent on the next
259 /// successful present.
260 fn flush(&mut self) -> Result<(), Self::Error>;
261
262 /// Return current display dimensions.
263 #[must_use]
264 fn size(&self) -> Size;
265
266 /// Clear the entire display.
267 ///
268 /// # Errors
269 ///
270 /// `Self::Error` is implementation-defined (a broken pipe, a closed terminal, a lost
271 /// surface). Unlike [`draw`](Self::draw)/[`flush`](Self::flush), this is not part of
272 /// [`crate::Terminal::present`]'s per-frame path; callers that invoke it directly
273 /// (some backends also call it internally on resize) should treat a failure as leaving
274 /// the display in an unknown, possibly partially cleared state and retry or tear down
275 /// rather than assume the previous contents are still intact.
276 fn clear(&mut self) -> Result<(), Self::Error>;
277
278 /// Notify the backend of a resize to `size`, updating what [`size`](Self::size) reports.
279 ///
280 /// Called automatically by [`crate::Terminal::resize`] after both grids are resized.
281 /// Backends that maintain internal state tied to terminal dimensions (such as
282 /// [`Headless`]) should override this to update that state. The default
283 /// implementation is a no-op.
284 ///
285 /// A driver may also call this directly, ahead of and independent from
286 /// [`crate::Terminal::resize`], to keep [`size`](Self::size) in sync with an underlying
287 /// surface the moment it changes (a windowed backend reacting to an OS resize, for
288 /// example) without waiting for the app to resize the terminal's grid content in
289 /// response. Doing so does not resize the grid; only [`crate::Terminal::resize`] does that.
290 fn resize(&mut self, size: Size) {
291 let _ = size;
292 }
293}
294
295/// Polls for and accepts input events.
296///
297/// Backends that never receive events from outside their own [`poll_event`](Self::poll_event)
298/// implementation (e.g. `Crossterm`, which reads its own event stream) can use the default
299/// no-op [`push_event`](Self::push_event) via an empty `impl Input for X {}`.
300///
301/// # Examples
302///
303/// ```
304/// use core::time::Duration;
305/// use retroglyph_core::backend::Input;
306/// use retroglyph_core::event::Event;
307/// use std::collections::VecDeque;
308///
309/// struct QueuedInput(VecDeque<Event>);
310///
311/// impl Input for QueuedInput {
312/// fn poll_event(&mut self, _timeout: Duration) -> Option<Event> {
313/// self.0.pop_front()
314/// }
315///
316/// fn push_event(&mut self, event: Event) {
317/// self.0.push_back(event);
318/// }
319/// }
320/// ```
321pub trait Input {
322 /// Poll for an input event, waiting up to `timeout`.
323 fn poll_event(&mut self, timeout: Duration) -> Option<Event>;
324
325 /// Push an event into the backend's event buffer.
326 ///
327 /// Backends that receive events externally (e.g., from a window event
328 /// loop or a test harness) override this to queue events for
329 /// [`poll_event`](Self::poll_event). The default is a no-op.
330 ///
331 /// - Windowed backends: called by `ApplicationHandler` on each event.
332 /// - Headless: called by tests to inject synthetic events.
333 /// - Crossterm: reads from its own event stream; no-op here.
334 fn push_event(&mut self, _event: Event) {}
335}
336
337/// Shows, hides, and moves a text cursor.
338///
339/// Both methods default to a no-op so backends with no text cursor to manage (pixel/windowed
340/// backends, where games draw their own cursor if they want one) can use an empty
341/// `impl Cursor for X {}` instead of writing dead stub bodies by hand.
342///
343/// # Examples
344///
345/// ```
346/// use retroglyph_core::backend::Cursor;
347/// use retroglyph_core::grid::Pos;
348///
349/// struct TrackedCursor {
350/// visible: bool,
351/// position: Pos,
352/// }
353///
354/// impl Cursor for TrackedCursor {
355/// fn set_cursor_visible(&mut self, visible: bool) {
356/// self.visible = visible;
357/// }
358///
359/// fn set_cursor_position(&mut self, position: Pos) {
360/// self.position = position;
361/// }
362/// }
363/// ```
364pub trait Cursor {
365 /// Show or hide the cursor.
366 fn set_cursor_visible(&mut self, _visible: bool) {}
367
368 /// Move the cursor to a position.
369 fn set_cursor_position(&mut self, _position: Pos) {}
370
371 /// Set the cursor's shape (and blink behavior).
372 ///
373 /// Defaults to a no-op, matching [`set_cursor_visible`](Self::set_cursor_visible)/
374 /// [`set_cursor_position`](Self::set_cursor_position): backends with no text cursor to
375 /// manage, or that render on a terminal emulator with no shape-changing escape sequence,
376 /// can ignore this via the default `impl Cursor for X {}`.
377 fn set_cursor_style(&mut self, _style: CursorStyle) {}
378}
379
380/// The text cursor's visual shape and blink behavior.
381///
382/// Mirrors the six shapes a DEC-compatible terminal's `DECSCUSR` escape (`CSI Ps SP q`)
383/// supports: block, underline, and bar, each either blinking or steady. `#[non_exhaustive]`
384/// leaves room for a future shape (e.g. a hollow/outline block) without a breaking change.
385#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
386#[non_exhaustive]
387pub enum CursorStyle {
388 /// A blinking solid block (`█`). The default terminal cursor shape on most emulators.
389 #[default]
390 BlinkingBlock,
391 /// A steady (non-blinking) solid block.
392 SteadyBlock,
393 /// A blinking underscore (`_`).
394 BlinkingUnderline,
395 /// A steady (non-blinking) underscore.
396 SteadyUnderline,
397 /// A blinking vertical bar (`|`), as commonly used for text-insertion cursors.
398 BlinkingBar,
399 /// A steady (non-blinking) vertical bar.
400 SteadyBar,
401}
402
403/// A rendering backend that presents grid content to a display and provides input events.
404///
405/// This is a pure ergonomic bundle over [`Output`], [`Input`], and [`Cursor`], with no members
406/// of its own: every type implementing all three gets `Backend` for free, and every generic
407/// call site that only needs one or two facets should bound on those directly instead of
408/// requiring all three through this trait.
409///
410/// # Examples
411///
412/// There is nothing to implement directly: a type gets `Backend` for free the moment it
413/// implements all three facet traits.
414///
415/// ```
416/// use core::time::Duration;
417/// use retroglyph_core::backend::{Backend, Cursor, DrawCell, Input, Output};
418/// use retroglyph_core::event::Event;
419/// use retroglyph_core::grid::Size;
420///
421/// struct NullBackend;
422///
423/// impl Output for NullBackend {
424/// type Error = core::convert::Infallible;
425///
426/// fn draw_layers<'a, I>(&mut self, _content: I) -> Result<(), Self::Error>
427/// where
428/// I: Iterator<Item = DrawCell<'a>>,
429/// {
430/// Ok(())
431/// }
432///
433/// fn flush(&mut self) -> Result<(), Self::Error> {
434/// Ok(())
435/// }
436///
437/// fn size(&self) -> Size {
438/// Size::new(1, 1)
439/// }
440///
441/// fn clear(&mut self) -> Result<(), Self::Error> {
442/// Ok(())
443/// }
444/// }
445///
446/// impl Input for NullBackend {
447/// fn poll_event(&mut self, _timeout: Duration) -> Option<Event> {
448/// None
449/// }
450/// }
451///
452/// impl Cursor for NullBackend {}
453///
454/// fn assert_is_backend<B: Backend>(_backend: &B) {}
455/// assert_is_backend(&NullBackend);
456/// ```
457pub trait Backend: Output + Input + Cursor {}
458
459impl<T: Output + Input + Cursor> Backend for T {}