//! ANSI style properties. //! //! `Style` records foreground/background colors and text attributes such as //! bold or italic. It is a value type shared by cells, labels, borders, and //! painted display wrappers. use std::fmt::{self, Display}; use std::hash::{Hash, Hasher}; use std::ops::BitOr; use super::{Color, Paint}; /// Bitset of ANSI text style properties. #[derive(Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)] pub struct Property(u8); impl Property { /// Bold text property. pub const BOLD: Self = Property(1 << 0); /// Dim text property. pub const DIM: Self = Property(1 << 1); /// Italic text property. pub const ITALIC: Self = Property(1 << 2); /// Underlined text property. pub const UNDERLINE: Self = Property(1 << 3); /// Blinking text property. pub const BLINK: Self = Property(1 << 4); /// Inverse-video text property. pub const INVERT: Self = Property(1 << 5); /// Hidden text property. pub const HIDDEN: Self = Property(1 << 6); /// Strikethrough text property. pub const STRIKETHROUGH: Self = Property(1 << 7); /// Returns an empty property set. pub const fn new() -> Self { Property(0) } /// Returns whether all bits in `other` are set. pub const fn contains(self, other: Property) -> bool { (other.0 & self.0) == other.0 } /// Adds all bits from `other`. #[inline(always)] pub fn set(&mut self, other: Property) { self.0 |= other.0; } /// Iterates over enabled ANSI property indexes. #[inline(always)] pub fn iter(self) -> Iter { Iter { index: 0, properties: self, } } } impl BitOr for Property { type Output = Self; #[inline(always)] fn bitor(self, rhs: Self) -> Self { Property(self.0 | rhs.0) } } /// Iterator over enabled ANSI property indexes. pub struct Iter { /// Next bit index to inspect. index: u8, /// Properties being iterated. properties: Property, } impl Iterator for Iter { type Item = usize; fn next(&mut self) -> Option { while self.index < 8 { let index = self.index; self.index += 1; if self.properties.contains(Property(1 << index)) { return Some(index as usize); } } None } } /// Represents a set of styling options. #[repr(C, packed)] #[derive(Default, Debug, Eq, Ord, PartialOrd, Copy, Clone)] pub struct Style { pub(crate) foreground: Color, pub(crate) background: Color, pub(crate) properties: Property, pub(crate) wrap: bool, } impl PartialEq for Style { fn eq(&self, other: &Style) -> bool { self.foreground == other.foreground && self.background == other.background && self.properties == other.properties } } impl Hash for Style { fn hash(&self, state: &mut H) { self.foreground.hash(state); self.background.hash(state); self.properties.hash(state); } } impl Style { /// Default style with the foreground set to `color` and no other set /// properties. pub const fn new(color: Color) -> Style { Self { foreground: color, background: Color::Unset, properties: Property::new(), wrap: false, } } /// Sets the foreground to `color`. pub const fn fg(mut self, color: Color) -> Style { self.foreground = color; self } /// Sets the background to `color`. pub const fn bg(mut self, color: Color) -> Style { self.background = color; self } /// Merge styles with other. This is an additive process, so colors will only /// be changed if they aren't set on the receiver object. pub fn merge(mut self, other: Style) -> Style { if self.foreground == Color::Unset { self.foreground = other.foreground; } if self.background == Color::Unset { self.background = other.background; } self.properties.set(other.properties); self } /// Sets `self` to be wrapping. /// /// A wrapping `Style` 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. pub const fn wrap(mut self) -> Style { self.wrap = true; self } /// Adds bold styling. pub fn bold(mut self) -> Self { self.properties.set(Property::BOLD); self } /// Adds dim styling. pub fn dim(mut self) -> Self { self.properties.set(Property::DIM); self } /// Adds italic styling. pub fn italic(mut self) -> Self { self.properties.set(Property::ITALIC); self } /// Adds underline styling. pub fn underline(mut self) -> Self { self.properties.set(Property::UNDERLINE); self } /// Adds inverse-video styling. pub fn invert(mut self) -> Self { self.properties.set(Property::INVERT); self } /// Adds strikethrough styling. pub fn strikethrough(mut self) -> Self { self.properties.set(Property::STRIKETHROUGH); self } /// Constructs a new `Paint` structure that encapsulates `item` with the /// style set to `self`. pub fn paint(self, item: T) -> Paint { Paint::new(item).with_style(self) } /// Returns the foreground color of `self`. pub const fn fg_color(&self) -> Color { self.foreground } /// Returns the foreground color of `self`. pub const fn bg_color(&self) -> Color { self.background } /// Returns `true` if `self` is wrapping. pub const fn is_wrapping(&self) -> bool { self.wrap } /// Returns whether the style has no visible properties. #[inline(always)] fn is_plain(&self) -> bool { self == &Style::default() } /// Writes the ANSI code prefix for the currently set styles. /// /// This method is intended to be used inside of [`fmt::Display`] and /// [`fmt::Debug`] implementations for custom or specialized use-cases. Most /// users should use [`Paint`] for all painting needs. /// /// This method writes the ANSI code prefix for non-plain styles. Most /// callers should use [`Paint::styled`] instead. pub fn fmt_prefix(&self, f: &mut dyn fmt::Write) -> fmt::Result { // A user may just want a code-free string when no styles are applied. if self.is_plain() { return Ok(()); } let mut splice = false; write!(f, "\x1B[")?; for i in self.properties.iter() { let k = if i >= 5 { i + 2 } else { i + 1 }; write_spliced(&mut splice, f, k)?; } if self.background != Color::Unset { write_spliced(&mut splice, f, "4")?; self.background.ansi_fmt(f)?; } if self.foreground != Color::Unset { write_spliced(&mut splice, f, "3")?; self.foreground.ansi_fmt(f)?; } // All the codes end with an `m`. write!(f, "m") } /// Writes the ANSI code suffix for the currently set styles. /// /// This method is intended to be used inside of [`fmt::Display`] and /// [`fmt::Debug`] implementations for custom or specialized use-cases. Most /// users should use [`Paint`] for all painting needs. /// /// This method writes the ANSI code suffix for non-plain styles. Most /// callers should use [`Paint::styled`] instead. pub fn fmt_suffix(&self, f: &mut dyn fmt::Write) -> fmt::Result { if self.is_plain() { return Ok(()); } write!(f, "\x1B[0m") } } /// Writes an ANSI parameter, inserting a separator after the first one. #[inline] fn write_spliced(c: &mut bool, f: &mut dyn fmt::Write, t: T) -> fmt::Result { if *c { write!(f, ";{t}") } else { *c = true; write!(f, "{t}") } } #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use super::*; fn prefix(style: Style) -> String { let mut out = String::new(); style.fmt_prefix(&mut out).unwrap(); out } fn suffix(style: Style) -> String { let mut out = String::new(); style.fmt_suffix(&mut out).unwrap(); out } #[test] fn property_iteration_yields_enabled_indexes() { let properties = Property::BOLD | Property::UNDERLINE | Property::STRIKETHROUGH; assert_eq!(properties.iter().collect::>(), vec![0, 3, 7]); } #[test] fn style_merge_keeps_receiver_colors_and_adds_properties() { let style = Style::new(Color::Red) .bg(Color::Blue) .bold() .merge(Style::new(Color::Green).bg(Color::Yellow).underline()); assert_eq!(style.fg_color(), Color::Red); assert_eq!(style.bg_color(), Color::Blue); assert!(style.properties.contains(Property::BOLD)); assert!(style.properties.contains(Property::UNDERLINE)); } #[test] fn plain_style_writes_no_ansi_codes() { let style = Style::default(); assert_eq!(prefix(style), ""); assert_eq!(suffix(style), ""); } #[test] fn style_prefix_splices_properties_background_and_foreground() { let style = Style::new(Color::Fixed(42)) .bg(Color::RGB(1, 2, 3)) .bold() .italic() .underline() .invert() .strikethrough(); assert_eq!(prefix(style), "\x1B[1;3;4;7;9;48;2;1;2;3;38;5;42m"); assert_eq!(suffix(style), "\x1B[0m"); } #[test] fn wrapping_flag_is_recorded() { assert!(Style::new(Color::Red).wrap().is_wrapping()); } }