tvision_rs/backend/traits.rs
1//! The `Backend` trait (documented on the type).
2
3use std::time::Duration;
4
5use crate::event::Event;
6use crate::screen::Cell;
7
8/// Caret size for the normal (insert-mode) caret, 1% of the cell. A terminal
9/// backend shows it as the terminal's own caret shape. See
10/// [`Backend::set_caret_size`].
11///
12/// # Turbo Vision heritage
13/// `TScreen::cursorLines & 0x0F`, which on the modern platform layer is the
14/// startup caret size clamped to `1..=100` — `1` on a terminal.
15pub const CARET_NORMAL: u8 = 1;
16
17/// Caret size for the block (overwrite-mode) caret: the whole cell. See
18/// [`Backend::set_caret_size`].
19///
20/// # Turbo Vision heritage
21/// The `100` that `TVCursor::decideCaretSize` returns for `sfCursorIns`.
22pub const CARET_INSERT: u8 = 100;
23
24/// Platform seam between the framework and the terminal.
25///
26/// The `Backend` trait — the object-safe terminal seam.
27///
28/// The app holds a `Box<dyn Backend>`; the view tree never carries a `<B>`
29/// type parameter. This trait must therefore be **object-safe** — no generic
30/// methods.
31///
32/// Two implementations exist:
33/// - [`CrosstermBackend`](crate::backend::CrosstermBackend) — production, wraps crossterm.
34/// - [`HeadlessBackend`](crate::backend::HeadlessBackend) — tests, in-memory buffer.
35///
36/// The trait is object-safe; the app holds `Box<dyn Backend>`.
37///
38/// # Turbo Vision heritage
39///
40/// Stands in for the platform layer of `TScreen` / `THardwareInfo`
41/// (`hardware.cpp`, `tscreen.cpp`) plus the event source pump. The original
42/// selected a platform driver at link time; here the seam is a runtime trait
43/// object so the view tree carries no backend type parameter, and tests can swap
44/// in an in-memory fake (deviation D11).
45pub trait Backend {
46 /// Live terminal dimensions in cells, returned as `(cols, rows)`.
47 ///
48 /// Called on each pump cycle to size the root group and therefore the
49 /// desktop. Because the query is on-demand there is no mutable global to
50 /// keep in sync: the program resizes the desktop whenever the value
51 /// changes between cycles.
52 ///
53 /// The production [`CrosstermBackend`](crate::backend::CrosstermBackend)
54 /// asks the terminal at every call; the
55 /// [`HeadlessBackend`](crate::backend::HeadlessBackend) returns the fixed
56 /// size passed to [`HeadlessBackend::new`](crate::backend::HeadlessBackend::new).
57 ///
58 /// Custom backend implementors should query the OS terminal size here —
59 /// the result is used directly for desktop layout, so a stale value will
60 /// leave the view tree sized incorrectly after a terminal resize.
61 ///
62 /// # Turbo Vision heritage
63 ///
64 /// Replaces the `ScreenWidth` and `ScreenHeight` mutable globals
65 /// (`Byte` each, set once by `InitVideo` in `drivers.cpp`). The Rust port
66 /// queries on demand instead of caching a stale global, so terminal
67 /// resizes are picked up automatically on the next pump cycle.
68 fn size(&self) -> (u16, u16);
69
70 /// Apply changed cells to the screen.
71 ///
72 /// Each tuple is `(x, y, &cell)`; the backend writes that cell at position
73 /// `(x, y)`. Called by [`Renderer::render`](crate::backend::Renderer::render)
74 /// with the diff slice produced by [`Buffer::diff`](crate::screen::Buffer::diff).
75 fn draw(&mut self, content: &[(u16, u16, &Cell)]);
76
77 /// Flush buffered output to the terminal. No-op for headless.
78 fn flush(&mut self);
79
80 /// Show the hardware cursor at `pos`, or hide it when `pos` is `None`.
81 fn set_cursor(&mut self, pos: Option<(u16, u16)>);
82
83 /// Set the shape of the visible caret. `size` is the percentage of the
84 /// character cell the caret fills, `1..=100`:
85 /// [`CARET_NORMAL`] (the normal caret) or [`CARET_INSERT`] (the whole
86 /// cell). Called
87 /// by [`Renderer::render`](crate::backend::Renderer::render) each frame
88 /// in which the caret is shown, after [`set_cursor`](Self::set_cursor);
89 /// hiding the caret is `set_cursor(None)`. The default does nothing, for
90 /// backends that cannot change the caret shape.
91 ///
92 /// The [`CrosstermBackend`](crate::backend::CrosstermBackend) shows
93 /// [`CARET_INSERT`] as a blinking block and keeps the terminal's own caret
94 /// shape for every other size (as the original's ncurses display does),
95 /// and restores the terminal's shape on exit and suspend.
96 ///
97 /// # Turbo Vision heritage
98 /// Ports `THardwareInfo::setCaretSize` (`hardware.cpp`). A size of `0`
99 /// (caret hidden) is carried by `set_cursor(None)` instead.
100 fn set_caret_size(&mut self, _size: u8) {}
101
102 /// Wait up to `timeout` for the next input event.
103 ///
104 /// - `None` timeout → block indefinitely (production) or return immediately
105 /// (headless — see the determinism note below).
106 /// - Returns `None` on timeout or when the queue is empty.
107 ///
108 /// **Headless never blocks** — it pops the next queued event or returns
109 /// `None` immediately, ignoring the timeout value. This is the headless
110 /// determinism contract: test code injects events and drives the loop
111 /// synchronously without wall-clock waits.
112 ///
113 /// # Turbo Vision heritage
114 ///
115 /// There is deliberately no app-level `getEvent` override / event-source
116 /// injection seam (C++ `TProgram::getEvent`). For periodic work use the timer
117 /// queue ([`Event::Timer`]) or [`crate::app::Program::set_on_idle`]; to feed synthetic
118 /// input in tests, push onto the headless backend's event queue.
119 fn poll_event(&mut self, timeout: Option<Duration>) -> Option<Event>;
120
121 /// Write `text` to the system clipboard.
122 ///
123 /// Returns `false` when the implementation fell back to an internal buffer
124 /// (no native clipboard took the text). The caller can treat a `false`
125 /// return as "clipboard unavailable but the string is stored internally
126 /// and can be retrieved via `get_clipboard`". Native first, internal only
127 /// on failure. The production impl runs the full fallback chain (native →
128 /// OSC 52 emit → internal — see `backend::clipboard`); headless is a
129 /// plain internal string by design (the test fake).
130 fn set_clipboard(&mut self, text: &str) -> bool;
131
132 /// Read the clipboard: native clipboard first, else the internal buffer,
133 /// else `None`.
134 fn get_clipboard(&mut self) -> Option<String>;
135
136 /// Read the X11/Wayland PRIMARY selection — what a middle-click pastes.
137 ///
138 /// PRIMARY is a display-server concept, so this has **one** rung: the
139 /// native clipboard. There is no internal-buffer fallback and no OSC 52 —
140 /// with no display (the SSH shape) the honest answer is `None`, and a
141 /// middle-click paste is simply inert. Serving the in-app buffer instead
142 /// would paste stale text the user never selected.
143 ///
144 /// # Turbo Vision heritage
145 /// **tvision-rs extension**: no Turbo Vision counterpart. magiblot's `TClipboard` reads only
146 /// the CLIPBOARD selection.
147 ///
148 /// Defaulted to `None` so an existing implementor keeps compiling and
149 /// silently gets the inert behaviour.
150 fn get_primary(&mut self) -> Option<String> {
151 None
152 }
153
154 /// Take ownership of the PRIMARY selection and serve `text` from it, so
155 /// another X client can middle-click-paste what the user selected here.
156 ///
157 /// Returns `false` when there is no PRIMARY selection to own (no display,
158 /// or a platform without one). Same single-rung rule as
159 /// [`get_primary`](Self::get_primary): the internal buffer is never
160 /// written, because it backs CLIPBOARD and must not be shadowed by a
161 /// selection the user merely swept with the mouse.
162 ///
163 /// # Turbo Vision heritage
164 /// **tvision-rs extension**: no Turbo Vision counterpart.
165 fn set_primary(&mut self, _text: &str) -> bool {
166 false
167 }
168
169 /// Suspend the terminal: leave alt-screen and restore normal terminal mode.
170 ///
171 /// Called by the event loop immediately before the process is suspended
172 /// (e.g. `SIGTSTP` on Unix, or the DOS-shell command on any platform).
173 /// A correct implementation tears down raw mode and the alternate screen
174 /// so the shell that takes over sees a clean terminal.
175 ///
176 /// The production
177 /// [`CrosstermBackend`](crate::backend::CrosstermBackend) executes
178 /// crossterm's `LeaveAlternateScreen` + `DisableMouseCapture` + `disable_raw_mode`
179 /// sequence. The
180 /// [`HeadlessBackend`](crate::backend::HeadlessBackend) is a no-op by
181 /// design (no real terminal to tear down).
182 ///
183 /// Custom backend implementors **must** pair this with [`resume`](Self::resume):
184 /// every `suspend` call will be followed by exactly one `resume` call when
185 /// the process is brought back to the foreground.
186 ///
187 /// # Turbo Vision heritage
188 ///
189 /// Stands in for `TApplication::suspend` (`tapplica.cpp`), which called
190 /// `TSystemError::suspend`, `TEventQueue::suspend`, and `TScreen::suspend`
191 /// in sequence. The Rust port collapses all three subsystem calls into this
192 /// single trait method on the `Backend`.
193 fn suspend(&mut self) {}
194
195 /// Resume the terminal: re-enter alt-screen, raw mode, and mouse capture.
196 ///
197 /// Called by the event loop immediately after the process returns to the
198 /// foreground following a [`suspend`](Self::suspend). A correct
199 /// implementation restores the full terminal state so the next draw cycle
200 /// re-paints the TUI correctly.
201 ///
202 /// The production
203 /// [`CrosstermBackend`](crate::backend::CrosstermBackend) executes
204 /// crossterm's `enable_raw_mode` + `EnterAlternateScreen` + `EnableMouseCapture`
205 /// sequence, followed by a full redraw. The
206 /// [`HeadlessBackend`](crate::backend::HeadlessBackend) is a no-op.
207 ///
208 /// # Turbo Vision heritage
209 ///
210 /// Stands in for `TApplication::resume` (`tapplica.cpp`), which called
211 /// `TScreen::resume`, `TEventQueue::resume`, and `TSystemError::resume`
212 /// in sequence.
213 fn resume(&mut self) {}
214}