//! Styled display wrappers. //! //! `Paint` pairs an arbitrary display value with a [`Style`](crate::Style). //! Its display adapters can render either plain text or ANSI-styled text, //! letting the same value be measured, buffered, or printed with explicit //! formatting mode. use std::fmt; use super::color::Color; use super::style::{Property, Style}; /// Paint formatting mode. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] pub enum PaintMode { /// Write plain text with no ANSI escapes. #[default] Plain, /// Write ANSI escapes for the stored style. Styled, } /// A paint object paired with an explicit formatting mode. #[derive(Debug, Clone, Copy)] pub struct Painted<'a, T> { paint: &'a Paint, mode: PaintMode, } /// A structure encapsulating an item and styling. #[derive(Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)] pub struct Paint { /// Wrapped display item. pub item: T, /// Style applied when the item is displayed. pub style: Style, } impl> Paint { /// Return plain content. pub fn content(&self) -> &str { self.item.as_ref() } } impl From for Paint { fn from(value: T) -> Self { Self::new(value) } } impl From<&str> for Paint { fn from(item: &str) -> Self { Self::new(item.to_string()) } } impl From> for Paint { fn from(paint: Paint<&str>) -> Self { Self { item: paint.item.to_owned(), style: paint.style, } } } impl From> for String { fn from(value: Paint) -> Self { value.item } } impl Paint { /// Constructs a new `Paint` structure encapsulating `item` with no set /// styling. #[inline] pub const fn new(item: T) -> Paint { Paint { item, style: Style { foreground: Color::Unset, background: Color::Unset, properties: Property::new(), wrap: false, }, } } /// Constructs a new _wrapping_ `Paint` structure encapsulating `item` with /// default styling. /// /// A wrapping `Paint` converts all color resets written out by the internal /// value to the styling of itself. This allows for seamless color wrapping /// of other colored text. /// /// # Performance /// /// In order to wrap an internal value, the internal value must first be /// written out to a local buffer and examined. As a result, displaying a /// wrapped value is likely to result in a heap allocation and copy. #[inline] pub const fn wrapping(item: T) -> Paint { Paint::new(item).wrap() } /// Constructs a new `Paint` structure encapsulating `item` with the /// foreground color set to the RGB color `r`, `g`, `b`. #[inline] pub const fn rgb(r: u8, g: u8, b: u8, item: T) -> Paint { Paint::new(item).fg(Color::RGB(r, g, b)) } /// Constructs a new `Paint` structure encapsulating `item` with the /// foreground color set to the fixed 8-bit color `color`. #[inline] pub const fn fixed(color: u8, item: T) -> Paint { Paint::new(item).fg(Color::Fixed(color)) } /// Constructs red foreground text. pub const fn red(item: T) -> Paint { Paint::new(item).fg(Color::Red) } /// Constructs black foreground text. pub const fn black(item: T) -> Paint { Paint::new(item).fg(Color::Black) } /// Constructs yellow foreground text. pub const fn yellow(item: T) -> Paint { Paint::new(item).fg(Color::Yellow) } /// Constructs green foreground text. pub const fn green(item: T) -> Paint { Paint::new(item).fg(Color::Green) } /// Constructs cyan foreground text. pub const fn cyan(item: T) -> Paint { Paint::new(item).fg(Color::Cyan) } /// Constructs blue foreground text. pub const fn blue(item: T) -> Paint { Paint::new(item).fg(Color::Blue) } /// Constructs magenta foreground text. pub const fn magenta(item: T) -> Paint { Paint::new(item).fg(Color::Magenta) } /// Constructs white foreground text. pub const fn white(item: T) -> Paint { Paint::new(item).fg(Color::White) } /// Retrieves the style currently set on `self`. #[inline] pub const fn style(&self) -> Style { self.style } /// Retrieves a borrow to the inner item. #[inline] pub const fn inner(&self) -> &T { &self.item } /// Sets the style of `self` to `style`. #[inline] pub fn with_style(mut self, style: Style) -> Paint { self.style = style; self } /// Makes `self` a _wrapping_ `Paint`. /// /// A wrapping `Paint` converts all color resets written out by the internal /// value to the styling of itself. This allows for seamless color wrapping /// of other colored text. /// /// # Performance /// /// In order to wrap an internal value, the internal value must first be /// written out to a local buffer and examined. As a result, displaying a /// wrapped value is likely to result in a heap allocation and copy. #[inline] pub const fn wrap(mut self) -> Paint { self.style.wrap = true; self } /// Sets the foreground to `color`. #[inline] pub const fn fg(mut self, color: Color) -> Paint { self.style.foreground = color; self } /// Sets the background to `color`. #[inline] pub const fn bg(mut self, color: Color) -> Paint { self.style.background = color; self } /// Adds bold styling. pub fn bold(mut self) -> Self { self.style.properties.set(Property::BOLD); self } /// Adds dim styling. pub fn dim(mut self) -> Self { self.style.properties.set(Property::DIM); self } /// Adds italic styling. pub fn italic(mut self) -> Self { self.style.properties.set(Property::ITALIC); self } /// Adds underline styling. pub fn underline(mut self) -> Self { self.style.properties.set(Property::UNDERLINE); self } /// Adds inverse-video styling. pub fn invert(mut self) -> Self { self.style.properties.set(Property::INVERT); self } /// Adds strikethrough styling. pub fn strikethrough(mut self) -> Self { self.style.properties.set(Property::STRIKETHROUGH); self } /// Adds blink styling. pub fn blink(mut self) -> Self { self.style.properties.set(Property::BLINK); self } /// Adds hidden styling. pub fn hidden(mut self) -> Self { self.style.properties.set(Property::HIDDEN); self } /// Return a display adapter using `mode`. pub const fn rendered(&self, mode: PaintMode) -> Painted<'_, T> { Painted { paint: self, mode } } /// Return a display adapter that writes styled text. pub const fn styled(&self) -> Painted<'_, T> { self.rendered(PaintMode::Styled) } /// Return a display adapter that writes plain text. pub const fn plain(&self) -> Painted<'_, T> { self.rendered(PaintMode::Plain) } } impl fmt::Display for Paint { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.item, f) } } impl fmt::Display for Painted<'_, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.mode { PaintMode::Plain => fmt::Display::fmt(&self.paint.item, f), PaintMode::Styled => self.paint.fmt_ansi(f), } } } impl Paint { /// Write the item with ANSI styling. pub fn fmt_ansi(&self, f: &mut dyn fmt::Write) -> fmt::Result { if self.style.wrap { let mut prefix = String::new(); prefix.push_str("\x1B[0m"); self.style.fmt_prefix(&mut prefix)?; self.style.fmt_prefix(f)?; let item = format!("{}", &self.item).replace("\x1B[0m", &prefix); write!(f, "{item}")?; self.style.fmt_suffix(f) } else { self.style.fmt_prefix(f)?; write!(f, "{}", &self.item)?; self.style.fmt_suffix(f) } } } impl Paint<()> { /// Check 24-bit RGB color support. pub fn truecolor() -> bool { std::env::var("COLORTERM").is_ok_and(|term| term.eq_ignore_ascii_case("truecolor")) } } /// An object filled with a background color. #[derive(Debug, Clone)] pub struct Filled { /// Wrapped display item. pub item: T, /// Background fill color. pub color: Color, } impl fmt::Display for Filled { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", Paint::wrapping(&self.item).bg(self.color)) } } /// Shorthand for [`Paint::new`]. pub fn paint(item: T) -> Paint { Paint::new(item) } #[cfg(test)] mod tests { use super::*; #[test] fn paint_constructors_set_expected_colors() { assert_eq!(Paint::red("x").style().fg_color(), Color::Red); assert_eq!(Paint::black("x").style().fg_color(), Color::Black); assert_eq!(Paint::yellow("x").style().fg_color(), Color::Yellow); assert_eq!(Paint::green("x").style().fg_color(), Color::Green); assert_eq!(Paint::cyan("x").style().fg_color(), Color::Cyan); assert_eq!(Paint::blue("x").style().fg_color(), Color::Blue); assert_eq!(Paint::magenta("x").style().fg_color(), Color::Magenta); assert_eq!(Paint::white("x").style().fg_color(), Color::White); assert_eq!(Paint::fixed(42, "x").style().fg_color(), Color::Fixed(42)); assert_eq!( Paint::rgb(1, 2, 3, "x").style().fg_color(), Color::RGB(1, 2, 3) ); } #[test] fn paint_records_background_and_wrapping() { let paint = Paint::wrapping("x").bg(Color::Blue); assert_eq!(paint.style().bg_color(), Color::Blue); assert!(paint.style().is_wrapping()); } #[test] fn paint_from_conversions_preserve_content_and_style() { let borrowed = Paint::red("content"); let owned = Paint::::from(borrowed); assert_eq!(owned.content(), "content"); assert_eq!(owned.style().fg_color(), Color::Red); assert_eq!(String::from(owned), "content"); assert_eq!(Paint::::from("other").content(), "other"); } #[test] fn display_is_plain_and_styled_adapter_is_explicit() { let paint = Paint::red("content"); assert_eq!(paint.to_string(), "content"); assert_eq!(paint.plain().to_string(), "content"); assert_eq!(paint.styled().to_string(), "\x1B[31mcontent\x1B[0m"); assert_eq!( paint.rendered(PaintMode::Styled).to_string(), "\x1B[31mcontent\x1B[0m" ); } #[test] fn styled_adapter_reapplies_wrapping_style_after_reset() { let paint = Paint::wrapping("a\x1B[0mb").fg(Color::Red); assert_eq!( paint.styled().to_string(), "\x1B[31ma\x1B[0m\x1B[31mb\x1B[0m" ); } #[test] fn filled_records_item_and_background_color() { let filled = Filled { item: "x", color: Color::Red, }; assert_eq!(filled.item, "x"); assert_eq!(filled.color, Color::Red); } }