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    /// Resize the presentation surface.
177    fn resize(&mut self, _cols: u16, _rows: u16) {}
178
179    /// Current screen mode.
180    fn screen_mode(&self) -> ScreenMode {
181        ScreenMode::default()
182    }
183
184    /// Set screen mode.
185    fn set_screen_mode(&mut self, _mode: ScreenMode) {}
186
187    /// Configure an evidence-writer callback.
188    fn set_evidence_writer(&mut self, _w: Option<Arc<dyn Fn(&str) + Send + Sync>>) {}
189
190    /// Last diff strategy used, if any.
191    fn last_diff_strategy(&self) -> Option<DiffStrategy> {
192        None
193    }
194
195    /// Last diff elapsed duration, if any.
196    fn last_diff_elapsed(&self) -> Option<Duration> {
197        None
198    }
199
200    /// Begin shutting down the presenter.
201    fn begin_shutdown(&mut self) -> Result<(), Self::Error> {
202        Ok(())
203    }
204
205    /// Flush any pending output to the terminal or host.
206    fn flush(&mut self) -> Result<(), Self::Error> {
207        Ok(())
208    }
209
210    /// Release presenter-owned terminal state ahead of a job-control stop:
211    /// close an open synchronized-output block, reset the scroll region, show
212    /// the cursor. On resume the runtime calls [`resize`](Self::resize), which
213    /// must drop any diff baseline, since the screen is no longer ours.
214    fn suspend(&mut self) -> Result<(), Self::Error> {
215        self.flush()
216    }
217
218    /// Take a reusable render buffer sized for the current frame.
219    fn take_render_buffer(&mut self, width: u16, height: u16) -> Buffer {
220        Buffer::new(width, height)
221    }
222
223    /// Mark the beginning of a frame for hyperlink tracking.
224    fn begin_link_frame(&mut self) {}
225
226    /// Mutably borrow the grapheme pool and link registry.
227    fn pool_and_links_mut(&mut self) -> (&mut GraphemePool, &mut LinkRegistry);
228
229    /// Mutably borrow the grapheme pool.
230    fn pool_mut(&mut self) -> &mut GraphemePool;
231
232    /// Configured bounds for inline auto mode, if active.
233    fn inline_auto_bounds(&self) -> Option<(u16, u16)> {
234        None
235    }
236
237    /// Current measured or auto-determined UI height for inline auto mode.
238    fn auto_ui_height(&self) -> Option<u16> {
239        None
240    }
241
242    /// Height hint to use when rendering a frame.
243    fn render_height_hint(&self) -> u16 {
244        0
245    }
246
247    /// Set auto UI height for inline auto mode.
248    fn set_auto_ui_height(&mut self, _height: u16) {}
249
250    /// Clear auto UI height for inline auto mode.
251    fn clear_auto_ui_height(&mut self) {}
252
253    /// Take presentation timings from the last rendered frame, if recorded.
254    fn take_last_present_timings(&mut self) -> Option<PresentTimings> {
255        None
256    }
257
258    /// Estimate memory usage of buffers and pools held by the presenter.
259    fn estimate_memory_usage(&self) -> usize {
260        0
261    }
262
263    /// Present a UI frame, taking ownership of the buffer.
264    fn present_ui_owned(
265        &mut self,
266        buf: Buffer,
267        cursor: Option<(u16, u16)>,
268        cursor_visible: bool,
269    ) -> Result<(), Self::Error> {
270        let _ = (cursor, cursor_visible);
271        self.present_ui(&buf, None, false)
272    }
273
274    /// Write a log line with a specific sanitization mode.
275    fn write_log_line_with_mode(
276        &mut self,
277        text: &str,
278        _mode: SanitizeMode,
279    ) -> Result<(), Self::Error> {
280        self.write_log(text)
281    }
282
283    /// Write an OSC 52 set clipboard sequence.
284    fn write_osc52_set(
285        &mut self,
286        _selection: ClipboardSelection,
287        _data: &[u8],
288    ) -> Result<(), Self::Error> {
289        Ok(())
290    }
291
292    /// Write an OSC 52 query clipboard sequence.
293    fn write_osc52_query(&mut self, _selection: ClipboardSelection) -> Result<(), Self::Error> {
294        Ok(())
295    }
296
297    /// Enable or disable presentation timing measurements.
298    fn set_timing_enabled(&mut self, _enabled: bool) {}
299
300    /// Set hyperlink limit for tracking.
301    fn set_hyperlink_limit(&mut self, _limit: usize) {}
302}
303
304/// Unified backend combining clock and event source.
305///
306/// The `Program` runtime drives event handling through this trait (or through
307/// [`BackendEventSource`] directly), and presents through [`BackendPresenter`].
308/// Concrete implementations:
309/// - `ftui-tty`: native Unix/macOS terminal (and eventually Windows).
310/// - `ftui-web`: WASM + DOM + WebGPU renderer.
311pub trait Backend {
312    /// Platform-specific error type shared across sub-traits.
313    type Error: core::fmt::Debug + core::fmt::Display;
314
315    /// Clock implementation.
316    type Clock: BackendClock;
317
318    /// Event source implementation.
319    type Events: BackendEventSource<Error = Self::Error>;
320
321    /// Access the monotonic clock.
322    fn clock(&self) -> &Self::Clock;
323
324    /// Access the event source (mutable for polling/reading).
325    fn events(&mut self) -> &mut Self::Events;
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331    use core::fmt;
332    use ftui_core::terminal_capabilities::TerminalCapabilities;
333
334    // -----------------------------------------------------------------------
335    // BackendFeatures tests
336    // -----------------------------------------------------------------------
337
338    #[test]
339    fn backend_features_default_all_false() {
340        let f = BackendFeatures::default();
341        assert!(!f.mouse_capture);
342        assert!(!f.bracketed_paste);
343        assert!(!f.focus_events);
344        assert!(!f.kitty_keyboard);
345    }
346
347    #[test]
348    fn backend_features_equality() {
349        let a = BackendFeatures {
350            mouse_capture: true,
351            bracketed_paste: false,
352            focus_events: true,
353            kitty_keyboard: false,
354        };
355        let b = BackendFeatures {
356            mouse_capture: true,
357            bracketed_paste: false,
358            focus_events: true,
359            kitty_keyboard: false,
360        };
361        assert_eq!(a, b);
362    }
363
364    #[test]
365    fn backend_features_inequality() {
366        let a = BackendFeatures::default();
367        let b = BackendFeatures {
368            mouse_capture: true,
369            ..BackendFeatures::default()
370        };
371        assert_ne!(a, b);
372    }
373
374    #[test]
375    fn backend_features_clone() {
376        let a = BackendFeatures {
377            mouse_capture: true,
378            bracketed_paste: true,
379            focus_events: true,
380            kitty_keyboard: true,
381        };
382        let b = a;
383        assert_eq!(a, b);
384    }
385
386    #[test]
387    fn backend_features_debug() {
388        let f = BackendFeatures::default();
389        let debug = format!("{f:?}");
390        assert!(debug.contains("BackendFeatures"));
391        assert!(debug.contains("mouse_capture"));
392    }
393
394    // -----------------------------------------------------------------------
395    // Mock implementations for trait testing
396    // -----------------------------------------------------------------------
397
398    struct TestClock {
399        elapsed: Duration,
400    }
401
402    impl BackendClock for TestClock {
403        fn now_mono(&self) -> Duration {
404            self.elapsed
405        }
406    }
407
408    #[derive(Debug)]
409    struct TestError(String);
410
411    impl fmt::Display for TestError {
412        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
413            write!(f, "TestError: {}", self.0)
414        }
415    }
416
417    struct TestEventSource {
418        features: BackendFeatures,
419        events: Vec<Event>,
420    }
421
422    impl BackendEventSource for TestEventSource {
423        type Error = TestError;
424
425        fn size(&self) -> Result<(u16, u16), Self::Error> {
426            Ok((80, 24))
427        }
428
429        fn set_features(&mut self, features: BackendFeatures) -> Result<(), Self::Error> {
430            self.features = features;
431            Ok(())
432        }
433
434        fn poll_event(&mut self, _timeout: Duration) -> Result<bool, Self::Error> {
435            Ok(!self.events.is_empty())
436        }
437
438        fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
439            Ok(if self.events.is_empty() {
440                None
441            } else {
442                Some(self.events.remove(0))
443            })
444        }
445    }
446
447    struct TestPresenter {
448        caps: TerminalCapabilities,
449        logs: Vec<String>,
450        present_count: usize,
451        gc_count: usize,
452        pool: GraphemePool,
453        links: LinkRegistry,
454    }
455
456    impl BackendPresenter for TestPresenter {
457        type Error = TestError;
458
459        fn capabilities(&self) -> &TerminalCapabilities {
460            &self.caps
461        }
462
463        fn write_log(&mut self, text: &str) -> Result<(), Self::Error> {
464            self.logs.push(text.to_owned());
465            Ok(())
466        }
467
468        fn present_ui(
469            &mut self,
470            _buf: &Buffer,
471            _diff: Option<&BufferDiff>,
472            _full_repaint_hint: bool,
473        ) -> Result<(), Self::Error> {
474            self.present_count += 1;
475            Ok(())
476        }
477
478        fn gc(&mut self) {
479            self.gc_count += 1;
480        }
481
482        fn pool_and_links_mut(&mut self) -> (&mut GraphemePool, &mut LinkRegistry) {
483            (&mut self.pool, &mut self.links)
484        }
485
486        fn pool_mut(&mut self) -> &mut GraphemePool {
487            &mut self.pool
488        }
489    }
490
491    struct TestBackend {
492        clock: TestClock,
493        events: TestEventSource,
494    }
495
496    impl Backend for TestBackend {
497        type Error = TestError;
498        type Clock = TestClock;
499        type Events = TestEventSource;
500
501        fn clock(&self) -> &Self::Clock {
502            &self.clock
503        }
504
505        fn events(&mut self) -> &mut Self::Events {
506            &mut self.events
507        }
508    }
509
510    fn make_test_backend() -> TestBackend {
511        TestBackend {
512            clock: TestClock {
513                elapsed: Duration::from_millis(42),
514            },
515            events: TestEventSource {
516                features: BackendFeatures::default(),
517                events: Vec::new(),
518            },
519        }
520    }
521
522    // -----------------------------------------------------------------------
523    // BackendClock tests
524    // -----------------------------------------------------------------------
525
526    #[test]
527    fn clock_returns_elapsed() {
528        let clock = TestClock {
529            elapsed: Duration::from_secs(5),
530        };
531        assert_eq!(clock.now_mono(), Duration::from_secs(5));
532    }
533
534    #[test]
535    fn clock_zero_duration() {
536        let clock = TestClock {
537            elapsed: Duration::ZERO,
538        };
539        assert_eq!(clock.now_mono(), Duration::ZERO);
540    }
541
542    // -----------------------------------------------------------------------
543    // BackendEventSource tests
544    // -----------------------------------------------------------------------
545
546    #[test]
547    fn event_source_size() {
548        let src = TestEventSource {
549            features: BackendFeatures::default(),
550            events: Vec::new(),
551        };
552        assert_eq!(src.size().unwrap(), (80, 24));
553    }
554
555    #[test]
556    fn event_source_set_features() {
557        let mut src = TestEventSource {
558            features: BackendFeatures::default(),
559            events: Vec::new(),
560        };
561        let features = BackendFeatures {
562            mouse_capture: true,
563            bracketed_paste: true,
564            focus_events: false,
565            kitty_keyboard: false,
566        };
567        src.set_features(features).unwrap();
568        assert!(src.features.mouse_capture);
569        assert!(src.features.bracketed_paste);
570    }
571
572    #[test]
573    fn event_source_poll_empty() {
574        let mut src = TestEventSource {
575            features: BackendFeatures::default(),
576            events: Vec::new(),
577        };
578        assert!(!src.poll_event(Duration::from_millis(10)).unwrap());
579    }
580
581    #[test]
582    fn event_source_read_none_when_empty() {
583        let mut src = TestEventSource {
584            features: BackendFeatures::default(),
585            events: Vec::new(),
586        };
587        assert!(src.read_event().unwrap().is_none());
588    }
589
590    #[test]
591    fn event_source_poll_with_events() {
592        let mut src = TestEventSource {
593            features: BackendFeatures::default(),
594            events: vec![Event::Focus(true)],
595        };
596        assert!(src.poll_event(Duration::from_millis(10)).unwrap());
597    }
598
599    #[test]
600    fn event_source_read_drains_events() {
601        let mut src = TestEventSource {
602            features: BackendFeatures::default(),
603            events: vec![Event::Focus(true), Event::Focus(false)],
604        };
605        let e1 = src.read_event().unwrap();
606        assert!(e1.is_some());
607        let e2 = src.read_event().unwrap();
608        assert!(e2.is_some());
609        let e3 = src.read_event().unwrap();
610        assert!(e3.is_none());
611    }
612
613    // -----------------------------------------------------------------------
614    // BackendPresenter tests
615    // -----------------------------------------------------------------------
616
617    fn make_test_presenter() -> TestPresenter {
618        TestPresenter {
619            caps: TerminalCapabilities::default(),
620            logs: Vec::new(),
621            present_count: 0,
622            gc_count: 0,
623            pool: GraphemePool::new(),
624            links: LinkRegistry::new(),
625        }
626    }
627
628    #[test]
629    fn presenter_capabilities() {
630        let p = make_test_presenter();
631        let _caps = p.capabilities();
632    }
633
634    #[test]
635    fn presenter_write_log() {
636        let mut p = make_test_presenter();
637        p.write_log("hello").unwrap();
638        p.write_log("world").unwrap();
639        assert_eq!(p.logs.len(), 2);
640        assert_eq!(p.logs[0], "hello");
641        assert_eq!(p.logs[1], "world");
642    }
643
644    #[test]
645    fn presenter_present_ui() {
646        let mut p = make_test_presenter();
647        let buf = Buffer::new(10, 5);
648        p.present_ui(&buf, None, false).unwrap();
649        p.present_ui(&buf, None, true).unwrap();
650        assert_eq!(p.present_count, 2);
651    }
652
653    #[test]
654    fn presenter_gc() {
655        let mut p = make_test_presenter();
656        p.gc();
657        p.gc();
658        assert_eq!(p.gc_count, 2);
659    }
660
661    #[test]
662    fn presenter_defaults() {
663        let mut p = make_test_presenter();
664        assert_eq!(p.screen_mode(), ScreenMode::default());
665        p.set_screen_mode(ScreenMode::AltScreen);
666        p.resize(120, 40);
667        assert_eq!(p.render_height_hint(), 0);
668        assert_eq!(p.estimate_memory_usage(), 0);
669        assert!(p.last_diff_strategy().is_none());
670        assert!(p.last_diff_elapsed().is_none());
671        assert!(p.begin_shutdown().is_ok());
672        assert!(p.flush().is_ok());
673    }
674
675    // -----------------------------------------------------------------------
676    // Unified Backend tests
677    // -----------------------------------------------------------------------
678
679    #[test]
680    fn backend_clock_access() {
681        let backend = make_test_backend();
682        assert_eq!(backend.clock().now_mono(), Duration::from_millis(42));
683    }
684
685    #[test]
686    fn backend_events_access() {
687        let mut backend = make_test_backend();
688        let size = backend.events().size().unwrap();
689        assert_eq!(size, (80, 24));
690    }
691
692    #[test]
693    fn backend_full_cycle() {
694        let mut backend = make_test_backend();
695        let mut presenter = make_test_presenter();
696
697        // Clock
698        let _now = backend.clock().now_mono();
699
700        // Features
701        backend
702            .events()
703            .set_features(BackendFeatures {
704                mouse_capture: true,
705                ..BackendFeatures::default()
706            })
707            .unwrap();
708        assert!(backend.events.features.mouse_capture);
709
710        // Present
711        let buf = Buffer::new(80, 24);
712        presenter.write_log("frame start").unwrap();
713        presenter.present_ui(&buf, None, false).unwrap();
714        presenter.gc();
715
716        assert_eq!(presenter.logs.len(), 1);
717        assert_eq!(presenter.present_count, 1);
718        assert_eq!(presenter.gc_count, 1);
719    }
720
721    // -----------------------------------------------------------------------
722    // Error type tests
723    // -----------------------------------------------------------------------
724
725    #[test]
726    fn test_error_display() {
727        let err = TestError("something failed".into());
728        assert_eq!(format!("{err}"), "TestError: something failed");
729    }
730
731    #[test]
732    fn test_error_debug() {
733        let err = TestError("oops".into());
734        let debug = format!("{err:?}");
735        assert!(debug.contains("oops"));
736    }
737}