use std::collections::TryReserveError;
use std::env;
use std::io::{self, Write};
use std::num::{NonZeroU16, NonZeroU32};
use std::sync::{Arc, Mutex, MutexGuard};
#[cfg(all(test, feature = "progress"))]
use std::sync::atomic::{AtomicU64, Ordering};
use crate::layout::render_options;
use crate::render::{AnsiStyle, render_text, style_encoding_for_style};
use crate::table::FixedTable;
use crate::{
Doc, HumanPrepareError, HumanText, MachineText, PreparedDoc, TextSafetyError, Theme, TokenId,
TokenStyle,
};
#[cfg(feature = "adaptive-tables")]
use crate::table::AdaptiveTable;
const DEFAULT_LAYOUT_WIDTH: NonZeroU16 = match NonZeroU16::new(80) {
Some(width) => width,
None => panic!("default layout width must be nonzero"),
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OutputClass {
Human,
MachineText,
OpaqueBytes,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Stream {
Stdout,
Stderr,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ColorChoice {
Auto,
Always,
Never,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ColorDepth {
Ansi16,
Ansi256,
TrueColor,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TerminalColorPolicy {
pub enabled: bool,
pub depth: ColorDepth,
}
impl TerminalColorPolicy {
pub fn detect_stdout(choice: ColorChoice) -> Self {
Self::detect(Stream::Stdout, choice)
}
pub fn detect_stderr(choice: ColorChoice) -> Self {
Self::detect(Stream::Stderr, choice)
}
fn detect(stream: Stream, choice: ColorChoice) -> Self {
let terminal = detect_terminal(stream);
let options = DestinationOptions {
output_class: OutputClass::Human,
color: choice,
terminal,
};
Self {
enabled: EnvironmentPolicy::Stdio.color_enabled(options),
depth: terminal.color_depth,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TerminalCapabilities {
pub is_terminal: bool,
pub color_depth: ColorDepth,
pub width: Option<NonZeroU16>,
pub interactive_cursor: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DestinationOptions {
pub output_class: OutputClass,
pub color: ColorChoice,
pub terminal: TerminalCapabilities,
}
#[derive(Clone)]
pub struct ConsoleOptions {
pub stdout: DestinationOptions,
pub stderr: DestinationOptions,
pub theme: Theme,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct StdioDestinationOptions {
pub output_class: OutputClass,
pub color: ColorChoice,
}
#[derive(Clone)]
pub struct StdioOptions {
pub stdout: StdioDestinationOptions,
pub stderr: StdioDestinationOptions,
pub theme: Theme,
}
impl TerminalCapabilities {
pub const fn non_terminal() -> Self {
Self {
is_terminal: false,
color_depth: ColorDepth::Ansi16,
width: None,
interactive_cursor: false,
}
}
}
impl DestinationOptions {
pub const fn new(
output_class: OutputClass,
color: ColorChoice,
terminal: TerminalCapabilities,
) -> Self {
Self {
output_class,
color,
terminal,
}
}
pub const fn non_terminal(output_class: OutputClass) -> Self {
Self::new(
output_class,
ColorChoice::Never,
TerminalCapabilities::non_terminal(),
)
}
}
impl ConsoleOptions {
pub fn new(stdout: DestinationOptions, stderr: DestinationOptions, theme: Theme) -> Self {
Self {
stdout,
stderr,
theme,
}
}
pub fn non_terminal(stdout: OutputClass, stderr: OutputClass, theme: Theme) -> Self {
Self::new(
DestinationOptions::non_terminal(stdout),
DestinationOptions::non_terminal(stderr),
theme,
)
}
}
impl StdioDestinationOptions {
pub const fn new(output_class: OutputClass, color: ColorChoice) -> Self {
Self {
output_class,
color,
}
}
pub const fn human() -> Self {
Self::new(OutputClass::Human, ColorChoice::Auto)
}
pub const fn machine_text() -> Self {
Self::new(OutputClass::MachineText, ColorChoice::Never)
}
pub const fn opaque_bytes() -> Self {
Self::new(OutputClass::OpaqueBytes, ColorChoice::Never)
}
pub const fn with_color(mut self, color: ColorChoice) -> Self {
self.color = color;
self
}
}
impl StdioOptions {
pub fn new(
stdout: StdioDestinationOptions,
stderr: StdioDestinationOptions,
theme: Theme,
) -> Self {
Self {
stdout,
stderr,
theme,
}
}
pub fn human(theme: Theme) -> Self {
Self::new(
StdioDestinationOptions::human(),
StdioDestinationOptions::human(),
theme,
)
}
}
pub struct Console {
pub(crate) stdout: Arc<DestinationState>,
pub(crate) stderr: Arc<DestinationState>,
theme: Theme,
}
pub(crate) struct DestinationState {
pub(crate) stream: Stream,
pub(crate) options: DestinationOptions,
pub(crate) color_enabled: bool,
pub(crate) sink: Arc<Mutex<Box<dyn Write + Send>>>,
#[cfg(all(test, feature = "progress"))]
lock_count: AtomicU64,
#[cfg(feature = "progress")]
pub(crate) progress: Arc<crate::progress::ProgressCoordinator>,
}
impl Console {
pub fn stdio(options: StdioOptions) -> Result<Self, ConsoleError> {
let stdout_terminal = detect_terminal(Stream::Stdout);
let stderr_terminal = detect_terminal(Stream::Stderr);
let console_options = ConsoleOptions {
stdout: DestinationOptions {
output_class: options.stdout.output_class,
color: options.stdout.color,
terminal: stdout_terminal,
},
stderr: DestinationOptions {
output_class: options.stderr.output_class,
color: options.stderr.color,
terminal: stderr_terminal,
},
theme: options.theme,
};
Self::construct(
io::stdout(),
io::stderr(),
console_options,
EnvironmentPolicy::Stdio,
)
}
pub fn with_writers<Out, Err>(
stdout: Out,
stderr: Err,
options: ConsoleOptions,
) -> Result<Self, ConsoleError>
where
Out: Write + Send + 'static,
Err: Write + Send + 'static,
{
Self::construct(stdout, stderr, options, EnvironmentPolicy::Injected)
}
fn construct<Out, Err>(
stdout: Out,
stderr: Err,
options: ConsoleOptions,
environment: EnvironmentPolicy,
) -> Result<Self, ConsoleError>
where
Out: Write + Send + 'static,
Err: Write + Send + 'static,
{
validate_terminal(Stream::Stdout, options.stdout.terminal)?;
validate_terminal(Stream::Stderr, options.stderr.terminal)?;
let stdout = destination(
Stream::Stdout,
stdout,
options.stdout,
environment.color_enabled(options.stdout),
);
let stderr = destination(
Stream::Stderr,
stderr,
options.stderr,
environment.color_enabled(options.stderr),
);
Ok(Self {
stdout,
stderr,
theme: options.theme,
})
}
pub fn human(&self, stream: Stream) -> Result<HumanWriter, ConsoleError> {
let destination = self.destination(stream);
require_class(&destination, OutputClass::Human)?;
Ok(HumanWriter {
destination,
theme: self.theme.clone(),
layout: laidout::RenderWorkspace::growable(),
ansi: Vec::new(),
ansi_limit: 0,
active_run: None,
deferred_indent: None,
last_was_newline: false,
})
}
pub fn machine_text(&self, stream: Stream) -> Result<MachineTextWriter, ConsoleError> {
let destination = self.destination(stream);
require_class(&destination, OutputClass::MachineText)?;
Ok(MachineTextWriter { destination })
}
pub fn opaque(&self, stream: Stream) -> Result<OpaqueWriter, ConsoleError> {
let destination = self.destination(stream);
require_class(&destination, OutputClass::OpaqueBytes)?;
Ok(OpaqueWriter { destination })
}
#[cfg(feature = "progress")]
pub fn stderr_progress(
&self,
options: crate::ProgressOptions,
) -> Result<crate::ProgressHandle, ConsoleError> {
require_class(&self.stderr, OutputClass::Human)?;
crate::progress::start(self.stderr.clone(), self.theme.clone(), options)
}
fn destination(&self, stream: Stream) -> Arc<DestinationState> {
match stream {
Stream::Stdout => self.stdout.clone(),
Stream::Stderr => self.stderr.clone(),
}
}
}
fn destination<W: Write + Send + 'static>(
stream: Stream,
writer: W,
options: DestinationOptions,
color_enabled: bool,
) -> Arc<DestinationState> {
let sink: Arc<Mutex<Box<dyn Write + Send>>> = Arc::new(Mutex::new(Box::new(writer)));
{
let _initialized = sink.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
}
Arc::new(DestinationState {
stream,
options,
color_enabled: color_enabled && options.output_class == OutputClass::Human,
sink,
#[cfg(all(test, feature = "progress"))]
lock_count: AtomicU64::new(0),
#[cfg(feature = "progress")]
progress: Arc::new(crate::progress::ProgressCoordinator::new()),
})
}
fn validate_terminal(stream: Stream, terminal: TerminalCapabilities) -> Result<(), ConsoleError> {
if terminal.interactive_cursor && !terminal.is_terminal {
return Err(ConsoleError::InvalidTerminalCapabilities { stream });
}
Ok(())
}
fn require_class(
destination: &Arc<DestinationState>,
requested: OutputClass,
) -> Result<(), ConsoleError> {
if destination.options.output_class != requested {
return Err(ConsoleError::OutputClassMismatch {
stream: destination.stream,
configured: destination.options.output_class,
requested,
});
}
Ok(())
}
#[derive(Clone, Copy)]
enum EnvironmentPolicy {
Stdio,
Injected,
}
impl EnvironmentPolicy {
fn color_enabled(self, options: DestinationOptions) -> bool {
match options.color {
ColorChoice::Always => true,
ColorChoice::Never => false,
ColorChoice::Auto => {
if !options.terminal.is_terminal {
return false;
}
match self {
EnvironmentPolicy::Injected => true,
EnvironmentPolicy::Stdio => stdio_auto_color(
options.terminal.is_terminal,
env::var_os("NO_COLOR").is_some(),
env::var("TERM").ok().as_deref(),
),
}
}
}
}
}
fn stdio_auto_color(is_terminal: bool, no_color: bool, term: Option<&str>) -> bool {
is_terminal && !no_color && !term.is_some_and(|value| value.eq_ignore_ascii_case("dumb"))
}
fn detect_terminal(stream: Stream) -> TerminalCapabilities {
let term = match stream {
Stream::Stdout => console::Term::stdout(),
Stream::Stderr => console::Term::stderr(),
};
let is_terminal = term.is_term();
let width = term
.size_checked()
.and_then(|(_, columns)| NonZeroU16::new(columns));
TerminalCapabilities {
is_terminal,
color_depth: detect_color_depth(),
width,
interactive_cursor: is_terminal,
}
}
fn detect_color_depth() -> ColorDepth {
let colorterm = env::var("COLORTERM").ok();
let term = env::var("TERM").ok();
detect_color_depth_from(colorterm.as_deref(), term.as_deref())
}
fn detect_color_depth_from(colorterm: Option<&str>, term: Option<&str>) -> ColorDepth {
if colorterm.is_some_and(|value| {
value.eq_ignore_ascii_case("truecolor") || value.eq_ignore_ascii_case("24bit")
}) {
ColorDepth::TrueColor
} else if term.is_some_and(|value| value.to_ascii_lowercase().contains("256color")) {
ColorDepth::Ansi256
} else {
ColorDepth::Ansi16
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Span {
pub token: TokenId,
pub text: HumanText,
}
impl Span {
pub fn new(token: TokenId, text: impl AsRef<str>) -> Self {
Self {
token,
text: HumanText::sanitize(text),
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct HumanRenderCapacity {
pub fast: HumanFastCapacity,
pub exact: HumanExactCapacity,
pub plan_nodes: usize,
pub visit: HumanVisitCapacity,
pub ansi_bytes: usize,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct HumanFastCapacity {
pub work_items: usize,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct HumanExactCapacity {
pub memo_entries: usize,
pub retained_candidates: usize,
pub frontier_scratch: usize,
pub work_items: usize,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct HumanVisitCapacity {
pub work_items: usize,
pub annotation_depth: usize,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LayoutStrategy {
Fast,
Exact,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HumanLayoutOptions {
strategy: LayoutStrategy,
newline_cost: u32,
}
impl HumanLayoutOptions {
pub const fn fast() -> Self {
Self {
strategy: LayoutStrategy::Fast,
newline_cost: 1,
}
}
pub const fn exact() -> Self {
Self {
strategy: LayoutStrategy::Exact,
newline_cost: 1,
}
}
pub const fn with_newline_cost(mut self, newline_cost: u32) -> Self {
self.newline_cost = newline_cost;
self
}
pub const fn strategy(&self) -> LayoutStrategy {
self.strategy
}
pub const fn newline_cost(&self) -> u32 {
self.newline_cost
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum HumanSolveCounter {
WorkItems,
FitChecks,
MemoHits,
MemoMisses,
CandidatesGenerated,
CandidatesPruned,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum HumanWorkspaceResource {
FastWorkItems,
ExactWorkItems,
MemoEntries,
RetainedCandidates,
FrontierScratch,
PlanNodes,
VisitWorkItems,
AnnotationDepth,
OutputBytes,
Spans,
AnsiBytes,
}
#[derive(Debug, thiserror::Error)]
pub enum HumanReserveError {
#[error("human workspace {resource:?} capacity {requested} is not representable")]
CapacityOverflow {
resource: HumanWorkspaceResource,
requested: usize,
},
#[error("failed to reserve {requested} entries for human workspace {resource:?}")]
Allocation {
resource: HumanWorkspaceResource,
requested: usize,
#[source]
source: TryReserveError,
},
}
#[derive(Debug, thiserror::Error)]
pub enum HumanLayoutError {
#[error(transparent)]
Prepare(#[from] HumanPrepareError),
#[error("human workspace {resource:?} requirement {required:?} exceeds {maximum}")]
WorkspaceCapacityOverflow {
resource: HumanWorkspaceResource,
required: Option<u128>,
maximum: u128,
},
#[error("fixed human workspace {resource:?} capacity {capacity} is below required {required}")]
WorkspaceExhausted {
resource: HumanWorkspaceResource,
capacity: usize,
required: usize,
},
#[error("failed to grow human workspace {resource:?} from {capacity} to {required}")]
WorkspaceGrowthFailed {
resource: HumanWorkspaceResource,
capacity: usize,
required: usize,
#[source]
source: TryReserveError,
},
#[error("human solve statistic {counter:?} requirement {required} exceeds {maximum}")]
StatisticsOverflow {
counter: HumanSolveCounter,
required: u128,
maximum: u64,
},
#[error("prepared human cost domain invariant was violated")]
CostDomainViolation,
#[error("selected human layout cost does not match its structural witness")]
CostWitnessMismatch,
#[error("ANSI output size overflow: current {current}, additional {additional}")]
AnsiSizeOverflow { current: usize, additional: usize },
}
#[derive(Debug, thiserror::Error)]
pub enum HumanRenderError {
#[error(transparent)]
Layout(HumanLayoutError),
#[error(transparent)]
Destination(ConsoleError),
}
#[derive(Clone, Copy)]
struct ActiveAnsiRun {
style: AnsiStyle,
reset_count: u8,
}
pub struct HumanWriter {
destination: Arc<DestinationState>,
theme: Theme,
layout: laidout::RenderWorkspace,
ansi: Vec<u8>,
ansi_limit: usize,
active_run: Option<ActiveAnsiRun>,
deferred_indent: Option<u32>,
last_was_newline: bool,
}
impl HumanWriter {
pub fn reserve_rendering(
&mut self,
capacity: HumanRenderCapacity,
) -> Result<(), HumanReserveError> {
self.clear_ansi_state();
if capacity.ansi_bytes > isize::MAX as usize {
return Err(HumanReserveError::CapacityOverflow {
resource: HumanWorkspaceResource::AnsiBytes,
requested: capacity.ansi_bytes,
});
}
let staged_ansi = if self.ansi.capacity() < capacity.ansi_bytes {
let mut replacement = Vec::new();
replacement
.try_reserve_exact(capacity.ansi_bytes)
.map_err(|source| HumanReserveError::Allocation {
resource: HumanWorkspaceResource::AnsiBytes,
requested: capacity.ansi_bytes,
source,
})?;
Some(replacement)
} else {
None
};
self.layout
.reserve(to_laidout_capacity(capacity))
.map_err(map_reserve_error)?;
if let Some(replacement) = staged_ansi {
self.ansi = replacement;
}
self.ansi_limit = self.ansi_limit.max(capacity.ansi_bytes);
Ok(())
}
pub fn rendering_capacity(&self) -> HumanRenderCapacity {
from_laidout_capacity(self.layout.capacity(), self.ansi_limit)
}
pub fn release_rendering_capacity(&mut self) {
self.clear_ansi_state();
self.layout.release_capacity();
self.ansi = Vec::new();
self.ansi_limit = 0;
}
pub fn warm_rendering(
&mut self,
doc: &PreparedDoc,
options: HumanLayoutOptions,
) -> Result<HumanRenderCapacity, HumanLayoutError> {
match self.render_prepared(doc, options, laidout::WorkspaceMode::Growable, false) {
Ok(()) => Ok(self.rendering_capacity()),
Err(HumanRenderError::Layout(error)) => Err(error),
Err(HumanRenderError::Destination(_)) => {
unreachable!("warming never hands bytes to a destination")
}
}
}
pub fn spans(&mut self, spans: &[Span]) -> Result<(), ConsoleError> {
let mut output = Vec::new();
self.render_spans(spans, &mut output);
self.destination.write_human_flushed(&output)
}
pub fn line(&mut self, spans: &[Span]) -> Result<(), ConsoleError> {
let mut output = Vec::new();
self.render_spans(spans, &mut output);
output.push(b'\n');
self.destination.write_human(&output)
}
pub fn blank_line(&mut self) -> Result<(), ConsoleError> {
self.destination.write_human(b"\n")
}
pub fn doc(&mut self, doc: &Doc) -> Result<(), ConsoleError> {
self.doc_with(doc, HumanLayoutOptions::fast())
}
pub fn doc_with(&mut self, doc: &Doc, options: HumanLayoutOptions) -> Result<(), ConsoleError> {
let prepared = doc
.prepare()
.map_err(|error| ConsoleError::HumanLayout(HumanLayoutError::Prepare(error)))?;
match self.doc_prepared(&prepared, options) {
Ok(()) => Ok(()),
Err(HumanRenderError::Layout(error)) => Err(ConsoleError::HumanLayout(error)),
Err(HumanRenderError::Destination(error)) => Err(error),
}
}
pub fn doc_prepared(
&mut self,
doc: &PreparedDoc,
options: HumanLayoutOptions,
) -> Result<(), HumanRenderError> {
self.render_prepared(doc, options, laidout::WorkspaceMode::Growable, true)
}
pub fn doc_strict(
&mut self,
doc: &PreparedDoc,
options: HumanLayoutOptions,
) -> Result<(), HumanRenderError> {
self.render_prepared(doc, options, laidout::WorkspaceMode::Fixed, true)
}
pub fn fixed_table<const N: usize>(
&mut self,
table: &FixedTable<N>,
) -> Result<(), ConsoleError> {
if table.header.is_none() && table.rows.is_empty() {
return self.destination.write_human(b"");
}
self.doc(&table.to_doc())
}
#[cfg(feature = "adaptive-tables")]
pub fn adaptive_table(&mut self, table: &AdaptiveTable) -> Result<(), ConsoleError> {
if table.header.is_none() && table.rows.is_empty() {
return self.destination.write_human(b"");
}
let width = self
.destination
.options
.terminal
.width
.unwrap_or(table.fallback_width);
self.doc(&table.to_doc(width, self.destination.options.terminal.is_terminal))
}
fn render_spans(&self, spans: &[Span], output: &mut Vec<u8>) {
for span in spans {
output.extend_from_slice(self.render(&span.token, span.text.as_str()).as_bytes());
}
}
fn render(&self, token: &TokenId, text: &str) -> String {
render_text(
&self.theme,
token,
text,
self.destination.options.terminal.color_depth,
self.destination.color_enabled,
self.destination.stream,
)
}
fn render_prepared(
&mut self,
doc: &PreparedDoc,
options: HumanLayoutOptions,
mode: laidout::WorkspaceMode,
handoff: bool,
) -> Result<(), HumanRenderError> {
let width = self
.destination
.options
.terminal
.width
.unwrap_or(DEFAULT_LAYOUT_WIDTH);
let width = NonZeroU32::from(width);
let Self {
destination,
theme,
layout,
ansi,
ansi_limit,
active_run,
deferred_indent,
last_was_newline,
} = self;
layout.set_mode(mode);
let mut attempt = HumanRenderAttempt::new(
ansi,
ansi_limit,
active_run,
deferred_indent,
last_was_newline,
mode,
);
let selected = laidout::solve_into(doc.inner(), render_options(width, options), layout)
.map_err(map_render_error)
.map_err(HumanRenderError::Layout)?;
let mut visitor = AnsiVisitor {
attempt: &mut attempt,
theme,
depth: destination.options.terminal.color_depth,
color_enabled: destination.color_enabled,
stream: destination.stream,
};
selected
.visit(&mut visitor)
.map_err(map_visit_error)
.map_err(HumanRenderError::Layout)?;
attempt.finish().map_err(HumanRenderError::Layout)?;
if handoff {
destination
.write_human(attempt.bytes())
.map_err(HumanRenderError::Destination)?;
}
Ok(())
}
fn clear_ansi_state(&mut self) {
self.ansi.clear();
self.active_run = None;
self.deferred_indent = None;
self.last_was_newline = false;
}
}
struct HumanRenderAttempt<'a> {
output: &'a mut Vec<u8>,
limit: &'a mut usize,
active_run: &'a mut Option<ActiveAnsiRun>,
deferred_indent: &'a mut Option<u32>,
last_was_newline: &'a mut bool,
mode: laidout::WorkspaceMode,
}
impl<'a> HumanRenderAttempt<'a> {
fn new(
output: &'a mut Vec<u8>,
limit: &'a mut usize,
active_run: &'a mut Option<ActiveAnsiRun>,
deferred_indent: &'a mut Option<u32>,
last_was_newline: &'a mut bool,
mode: laidout::WorkspaceMode,
) -> Self {
output.clear();
*active_run = None;
*deferred_indent = None;
*last_was_newline = false;
Self {
output,
limit,
active_run,
deferred_indent,
last_was_newline,
mode,
}
}
fn bytes(&self) -> &[u8] {
self.output
}
fn finish(&mut self) -> Result<(), HumanLayoutError> {
self.close_run()?;
*self.deferred_indent = None;
if !*self.last_was_newline {
self.append(b"\n")?;
*self.last_was_newline = true;
}
Ok(())
}
fn text(
&mut self,
style: TokenStyle,
text: &str,
depth: ColorDepth,
color_enabled: bool,
stream: Stream,
) -> Result<(), HumanLayoutError> {
if text.is_empty() {
return Ok(());
}
if let Some(indent) = *self.deferred_indent {
self.append_spaces(indent)?;
*self.deferred_indent = None;
}
let ansi_style = AnsiStyle::from_style(&style);
if self
.active_run
.is_some_and(|active| active.style != ansi_style)
{
self.close_run()?;
}
if self.active_run.is_none() {
let encoding = style_encoding_for_style(&style, depth, color_enabled, stream);
self.append(encoding.prefix())?;
*self.active_run = Some(ActiveAnsiRun {
style: ansi_style,
reset_count: encoding.reset_count(),
});
}
self.append(text.as_bytes())?;
*self.last_was_newline = false;
Ok(())
}
fn plain_text(&mut self, text: &str) -> Result<(), HumanLayoutError> {
if text.is_empty() {
return Ok(());
}
debug_assert!(self.active_run.is_none());
if let Some(indent) = *self.deferred_indent {
self.append_spaces(indent)?;
*self.deferred_indent = None;
}
self.append(text.as_bytes())?;
*self.last_was_newline = false;
Ok(())
}
fn newline(&mut self, indent: u32) -> Result<(), HumanLayoutError> {
self.close_run()?;
*self.deferred_indent = None;
self.append(b"\n")?;
*self.deferred_indent = Some(indent);
*self.last_was_newline = true;
Ok(())
}
fn close_run(&mut self) -> Result<(), HumanLayoutError> {
let Some(active) = self.active_run.take() else {
return Ok(());
};
for _ in 0..active.reset_count {
self.append(b"\x1b[0m")?;
}
Ok(())
}
fn append_spaces(&mut self, indent: u32) -> Result<(), HumanLayoutError> {
let additional =
usize::try_from(indent).map_err(|_| HumanLayoutError::AnsiSizeOverflow {
current: self.output.len(),
additional: usize::MAX,
})?;
let required = self.ensure(additional)?;
self.output.resize(required, b' ');
Ok(())
}
fn append(&mut self, bytes: &[u8]) -> Result<(), HumanLayoutError> {
let required = self.ensure(bytes.len())?;
debug_assert_eq!(required, self.output.len() + bytes.len());
self.output.extend_from_slice(bytes);
Ok(())
}
fn ensure(&mut self, additional: usize) -> Result<usize, HumanLayoutError> {
let current = self.output.len();
let required =
current
.checked_add(additional)
.ok_or(HumanLayoutError::AnsiSizeOverflow {
current,
additional,
})?;
if required <= *self.limit && required <= self.output.capacity() {
return Ok(required);
}
if self.mode == laidout::WorkspaceMode::Fixed {
return Err(HumanLayoutError::WorkspaceExhausted {
resource: HumanWorkspaceResource::AnsiBytes,
capacity: *self.limit,
required,
});
}
if required > self.output.capacity() {
self.output
.try_reserve_exact(required - current)
.map_err(|source| HumanLayoutError::WorkspaceGrowthFailed {
resource: HumanWorkspaceResource::AnsiBytes,
capacity: *self.limit,
required,
source,
})?;
}
*self.limit = (*self.limit).max(required);
Ok(required)
}
}
impl Drop for HumanRenderAttempt<'_> {
fn drop(&mut self) {
self.output.clear();
*self.active_run = None;
*self.deferred_indent = None;
*self.last_was_newline = false;
}
}
struct AnsiVisitor<'attempt, 'state> {
attempt: &'attempt mut HumanRenderAttempt<'state>,
theme: &'attempt Theme,
depth: ColorDepth,
color_enabled: bool,
stream: Stream,
}
impl laidout::LayoutVisitor<TokenId> for AnsiVisitor<'_, '_> {
type Error = HumanLayoutError;
fn text(
&mut self,
text: &str,
annotations: laidout::ActiveAnnotations<'_, TokenId>,
) -> Result<(), Self::Error> {
if !self.color_enabled {
return self.attempt.plain_text(text);
}
let (_, token) = annotations
.innermost()
.expect("Termosaic preparation installs a default token annotation");
let style = self.theme.resolve(token);
self.attempt
.text(style, text, self.depth, self.color_enabled, self.stream)
}
fn newline(
&mut self,
indent: u32,
_annotations: laidout::ActiveAnnotations<'_, TokenId>,
) -> Result<(), Self::Error> {
self.attempt.newline(indent)
}
}
fn to_laidout_capacity(capacity: HumanRenderCapacity) -> laidout::RenderCapacity {
laidout::RenderCapacity::new(
laidout::FastSolveCapacity::new(capacity.fast.work_items),
laidout::ExactSolveCapacity::new(
capacity.exact.memo_entries,
capacity.exact.retained_candidates,
capacity.exact.frontier_scratch,
capacity.exact.work_items,
),
capacity.plan_nodes,
laidout::VisitCapacity::new(capacity.visit.work_items, capacity.visit.annotation_depth),
laidout::MaterializeCapacity::new(0, 0),
)
}
fn from_laidout_capacity(
capacity: laidout::RenderCapacity,
ansi_bytes: usize,
) -> HumanRenderCapacity {
HumanRenderCapacity {
fast: HumanFastCapacity {
work_items: capacity.fast.work_items,
},
exact: HumanExactCapacity {
memo_entries: capacity.exact.memo_entries,
retained_candidates: capacity.exact.retained_candidates,
frontier_scratch: capacity.exact.frontier_scratch,
work_items: capacity.exact.work_items,
},
plan_nodes: capacity.plan_nodes,
visit: HumanVisitCapacity {
work_items: capacity.visit.work_items,
annotation_depth: capacity.visit.annotation_depth,
},
ansi_bytes,
}
}
fn map_workspace_resource(resource: laidout::WorkspaceResource) -> HumanWorkspaceResource {
match resource {
laidout::WorkspaceResource::FastWorkItems => HumanWorkspaceResource::FastWorkItems,
laidout::WorkspaceResource::ExactWorkItems => HumanWorkspaceResource::ExactWorkItems,
laidout::WorkspaceResource::MemoEntries => HumanWorkspaceResource::MemoEntries,
laidout::WorkspaceResource::RetainedCandidates => {
HumanWorkspaceResource::RetainedCandidates
}
laidout::WorkspaceResource::FrontierScratch => HumanWorkspaceResource::FrontierScratch,
laidout::WorkspaceResource::PlanNodes => HumanWorkspaceResource::PlanNodes,
laidout::WorkspaceResource::VisitWorkItems => HumanWorkspaceResource::VisitWorkItems,
laidout::WorkspaceResource::AnnotationDepth => HumanWorkspaceResource::AnnotationDepth,
laidout::WorkspaceResource::OutputBytes => HumanWorkspaceResource::OutputBytes,
laidout::WorkspaceResource::Spans => HumanWorkspaceResource::Spans,
_ => unreachable!("the exact Laidout 0.3.0 resource vocabulary is pinned"),
}
}
fn map_solve_counter(counter: laidout::SolveCounter) -> HumanSolveCounter {
match counter {
laidout::SolveCounter::WorkItems => HumanSolveCounter::WorkItems,
laidout::SolveCounter::FitChecks => HumanSolveCounter::FitChecks,
laidout::SolveCounter::MemoHits => HumanSolveCounter::MemoHits,
laidout::SolveCounter::MemoMisses => HumanSolveCounter::MemoMisses,
laidout::SolveCounter::CandidatesGenerated => HumanSolveCounter::CandidatesGenerated,
laidout::SolveCounter::CandidatesPruned => HumanSolveCounter::CandidatesPruned,
}
}
fn map_reserve_error(error: laidout::ReserveError) -> HumanReserveError {
match error {
laidout::ReserveError::CapacityOverflow {
resource,
requested,
} => HumanReserveError::CapacityOverflow {
resource: map_workspace_resource(resource),
requested,
},
laidout::ReserveError::Allocation {
resource,
requested,
source,
} => HumanReserveError::Allocation {
resource: map_workspace_resource(resource),
requested,
source,
},
_ => unreachable!("the exact Laidout 0.3.0 reserve-error vocabulary is pinned"),
}
}
pub(crate) fn map_render_error(error: laidout::RenderError) -> HumanLayoutError {
match error {
laidout::RenderError::WorkspaceCapacityOverflow {
resource,
required,
maximum,
..
} => HumanLayoutError::WorkspaceCapacityOverflow {
resource: map_workspace_resource(resource),
required,
maximum,
},
laidout::RenderError::WorkspaceExhausted {
resource,
capacity,
required,
..
} => HumanLayoutError::WorkspaceExhausted {
resource: map_workspace_resource(resource),
capacity,
required,
},
laidout::RenderError::WorkspaceGrowthFailed {
resource,
capacity,
required,
source,
..
} => HumanLayoutError::WorkspaceGrowthFailed {
resource: map_workspace_resource(resource),
capacity,
required,
source,
},
laidout::RenderError::StatisticsOverflow {
counter,
required,
maximum,
..
} => HumanLayoutError::StatisticsOverflow {
counter: map_solve_counter(counter),
required,
maximum,
},
laidout::RenderError::CostDomainViolation => HumanLayoutError::CostDomainViolation,
laidout::RenderError::CostWitnessMismatch => HumanLayoutError::CostWitnessMismatch,
_ => unreachable!("the exact Laidout 0.3.0 render-error vocabulary is pinned"),
}
}
fn map_visit_error(error: laidout::VisitError<HumanLayoutError>) -> HumanLayoutError {
match error {
laidout::VisitError::Workspace(error) => map_render_error(error),
laidout::VisitError::Visitor(error) => error,
}
}
pub struct MachineTextWriter {
destination: Arc<DestinationState>,
}
impl MachineTextWriter {
pub fn write(&mut self, value: &MachineText) -> Result<(), ConsoleError> {
self.destination.write_exact(value.as_str().as_bytes())
}
pub fn write_str(&mut self, value: &str) -> Result<(), MachineOutputError> {
let value = MachineText::parse(value.to_owned()).map_err(MachineOutputError::UnsafeText)?;
self.write(&value).map_err(MachineOutputError::Write)
}
pub fn flush(&mut self) -> Result<(), ConsoleError> {
self.destination.flush()
}
#[cfg(feature = "json")]
pub fn write_json<T: serde::Serialize + ?Sized>(
&mut self,
value: &T,
style: JsonStyle,
) -> Result<(), JsonOutputError> {
let mut encoded = match style {
JsonStyle::Compact => serde_json::to_vec(value),
JsonStyle::Pretty => serde_json::to_vec_pretty(value),
}
.map_err(|error| {
JsonOutputError::Serialize(JsonSerializeError {
message: error.to_string(),
})
})?;
encoded.push(b'\n');
let encoded = String::from_utf8(encoded).map_err(|error| {
JsonOutputError::Serialize(JsonSerializeError {
message: error.to_string(),
})
})?;
let text = MachineText::parse(encoded).map_err(|error| {
JsonOutputError::Serialize(JsonSerializeError {
message: error.to_string(),
})
})?;
self.write(&text).map_err(JsonOutputError::Write)
}
#[cfg(feature = "json")]
pub fn write_json_line<T: serde::Serialize + ?Sized>(
&mut self,
value: &T,
) -> Result<(), JsonOutputError> {
self.write_json(value, JsonStyle::Compact)
}
#[cfg(feature = "json")]
pub fn write_ndjson<T: serde::Serialize + ?Sized>(
&mut self,
value: &T,
) -> Result<(), JsonOutputError> {
self.write_json_line(value)
}
}
pub struct OpaqueWriter {
destination: Arc<DestinationState>,
}
impl OpaqueWriter {
pub fn write_all(&mut self, bytes: &[u8]) -> Result<(), ConsoleError> {
self.destination.write_exact(bytes)
}
pub fn flush(&mut self) -> Result<(), ConsoleError> {
self.destination.flush()
}
}
impl DestinationState {
fn write_exact(&self, bytes: &[u8]) -> Result<(), ConsoleError> {
let mut sink = self.lock_sink();
sink.write_all(bytes).map_err(|source| ConsoleError::Write {
stream: self.stream,
source,
})
}
fn write_human(&self, bytes: &[u8]) -> Result<(), ConsoleError> {
#[cfg(feature = "progress")]
{
self.progress.suspend(|| self.write_exact(bytes))
}
#[cfg(not(feature = "progress"))]
{
self.write_exact(bytes)
}
}
fn write_human_flushed(&self, bytes: &[u8]) -> Result<(), ConsoleError> {
let operation = || {
let mut sink = self.lock_sink();
sink.write_all(bytes)
.and_then(|()| sink.flush())
.map_err(|source| ConsoleError::Write {
stream: self.stream,
source,
})
};
#[cfg(feature = "progress")]
{
self.progress.suspend(operation)
}
#[cfg(not(feature = "progress"))]
{
operation()
}
}
fn flush(&self) -> Result<(), ConsoleError> {
let mut sink = self.lock_sink();
sink.flush().map_err(|source| ConsoleError::Write {
stream: self.stream,
source,
})
}
pub(crate) fn lock_sink(&self) -> MutexGuard<'_, Box<dyn Write + Send>> {
#[cfg(all(test, feature = "progress"))]
self.lock_count.fetch_add(1, Ordering::Relaxed);
self.sink
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
#[cfg(all(test, feature = "progress"))]
pub(crate) fn take_lock_count(&self) -> u64 {
self.lock_count.swap(0, Ordering::Relaxed)
}
}
#[derive(Debug, thiserror::Error)]
pub enum ConsoleError {
#[error("{stream:?} enables interactive cursor operations without being a terminal")]
InvalidTerminalCapabilities { stream: Stream },
#[error("{stream:?} is configured for {configured:?}, not {requested:?}")]
OutputClassMismatch {
stream: Stream,
configured: OutputClass,
requested: OutputClass,
},
#[cfg(feature = "progress")]
#[error("stderr already has an active progress handle")]
ProgressAlreadyActive,
#[error(transparent)]
HumanLayout(HumanLayoutError),
#[error("failed to write {stream:?}: {source}")]
Write {
stream: Stream,
#[source]
source: io::Error,
},
}
#[derive(Debug, thiserror::Error)]
pub enum MachineOutputError {
#[error(transparent)]
UnsafeText(#[from] TextSafetyError),
#[error(transparent)]
Write(#[from] ConsoleError),
}
#[cfg(feature = "json")]
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[error("{message}")]
pub struct JsonSerializeError {
pub message: String,
}
#[cfg(feature = "json")]
#[derive(Debug, thiserror::Error)]
pub enum JsonOutputError {
#[error("failed to serialize JSON output: {0}")]
Serialize(JsonSerializeError),
#[error(transparent)]
Write(ConsoleError),
}
#[cfg(feature = "json")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum JsonStyle {
Compact,
Pretty,
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Clone, Default)]
struct OrderedCapture(Arc<Mutex<Vec<String>>>);
impl Write for OrderedCapture {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self.0
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.push(format!("write:{}", String::from_utf8_lossy(bytes)));
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
self.0
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.push("flush".to_owned());
Ok(())
}
}
struct FlushFailingWriter;
impl Write for FlushFailingWriter {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"injected prompt flush failure",
))
}
}
fn human_options(color: ColorChoice, is_terminal: bool) -> DestinationOptions {
DestinationOptions {
output_class: OutputClass::Human,
color,
terminal: TerminalCapabilities {
is_terminal,
color_depth: ColorDepth::Ansi16,
width: None,
interactive_cursor: false,
},
}
}
#[test]
fn color_choice_and_stdio_environment_precedence_are_pinned() {
let disabled = TerminalColorPolicy::detect_stdout(ColorChoice::Never);
assert!(!disabled.enabled);
assert!(matches!(
disabled.depth,
ColorDepth::Ansi16 | ColorDepth::Ansi256 | ColorDepth::TrueColor
));
assert!(
EnvironmentPolicy::Injected.color_enabled(human_options(ColorChoice::Always, false))
);
assert!(
!EnvironmentPolicy::Injected.color_enabled(human_options(ColorChoice::Never, true))
);
assert!(EnvironmentPolicy::Injected.color_enabled(human_options(ColorChoice::Auto, true)));
assert!(
!EnvironmentPolicy::Injected.color_enabled(human_options(ColorChoice::Auto, false))
);
assert!(stdio_auto_color(true, false, Some("xterm-256color")));
assert!(!stdio_auto_color(true, true, Some("xterm-256color")));
assert!(!stdio_auto_color(true, false, Some("DuMb")));
assert!(!stdio_auto_color(false, false, Some("xterm")));
}
#[test]
fn mixed_case_stdio_depth_detection_is_pinned() {
assert_eq!(
detect_color_depth_from(Some("TrUeCoLoR"), Some("xterm")),
ColorDepth::TrueColor
);
assert_eq!(
detect_color_depth_from(Some("24BiT"), Some("xterm")),
ColorDepth::TrueColor
);
assert_eq!(
detect_color_depth_from(None, Some("XTERM-256CoLoR")),
ColorDepth::Ansi256
);
assert_eq!(
detect_color_depth_from(None, Some("xterm")),
ColorDepth::Ansi16
);
}
#[test]
fn span_records_are_flushed_before_returning() {
let stderr = OrderedCapture::default();
let events = stderr.0.clone();
let console = Console::with_writers(
io::sink(),
stderr,
ConsoleOptions {
stdout: human_options(ColorChoice::Never, false),
stderr: human_options(ColorChoice::Never, false),
theme: crate::themes::default(),
},
)
.expect("injected console");
console
.human(Stream::Stderr)
.expect("human stderr")
.spans(&[Span::new(crate::tokens::PROMPT, "Choice: ")])
.expect("prompt span");
assert_eq!(
*events
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner()),
["write:Choice: ", "flush"]
);
}
#[test]
fn span_flush_failures_are_typed_write_errors() {
let console = Console::with_writers(
io::sink(),
FlushFailingWriter,
ConsoleOptions {
stdout: human_options(ColorChoice::Never, false),
stderr: human_options(ColorChoice::Never, false),
theme: crate::themes::default(),
},
)
.expect("injected console");
let error = console
.human(Stream::Stderr)
.expect("human stderr")
.spans(&[Span::new(crate::tokens::PROMPT, "Choice: ")])
.expect_err("flush failure must propagate");
assert!(matches!(
error,
ConsoleError::Write {
stream: Stream::Stderr,
..
}
));
}
}