1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
//! This module contains the logic to style some content.

use std::{
    fmt::{self, Display, Formatter},
    result,
};

use crate::{
    queue,
    style::{
        Attribute, Color, Colorize, ContentStyle, ResetColor, SetAttributes, SetBackgroundColor,
        SetForegroundColor, Styler,
    },
};

/// The style with the content to be styled.
///
/// # Examples
///
/// ```rust
/// use crossterm::style::{style, Color, Attribute};
///
/// let styled = style("Hello there")
///     .with(Color::Yellow)
///     .on(Color::Blue)
///     .attribute(Attribute::Bold);
///
/// println!("{}", styled);
/// ```
#[derive(Clone, Debug)]
pub struct StyledContent<D: Display> {
    /// The style (colors, content attributes).
    style: ContentStyle,
    /// A content to apply the style on.
    content: D,
}

impl<D: Display> StyledContent<D> {
    /// Creates a new `StyledContent`.
    #[inline]
    pub fn new(style: ContentStyle, content: D) -> StyledContent<D> {
        StyledContent { style, content }
    }

    /// Sets the foreground color.
    #[inline]
    pub fn with(self, foreground_color: Color) -> StyledContent<D> {
        Self {
            style: self.style.foreground(foreground_color),
            ..self
        }
    }

    /// Sets the background color.
    #[inline]
    pub fn on(self, background_color: Color) -> StyledContent<D> {
        Self {
            style: self.style.background(background_color),
            ..self
        }
    }

    /// Adds the attribute.
    ///
    /// You can add more attributes by calling this method multiple times.
    #[inline]
    pub fn attribute(self, attr: Attribute) -> StyledContent<D> {
        Self {
            style: self.style.attribute(attr),
            ..self
        }
    }

    /// Returns the content.
    #[inline]
    pub fn content(&self) -> &D {
        &self.content
    }

    /// Returns the style.
    #[inline]
    pub fn style(&self) -> &ContentStyle {
        &self.style
    }

    /// Returns a mutable reference to the style, so that it can be futher
    /// manipulated
    #[inline]
    pub fn style_mut(&mut self) -> &mut ContentStyle {
        &mut self.style
    }
}

impl<D: Display> Display for StyledContent<D> {
    fn fmt(&self, f: &mut Formatter<'_>) -> result::Result<(), fmt::Error> {
        let mut reset = false;

        if let Some(bg) = self.style.background_color {
            queue!(f, SetBackgroundColor(bg)).map_err(|_| fmt::Error)?;
            reset = true;
        }
        if let Some(fg) = self.style.foreground_color {
            queue!(f, SetForegroundColor(fg)).map_err(|_| fmt::Error)?;
            reset = true;
        }

        if !self.style.attributes.is_empty() {
            queue!(f, SetAttributes(self.style.attributes)).map_err(|_| fmt::Error)?;
            reset = true;
        }

        self.content.fmt(f)?;

        // TODO: There are specific command sequences for "reset forground
        // color (39m)" and "reset background color (49m)"; consider using
        // these.
        if reset {
            queue!(f, ResetColor).map_err(|_| fmt::Error)?;
        }

        Ok(())
    }
}

impl<D: Display + Clone> Colorize<D> for StyledContent<D> {
    // foreground colors
    def_color!(foreground_color: black => Color::Black);
    def_color!(foreground_color: dark_grey => Color::DarkGrey);
    def_color!(foreground_color: red => Color::Red);
    def_color!(foreground_color: dark_red => Color::DarkRed);
    def_color!(foreground_color: green => Color::Green);
    def_color!(foreground_color: dark_green => Color::DarkGreen);
    def_color!(foreground_color: yellow => Color::Yellow);
    def_color!(foreground_color: dark_yellow => Color::DarkYellow);
    def_color!(foreground_color: blue => Color::Blue);
    def_color!(foreground_color: dark_blue => Color::DarkBlue);
    def_color!(foreground_color: magenta => Color::Magenta);
    def_color!(foreground_color: dark_magenta => Color::DarkMagenta);
    def_color!(foreground_color: cyan => Color::Cyan);
    def_color!(foreground_color: dark_cyan => Color::DarkCyan);
    def_color!(foreground_color: white => Color::White);
    def_color!(foreground_color: grey => Color::Grey);

    // background colors
    def_color!(background_color: on_black => Color::Black);
    def_color!(background_color: on_dark_grey => Color::DarkGrey);
    def_color!(background_color: on_red => Color::Red);
    def_color!(background_color: on_dark_red => Color::DarkRed);
    def_color!(background_color: on_green => Color::Green);
    def_color!(background_color: on_dark_green => Color::DarkGreen);
    def_color!(background_color: on_yellow => Color::Yellow);
    def_color!(background_color: on_dark_yellow => Color::DarkYellow);
    def_color!(background_color: on_blue => Color::Blue);
    def_color!(background_color: on_dark_blue => Color::DarkBlue);
    def_color!(background_color: on_magenta => Color::Magenta);
    def_color!(background_color: on_dark_magenta => Color::DarkMagenta);
    def_color!(background_color: on_cyan => Color::Cyan);
    def_color!(background_color: on_dark_cyan => Color::DarkCyan);
    def_color!(background_color: on_white => Color::White);
    def_color!(background_color: on_grey => Color::Grey);
}

impl<D: Display + Clone> Styler<D> for StyledContent<D> {
    def_attr!(reset => Attribute::Reset);
    def_attr!(bold => Attribute::Bold);
    def_attr!(underlined => Attribute::Underlined);
    def_attr!(reverse => Attribute::Reverse);
    def_attr!(dim => Attribute::Dim);
    def_attr!(italic => Attribute::Italic);
    def_attr!(negative => Attribute::Reverse);
    def_attr!(slow_blink => Attribute::SlowBlink);
    def_attr!(rapid_blink => Attribute::RapidBlink);
    def_attr!(hidden => Attribute::Hidden);
    def_attr!(crossed_out => Attribute::CrossedOut);
}

#[cfg(test)]
mod tests {
    use super::{Attribute, Color, ContentStyle};

    #[test]
    fn test_set_fg_bg_add_attr() {
        let style = ContentStyle::new()
            .foreground(Color::Blue)
            .background(Color::Red)
            .attribute(Attribute::Bold);

        let mut styled_content = style.apply("test");

        styled_content = styled_content
            .with(Color::Green)
            .on(Color::Magenta)
            .attribute(Attribute::NoItalic);

        assert_eq!(styled_content.style.foreground_color, Some(Color::Green));
        assert_eq!(styled_content.style.background_color, Some(Color::Magenta));
        assert!(styled_content.style.attributes.has(Attribute::Bold));
        assert!(styled_content.style.attributes.has(Attribute::NoItalic));
    }
}