Skip to main content

ftui_runtime/
terminal_presenter.rs

1#![forbid(unsafe_code)]
2
3//! Terminal presenter implementation wrapping [`TerminalWriter`].
4//!
5//! Provides the [`BackendPresenter`] implementation for terminal output (ANSI escape
6//! sequences over stdout or arbitrary `Write` sinks).
7
8use std::io::{self, Stdout, Write};
9use std::sync::Arc;
10use std::time::Duration;
11
12use ftui_backend::{
13    BackendPresenter, DiffStrategy, PresentTimings, SanitizeMode, ScreenMode, UiAnchor,
14};
15use ftui_core::osc52::ClipboardSelection;
16use ftui_core::terminal_capabilities::TerminalCapabilities;
17use ftui_render::buffer::Buffer;
18use ftui_render::diff::BufferDiff;
19use ftui_render::grapheme_pool::GraphemePool;
20use ftui_render::link_registry::LinkRegistry;
21
22use crate::terminal_writer::{RuntimeDiffConfig, TerminalWriter};
23
24/// Presenter implementation wrapping [`TerminalWriter`] for native/terminal output.
25pub struct TerminalPresenter<W: Write + Send = Stdout> {
26    /// Inner terminal writer handling low-level terminal I/O.
27    pub writer: TerminalWriter<W>,
28}
29
30impl<W: Write + Send> TerminalPresenter<W> {
31    /// Create a presenter wrapping an existing [`TerminalWriter`].
32    pub fn new(writer: TerminalWriter<W>) -> Self {
33        Self { writer }
34    }
35
36    /// Create a presenter writing to an arbitrary `Write` sink with default diff config.
37    pub fn with_writer(
38        writer: W,
39        mode: ScreenMode,
40        anchor: UiAnchor,
41        capabilities: TerminalCapabilities,
42    ) -> Self {
43        Self {
44            writer: TerminalWriter::new(writer, mode, anchor, capabilities),
45        }
46    }
47
48    /// Create a presenter writing to an arbitrary `Write` sink with custom diff config.
49    pub fn with_diff_config(
50        writer: W,
51        mode: ScreenMode,
52        anchor: UiAnchor,
53        capabilities: TerminalCapabilities,
54        diff_config: RuntimeDiffConfig,
55    ) -> Self {
56        Self {
57            writer: TerminalWriter::with_diff_config(
58                writer,
59                mode,
60                anchor,
61                capabilities,
62                diff_config,
63            ),
64        }
65    }
66
67    /// Reference the inner terminal writer.
68    #[must_use]
69    pub const fn writer(&self) -> &TerminalWriter<W> {
70        &self.writer
71    }
72
73    /// Mutably access the inner terminal writer.
74    pub fn writer_mut(&mut self) -> &mut TerminalWriter<W> {
75        &mut self.writer
76    }
77
78    /// Consume the presenter and return the inner terminal writer.
79    pub fn into_writer(self) -> TerminalWriter<W> {
80        self.writer
81    }
82
83    /// Consume the presenter and attempt to extract the underlying writer.
84    pub fn into_inner(self) -> Option<W> {
85        self.writer.into_inner()
86    }
87
88    /// Get the current UI height.
89    #[must_use]
90    pub fn ui_height(&self) -> u16 {
91        self.writer.ui_height()
92    }
93
94    /// Set the terminal dimensions.
95    pub fn set_size(&mut self, cols: u16, rows: u16) {
96        self.writer.set_size(cols, rows);
97    }
98}
99
100impl<W: Write + Send> From<TerminalWriter<W>> for TerminalPresenter<W> {
101    fn from(writer: TerminalWriter<W>) -> Self {
102        Self::new(writer)
103    }
104}
105
106impl TerminalPresenter<Stdout> {
107    /// Create a live presenter writing to stdout with default capabilities.
108    #[must_use]
109    pub fn live(capabilities: TerminalCapabilities) -> Self {
110        Self::with_writer(
111            io::stdout(),
112            ScreenMode::default(),
113            UiAnchor::default(),
114            capabilities,
115        )
116    }
117}
118
119impl<W: Write + Send> BackendPresenter for TerminalPresenter<W> {
120    type Error = io::Error;
121
122    fn capabilities(&self) -> &TerminalCapabilities {
123        self.writer.capabilities()
124    }
125
126    fn write_log(&mut self, text: &str) -> Result<(), Self::Error> {
127        self.writer.write_log(text)
128    }
129
130    fn write_log_line_with_mode(
131        &mut self,
132        text: &str,
133        mode: SanitizeMode,
134    ) -> Result<(), Self::Error> {
135        self.writer.write_log_line_with_mode(text, mode)
136    }
137
138    fn present_ui(
139        &mut self,
140        buf: &Buffer,
141        _diff: Option<&BufferDiff>,
142        full_repaint_hint: bool,
143    ) -> Result<(), Self::Error> {
144        // The writer's trailing arguments are the cursor and its visibility.
145        // Passing `None, false` hid the cursor on every frame; the trait has
146        // no cursor, so its visibility is left as it was. The repaint hint
147        // was dropped, so a damaged screen was diffed against a stale
148        // baseline and never rewritten.
149        if full_repaint_hint {
150            self.writer.invalidate_diff_baseline();
151        }
152        let cursor_visible = self.writer.cursor_visible();
153        self.writer.present_ui(buf, None, cursor_visible)
154    }
155
156    fn present_ui_owned(
157        &mut self,
158        buf: Buffer,
159        cursor: Option<(u16, u16)>,
160        cursor_visible: bool,
161    ) -> Result<(), Self::Error> {
162        self.writer.present_ui_owned(buf, cursor, cursor_visible)
163    }
164
165    fn gc(&mut self) {
166        self.writer.gc(None);
167    }
168
169    fn notify_resize(&mut self, cols: u16, rows: u16) {
170        self.writer.notify_resize(cols, rows);
171    }
172
173    fn resize(&mut self, cols: u16, rows: u16) {
174        self.writer.set_size(cols, rows);
175    }
176
177    fn screen_mode(&self) -> ScreenMode {
178        self.writer.screen_mode()
179    }
180
181    fn set_screen_mode(&mut self, mode: ScreenMode) {
182        self.writer.set_screen_mode(mode);
183    }
184
185    fn set_evidence_writer(&mut self, w: Option<Arc<dyn Fn(&str) + Send + Sync>>) {
186        self.writer.set_evidence_callback(w);
187    }
188
189    fn last_diff_strategy(&self) -> Option<DiffStrategy> {
190        self.writer.last_diff_strategy()
191    }
192
193    fn last_diff_elapsed(&self) -> Option<Duration> {
194        self.writer
195            .last_present_timings()
196            .map(|t| Duration::from_micros(t.diff_us))
197    }
198
199    fn begin_shutdown(&mut self) -> Result<(), Self::Error> {
200        self.writer.flush()
201    }
202
203    fn flush(&mut self) -> Result<(), Self::Error> {
204        self.writer.flush()
205    }
206
207    fn suspend(&mut self) -> Result<(), Self::Error> {
208        // Best-effort by design, like the drop-time cleanup it shares: a
209        // write error here must not stop the terminal being handed back.
210        self.writer.release_for_suspend();
211        Ok(())
212    }
213
214    fn take_render_buffer(&mut self, width: u16, height: u16) -> Buffer {
215        self.writer.take_render_buffer(width, height)
216    }
217
218    fn begin_link_frame(&mut self) {
219        self.writer.begin_link_frame();
220    }
221
222    fn pool_and_links_mut(&mut self) -> (&mut GraphemePool, &mut LinkRegistry) {
223        self.writer.pool_and_links_mut()
224    }
225
226    fn pool_mut(&mut self) -> &mut GraphemePool {
227        self.writer.pool_mut()
228    }
229
230    fn inline_auto_bounds(&self) -> Option<(u16, u16)> {
231        self.writer.inline_auto_bounds()
232    }
233
234    fn auto_ui_height(&self) -> Option<u16> {
235        self.writer.auto_ui_height()
236    }
237
238    fn render_height_hint(&self) -> u16 {
239        self.writer.render_height_hint()
240    }
241
242    fn set_auto_ui_height(&mut self, height: u16) {
243        self.writer.set_auto_ui_height(height);
244    }
245
246    fn clear_auto_ui_height(&mut self) {
247        self.writer.clear_auto_ui_height();
248    }
249
250    fn take_last_present_timings(&mut self) -> Option<PresentTimings> {
251        self.writer.take_last_present_timings()
252    }
253
254    fn estimate_memory_usage(&self) -> usize {
255        self.writer.estimate_memory_usage()
256    }
257
258    fn write_osc52_set(
259        &mut self,
260        selection: ClipboardSelection,
261        data: &[u8],
262    ) -> Result<(), Self::Error> {
263        self.writer.write_osc52_set(selection, data)
264    }
265
266    fn write_osc52_query(&mut self, selection: ClipboardSelection) -> Result<(), Self::Error> {
267        self.writer.write_osc52_query(selection)
268    }
269
270    fn set_timing_enabled(&mut self, enabled: bool) {
271        self.writer.set_timing_enabled(enabled);
272    }
273
274    fn set_hyperlink_limit(&mut self, limit: usize) {
275        self.writer.set_hyperlink_limit(limit);
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use std::sync::Mutex;
282
283    use super::*;
284
285    #[test]
286    fn resize_forwards_to_writer() {
287        let caps = TerminalCapabilities::detect();
288        let writer = TerminalWriter::new(
289            Vec::<u8>::new(),
290            ScreenMode::AltScreen,
291            UiAnchor::Bottom,
292            caps,
293        );
294        let mut presenter = TerminalPresenter::new(writer);
295        assert_eq!(presenter.writer.width(), 80);
296        assert_eq!(presenter.writer.height(), 24);
297
298        presenter.resize(120, 40);
299        assert_eq!(presenter.writer.width(), 120);
300        assert_eq!(presenter.writer.height(), 40);
301    }
302
303    #[test]
304    fn present_ui_honors_the_repaint_hint_and_keeps_the_cursor() {
305        let caps = TerminalCapabilities::basic();
306        let writer = TerminalWriter::new(
307            Vec::<u8>::new(),
308            ScreenMode::AltScreen,
309            UiAnchor::Bottom,
310            caps,
311        );
312        let mut presenter = TerminalPresenter::new(writer);
313        presenter.resize(10, 5);
314        let mut buf = Buffer::new(10, 5);
315        buf.set(2, 1, ftui_render::cell::Cell::from_char('Ж'));
316
317        presenter.present_ui(&buf, None, false).unwrap();
318        // Unchanged: nothing to write.
319        presenter.present_ui(&buf, None, false).unwrap();
320        // The hint repaints every cell.
321        presenter.present_ui(&buf, None, true).unwrap();
322
323        let TerminalPresenter { writer, .. } = presenter;
324        let bytes = writer.into_inner().expect("writer output");
325        let output = String::from_utf8_lossy(&bytes);
326        assert_eq!(output.matches('Ж').count(), 2, "{output:?}");
327        // The cursor may be hidden while drawing, but ends up visible again.
328        let hidden = output.rfind("\x1b[?25l");
329        let shown = output.rfind("\x1b[?25h");
330        assert!(shown > hidden, "cursor left hidden: {output:?}");
331    }
332
333    #[test]
334    fn evidence_callback_receives_diff_decision() {
335        let caps = TerminalCapabilities::detect();
336        let writer = TerminalWriter::new(
337            Vec::<u8>::new(),
338            ScreenMode::AltScreen,
339            UiAnchor::Bottom,
340            caps,
341        );
342        let mut presenter = TerminalPresenter::new(writer);
343        presenter.resize(10, 5);
344
345        let lines = Arc::new(Mutex::new(Vec::new()));
346        let lines_cb = Arc::clone(&lines);
347        presenter.set_evidence_writer(Some(Arc::new(move |line| {
348            lines_cb.lock().unwrap().push(line.to_string());
349        })));
350
351        let mut buf1 = presenter.take_render_buffer(10, 5);
352        buf1.set(0, 0, ftui_render::cell::Cell::from_char('A'));
353        presenter.present_ui_owned(buf1, None, false).unwrap();
354
355        let mut buf2 = presenter.take_render_buffer(10, 5);
356        buf2.set(1, 1, ftui_render::cell::Cell::from_char('B'));
357        presenter.present_ui_owned(buf2, None, false).unwrap();
358
359        let captured = lines.lock().unwrap();
360        assert!(
361            !captured.is_empty(),
362            "evidence callback should have received evidence lines, got: {captured:?}"
363        );
364        assert!(
365            captured.iter().any(|l| l.contains("diff_decision")),
366            "expected diff_decision event in evidence, got: {captured:?}"
367        );
368    }
369}