Skip to main content

TerminalWriter

Struct TerminalWriter 

Source
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>

Source

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 mode
  • ui_anchor - Where to anchor UI in inline mode
  • capabilities - Terminal capabilities
Source

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 mode
  • ui_anchor - Where to anchor UI in inline mode
  • capabilities - Terminal capabilities
  • diff_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,
);
Source

pub fn diff_config(&self) -> &RuntimeDiffConfig

Get the current diff configuration.

Source

pub fn take_last_present_timings(&mut self) -> Option<PresentTimings>

Take the last present timings (if available).

Source

pub fn last_present_timings(&self) -> Option<&PresentTimings>

Access the last present timings (if available).

Source

pub fn with_evidence_sink(self, sink: EvidenceSink) -> Self

Attach an evidence sink for diff decision logging.

Source

pub fn set_evidence_sink(&mut self, sink: Option<EvidenceSink>)

Set the evidence JSONL sink for diff decision logging.

Source

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.

Source

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).

Source

pub fn with_render_trace(self, recorder: RenderTraceRecorder) -> Self

Attach a render-trace recorder.

Source

pub fn set_render_trace(&mut self, recorder: Option<RenderTraceRecorder>)

Set the render-trace recorder.

Source

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.

Source

pub fn diff_strategy(&self) -> &DiffStrategySelector

Get the diff strategy selector (read-only).

Source

pub fn last_diff_strategy(&self) -> Option<DiffStrategy>

Get the last diff strategy selected during present, if any.

Source

pub fn diff_regime(&self) -> DiffRegime

Current diff regime classification.

Source

pub fn diff_regime_frames(&self) -> u64

Number of consecutive frames spent in the current diff regime.

Source

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).

Source

pub fn set_size(&mut self, width: u16, height: u16)

Set the terminal size.

Call this when the terminal is resized.

Source

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.

Source

pub fn width(&self) -> u16

Get the current terminal width.

Source

pub fn height(&self) -> u16

Get the current terminal height.

Source

pub fn screen_mode(&self) -> ScreenMode

Get the current screen mode.

Source

pub fn set_screen_mode(&mut self, mode: ScreenMode)

Set the screen mode.

Source

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.

Source

pub fn inline_auto_bounds(&self) -> Option<(u16, u16)>

Get sanitized min/max bounds for inline auto mode (clamped to terminal height).

Source

pub fn auto_ui_height(&self) -> Option<u16>

Get the cached auto UI height (inline auto mode only).

Source

pub fn set_auto_ui_height(&mut self, height: u16)

Update the computed height for inline auto mode.

Source

pub fn clear_auto_ui_height(&mut self)

Clear the cached auto UI height (inline auto mode only).

Source

pub fn ui_height(&self) -> u16

Get the UI height for the current mode.

Source

pub fn inline_strategy(&self) -> InlineStrategy

Get the inline mode rendering strategy.

Source

pub fn scroll_region_active(&self) -> bool

Check if a scroll region is currently active.

Source

pub fn scroll_region_verified(&self) -> Option<bool>

The DECSTBM self-test verdict recorded by Self::set_scroll_region_verified (None: not run).

Source

pub fn strategy_fallback(&self) -> Option<&InlineStrategyFallback>

The strategy fallback the self-test forced, if any.

Source

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.

Source

pub fn present_ui( &mut self, buffer: &Buffer, cursor: Option<(u16, u16)>, cursor_visible: bool, ) -> Result<()>

Present a UI frame.

In inline mode, this:

  1. Begins synchronized output (if supported)
  2. Saves cursor position
  3. Moves to UI region and clears it
  4. Renders the buffer using the presenter
  5. Restores cursor position
  6. Moves cursor to requested UI position (if any)
  7. Applies cursor visibility
  8. Ends synchronized output

In AltScreen mode, this just renders the buffer and positions cursor.

Source

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.

Source

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).

Source

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.

Source

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.

Source

pub fn write_log_text(&mut self, text: &Text<'_>) -> Result<()>

Write annotated text, reapplying its policy at the emission boundary.

Source

pub fn clear_screen(&mut self) -> Result<()>

Clear the screen.

Source

pub fn hide_cursor(&mut self) -> Result<()>

Hide the cursor.

Source

pub fn show_cursor(&mut self) -> Result<()>

Show the cursor.

Source

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.

Source

pub fn write_osc52_query(&mut self, selection: ClipboardSelection) -> Result<()>

Queue an asynchronous OSC 52 clipboard read request.

Source

pub fn flush(&mut self) -> Result<()>

Flush any buffered output.

Source

pub fn pool(&self) -> &GraphemePool

Get the grapheme pool for interning complex characters.

Source

pub fn pool_mut(&mut self) -> &mut GraphemePool

Get mutable access to the grapheme pool.

Get the link registry.

Get mutable access to the link registry.

Borrow the grapheme pool and link registry together.

This avoids double-borrowing self at call sites that need both.

Source

pub fn capabilities(&self) -> &TerminalCapabilities

Get the terminal capabilities.

Source

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.

Source

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.

Source

pub fn estimate_memory_usage(&self) -> usize

Estimate total memory usage in bytes (buffers + pools).

Trait Implementations§

Source§

impl<W: Write> Drop for TerminalWriter<W>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl<W: Write + Send> From<TerminalWriter<W>> for TerminalPresenter<W>

Source§

fn from(writer: TerminalWriter<W>) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more