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 resize(&mut self, cols: u16, rows: u16) {
170        self.writer.set_size(cols, rows);
171    }
172
173    fn screen_mode(&self) -> ScreenMode {
174        self.writer.screen_mode()
175    }
176
177    fn set_screen_mode(&mut self, mode: ScreenMode) {
178        self.writer.set_screen_mode(mode);
179    }
180
181    fn set_evidence_writer(&mut self, w: Option<Arc<dyn Fn(&str) + Send + Sync>>) {
182        self.writer.set_evidence_callback(w);
183    }
184
185    fn last_diff_strategy(&self) -> Option<DiffStrategy> {
186        self.writer.last_diff_strategy()
187    }
188
189    fn last_diff_elapsed(&self) -> Option<Duration> {
190        self.writer
191            .last_present_timings()
192            .map(|t| Duration::from_micros(t.diff_us))
193    }
194
195    fn begin_shutdown(&mut self) -> Result<(), Self::Error> {
196        self.writer.flush()
197    }
198
199    fn flush(&mut self) -> Result<(), Self::Error> {
200        self.writer.flush()
201    }
202
203    fn suspend(&mut self) -> Result<(), Self::Error> {
204        // Best-effort by design, like the drop-time cleanup it shares: a
205        // write error here must not stop the terminal being handed back.
206        self.writer.release_for_suspend();
207        Ok(())
208    }
209
210    fn take_render_buffer(&mut self, width: u16, height: u16) -> Buffer {
211        self.writer.take_render_buffer(width, height)
212    }
213
214    fn begin_link_frame(&mut self) {
215        self.writer.begin_link_frame();
216    }
217
218    fn pool_and_links_mut(&mut self) -> (&mut GraphemePool, &mut LinkRegistry) {
219        self.writer.pool_and_links_mut()
220    }
221
222    fn pool_mut(&mut self) -> &mut GraphemePool {
223        self.writer.pool_mut()
224    }
225
226    fn inline_auto_bounds(&self) -> Option<(u16, u16)> {
227        self.writer.inline_auto_bounds()
228    }
229
230    fn auto_ui_height(&self) -> Option<u16> {
231        self.writer.auto_ui_height()
232    }
233
234    fn render_height_hint(&self) -> u16 {
235        self.writer.render_height_hint()
236    }
237
238    fn set_auto_ui_height(&mut self, height: u16) {
239        self.writer.set_auto_ui_height(height);
240    }
241
242    fn clear_auto_ui_height(&mut self) {
243        self.writer.clear_auto_ui_height();
244    }
245
246    fn take_last_present_timings(&mut self) -> Option<PresentTimings> {
247        self.writer.take_last_present_timings()
248    }
249
250    fn estimate_memory_usage(&self) -> usize {
251        self.writer.estimate_memory_usage()
252    }
253
254    fn write_osc52_set(
255        &mut self,
256        selection: ClipboardSelection,
257        data: &[u8],
258    ) -> Result<(), Self::Error> {
259        self.writer.write_osc52_set(selection, data)
260    }
261
262    fn write_osc52_query(&mut self, selection: ClipboardSelection) -> Result<(), Self::Error> {
263        self.writer.write_osc52_query(selection)
264    }
265
266    fn set_timing_enabled(&mut self, enabled: bool) {
267        self.writer.set_timing_enabled(enabled);
268    }
269
270    fn set_hyperlink_limit(&mut self, limit: usize) {
271        self.writer.set_hyperlink_limit(limit);
272    }
273}
274
275#[cfg(test)]
276mod tests {
277    use std::sync::Mutex;
278
279    use super::*;
280
281    #[test]
282    fn resize_forwards_to_writer() {
283        let caps = TerminalCapabilities::detect();
284        let writer = TerminalWriter::new(
285            Vec::<u8>::new(),
286            ScreenMode::AltScreen,
287            UiAnchor::Bottom,
288            caps,
289        );
290        let mut presenter = TerminalPresenter::new(writer);
291        assert_eq!(presenter.writer.width(), 80);
292        assert_eq!(presenter.writer.height(), 24);
293
294        presenter.resize(120, 40);
295        assert_eq!(presenter.writer.width(), 120);
296        assert_eq!(presenter.writer.height(), 40);
297    }
298
299    #[test]
300    fn present_ui_honors_the_repaint_hint_and_keeps_the_cursor() {
301        let caps = TerminalCapabilities::basic();
302        let writer = TerminalWriter::new(
303            Vec::<u8>::new(),
304            ScreenMode::AltScreen,
305            UiAnchor::Bottom,
306            caps,
307        );
308        let mut presenter = TerminalPresenter::new(writer);
309        presenter.resize(10, 5);
310        let mut buf = Buffer::new(10, 5);
311        buf.set(2, 1, ftui_render::cell::Cell::from_char('Ж'));
312
313        presenter.present_ui(&buf, None, false).unwrap();
314        // Unchanged: nothing to write.
315        presenter.present_ui(&buf, None, false).unwrap();
316        // The hint repaints every cell.
317        presenter.present_ui(&buf, None, true).unwrap();
318
319        let TerminalPresenter { writer, .. } = presenter;
320        let bytes = writer.into_inner().expect("writer output");
321        let output = String::from_utf8_lossy(&bytes);
322        assert_eq!(output.matches('Ж').count(), 2, "{output:?}");
323        // The cursor may be hidden while drawing, but ends up visible again.
324        let hidden = output.rfind("\x1b[?25l");
325        let shown = output.rfind("\x1b[?25h");
326        assert!(shown > hidden, "cursor left hidden: {output:?}");
327    }
328
329    #[test]
330    fn evidence_callback_receives_diff_decision() {
331        let caps = TerminalCapabilities::detect();
332        let writer = TerminalWriter::new(
333            Vec::<u8>::new(),
334            ScreenMode::AltScreen,
335            UiAnchor::Bottom,
336            caps,
337        );
338        let mut presenter = TerminalPresenter::new(writer);
339        presenter.resize(10, 5);
340
341        let lines = Arc::new(Mutex::new(Vec::new()));
342        let lines_cb = Arc::clone(&lines);
343        presenter.set_evidence_writer(Some(Arc::new(move |line| {
344            lines_cb.lock().unwrap().push(line.to_string());
345        })));
346
347        let mut buf1 = presenter.take_render_buffer(10, 5);
348        buf1.set(0, 0, ftui_render::cell::Cell::from_char('A'));
349        presenter.present_ui_owned(buf1, None, false).unwrap();
350
351        let mut buf2 = presenter.take_render_buffer(10, 5);
352        buf2.set(1, 1, ftui_render::cell::Cell::from_char('B'));
353        presenter.present_ui_owned(buf2, None, false).unwrap();
354
355        let captured = lines.lock().unwrap();
356        assert!(
357            !captured.is_empty(),
358            "evidence callback should have received evidence lines, got: {captured:?}"
359        );
360        assert!(
361            captured.iter().any(|l| l.contains("diff_decision")),
362            "expected diff_decision event in evidence, got: {captured:?}"
363        );
364    }
365}