crates/tui-core/src/ansi/style.rs 9.7 KiB raw
1
//! ANSI style properties.
2
//!
3
//! `Style` records foreground/background colors and text attributes such as
4
//! bold or italic. It is a value type shared by cells, labels, borders, and
5
//! painted display wrappers.
6
7
use std::fmt::{self, Display};
8
use std::hash::{Hash, Hasher};
9
use std::ops::BitOr;
10
11
use super::{Color, Paint};
12
13
/// Bitset of ANSI text style properties.
14
#[derive(Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)]
15
pub struct Property(u8);
16
17
impl Property {
18
    /// Bold text property.
19
    pub const BOLD: Self = Property(1 << 0);
20
    /// Dim text property.
21
    pub const DIM: Self = Property(1 << 1);
22
    /// Italic text property.
23
    pub const ITALIC: Self = Property(1 << 2);
24
    /// Underlined text property.
25
    pub const UNDERLINE: Self = Property(1 << 3);
26
    /// Blinking text property.
27
    pub const BLINK: Self = Property(1 << 4);
28
    /// Inverse-video text property.
29
    pub const INVERT: Self = Property(1 << 5);
30
    /// Hidden text property.
31
    pub const HIDDEN: Self = Property(1 << 6);
32
    /// Strikethrough text property.
33
    pub const STRIKETHROUGH: Self = Property(1 << 7);
34
35
    /// Returns an empty property set.
36
    pub const fn new() -> Self {
37
        Property(0)
38
    }
39
40
    /// Returns whether all bits in `other` are set.
41
    pub const fn contains(self, other: Property) -> bool {
42
        (other.0 & self.0) == other.0
43
    }
44
45
    /// Adds all bits from `other`.
46
    #[inline(always)]
47
    pub fn set(&mut self, other: Property) {
48
        self.0 |= other.0;
49
    }
50
51
    /// Iterates over enabled ANSI property indexes.
52
    #[inline(always)]
53
    pub fn iter(self) -> Iter {
54
        Iter {
55
            index: 0,
56
            properties: self,
57
        }
58
    }
59
}
60
61
impl BitOr for Property {
62
    type Output = Self;
63
64
    #[inline(always)]
65
    fn bitor(self, rhs: Self) -> Self {
66
        Property(self.0 | rhs.0)
67
    }
68
}
69
70
/// Iterator over enabled ANSI property indexes.
71
pub struct Iter {
72
    /// Next bit index to inspect.
73
    index: u8,
74
    /// Properties being iterated.
75
    properties: Property,
76
}
77
78
impl Iterator for Iter {
79
    type Item = usize;
80
81
    fn next(&mut self) -> Option<Self::Item> {
82
        while self.index < 8 {
83
            let index = self.index;
84
            self.index += 1;
85
86
            if self.properties.contains(Property(1 << index)) {
87
                return Some(index as usize);
88
            }
89
        }
90
        None
91
    }
92
}
93
94
/// Represents a set of styling options.
95
#[repr(C, packed)]
96
#[derive(Default, Debug, Eq, Ord, PartialOrd, Copy, Clone)]
97
pub struct Style {
98
    pub(crate) foreground: Color,
99
    pub(crate) background: Color,
100
    pub(crate) properties: Property,
101
    pub(crate) wrap: bool,
102
}
103
104
impl PartialEq for Style {
105
    fn eq(&self, other: &Style) -> bool {
106
        self.foreground == other.foreground
107
            && self.background == other.background
108
            && self.properties == other.properties
109
    }
110
}
111
112
impl Hash for Style {
113
    fn hash<H: Hasher>(&self, state: &mut H) {
114
        self.foreground.hash(state);
115
        self.background.hash(state);
116
        self.properties.hash(state);
117
    }
118
}
119
120
impl Style {
121
    /// Default style with the foreground set to `color` and no other set
122
    /// properties.
123
    pub const fn new(color: Color) -> Style {
124
        Self {
125
            foreground: color,
126
            background: Color::Unset,
127
            properties: Property::new(),
128
            wrap: false,
129
        }
130
    }
131
132
    /// Sets the foreground to `color`.
133
    pub const fn fg(mut self, color: Color) -> Style {
134
        self.foreground = color;
135
        self
136
    }
137
138
    /// Sets the background to `color`.
139
    pub const fn bg(mut self, color: Color) -> Style {
140
        self.background = color;
141
        self
142
    }
143
144
    /// Merge styles with other. This is an additive process, so colors will only
145
    /// be changed if they aren't set on the receiver object.
146
    pub fn merge(mut self, other: Style) -> Style {
147
        if self.foreground == Color::Unset {
148
            self.foreground = other.foreground;
149
        }
150
        if self.background == Color::Unset {
151
            self.background = other.background;
152
        }
153
        self.properties.set(other.properties);
154
        self
155
    }
156
157
    /// Sets `self` to be wrapping.
158
    ///
159
    /// A wrapping `Style` converts all color resets written out by the internal
160
    /// value to the styling of itself. This allows for seamless color wrapping
161
    /// of other colored text.
162
    pub const fn wrap(mut self) -> Style {
163
        self.wrap = true;
164
        self
165
    }
166
167
    /// Adds bold styling.
168
    pub fn bold(mut self) -> Self {
169
        self.properties.set(Property::BOLD);
170
        self
171
    }
172
173
    /// Adds dim styling.
174
    pub fn dim(mut self) -> Self {
175
        self.properties.set(Property::DIM);
176
        self
177
    }
178
179
    /// Adds italic styling.
180
    pub fn italic(mut self) -> Self {
181
        self.properties.set(Property::ITALIC);
182
        self
183
    }
184
185
    /// Adds underline styling.
186
    pub fn underline(mut self) -> Self {
187
        self.properties.set(Property::UNDERLINE);
188
        self
189
    }
190
191
    /// Adds inverse-video styling.
192
    pub fn invert(mut self) -> Self {
193
        self.properties.set(Property::INVERT);
194
        self
195
    }
196
197
    /// Adds strikethrough styling.
198
    pub fn strikethrough(mut self) -> Self {
199
        self.properties.set(Property::STRIKETHROUGH);
200
        self
201
    }
202
203
    /// Constructs a new `Paint` structure that encapsulates `item` with the
204
    /// style set to `self`.
205
    pub fn paint<T>(self, item: T) -> Paint<T> {
206
        Paint::new(item).with_style(self)
207
    }
208
209
    /// Returns the foreground color of `self`.
210
    pub const fn fg_color(&self) -> Color {
211
        self.foreground
212
    }
213
214
    /// Returns the foreground color of `self`.
215
    pub const fn bg_color(&self) -> Color {
216
        self.background
217
    }
218
219
    /// Returns `true` if `self` is wrapping.
220
    pub const fn is_wrapping(&self) -> bool {
221
        self.wrap
222
    }
223
224
    /// Returns whether the style has no visible properties.
225
    #[inline(always)]
226
    fn is_plain(&self) -> bool {
227
        self == &Style::default()
228
    }
229
230
    /// Writes the ANSI code prefix for the currently set styles.
231
    ///
232
    /// This method is intended to be used inside of [`fmt::Display`] and
233
    /// [`fmt::Debug`] implementations for custom or specialized use-cases. Most
234
    /// users should use [`Paint`] for all painting needs.
235
    ///
236
    /// This method writes the ANSI code prefix for non-plain styles. Most
237
    /// callers should use [`Paint::styled`] instead.
238
    pub fn fmt_prefix(&self, f: &mut dyn fmt::Write) -> fmt::Result {
239
        // A user may just want a code-free string when no styles are applied.
240
        if self.is_plain() {
241
            return Ok(());
242
        }
243
        let mut splice = false;
244
        write!(f, "\x1B[")?;
245
246
        for i in self.properties.iter() {
247
            let k = if i >= 5 { i + 2 } else { i + 1 };
248
            write_spliced(&mut splice, f, k)?;
249
        }
250
        if self.background != Color::Unset {
251
            write_spliced(&mut splice, f, "4")?;
252
            self.background.ansi_fmt(f)?;
253
        }
254
        if self.foreground != Color::Unset {
255
            write_spliced(&mut splice, f, "3")?;
256
            self.foreground.ansi_fmt(f)?;
257
        }
258
        // All the codes end with an `m`.
259
        write!(f, "m")
260
    }
261
262
    /// Writes the ANSI code suffix for the currently set styles.
263
    ///
264
    /// This method is intended to be used inside of [`fmt::Display`] and
265
    /// [`fmt::Debug`] implementations for custom or specialized use-cases. Most
266
    /// users should use [`Paint`] for all painting needs.
267
    ///
268
    /// This method writes the ANSI code suffix for non-plain styles. Most
269
    /// callers should use [`Paint::styled`] instead.
270
    pub fn fmt_suffix(&self, f: &mut dyn fmt::Write) -> fmt::Result {
271
        if self.is_plain() {
272
            return Ok(());
273
        }
274
        write!(f, "\x1B[0m")
275
    }
276
}
277
278
/// Writes an ANSI parameter, inserting a separator after the first one.
279
#[inline]
280
fn write_spliced<T: Display>(c: &mut bool, f: &mut dyn fmt::Write, t: T) -> fmt::Result {
281
    if *c {
282
        write!(f, ";{t}")
283
    } else {
284
        *c = true;
285
        write!(f, "{t}")
286
    }
287
}
288
289
#[cfg(test)]
290
#[allow(clippy::unwrap_used)]
291
mod tests {
292
    use super::*;
293
294
    fn prefix(style: Style) -> String {
295
        let mut out = String::new();
296
        style.fmt_prefix(&mut out).unwrap();
297
        out
298
    }
299
300
    fn suffix(style: Style) -> String {
301
        let mut out = String::new();
302
        style.fmt_suffix(&mut out).unwrap();
303
        out
304
    }
305
306
    #[test]
307
    fn property_iteration_yields_enabled_indexes() {
308
        let properties = Property::BOLD | Property::UNDERLINE | Property::STRIKETHROUGH;
309
310
        assert_eq!(properties.iter().collect::<Vec<_>>(), vec![0, 3, 7]);
311
    }
312
313
    #[test]
314
    fn style_merge_keeps_receiver_colors_and_adds_properties() {
315
        let style = Style::new(Color::Red)
316
            .bg(Color::Blue)
317
            .bold()
318
            .merge(Style::new(Color::Green).bg(Color::Yellow).underline());
319
320
        assert_eq!(style.fg_color(), Color::Red);
321
        assert_eq!(style.bg_color(), Color::Blue);
322
        assert!(style.properties.contains(Property::BOLD));
323
        assert!(style.properties.contains(Property::UNDERLINE));
324
    }
325
326
    #[test]
327
    fn plain_style_writes_no_ansi_codes() {
328
        let style = Style::default();
329
330
        assert_eq!(prefix(style), "");
331
        assert_eq!(suffix(style), "");
332
    }
333
334
    #[test]
335
    fn style_prefix_splices_properties_background_and_foreground() {
336
        let style = Style::new(Color::Fixed(42))
337
            .bg(Color::RGB(1, 2, 3))
338
            .bold()
339
            .italic()
340
            .underline()
341
            .invert()
342
            .strikethrough();
343
344
        assert_eq!(prefix(style), "\x1B[1;3;4;7;9;48;2;1;2;3;38;5;42m");
345
        assert_eq!(suffix(style), "\x1B[0m");
346
    }
347
348
    #[test]
349
    fn wrapping_flag_is_recorded() {
350
        assert!(Style::new(Color::Red).wrap().is_wrapping());
351
    }
352
}