Skip to main content

ftui_backend/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = "Backend traits for FrankenTUI: platform abstraction for input, presentation, and time."]
3#![doc = ""]
4#![doc = "This crate defines the boundary between the ftui runtime and platform-specific"]
5#![doc = "implementations (native terminal via `ftui-tty`, WASM via `ftui-web`)."]
6#![doc = ""]
7#![doc = "See ADR-008 for the design rationale."]
8
9use core::time::Duration;
10
11use ftui_core::event::Event;
12use ftui_core::terminal_capabilities::TerminalCapabilities;
13use ftui_render::buffer::Buffer;
14use ftui_render::diff::BufferDiff;
15
16/// Terminal feature toggles that backends must support.
17///
18/// These map to terminal modes that are enabled/disabled at session start/end.
19/// Backends translate these into platform-specific escape sequences or API calls.
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
21pub struct BackendFeatures {
22    /// SGR mouse capture
23    /// (`CSI ? 1000 h` + `CSI ? 1002 h` + `CSI ? 1003 h` + `CSI ? 1006 h`, and matching `l` disables).
24    pub mouse_capture: bool,
25    /// Bracketed paste mode (CSI ? 2004 h/l on native).
26    pub bracketed_paste: bool,
27    /// Focus-in/focus-out reporting (CSI ? 1004 h/l on native).
28    pub focus_events: bool,
29    /// Kitty keyboard protocol (CSI > 15 u on native).
30    pub kitty_keyboard: bool,
31}
32
33/// Monotonic clock abstraction.
34///
35/// Native backends use `std::time::Instant`; WASM backends use `performance.now()`.
36/// The runtime never calls `Instant::now()` directly — all time flows through this trait.
37pub trait BackendClock {
38    /// Returns elapsed time since an unspecified epoch, monotonically increasing.
39    fn now_mono(&self) -> Duration;
40}
41
42/// Event source abstraction: terminal size queries, feature toggles, and event I/O.
43///
44/// This is the input half of the backend boundary. The runtime polls this for
45/// canonical `Event` values without knowing whether they come from crossterm,
46/// raw Unix reads, or DOM events.
47pub trait BackendEventSource {
48    /// Platform-specific error type.
49    type Error: core::fmt::Debug + core::fmt::Display;
50
51    /// Query current terminal dimensions (columns, rows).
52    fn size(&self) -> Result<(u16, u16), Self::Error>;
53
54    /// Enable or disable terminal features (mouse, paste, focus, kitty keyboard).
55    ///
56    /// Backends must track current state and only emit escape sequences for changes.
57    fn set_features(&mut self, features: BackendFeatures) -> Result<(), Self::Error>;
58
59    /// Poll for an available event, returning `true` if one is ready.
60    ///
61    /// Must not block longer than `timeout`. Returns `Ok(false)` on timeout.
62    fn poll_event(&mut self, timeout: Duration) -> Result<bool, Self::Error>;
63
64    /// Read the next available event, or `None` if none is ready.
65    ///
66    /// Call after `poll_event` returns `true`, or speculatively.
67    ///
68    /// A prior `poll_event` readiness result is a hint, not a guarantee:
69    /// implementations may return `Ok(None)` even immediately after a `true`
70    /// poll (e.g. the pending input was discarded by the parser, or, on
71    /// Windows, console readiness was spurious — see frankentui#95).
72    /// Implementations must not park indefinitely when no event is actually
73    /// pending; callers must treat `Ok(None)` as "nothing decodable right
74    /// now" and return to their poll loop.
75    fn read_event(&mut self) -> Result<Option<Event>, Self::Error>;
76}
77
78/// Presentation abstraction: UI rendering and log output.
79///
80/// This is the output half of the backend boundary. The runtime hands a `Buffer`
81/// (and optional `BufferDiff`) to the presenter, which emits platform-specific
82/// output (ANSI escape sequences on native, DOM mutations on web).
83pub trait BackendPresenter {
84    /// Platform-specific error type.
85    type Error: core::fmt::Debug + core::fmt::Display;
86
87    /// Terminal capabilities detected by this backend.
88    fn capabilities(&self) -> &TerminalCapabilities;
89
90    /// Write a log line to the scrollback region (inline mode) or stderr.
91    fn write_log(&mut self, text: &str) -> Result<(), Self::Error>;
92
93    /// Present a UI frame.
94    ///
95    /// - `buf`: the full rendered buffer for this frame.
96    /// - `diff`: optional pre-computed diff (backends may recompute if `None`).
97    /// - `full_repaint_hint`: if `true`, the backend should skip diffing and repaint everything.
98    fn present_ui(
99        &mut self,
100        buf: &Buffer,
101        diff: Option<&BufferDiff>,
102        full_repaint_hint: bool,
103    ) -> Result<(), Self::Error>;
104
105    /// Optional: release resources held by the presenter (e.g., grapheme pool compaction).
106    fn gc(&mut self) {}
107}
108
109/// Unified backend combining clock, event source, and presenter.
110///
111/// The `Program` runtime is generic over this trait. Concrete implementations:
112/// - `ftui-tty`: native Unix/macOS terminal (and eventually Windows).
113/// - `ftui-web`: WASM + DOM + WebGPU renderer.
114pub trait Backend {
115    /// Platform-specific error type shared across sub-traits.
116    type Error: core::fmt::Debug + core::fmt::Display;
117
118    /// Clock implementation.
119    type Clock: BackendClock;
120
121    /// Event source implementation.
122    type Events: BackendEventSource<Error = Self::Error>;
123
124    /// Presenter implementation.
125    type Presenter: BackendPresenter<Error = Self::Error>;
126
127    /// Access the monotonic clock.
128    fn clock(&self) -> &Self::Clock;
129
130    /// Access the event source (mutable for polling/reading).
131    fn events(&mut self) -> &mut Self::Events;
132
133    /// Access the presenter (mutable for rendering).
134    fn presenter(&mut self) -> &mut Self::Presenter;
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140    use core::fmt;
141    use ftui_core::terminal_capabilities::TerminalCapabilities;
142
143    // -----------------------------------------------------------------------
144    // BackendFeatures tests
145    // -----------------------------------------------------------------------
146
147    #[test]
148    fn backend_features_default_all_false() {
149        let f = BackendFeatures::default();
150        assert!(!f.mouse_capture);
151        assert!(!f.bracketed_paste);
152        assert!(!f.focus_events);
153        assert!(!f.kitty_keyboard);
154    }
155
156    #[test]
157    fn backend_features_equality() {
158        let a = BackendFeatures {
159            mouse_capture: true,
160            bracketed_paste: false,
161            focus_events: true,
162            kitty_keyboard: false,
163        };
164        let b = BackendFeatures {
165            mouse_capture: true,
166            bracketed_paste: false,
167            focus_events: true,
168            kitty_keyboard: false,
169        };
170        assert_eq!(a, b);
171    }
172
173    #[test]
174    fn backend_features_inequality() {
175        let a = BackendFeatures::default();
176        let b = BackendFeatures {
177            mouse_capture: true,
178            ..BackendFeatures::default()
179        };
180        assert_ne!(a, b);
181    }
182
183    #[test]
184    fn backend_features_clone() {
185        let a = BackendFeatures {
186            mouse_capture: true,
187            bracketed_paste: true,
188            focus_events: true,
189            kitty_keyboard: true,
190        };
191        let b = a;
192        assert_eq!(a, b);
193    }
194
195    #[test]
196    fn backend_features_debug() {
197        let f = BackendFeatures::default();
198        let debug = format!("{f:?}");
199        assert!(debug.contains("BackendFeatures"));
200        assert!(debug.contains("mouse_capture"));
201    }
202
203    // -----------------------------------------------------------------------
204    // Mock implementations for trait testing
205    // -----------------------------------------------------------------------
206
207    struct TestClock {
208        elapsed: Duration,
209    }
210
211    impl BackendClock for TestClock {
212        fn now_mono(&self) -> Duration {
213            self.elapsed
214        }
215    }
216
217    #[derive(Debug)]
218    struct TestError(String);
219
220    impl fmt::Display for TestError {
221        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222            write!(f, "TestError: {}", self.0)
223        }
224    }
225
226    struct TestEventSource {
227        features: BackendFeatures,
228        events: Vec<Event>,
229    }
230
231    impl BackendEventSource for TestEventSource {
232        type Error = TestError;
233
234        fn size(&self) -> Result<(u16, u16), Self::Error> {
235            Ok((80, 24))
236        }
237
238        fn set_features(&mut self, features: BackendFeatures) -> Result<(), Self::Error> {
239            self.features = features;
240            Ok(())
241        }
242
243        fn poll_event(&mut self, _timeout: Duration) -> Result<bool, Self::Error> {
244            Ok(!self.events.is_empty())
245        }
246
247        fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
248            Ok(if self.events.is_empty() {
249                None
250            } else {
251                Some(self.events.remove(0))
252            })
253        }
254    }
255
256    struct TestPresenter {
257        caps: TerminalCapabilities,
258        logs: Vec<String>,
259        present_count: usize,
260        gc_count: usize,
261    }
262
263    impl BackendPresenter for TestPresenter {
264        type Error = TestError;
265
266        fn capabilities(&self) -> &TerminalCapabilities {
267            &self.caps
268        }
269
270        fn write_log(&mut self, text: &str) -> Result<(), Self::Error> {
271            self.logs.push(text.to_owned());
272            Ok(())
273        }
274
275        fn present_ui(
276            &mut self,
277            _buf: &Buffer,
278            _diff: Option<&BufferDiff>,
279            _full_repaint_hint: bool,
280        ) -> Result<(), Self::Error> {
281            self.present_count += 1;
282            Ok(())
283        }
284
285        fn gc(&mut self) {
286            self.gc_count += 1;
287        }
288    }
289
290    struct TestBackend {
291        clock: TestClock,
292        events: TestEventSource,
293        presenter: TestPresenter,
294    }
295
296    impl Backend for TestBackend {
297        type Error = TestError;
298        type Clock = TestClock;
299        type Events = TestEventSource;
300        type Presenter = TestPresenter;
301
302        fn clock(&self) -> &Self::Clock {
303            &self.clock
304        }
305
306        fn events(&mut self) -> &mut Self::Events {
307            &mut self.events
308        }
309
310        fn presenter(&mut self) -> &mut Self::Presenter {
311            &mut self.presenter
312        }
313    }
314
315    fn make_test_backend() -> TestBackend {
316        TestBackend {
317            clock: TestClock {
318                elapsed: Duration::from_millis(42),
319            },
320            events: TestEventSource {
321                features: BackendFeatures::default(),
322                events: Vec::new(),
323            },
324            presenter: TestPresenter {
325                caps: TerminalCapabilities::default(),
326                logs: Vec::new(),
327                present_count: 0,
328                gc_count: 0,
329            },
330        }
331    }
332
333    // -----------------------------------------------------------------------
334    // BackendClock tests
335    // -----------------------------------------------------------------------
336
337    #[test]
338    fn clock_returns_elapsed() {
339        let clock = TestClock {
340            elapsed: Duration::from_secs(5),
341        };
342        assert_eq!(clock.now_mono(), Duration::from_secs(5));
343    }
344
345    #[test]
346    fn clock_zero_duration() {
347        let clock = TestClock {
348            elapsed: Duration::ZERO,
349        };
350        assert_eq!(clock.now_mono(), Duration::ZERO);
351    }
352
353    // -----------------------------------------------------------------------
354    // BackendEventSource tests
355    // -----------------------------------------------------------------------
356
357    #[test]
358    fn event_source_size() {
359        let src = TestEventSource {
360            features: BackendFeatures::default(),
361            events: Vec::new(),
362        };
363        assert_eq!(src.size().unwrap(), (80, 24));
364    }
365
366    #[test]
367    fn event_source_set_features() {
368        let mut src = TestEventSource {
369            features: BackendFeatures::default(),
370            events: Vec::new(),
371        };
372        let features = BackendFeatures {
373            mouse_capture: true,
374            bracketed_paste: true,
375            focus_events: false,
376            kitty_keyboard: false,
377        };
378        src.set_features(features).unwrap();
379        assert!(src.features.mouse_capture);
380        assert!(src.features.bracketed_paste);
381    }
382
383    #[test]
384    fn event_source_poll_empty() {
385        let mut src = TestEventSource {
386            features: BackendFeatures::default(),
387            events: Vec::new(),
388        };
389        assert!(!src.poll_event(Duration::from_millis(10)).unwrap());
390    }
391
392    #[test]
393    fn event_source_read_none_when_empty() {
394        let mut src = TestEventSource {
395            features: BackendFeatures::default(),
396            events: Vec::new(),
397        };
398        assert!(src.read_event().unwrap().is_none());
399    }
400
401    #[test]
402    fn event_source_poll_with_events() {
403        let mut src = TestEventSource {
404            features: BackendFeatures::default(),
405            events: vec![Event::Focus(true)],
406        };
407        assert!(src.poll_event(Duration::from_millis(10)).unwrap());
408    }
409
410    #[test]
411    fn event_source_read_drains_events() {
412        let mut src = TestEventSource {
413            features: BackendFeatures::default(),
414            events: vec![Event::Focus(true), Event::Focus(false)],
415        };
416        let e1 = src.read_event().unwrap();
417        assert!(e1.is_some());
418        let e2 = src.read_event().unwrap();
419        assert!(e2.is_some());
420        let e3 = src.read_event().unwrap();
421        assert!(e3.is_none());
422    }
423
424    // -----------------------------------------------------------------------
425    // BackendPresenter tests
426    // -----------------------------------------------------------------------
427
428    #[test]
429    fn presenter_capabilities() {
430        let p = TestPresenter {
431            caps: TerminalCapabilities::default(),
432            logs: Vec::new(),
433            present_count: 0,
434            gc_count: 0,
435        };
436        let _caps = p.capabilities();
437    }
438
439    #[test]
440    fn presenter_write_log() {
441        let mut p = TestPresenter {
442            caps: TerminalCapabilities::default(),
443            logs: Vec::new(),
444            present_count: 0,
445            gc_count: 0,
446        };
447        p.write_log("hello").unwrap();
448        p.write_log("world").unwrap();
449        assert_eq!(p.logs.len(), 2);
450        assert_eq!(p.logs[0], "hello");
451        assert_eq!(p.logs[1], "world");
452    }
453
454    #[test]
455    fn presenter_present_ui() {
456        let mut p = TestPresenter {
457            caps: TerminalCapabilities::default(),
458            logs: Vec::new(),
459            present_count: 0,
460            gc_count: 0,
461        };
462        let buf = Buffer::new(10, 5);
463        p.present_ui(&buf, None, false).unwrap();
464        p.present_ui(&buf, None, true).unwrap();
465        assert_eq!(p.present_count, 2);
466    }
467
468    #[test]
469    fn presenter_gc() {
470        let mut p = TestPresenter {
471            caps: TerminalCapabilities::default(),
472            logs: Vec::new(),
473            present_count: 0,
474            gc_count: 0,
475        };
476        p.gc();
477        p.gc();
478        assert_eq!(p.gc_count, 2);
479    }
480
481    // -----------------------------------------------------------------------
482    // Unified Backend tests
483    // -----------------------------------------------------------------------
484
485    #[test]
486    fn backend_clock_access() {
487        let backend = make_test_backend();
488        assert_eq!(backend.clock().now_mono(), Duration::from_millis(42));
489    }
490
491    #[test]
492    fn backend_events_access() {
493        let mut backend = make_test_backend();
494        let size = backend.events().size().unwrap();
495        assert_eq!(size, (80, 24));
496    }
497
498    #[test]
499    fn backend_presenter_access() {
500        let mut backend = make_test_backend();
501        let buf = Buffer::new(10, 5);
502        backend.presenter().present_ui(&buf, None, false).unwrap();
503        assert_eq!(backend.presenter.present_count, 1);
504    }
505
506    #[test]
507    fn backend_full_cycle() {
508        let mut backend = make_test_backend();
509
510        // Clock
511        let _now = backend.clock().now_mono();
512
513        // Features
514        backend
515            .events()
516            .set_features(BackendFeatures {
517                mouse_capture: true,
518                ..BackendFeatures::default()
519            })
520            .unwrap();
521        assert!(backend.events.features.mouse_capture);
522
523        // Present
524        let buf = Buffer::new(80, 24);
525        backend.presenter().write_log("frame start").unwrap();
526        backend.presenter().present_ui(&buf, None, false).unwrap();
527        backend.presenter().gc();
528
529        assert_eq!(backend.presenter.logs.len(), 1);
530        assert_eq!(backend.presenter.present_count, 1);
531        assert_eq!(backend.presenter.gc_count, 1);
532    }
533
534    // -----------------------------------------------------------------------
535    // Error type tests
536    // -----------------------------------------------------------------------
537
538    #[test]
539    fn test_error_display() {
540        let err = TestError("something failed".into());
541        assert_eq!(format!("{err}"), "TestError: something failed");
542    }
543
544    #[test]
545    fn test_error_debug() {
546        let err = TestError("oops".into());
547        let debug = format!("{err:?}");
548        assert!(debug.contains("oops"));
549    }
550}