Guide API
Skip to main content

tvision_rs/backend/
headless.rs

1//! `HeadlessBackend`, the deterministic test backend (documented on the type).
2
3use std::cell::{Cell as StdCell, RefCell};
4use std::collections::VecDeque;
5use std::rc::Rc;
6use std::time::Duration;
7
8use crate::backend::Backend;
9use crate::event::{Event, Key, KeyEvent, KeyModifiers};
10use crate::screen::{Buffer, Cell};
11
12// ---------------------------------------------------------------------------
13// HeadlessHandle — the test-visible window into backend state
14// ---------------------------------------------------------------------------
15
16/// A cloneable window into a [`HeadlessBackend`]'s screen and event queue.
17///
18/// Retain this value after constructing the backend with [`HeadlessBackend::new`]
19/// — the backend is then boxed and given to the [`Renderer`](crate::backend::Renderer).
20/// The handle outlives that move and lets tests inspect or drive the backend:
21///
22/// ```
23/// # use tvision_rs::{HeadlessBackend, Renderer};
24/// let (backend, screen) = HeadlessBackend::new(80, 25);
25/// let mut renderer = Renderer::new(Box::new(backend));
26/// // … render frames …
27/// let _ = screen.snapshot();
28/// ```
29#[derive(Clone)]
30pub struct HeadlessHandle {
31    buffer: Rc<RefCell<Buffer>>,
32    cursor: Rc<StdCell<Option<(u16, u16)>>>,
33    caret_size: Rc<StdCell<u8>>,
34    events: Rc<RefCell<VecDeque<Event>>>,
35    clipboard: Rc<RefCell<String>>,
36    /// The PRIMARY selection — a second, independent buffer. Separate from
37    /// `clipboard` because X11 keeps the two selections apart, and tests must
38    /// be able to prove a copy did not leak into a middle-click paste.
39    primary: Rc<RefCell<String>>,
40    size: Rc<StdCell<(u16, u16)>>,
41}
42
43impl HeadlessHandle {
44    /// The golden-snapshot string of the current screen.
45    ///
46    /// Delegates to [`crate::screen::snapshot::snapshot`], which produces the
47    /// frozen `size / cursor / text / attr / legend` format documented on that
48    /// module.  Pass the result to `insta::assert_snapshot!`.
49    pub fn snapshot(&self) -> String {
50        crate::screen::snapshot::snapshot(&self.buffer.borrow(), self.cursor.get())
51    }
52
53    /// Queue an input event to be returned by the next `poll_event`.
54    pub fn push_event(&self, ev: Event) {
55        self.events.borrow_mut().push_back(ev);
56    }
57
58    /// Convenience: queue a [`Event::KeyDown`] event.
59    ///
60    /// Builds a `KeyEvent` from `key` and `modifiers` and pushes
61    /// `Event::KeyDown(…)` onto the queue.
62    pub fn push_key(&self, key: Key, modifiers: KeyModifiers) {
63        self.push_event(Event::KeyDown(KeyEvent::new(key, modifiers)));
64    }
65
66    /// Queue a bracketed-paste event.  Equivalent to the terminal delivering
67    /// an `EnableBracketedPaste`-wrapped paste sequence.
68    pub fn push_paste(&self, text: impl Into<String>) {
69        self.push_event(Event::Paste(text.into()));
70    }
71
72    /// Borrow the current screen buffer (for assertions beyond the snapshot).
73    pub fn buffer(&self) -> std::cell::Ref<'_, Buffer> {
74        self.buffer.borrow()
75    }
76
77    /// The current cursor position: `Some((x, y))` when visible, `None` when hidden.
78    pub fn cursor(&self) -> Option<(u16, u16)> {
79        self.cursor.get()
80    }
81
82    /// The caret size last set by the renderer (see
83    /// [`Backend::set_caret_size`](crate::backend::Backend::set_caret_size));
84    /// [`CARET_NORMAL`](crate::backend::CARET_NORMAL) until a caret is shown.
85    pub fn caret_size(&self) -> u8 {
86        self.caret_size.get()
87    }
88
89    /// The backend's clipboard text, or `None` if nothing has been written or
90    /// the stored text is empty (an empty string is indistinguishable from
91    /// never-written — mirroring `ClipboardChain::get`'s empty→`None`) —
92    /// lets tests assert what a copy path (`Deferred::SetClipboard`) stored.
93    pub fn clipboard(&self) -> Option<String> {
94        let clip = self.clipboard.borrow();
95        if clip.is_empty() {
96            None
97        } else {
98            Some(clip.clone())
99        }
100    }
101
102    /// Seed the backend clipboard — lets tests stage text for a paste path
103    /// (`Deferred::EditorPaste`) without going through `set_clipboard`.
104    pub fn set_clipboard(&self, text: &str) {
105        *self.clipboard.borrow_mut() = text.to_string();
106    }
107
108    /// The backend's PRIMARY selection, or `None` when nothing has been
109    /// selected (empty→`None`, matching [`clipboard`](Self::clipboard)) — lets
110    /// tests assert what a mouse selection published.
111    pub fn primary(&self) -> Option<String> {
112        let prim = self.primary.borrow();
113        if prim.is_empty() {
114            None
115        } else {
116            Some(prim.clone())
117        }
118    }
119
120    /// Seed the PRIMARY selection — stages the "another X client owns a
121    /// selection" state a middle-click paste reads.
122    pub fn set_primary(&self, text: &str) {
123        *self.primary.borrow_mut() = text.to_string();
124    }
125
126    /// Simulate a terminal resize.
127    ///
128    /// Updates the shared size cell and pre-resizes the shared screen buffer so
129    /// that the next `pump_once` resize check (`backend.size()` ≠ current group
130    /// bounds) detects the change and calls `group.change_bounds` /
131    /// `renderer.resize`, relaying the resize to all child views through their
132    /// grow-modes.
133    ///
134    /// The shared buffer is cleared to blank cells at the new size so
135    /// `backend.draw()` can safely write any cell within the new bounds.
136    pub fn resize(&self, width: u16, height: u16) {
137        self.size.set((width, height));
138        self.buffer.borrow_mut().resize(width, height);
139    }
140}
141
142// ---------------------------------------------------------------------------
143// HeadlessBackend
144// ---------------------------------------------------------------------------
145
146/// In-memory backend for deterministic tests.
147///
148/// `HeadlessBackend` stores an in-memory cell buffer and a programmable event
149/// queue. It never performs I/O and never blocks. Create it with
150/// [`HeadlessBackend::new`]; move the backend into a
151/// [`Renderer`](crate::backend::Renderer) and keep the returned
152/// [`HeadlessHandle`] to inject events and inspect the screen after each
153/// `Renderer::render` call.
154///
155/// The shared-state pattern avoids downcasting: the handle and the backend share
156/// the same `Rc<RefCell<…>>` cells, so tests can observe the screen without
157/// needing to reach through the `Box<dyn Backend>` that the `Renderer` owns.
158///
159/// # Turbo Vision heritage
160/// **tvision-rs extension**: no Turbo Vision counterpart. It stands in for the
161/// platform terminal driver so the snapshot test suite, or an application's
162/// own tests, can drive the framework synchronously, with injected input and an
163/// inspectable screen (deviation D11).
164pub struct HeadlessBackend {
165    shared: HeadlessHandle,
166}
167
168impl HeadlessBackend {
169    /// Create a `width × height` headless backend.
170    ///
171    /// Returns `(backend, handle)`: move `backend` into a `Renderer` and retain
172    /// `handle` to inspect the screen and inject input.  Call
173    /// [`HeadlessHandle::resize`] on the handle to simulate a terminal resize;
174    /// the next `pump_once` will detect the change and relay it through the view
175    /// tree via each child's grow-mode.
176    pub fn new(width: u16, height: u16) -> (Self, HeadlessHandle) {
177        let shared = HeadlessHandle {
178            buffer: Rc::new(RefCell::new(Buffer::new(width, height))),
179            cursor: Rc::new(StdCell::new(None)),
180            caret_size: Rc::new(StdCell::new(crate::backend::CARET_NORMAL)),
181            events: Rc::new(RefCell::new(VecDeque::new())),
182            clipboard: Rc::new(RefCell::new(String::new())),
183            primary: Rc::new(RefCell::new(String::new())),
184            size: Rc::new(StdCell::new((width, height))),
185        };
186        let backend = HeadlessBackend {
187            shared: shared.clone(),
188        };
189        (backend, shared)
190    }
191}
192
193impl Backend for HeadlessBackend {
194    fn size(&self) -> (u16, u16) {
195        self.shared.size.get()
196    }
197
198    /// Write each changed cell into the internal buffer.
199    fn draw(&mut self, content: &[(u16, u16, &Cell)]) {
200        let mut buf = self.shared.buffer.borrow_mut();
201        for &(x, y, cell) in content {
202            *buf.get_mut(x, y) = cell.clone();
203        }
204    }
205
206    /// No-op: headless has no output stream.
207    fn flush(&mut self) {}
208
209    fn set_cursor(&mut self, pos: Option<(u16, u16)>) {
210        self.shared.cursor.set(pos);
211    }
212
213    /// Record the caret size for [`HeadlessHandle::caret_size`].
214    fn set_caret_size(&mut self, size: u8) {
215        self.shared.caret_size.set(size);
216    }
217
218    /// Pop the front event from the queue, or `None` if the queue is empty.
219    ///
220    /// **Never blocks** regardless of `timeout`.  This is the determinism
221    /// contract: tests drive the loop synchronously by pre-loading events.
222    fn poll_event(&mut self, _timeout: Option<Duration>) -> Option<Event> {
223        self.shared.events.borrow_mut().pop_front()
224    }
225
226    /// Store `text` in the shared internal buffer; always returns `false`.
227    ///
228    /// Headless deliberately does **not** run the production
229    /// `ClipboardChain` — it is the test
230    /// fake: no OS clipboard, no OSC 52 bytes, just a plain string tests can
231    /// read via [`HeadlessHandle::clipboard`] and seed via
232    /// [`HeadlessHandle::set_clipboard`].
233    fn set_clipboard(&mut self, text: &str) -> bool {
234        *self.shared.clipboard.borrow_mut() = text.to_string();
235        false // internal fallback — no real clipboard
236    }
237
238    /// Return the most recently stored clipboard text, or `None` if nothing
239    /// has been written.
240    fn get_clipboard(&mut self) -> Option<String> {
241        self.shared.clipboard()
242    }
243
244    /// The staged PRIMARY selection — the test fake for a display server that
245    /// already owns one.
246    fn get_primary(&mut self) -> Option<String> {
247        self.shared.primary()
248    }
249
250    /// Record the PRIMARY selection so a test can assert what was published.
251    /// Returns `true`: headless always "owns" the selection successfully.
252    fn set_primary(&mut self, text: &str) -> bool {
253        self.shared.set_primary(text);
254        true
255    }
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261    use crate::backend::Backend;
262
263    /// The two X selections are independent: a CLIPBOARD copy must not become
264    /// the PRIMARY selection, nor the other way round.
265    #[test]
266    fn primary_and_clipboard_are_separate_buffers() {
267        let (mut backend, handle) = HeadlessBackend::new(10, 2);
268        backend.set_clipboard("copied-with-ctrl-c");
269        backend.set_primary("selected-with-the-mouse");
270
271        assert_eq!(
272            backend.get_clipboard().as_deref(),
273            Some("copied-with-ctrl-c")
274        );
275        assert_eq!(
276            backend.get_primary().as_deref(),
277            Some("selected-with-the-mouse")
278        );
279        assert_eq!(handle.clipboard().as_deref(), Some("copied-with-ctrl-c"));
280        assert_eq!(handle.primary().as_deref(), Some("selected-with-the-mouse"));
281    }
282
283    /// Nothing selected yet → `None`, so a middle-click paste is simply inert.
284    #[test]
285    fn primary_starts_empty() {
286        let (mut backend, handle) = HeadlessBackend::new(10, 2);
287        assert_eq!(backend.get_primary(), None);
288        assert_eq!(handle.primary(), None);
289    }
290
291    /// Tests stage a selection through the handle, the way a real X client
292    /// would have owned it before the app started.
293    #[test]
294    fn handle_seeds_the_primary_selection() {
295        let (mut backend, handle) = HeadlessBackend::new(10, 2);
296        handle.set_primary("staged-by-the-test");
297        assert_eq!(backend.get_primary().as_deref(), Some("staged-by-the-test"));
298    }
299}