pub struct TerminalWriter<W: Write> { /* private fields */ }Expand description
Unified terminal output coordinator.
Enforces the one-writer rule and implements inline mode correctly. All terminal output should go through this struct.
Implementations§
Source§impl<W: Write> TerminalWriter<W>
impl<W: Write> TerminalWriter<W>
Sourcepub fn new(
writer: W,
screen_mode: ScreenMode,
ui_anchor: UiAnchor,
capabilities: TerminalCapabilities,
) -> Self
pub fn new( writer: W, screen_mode: ScreenMode, ui_anchor: UiAnchor, capabilities: TerminalCapabilities, ) -> Self
Create a new terminal writer.
§Arguments
writer- Output destination (takes ownership for one-writer rule)screen_mode- Inline or alternate screen modeui_anchor- Where to anchor UI in inline modecapabilities- Terminal capabilities
Sourcepub fn with_diff_config(
writer: W,
screen_mode: ScreenMode,
ui_anchor: UiAnchor,
capabilities: TerminalCapabilities,
diff_config: RuntimeDiffConfig,
) -> Self
pub fn with_diff_config( writer: W, screen_mode: ScreenMode, ui_anchor: UiAnchor, capabilities: TerminalCapabilities, diff_config: RuntimeDiffConfig, ) -> Self
Create a new terminal writer with custom diff strategy configuration.
§Arguments
writer- Output destination (takes ownership for one-writer rule)screen_mode- Inline or alternate screen modeui_anchor- Where to anchor UI in inline modecapabilities- Terminal capabilitiesdiff_config- Configuration for diff strategy selection
§Example
use ftui_runtime::{TerminalWriter, ScreenMode, UiAnchor, RuntimeDiffConfig};
use ftui_core::terminal_capabilities::TerminalCapabilities;
// Disable Bayesian selection for deterministic diffing
let config = RuntimeDiffConfig::default()
.with_bayesian_enabled(false);
let writer = TerminalWriter::with_diff_config(
std::io::stdout(),
ScreenMode::AltScreen,
UiAnchor::Bottom,
TerminalCapabilities::detect(),
config,
);Sourcepub fn diff_config(&self) -> &RuntimeDiffConfig
pub fn diff_config(&self) -> &RuntimeDiffConfig
Get the current diff configuration.
Sourcepub fn take_last_present_timings(&mut self) -> Option<PresentTimings>
pub fn take_last_present_timings(&mut self) -> Option<PresentTimings>
Take the last present timings (if available).
Sourcepub fn last_present_timings(&self) -> Option<&PresentTimings>
pub fn last_present_timings(&self) -> Option<&PresentTimings>
Access the last present timings (if available).
Sourcepub fn with_evidence_sink(self, sink: EvidenceSink) -> Self
pub fn with_evidence_sink(self, sink: EvidenceSink) -> Self
Attach an evidence sink for diff decision logging.
Sourcepub fn set_evidence_sink(&mut self, sink: Option<EvidenceSink>)
pub fn set_evidence_sink(&mut self, sink: Option<EvidenceSink>)
Set the evidence JSONL sink for diff decision logging.
Sourcepub fn set_evidence_callback(
&mut self,
callback: Option<Arc<dyn Fn(&str) + Send + Sync>>,
)
pub fn set_evidence_callback( &mut self, callback: Option<Arc<dyn Fn(&str) + Send + Sync>>, )
Set a callback that receives every formatted JSONL evidence line.
Sourcepub fn with_capability_decisions(
self,
decisions: Vec<CapabilityDecision>,
) -> Self
pub fn with_capability_decisions( self, decisions: Vec<CapabilityDecision>, ) -> Self
Attach the capability decision ledger produced by the live terminal
probe. The rows are written to the evidence sink as
capability_decision events, followed by one inline_strategy event
naming the strategy selected from those capabilities, as soon as both
the ledger and a sink are present (in either order).
Sourcepub fn with_render_trace(self, recorder: RenderTraceRecorder) -> Self
pub fn with_render_trace(self, recorder: RenderTraceRecorder) -> Self
Attach a render-trace recorder.
Sourcepub fn set_render_trace(&mut self, recorder: Option<RenderTraceRecorder>)
pub fn set_render_trace(&mut self, recorder: Option<RenderTraceRecorder>)
Set the render-trace recorder.
Sourcepub fn diff_strategy_mut(&mut self) -> &mut DiffStrategySelector
pub fn diff_strategy_mut(&mut self) -> &mut DiffStrategySelector
Get mutable access to the diff strategy selector.
Useful for advanced scenarios like manual posterior updates.
Sourcepub fn diff_strategy(&self) -> &DiffStrategySelector
pub fn diff_strategy(&self) -> &DiffStrategySelector
Get the diff strategy selector (read-only).
Sourcepub fn last_diff_strategy(&self) -> Option<DiffStrategy>
pub fn last_diff_strategy(&self) -> Option<DiffStrategy>
Get the last diff strategy selected during present, if any.
Sourcepub fn diff_regime(&self) -> DiffRegime
pub fn diff_regime(&self) -> DiffRegime
Current diff regime classification.
Sourcepub fn diff_regime_frames(&self) -> u64
pub fn diff_regime_frames(&self) -> u64
Number of consecutive frames spent in the current diff regime.
Sourcepub fn last_render_certificate(&self) -> Option<&RenderCertificate>
pub fn last_render_certificate(&self) -> Option<&RenderCertificate>
The explicit render certificate behind the most recent diff decision
(None before the first present or when certified skips are
disabled).
Sourcepub fn set_size(&mut self, width: u16, height: u16)
pub fn set_size(&mut self, width: u16, height: u16)
Set the terminal size.
Call this when the terminal is resized.
Sourcepub fn take_render_buffer(&mut self, width: u16, height: u16) -> Buffer
pub fn take_render_buffer(&mut self, width: u16, height: u16) -> Buffer
Take a reusable render buffer sized for the current frame.
Uses a spare buffer when available to avoid per-frame allocation.
Sourcepub fn screen_mode(&self) -> ScreenMode
pub fn screen_mode(&self) -> ScreenMode
Get the current screen mode.
Sourcepub fn set_screen_mode(&mut self, mode: ScreenMode)
pub fn set_screen_mode(&mut self, mode: ScreenMode)
Set the screen mode.
Sourcepub fn render_height_hint(&self) -> u16
pub fn render_height_hint(&self) -> u16
Height to use for rendering a frame.
Fixed inline heights are clamped to the current terminal height so models lay out their controls within the rows that can be presented. In inline auto mode, this returns the configured maximum (clamped to terminal height) so measurement can determine actual UI height.
Sourcepub fn inline_auto_bounds(&self) -> Option<(u16, u16)>
pub fn inline_auto_bounds(&self) -> Option<(u16, u16)>
Get sanitized min/max bounds for inline auto mode (clamped to terminal height).
Sourcepub fn auto_ui_height(&self) -> Option<u16>
pub fn auto_ui_height(&self) -> Option<u16>
Get the cached auto UI height (inline auto mode only).
Sourcepub fn set_auto_ui_height(&mut self, height: u16)
pub fn set_auto_ui_height(&mut self, height: u16)
Update the computed height for inline auto mode.
Sourcepub fn clear_auto_ui_height(&mut self)
pub fn clear_auto_ui_height(&mut self)
Clear the cached auto UI height (inline auto mode only).
Sourcepub fn inline_strategy(&self) -> InlineStrategy
pub fn inline_strategy(&self) -> InlineStrategy
Get the inline mode rendering strategy.
Sourcepub fn scroll_region_active(&self) -> bool
pub fn scroll_region_active(&self) -> bool
Check if a scroll region is currently active.
Sourcepub fn scroll_region_verified(&self) -> Option<bool>
pub fn scroll_region_verified(&self) -> Option<bool>
The DECSTBM self-test verdict recorded by
Self::set_scroll_region_verified (None: not run).
Sourcepub fn strategy_fallback(&self) -> Option<&InlineStrategyFallback>
pub fn strategy_fallback(&self) -> Option<&InlineStrategyFallback>
The strategy fallback the self-test forced, if any.
Sourcepub fn set_scroll_region_verified(
&mut self,
verdict: Option<ScrollRegionVerdict>,
rows: u16,
region_bottom: u16,
)
pub fn set_scroll_region_verified( &mut self, verdict: Option<ScrollRegionVerdict>, rows: u16, region_bottom: u16, )
Record the DECSTBM self-test verdict
(ftui_core::caps_probe::probe_scroll_region), taken by the runtime
at construction time before the input reader starts. A negative
verdict while the strategy is ScrollRegion or Hybrid switches the
writer to OverlayRedraw before its first frame, so a terminal that
ignores DECSTBM never scrolls the whole screen into the UI; the
fallback is exported as an inline_strategy_fallback evidence row
when a sink attaches. None leaves the strategy as selected.
Sourcepub fn present_ui(
&mut self,
buffer: &Buffer,
cursor: Option<(u16, u16)>,
cursor_visible: bool,
) -> Result<()>
pub fn present_ui( &mut self, buffer: &Buffer, cursor: Option<(u16, u16)>, cursor_visible: bool, ) -> Result<()>
Present a UI frame.
In inline mode, this:
- Begins synchronized output (if supported)
- Saves cursor position
- Moves to UI region and clears it
- Renders the buffer using the presenter
- Restores cursor position
- Moves cursor to requested UI position (if any)
- Applies cursor visibility
- Ends synchronized output
In AltScreen mode, this just renders the buffer and positions cursor.
Sourcepub fn present_ui_owned(
&mut self,
buffer: Buffer,
cursor: Option<(u16, u16)>,
cursor_visible: bool,
) -> Result<()>
pub fn present_ui_owned( &mut self, buffer: Buffer, cursor: Option<(u16, u16)>, cursor_visible: bool, ) -> Result<()>
Present a UI frame, taking ownership of the buffer (O(1) — no clone).
Prefer this over present_ui when the caller has an owned buffer
that won’t be reused, as it avoids an O(width × height) clone.
Sourcepub fn write_log(&mut self, text: &str) -> Result<()>
pub fn write_log(&mut self, text: &str) -> Result<()>
Write log output (goes to the log region in inline mode).
Behavior depends on how the UI is anchored on screen:
-
Scroll region active (ScrollRegion/Hybrid strategies): the cursor is parked at the bottom margin of the DECSTBM log region and the text is written verbatim (after escape-stripping). Each LF scrolls only the log region, so lines accumulate upward into scrollback while the UI stays put.
-
Overlay fallback (OverlayRedraw strategy, or any transient state without an active region): an unqualified LF would scroll the whole screen and displace or corrupt the displayed UI, so logs NEVER emit one. Instead exactly one width-clamped line is erased-and-rewritten, referenced against the displayed region (
last_inline_region) so height changes between presents cannot land the line inside on-screen UI. Older lines remain visible above until displaced by present repaints; accumulation into scrollback requires the scroll-region path.
If the UI consumes the entire terminal height, there is no log region available and the write becomes a no-op.
In AltScreen mode, logs are typically not shown (returns Ok silently).
Sourcepub fn write_log_sgr_only(&mut self, text: &str) -> Result<()>
pub fn write_log_sgr_only(&mut self, text: &str) -> Result<()>
Write colored log text, allowing only bounded SGR sequences.
Cursor commands, terminal modes and other controls are filtered at the
emission boundary. Inline overlay logs retain the first-line and visible
width limits of Self::write_log. Styling resets at every line/write;
callers must repeat styling on subsequent lines. Alt-screen logs are
suppressed, as with the default mode.
Sourcepub fn write_log_raw(&mut self, text: &str) -> Result<()>
pub fn write_log_raw(&mut self, text: &str) -> Result<()>
Write trusted log text without sanitization or overlay clamping.
Trusted input only: cursor movement, mode changes, clearing and
wrapping/newlines can corrupt inline UI or terminal state. Prefer
Self::write_log_sgr_only for colored compiler/test output. This still
uses the terminal output lock and log region, and suppresses alt-screen
logs, but arbitrary commands can defeat cursor restoration.
Sourcepub fn write_log_text(&mut self, text: &Text<'_>) -> Result<()>
pub fn write_log_text(&mut self, text: &Text<'_>) -> Result<()>
Write annotated text, reapplying its policy at the emission boundary.
Sourcepub fn clear_screen(&mut self) -> Result<()>
pub fn clear_screen(&mut self) -> Result<()>
Clear the screen.
Sourcepub fn hide_cursor(&mut self) -> Result<()>
pub fn hide_cursor(&mut self) -> Result<()>
Hide the cursor.
Sourcepub fn show_cursor(&mut self) -> Result<()>
pub fn show_cursor(&mut self) -> Result<()>
Show the cursor.
Sourcepub fn write_osc52_set(
&mut self,
selection: ClipboardSelection,
bytes: &[u8],
) -> Result<()>
pub fn write_osc52_set( &mut self, selection: ClipboardSelection, bytes: &[u8], ) -> Result<()>
Queue an OSC 52 clipboard write in the presenter’s existing output buffer.
Call flush when no frame follows. Unsupported capability
sets are skipped; invalid selections and oversized payloads are errors.
Sourcepub fn write_osc52_query(&mut self, selection: ClipboardSelection) -> Result<()>
pub fn write_osc52_query(&mut self, selection: ClipboardSelection) -> Result<()>
Queue an asynchronous OSC 52 clipboard read request.
Sourcepub fn pool(&self) -> &GraphemePool
pub fn pool(&self) -> &GraphemePool
Get the grapheme pool for interning complex characters.
Sourcepub fn pool_mut(&mut self) -> &mut GraphemePool
pub fn pool_mut(&mut self) -> &mut GraphemePool
Get mutable access to the grapheme pool.
Sourcepub fn links(&self) -> &LinkRegistry
pub fn links(&self) -> &LinkRegistry
Get the link registry.
Sourcepub fn links_mut(&mut self) -> &mut LinkRegistry
pub fn links_mut(&mut self) -> &mut LinkRegistry
Get mutable access to the link registry.
Sourcepub fn pool_and_links_mut(&mut self) -> (&mut GraphemePool, &mut LinkRegistry)
pub fn pool_and_links_mut(&mut self) -> (&mut GraphemePool, &mut LinkRegistry)
Borrow the grapheme pool and link registry together.
This avoids double-borrowing self at call sites that need both.
Sourcepub fn capabilities(&self) -> &TerminalCapabilities
pub fn capabilities(&self) -> &TerminalCapabilities
Get the terminal capabilities.
Sourcepub fn into_inner(self) -> Option<W>
pub fn into_inner(self) -> Option<W>
Consume the writer and return the underlying writer.
Performs cleanup operations before returning.
Returns None if the buffer could not be flushed.
Sourcepub fn gc(&mut self, extra_buffer: Option<&Buffer>)
pub fn gc(&mut self, extra_buffer: Option<&Buffer>)
Perform garbage collection on the grapheme pool.
Frees graphemes that are not referenced by the current front buffer (prev_buffer)
or the optional extra_buffer (e.g. a pending render).
This should be called periodically (e.g. every N frames) to prevent memory leaks in long-running applications with dynamic content.
Sourcepub fn estimate_memory_usage(&self) -> usize
pub fn estimate_memory_usage(&self) -> usize
Estimate total memory usage in bytes (buffers + pools).