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;
10use std::sync::Arc;
11
12use ftui_core::event::Event;
13use ftui_core::osc52::ClipboardSelection;
14use ftui_core::terminal_capabilities::TerminalCapabilities;
15use ftui_render::buffer::Buffer;
16use ftui_render::diff::BufferDiff;
17pub use ftui_render::diff_strategy::DiffStrategy;
18use ftui_render::grapheme_pool::GraphemePool;
19use ftui_render::link_registry::LinkRegistry;
20pub use ftui_render::sanitize::SanitizeMode;
21
22/// Presentation phase timing measurements.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub struct PresentTimings {
25    /// Time spent computing the buffer diff in microseconds.
26    pub diff_us: u64,
27}
28
29/// Screen mode determines whether we use alternate screen or inline mode.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
31pub enum ScreenMode {
32    /// Inline mode preserves scrollback. UI is anchored at bottom/top.
33    Inline {
34        /// Height of the UI region in rows.
35        ui_height: u16,
36    },
37    /// Inline mode with automatic UI height based on rendered content.
38    ///
39    /// The measured height is clamped between `min_height` and `max_height`.
40    InlineAuto {
41        /// Minimum UI height in rows.
42        min_height: u16,
43        /// Maximum UI height in rows.
44        max_height: u16,
45    },
46    /// Alternate screen mode for full-screen applications.
47    #[default]
48    AltScreen,
49}
50
51/// Where the UI region is anchored in inline mode.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
53pub enum UiAnchor {
54    /// UI at bottom of terminal (default for agent harness).
55    #[default]
56    Bottom,
57    /// UI at top of terminal.
58    Top,
59}
60
61/// Terminal feature toggles that backends must support.
62///
63/// These map to terminal modes that are enabled/disabled at session start/end.
64/// Backends translate these into platform-specific escape sequences or API calls.
65#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
66pub struct BackendFeatures {
67    /// SGR mouse capture
68    /// (`CSI ? 1000 h` + `CSI ? 1002 h` + `CSI ? 1003 h` + `CSI ? 1006 h`, and matching `l` disables).
69    pub mouse_capture: bool,
70    /// Bracketed paste mode (CSI ? 2004 h/l on native).
71    pub bracketed_paste: bool,
72    /// Focus-in/focus-out reporting (CSI ? 1004 h/l on native).
73    pub focus_events: bool,
74    /// Kitty keyboard protocol (CSI > 15 u on native).
75    pub kitty_keyboard: bool,
76}
77
78/// Monotonic clock abstraction.
79///
80/// Native backends use `std::time::Instant`; WASM backends use `performance.now()`.
81/// The runtime never calls `Instant::now()` directly — all time flows through this trait.
82pub trait BackendClock {
83    /// Returns elapsed time since an unspecified epoch, monotonically increasing.
84    fn now_mono(&self) -> Duration;
85}
86
87/// Event source abstraction: terminal size queries, feature toggles, and event I/O.
88///
89/// This is the input half of the backend boundary. The runtime polls this for
90/// canonical `Event` values without knowing whether they come from crossterm,
91/// raw Unix reads, or DOM events.
92pub trait BackendEventSource {
93    /// Platform-specific error type.
94    type Error: core::fmt::Debug + core::fmt::Display;
95
96    /// Query current terminal dimensions (columns, rows).
97    fn size(&self) -> Result<(u16, u16), Self::Error>;
98
99    /// Enable or disable terminal features (mouse, paste, focus, kitty keyboard).
100    ///
101    /// Backends must track current state and only emit escape sequences for changes.
102    fn set_features(&mut self, features: BackendFeatures) -> Result<(), Self::Error>;
103
104    /// Poll for an available event, returning `true` if one is ready.
105    ///
106    /// Must not block longer than `timeout`. Returns `Ok(false)` on timeout.
107    fn poll_event(&mut self, timeout: Duration) -> Result<bool, Self::Error>;
108
109    /// Read the next available event, or `None` if none is ready.
110    ///
111    /// Call after `poll_event` returns `true`, or speculatively.
112    ///
113    /// A prior `poll_event` readiness result is a hint, not a guarantee:
114    /// implementations may return `Ok(None)` even immediately after a `true`
115    /// poll (e.g. the pending input was discarded by the parser, or, on
116    /// Windows, console readiness was spurious — see frankentui#95).
117    /// Implementations must not park indefinitely when no event is actually
118    /// pending; callers must treat `Ok(None)` as "nothing decodable right
119    /// now" and return to their poll loop.
120    fn read_event(&mut self) -> Result<Option<Event>, Self::Error>;
121
122    /// Whether [`suspend`](Self::suspend) can hand the terminal back for a
123    /// job-control stop. The runtime claims SIGTSTP/SIGTTIN/SIGTTOU only for a
124    /// source that says so; others keep the signals' default action.
125    fn supports_suspend(&self) -> bool {
126        false
127    }
128
129    /// Hand the terminal back to the shell ahead of a job-control stop:
130    /// disable input modes, leave the alternate screen and restore the
131    /// original terminal modes, keeping what is needed to undo it.
132    ///
133    /// Returns `Ok(false)` when this source owns no terminal session to
134    /// release; the runtime then does not stop the process.
135    fn suspend(&mut self) -> Result<bool, Self::Error> {
136        Ok(false)
137    }
138
139    /// Undo [`suspend`](Self::suspend) after the process is continued.
140    /// A no-op when nothing is suspended.
141    fn resume(&mut self) -> Result<(), Self::Error> {
142        Ok(())
143    }
144}
145
146/// Presentation abstraction: UI rendering and log output.
147///
148/// This is the output half of the backend boundary. The runtime hands a `Buffer`
149/// (and optional `BufferDiff`) to the presenter, which emits platform-specific
150/// output (ANSI escape sequences on native, DOM mutations on web).
151pub trait BackendPresenter {
152    /// Platform-specific error type.
153    type Error: core::fmt::Debug + core::fmt::Display;
154
155    /// Terminal capabilities detected by this backend.
156    fn capabilities(&self) -> &TerminalCapabilities;
157
158    /// Write a log line to the scrollback region (inline mode) or stderr.
159    fn write_log(&mut self, text: &str) -> Result<(), Self::Error>;
160
161    /// Present a UI frame.
162    ///
163    /// - `buf`: the full rendered buffer for this frame.
164    /// - `diff`: optional pre-computed diff (backends may recompute if `None`).
165    /// - `full_repaint_hint`: if `true`, the backend should skip diffing and repaint everything.
166    fn present_ui(
167        &mut self,
168        buf: &Buffer,
169        diff: Option<&BufferDiff>,
170        full_repaint_hint: bool,
171    ) -> Result<(), Self::Error>;
172
173    /// Optional: release resources held by the presenter (e.g., grapheme pool compaction).
174    fn gc(&mut self) {}
175
176    /// Notify the presenter immediately when a resize event arrives, before
177    /// resize coalescing defers the frame redraw.
178    fn notify_resize(&mut self, _cols: u16, _rows: u16) {}
179
180    /// Resize the presentation surface.
181    fn resize(&mut self, _cols: u16, _rows: u16) {}
182
183    /// Current screen mode.
184    fn screen_mode(&self) -> ScreenMode {
185        ScreenMode::default()
186    }
187
188    /// Set screen mode.
189    fn set_screen_mode(&mut self, _mode: ScreenMode) {}
190
191    /// Configure an evidence-writer callback.
192    fn set_evidence_writer(&mut self, _w: Option<Arc<dyn Fn(&str) + Send + Sync>>) {}
193
194    /// Last diff strategy used, if any.
195    fn last_diff_strategy(&self) -> Option<DiffStrategy> {
196        None
197    }
198
199    /// Last diff elapsed duration, if any.
200    fn last_diff_elapsed(&self) -> Option<Duration> {
201        None
202    }
203
204    /// Begin shutting down the presenter.
205    fn begin_shutdown(&mut self) -> Result<(), Self::Error> {
206        Ok(())
207    }
208
209    /// Flush any pending output to the terminal or host.
210    fn flush(&mut self) -> Result<(), Self::Error> {
211        Ok(())
212    }
213
214    /// Release presenter-owned terminal state ahead of a job-control stop:
215    /// close an open synchronized-output block, reset the scroll region, show
216    /// the cursor. On resume the runtime calls [`resize`](Self::resize), which
217    /// must drop any diff baseline, since the screen is no longer ours.
218    fn suspend(&mut self) -> Result<(), Self::Error> {
219        self.flush()
220    }
221
222    /// Take a reusable render buffer sized for the current frame.
223    fn take_render_buffer(&mut self, width: u16, height: u16) -> Buffer {
224        Buffer::new(width, height)
225    }
226
227    /// Mark the beginning of a frame for hyperlink tracking.
228    fn begin_link_frame(&mut self) {}
229
230    /// Mutably borrow the grapheme pool and link registry.
231    fn pool_and_links_mut(&mut self) -> (&mut GraphemePool, &mut LinkRegistry);
232
233    /// Mutably borrow the grapheme pool.
234    fn pool_mut(&mut self) -> &mut GraphemePool;
235
236    /// Configured bounds for inline auto mode, if active.
237    fn inline_auto_bounds(&self) -> Option<(u16, u16)> {
238        None
239    }
240
241    /// Current measured or auto-determined UI height for inline auto mode.
242    fn auto_ui_height(&self) -> Option<u16> {
243        None
244    }
245
246    /// Height hint to use when rendering a frame.
247    fn render_height_hint(&self) -> u16 {
248        0
249    }
250
251    /// Set auto UI height for inline auto mode.
252    fn set_auto_ui_height(&mut self, _height: u16) {}
253
254    /// Clear auto UI height for inline auto mode.
255    fn clear_auto_ui_height(&mut self) {}
256
257    /// Take presentation timings from the last rendered frame, if recorded.
258    fn take_last_present_timings(&mut self) -> Option<PresentTimings> {
259        None
260    }
261
262    /// Estimate memory usage of buffers and pools held by the presenter.
263    fn estimate_memory_usage(&self) -> usize {
264        0
265    }
266
267    /// Present a UI frame, taking ownership of the buffer.
268    fn present_ui_owned(
269        &mut self,
270        buf: Buffer,
271        cursor: Option<(u16, u16)>,
272        cursor_visible: bool,
273    ) -> Result<(), Self::Error> {
274        let _ = (cursor, cursor_visible);
275        self.present_ui(&buf, None, false)
276    }
277
278    /// Write a log line with a specific sanitization mode.
279    fn write_log_line_with_mode(
280        &mut self,
281        text: &str,
282        _mode: SanitizeMode,
283    ) -> Result<(), Self::Error> {
284        self.write_log(text)
285    }
286
287    /// Write an OSC 52 set clipboard sequence.
288    fn write_osc52_set(
289        &mut self,
290        _selection: ClipboardSelection,
291        _data: &[u8],
292    ) -> Result<(), Self::Error> {
293        Ok(())
294    }
295
296    /// Write an OSC 52 query clipboard sequence.
297    fn write_osc52_query(&mut self, _selection: ClipboardSelection) -> Result<(), Self::Error> {
298        Ok(())
299    }
300
301    /// Enable or disable presentation timing measurements.
302    fn set_timing_enabled(&mut self, _enabled: bool) {}
303
304    /// Set hyperlink limit for tracking.
305    fn set_hyperlink_limit(&mut self, _limit: usize) {}
306}
307
308/// Unified backend combining clock and event source.
309///
310/// The `Program` runtime drives event handling through this trait (or through
311/// [`BackendEventSource`] directly), and presents through [`BackendPresenter`].
312/// Concrete implementations:
313/// - `ftui-tty`: native Unix/macOS terminal (and eventually Windows).
314/// - `ftui-web`: WASM + DOM + WebGPU renderer.
315pub trait Backend {
316    /// Platform-specific error type shared across sub-traits.
317    type Error: core::fmt::Debug + core::fmt::Display;
318
319    /// Clock implementation.
320    type Clock: BackendClock;
321
322    /// Event source implementation.
323    type Events: BackendEventSource<Error = Self::Error>;
324
325    /// Access the monotonic clock.
326    fn clock(&self) -> &Self::Clock;
327
328    /// Access the event source (mutable for polling/reading).
329    fn events(&mut self) -> &mut Self::Events;
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335    use core::fmt;
336    use ftui_core::terminal_capabilities::TerminalCapabilities;
337
338    // -----------------------------------------------------------------------
339    // BackendFeatures tests
340    // -----------------------------------------------------------------------
341
342    #[test]
343    fn backend_features_default_all_false() {
344        let f = BackendFeatures::default();
345        assert!(!f.mouse_capture);
346        assert!(!f.bracketed_paste);
347        assert!(!f.focus_events);
348        assert!(!f.kitty_keyboard);
349    }
350
351    #[test]
352    fn backend_features_equality() {
353        let a = BackendFeatures {
354            mouse_capture: true,
355            bracketed_paste: false,
356            focus_events: true,
357            kitty_keyboard: false,
358        };
359        let b = BackendFeatures {
360            mouse_capture: true,
361            bracketed_paste: false,
362            focus_events: true,
363            kitty_keyboard: false,
364        };
365        assert_eq!(a, b);
366    }
367
368    #[test]
369    fn backend_features_inequality() {
370        let a = BackendFeatures::default();
371        let b = BackendFeatures {
372            mouse_capture: true,
373            ..BackendFeatures::default()
374        };
375        assert_ne!(a, b);
376    }
377
378    #[test]
379    fn backend_features_clone() {
380        let a = BackendFeatures {
381            mouse_capture: true,
382            bracketed_paste: true,
383            focus_events: true,
384            kitty_keyboard: true,
385        };
386        let b = a;
387        assert_eq!(a, b);
388    }
389
390    #[test]
391    fn backend_features_debug() {
392        let f = BackendFeatures::default();
393        let debug = format!("{f:?}");
394        assert!(debug.contains("BackendFeatures"));
395        assert!(debug.contains("mouse_capture"));
396    }
397
398    // -----------------------------------------------------------------------
399    // Mock implementations for trait testing
400    // -----------------------------------------------------------------------
401
402    struct TestClock {
403        elapsed: Duration,
404    }
405
406    impl BackendClock for TestClock {
407        fn now_mono(&self) -> Duration {
408            self.elapsed
409        }
410    }
411
412    #[derive(Debug)]
413    struct TestError(String);
414
415    impl fmt::Display for TestError {
416        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417            write!(f, "TestError: {}", self.0)
418        }
419    }
420
421    struct TestEventSource {
422        features: BackendFeatures,
423        events: Vec<Event>,
424    }
425
426    impl BackendEventSource for TestEventSource {
427        type Error = TestError;
428
429        fn size(&self) -> Result<(u16, u16), Self::Error> {
430            Ok((80, 24))
431        }
432
433        fn set_features(&mut self, features: BackendFeatures) -> Result<(), Self::Error> {
434            self.features = features;
435            Ok(())
436        }
437
438        fn poll_event(&mut self, _timeout: Duration) -> Result<bool, Self::Error> {
439            Ok(!self.events.is_empty())
440        }
441
442        fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
443            Ok(if self.events.is_empty() {
444                None
445            } else {
446                Some(self.events.remove(0))
447            })
448        }
449    }
450
451    struct TestPresenter {
452        caps: TerminalCapabilities,
453        logs: Vec<String>,
454        present_count: usize,
455        gc_count: usize,
456        pool: GraphemePool,
457        links: LinkRegistry,
458    }
459
460    impl BackendPresenter for TestPresenter {
461        type Error = TestError;
462
463        fn capabilities(&self) -> &TerminalCapabilities {
464            &self.caps
465        }
466
467        fn write_log(&mut self, text: &str) -> Result<(), Self::Error> {
468            self.logs.push(text.to_owned());
469            Ok(())
470        }
471
472        fn present_ui(
473            &mut self,
474            _buf: &Buffer,
475            _diff: Option<&BufferDiff>,
476            _full_repaint_hint: bool,
477        ) -> Result<(), Self::Error> {
478            self.present_count += 1;
479            Ok(())
480        }
481
482        fn gc(&mut self) {
483            self.gc_count += 1;
484        }
485
486        fn pool_and_links_mut(&mut self) -> (&mut GraphemePool, &mut LinkRegistry) {
487            (&mut self.pool, &mut self.links)
488        }
489
490        fn pool_mut(&mut self) -> &mut GraphemePool {
491            &mut self.pool
492        }
493    }
494
495    struct TestBackend {
496        clock: TestClock,
497        events: TestEventSource,
498    }
499
500    impl Backend for TestBackend {
501        type Error = TestError;
502        type Clock = TestClock;
503        type Events = TestEventSource;
504
505        fn clock(&self) -> &Self::Clock {
506            &self.clock
507        }
508
509        fn events(&mut self) -> &mut Self::Events {
510            &mut self.events
511        }
512    }
513
514    fn make_test_backend() -> TestBackend {
515        TestBackend {
516            clock: TestClock {
517                elapsed: Duration::from_millis(42),
518            },
519            events: TestEventSource {
520                features: BackendFeatures::default(),
521                events: Vec::new(),
522            },
523        }
524    }
525
526    // -----------------------------------------------------------------------
527    // BackendClock tests
528    // -----------------------------------------------------------------------
529
530    #[test]
531    fn clock_returns_elapsed() {
532        let clock = TestClock {
533            elapsed: Duration::from_secs(5),
534        };
535        assert_eq!(clock.now_mono(), Duration::from_secs(5));
536    }
537
538    #[test]
539    fn clock_zero_duration() {
540        let clock = TestClock {
541            elapsed: Duration::ZERO,
542        };
543        assert_eq!(clock.now_mono(), Duration::ZERO);
544    }
545
546    // -----------------------------------------------------------------------
547    // BackendEventSource tests
548    // -----------------------------------------------------------------------
549
550    #[test]
551    fn event_source_size() {
552        let src = TestEventSource {
553            features: BackendFeatures::default(),
554            events: Vec::new(),
555        };
556        assert_eq!(src.size().unwrap(), (80, 24));
557    }
558
559    #[test]
560    fn event_source_set_features() {
561        let mut src = TestEventSource {
562            features: BackendFeatures::default(),
563            events: Vec::new(),
564        };
565        let features = BackendFeatures {
566            mouse_capture: true,
567            bracketed_paste: true,
568            focus_events: false,
569            kitty_keyboard: false,
570        };
571        src.set_features(features).unwrap();
572        assert!(src.features.mouse_capture);
573        assert!(src.features.bracketed_paste);
574    }
575
576    #[test]
577    fn event_source_poll_empty() {
578        let mut src = TestEventSource {
579            features: BackendFeatures::default(),
580            events: Vec::new(),
581        };
582        assert!(!src.poll_event(Duration::from_millis(10)).unwrap());
583    }
584
585    #[test]
586    fn event_source_read_none_when_empty() {
587        let mut src = TestEventSource {
588            features: BackendFeatures::default(),
589            events: Vec::new(),
590        };
591        assert!(src.read_event().unwrap().is_none());
592    }
593
594    #[test]
595    fn event_source_poll_with_events() {
596        let mut src = TestEventSource {
597            features: BackendFeatures::default(),
598            events: vec![Event::Focus(true)],
599        };
600        assert!(src.poll_event(Duration::from_millis(10)).unwrap());
601    }
602
603    #[test]
604    fn event_source_read_drains_events() {
605        let mut src = TestEventSource {
606            features: BackendFeatures::default(),
607            events: vec![Event::Focus(true), Event::Focus(false)],
608        };
609        let e1 = src.read_event().unwrap();
610        assert!(e1.is_some());
611        let e2 = src.read_event().unwrap();
612        assert!(e2.is_some());
613        let e3 = src.read_event().unwrap();
614        assert!(e3.is_none());
615    }
616
617    // -----------------------------------------------------------------------
618    // BackendPresenter tests
619    // -----------------------------------------------------------------------
620
621    fn make_test_presenter() -> TestPresenter {
622        TestPresenter {
623            caps: TerminalCapabilities::default(),
624            logs: Vec::new(),
625            present_count: 0,
626            gc_count: 0,
627            pool: GraphemePool::new(),
628            links: LinkRegistry::new(),
629        }
630    }
631
632    #[test]
633    fn presenter_capabilities() {
634        let p = make_test_presenter();
635        let _caps = p.capabilities();
636    }
637
638    #[test]
639    fn presenter_write_log() {
640        let mut p = make_test_presenter();
641        p.write_log("hello").unwrap();
642        p.write_log("world").unwrap();
643        assert_eq!(p.logs.len(), 2);
644        assert_eq!(p.logs[0], "hello");
645        assert_eq!(p.logs[1], "world");
646    }
647
648    #[test]
649    fn presenter_present_ui() {
650        let mut p = make_test_presenter();
651        let buf = Buffer::new(10, 5);
652        p.present_ui(&buf, None, false).unwrap();
653        p.present_ui(&buf, None, true).unwrap();
654        assert_eq!(p.present_count, 2);
655    }
656
657    #[test]
658    fn presenter_gc() {
659        let mut p = make_test_presenter();
660        p.gc();
661        p.gc();
662        assert_eq!(p.gc_count, 2);
663    }
664
665    #[test]
666    fn presenter_defaults() {
667        let mut p = make_test_presenter();
668        assert_eq!(p.screen_mode(), ScreenMode::default());
669        p.set_screen_mode(ScreenMode::AltScreen);
670        p.resize(120, 40);
671        assert_eq!(p.render_height_hint(), 0);
672        assert_eq!(p.estimate_memory_usage(), 0);
673        assert!(p.last_diff_strategy().is_none());
674        assert!(p.last_diff_elapsed().is_none());
675        assert!(p.begin_shutdown().is_ok());
676        assert!(p.flush().is_ok());
677    }
678
679    // -----------------------------------------------------------------------
680    // Unified Backend tests
681    // -----------------------------------------------------------------------
682
683    #[test]
684    fn backend_clock_access() {
685        let backend = make_test_backend();
686        assert_eq!(backend.clock().now_mono(), Duration::from_millis(42));
687    }
688
689    #[test]
690    fn backend_events_access() {
691        let mut backend = make_test_backend();
692        let size = backend.events().size().unwrap();
693        assert_eq!(size, (80, 24));
694    }
695
696    #[test]
697    fn backend_full_cycle() {
698        let mut backend = make_test_backend();
699        let mut presenter = make_test_presenter();
700
701        // Clock
702        let _now = backend.clock().now_mono();
703
704        // Features
705        backend
706            .events()
707            .set_features(BackendFeatures {
708                mouse_capture: true,
709                ..BackendFeatures::default()
710            })
711            .unwrap();
712        assert!(backend.events.features.mouse_capture);
713
714        // Present
715        let buf = Buffer::new(80, 24);
716        presenter.write_log("frame start").unwrap();
717        presenter.present_ui(&buf, None, false).unwrap();
718        presenter.gc();
719
720        assert_eq!(presenter.logs.len(), 1);
721        assert_eq!(presenter.present_count, 1);
722        assert_eq!(presenter.gc_count, 1);
723    }
724
725    // -----------------------------------------------------------------------
726    // Error type tests
727    // -----------------------------------------------------------------------
728
729    #[test]
730    fn test_error_display() {
731        let err = TestError("something failed".into());
732        assert_eq!(format!("{err}"), "TestError: something failed");
733    }
734
735    #[test]
736    fn test_error_debug() {
737        let err = TestError("oops".into());
738        let debug = format!("{err:?}");
739        assert!(debug.contains("oops"));
740    }
741}