use std::convert::Infallible;
use std::fmt;
use std::num::{NonZeroU16, NonZeroU32};
use crate::console_api::map_render_error;
use crate::layout::render_options;
use crate::{
Doc, HumanLayoutError, HumanLayoutOptions, PreparedDoc, Theme, TokenId, TokenStyle, tokens,
};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StyledRun {
text: String,
token: TokenId,
style: TokenStyle,
}
impl StyledRun {
pub fn text(&self) -> &str {
&self.text
}
pub const fn token(&self) -> &TokenId {
&self.token
}
pub const fn style(&self) -> TokenStyle {
self.style
}
}
#[derive(Default)]
pub struct StyledLine {
runs: Vec<StyledRun>,
used_runs: usize,
}
impl Clone for StyledLine {
fn clone(&self) -> Self {
Self {
runs: self.runs().to_vec(),
used_runs: self.used_runs,
}
}
}
impl fmt::Debug for StyledLine {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("StyledLine")
.field("runs", &self.runs())
.finish()
}
}
impl PartialEq for StyledLine {
fn eq(&self, other: &Self) -> bool {
self.runs() == other.runs()
}
}
impl Eq for StyledLine {}
impl StyledLine {
pub fn runs(&self) -> &[StyledRun] {
&self.runs[..self.used_runs]
}
pub fn text(&self) -> String {
self.runs().iter().map(StyledRun::text).collect()
}
}
pub struct StyledRenderWorkspace {
layout: laidout::RenderWorkspace,
output: StyledOutputWorkspace,
}
#[derive(Default)]
struct StyledOutputWorkspace {
lines: Vec<StyledLine>,
used_lines: usize,
}
impl Default for StyledRenderWorkspace {
fn default() -> Self {
Self::new()
}
}
impl StyledRenderWorkspace {
pub fn new() -> Self {
Self {
layout: laidout::RenderWorkspace::growable(),
output: StyledOutputWorkspace::default(),
}
}
pub fn release_capacity(&mut self) {
self.layout.release_capacity();
self.output = StyledOutputWorkspace::default();
}
}
impl StyledOutputWorkspace {
fn reset(&mut self) {
self.used_lines = 0;
self.push_line();
}
fn push_line(&mut self) {
if self.used_lines == self.lines.len() {
self.lines.push(StyledLine::default());
}
self.lines[self.used_lines].used_runs = 0;
self.used_lines += 1;
}
fn push_text(&mut self, value: &str, token: &TokenId, style: TokenStyle) {
if value.is_empty() {
return;
}
let line = self
.lines
.get_mut(self.used_lines - 1)
.expect("styled output always has a current line");
if line.used_runs > 0 {
let last = &mut line.runs[line.used_runs - 1];
if last.token == *token && last.style == style {
last.text.push_str(value);
return;
}
}
if line.used_runs == line.runs.len() {
line.runs.push(StyledRun {
text: String::new(),
token: token.clone(),
style,
});
} else {
let run = &mut line.runs[line.used_runs];
run.text.clear();
run.token.clone_from(token);
run.style = style;
}
let run = &mut line.runs[line.used_runs];
run.text.push_str(value);
line.used_runs += 1;
}
fn push_indent(&mut self, indent: u32, token: &TokenId, style: TokenStyle) {
if indent == 0 {
return;
}
let line = self
.lines
.get_mut(self.used_lines - 1)
.expect("styled output always has a current line");
if line.used_runs == line.runs.len() {
line.runs.push(StyledRun {
text: String::new(),
token: token.clone(),
style,
});
} else {
let run = &mut line.runs[line.used_runs];
run.text.clear();
run.token.clone_from(token);
run.style = style;
}
let run = &mut line.runs[line.used_runs];
for _ in 0..indent {
run.text.push(' ');
}
line.used_runs += 1;
}
fn output(&self) -> &[StyledLine] {
&self.lines[..self.used_lines]
}
}
impl Doc {
pub fn render_styled(
&self,
width: NonZeroU16,
theme: &Theme,
options: HumanLayoutOptions,
) -> Result<Vec<StyledLine>, HumanLayoutError> {
self.prepare()?.render_styled(width, theme, options)
}
pub fn render_styled_into<'workspace>(
&self,
width: NonZeroU16,
theme: &Theme,
options: HumanLayoutOptions,
workspace: &'workspace mut StyledRenderWorkspace,
) -> Result<&'workspace [StyledLine], HumanLayoutError> {
self.prepare()?
.render_styled_into(width, theme, options, workspace)
}
}
impl PreparedDoc {
pub fn render_styled(
&self,
width: NonZeroU16,
theme: &Theme,
options: HumanLayoutOptions,
) -> Result<Vec<StyledLine>, HumanLayoutError> {
let mut workspace = StyledRenderWorkspace::new();
Ok(self
.render_styled_into(width, theme, options, &mut workspace)?
.to_vec())
}
pub fn render_styled_into<'workspace>(
&self,
width: NonZeroU16,
theme: &Theme,
options: HumanLayoutOptions,
workspace: &'workspace mut StyledRenderWorkspace,
) -> Result<&'workspace [StyledLine], HumanLayoutError> {
workspace.output.reset();
let layout = laidout::solve_into(
self.inner(),
render_options(NonZeroU32::from(width), options),
&mut workspace.layout,
)
.map_err(map_render_error)?;
let mut visitor = StyledVisitor {
theme,
output: &mut workspace.output,
};
layout.visit(&mut visitor).map_err(|error| match error {
laidout::VisitError::Workspace(error) => map_render_error(error),
laidout::VisitError::Visitor(error) => match error {},
})?;
Ok(workspace.output.output())
}
}
struct StyledVisitor<'a> {
theme: &'a Theme,
output: &'a mut StyledOutputWorkspace,
}
impl laidout::LayoutVisitor<TokenId> for StyledVisitor<'_> {
type Error = Infallible;
fn text(
&mut self,
text: &str,
annotations: laidout::ActiveAnnotations<'_, TokenId>,
) -> Result<(), Self::Error> {
let style = self
.theme
.resolve_stack(annotations.iter().map(|(_, token)| token));
if let Some((_, token)) = annotations.innermost() {
self.output.push_text(text, token, style);
} else {
self.output.push_text(text, &tokens::TEXT, style);
}
Ok(())
}
fn newline(
&mut self,
indent: u32,
annotations: laidout::ActiveAnnotations<'_, TokenId>,
) -> Result<(), Self::Error> {
let style = self
.theme
.resolve_stack(annotations.iter().map(|(_, token)| token));
self.output.push_line();
if let Some((_, token)) = annotations.innermost() {
self.output.push_indent(indent, token, style);
} else {
self.output.push_indent(indent, &tokens::TEXT, style);
}
Ok(())
}
}