crates/tui-core/src/ansi/paint.rs 11.4 KiB raw
1
//! Styled display wrappers.
2
//!
3
//! `Paint` pairs an arbitrary display value with a [`Style`](crate::Style).
4
//! Its display adapters can render either plain text or ANSI-styled text,
5
//! letting the same value be measured, buffered, or printed with explicit
6
//! formatting mode.
7
8
use std::fmt;
9
10
use super::color::Color;
11
use super::style::{Property, Style};
12
13
/// Paint formatting mode.
14
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
15
pub enum PaintMode {
16
    /// Write plain text with no ANSI escapes.
17
    #[default]
18
    Plain,
19
    /// Write ANSI escapes for the stored style.
20
    Styled,
21
}
22
23
/// A paint object paired with an explicit formatting mode.
24
#[derive(Debug, Clone, Copy)]
25
pub struct Painted<'a, T> {
26
    paint: &'a Paint<T>,
27
    mode: PaintMode,
28
}
29
30
/// A structure encapsulating an item and styling.
31
#[derive(Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)]
32
pub struct Paint<T> {
33
    /// Wrapped display item.
34
    pub item: T,
35
    /// Style applied when the item is displayed.
36
    pub style: Style,
37
}
38
39
impl<T: AsRef<str>> Paint<T> {
40
    /// Return plain content.
41
    pub fn content(&self) -> &str {
42
        self.item.as_ref()
43
    }
44
}
45
46
impl<T> From<T> for Paint<T> {
47
    fn from(value: T) -> Self {
48
        Self::new(value)
49
    }
50
}
51
52
impl From<&str> for Paint<String> {
53
    fn from(item: &str) -> Self {
54
        Self::new(item.to_string())
55
    }
56
}
57
58
impl From<Paint<&str>> for Paint<String> {
59
    fn from(paint: Paint<&str>) -> Self {
60
        Self {
61
            item: paint.item.to_owned(),
62
            style: paint.style,
63
        }
64
    }
65
}
66
67
impl From<Paint<String>> for String {
68
    fn from(value: Paint<String>) -> Self {
69
        value.item
70
    }
71
}
72
73
impl<T> Paint<T> {
74
    /// Constructs a new `Paint` structure encapsulating `item` with no set
75
    /// styling.
76
    #[inline]
77
    pub const fn new(item: T) -> Paint<T> {
78
        Paint {
79
            item,
80
            style: Style {
81
                foreground: Color::Unset,
82
                background: Color::Unset,
83
                properties: Property::new(),
84
                wrap: false,
85
            },
86
        }
87
    }
88
89
    /// Constructs a new _wrapping_ `Paint` structure encapsulating `item` with
90
    /// default styling.
91
    ///
92
    /// A wrapping `Paint` converts all color resets written out by the internal
93
    /// value to the styling of itself. This allows for seamless color wrapping
94
    /// of other colored text.
95
    ///
96
    /// # Performance
97
    ///
98
    /// In order to wrap an internal value, the internal value must first be
99
    /// written out to a local buffer and examined. As a result, displaying a
100
    /// wrapped value is likely to result in a heap allocation and copy.
101
    #[inline]
102
    pub const fn wrapping(item: T) -> Paint<T> {
103
        Paint::new(item).wrap()
104
    }
105
106
    /// Constructs a new `Paint` structure encapsulating `item` with the
107
    /// foreground color set to the RGB color `r`, `g`, `b`.
108
    #[inline]
109
    pub const fn rgb(r: u8, g: u8, b: u8, item: T) -> Paint<T> {
110
        Paint::new(item).fg(Color::RGB(r, g, b))
111
    }
112
113
    /// Constructs a new `Paint` structure encapsulating `item` with the
114
    /// foreground color set to the fixed 8-bit color `color`.
115
    #[inline]
116
    pub const fn fixed(color: u8, item: T) -> Paint<T> {
117
        Paint::new(item).fg(Color::Fixed(color))
118
    }
119
120
    /// Constructs red foreground text.
121
    pub const fn red(item: T) -> Paint<T> {
122
        Paint::new(item).fg(Color::Red)
123
    }
124
125
    /// Constructs black foreground text.
126
    pub const fn black(item: T) -> Paint<T> {
127
        Paint::new(item).fg(Color::Black)
128
    }
129
130
    /// Constructs yellow foreground text.
131
    pub const fn yellow(item: T) -> Paint<T> {
132
        Paint::new(item).fg(Color::Yellow)
133
    }
134
135
    /// Constructs green foreground text.
136
    pub const fn green(item: T) -> Paint<T> {
137
        Paint::new(item).fg(Color::Green)
138
    }
139
140
    /// Constructs cyan foreground text.
141
    pub const fn cyan(item: T) -> Paint<T> {
142
        Paint::new(item).fg(Color::Cyan)
143
    }
144
145
    /// Constructs blue foreground text.
146
    pub const fn blue(item: T) -> Paint<T> {
147
        Paint::new(item).fg(Color::Blue)
148
    }
149
150
    /// Constructs magenta foreground text.
151
    pub const fn magenta(item: T) -> Paint<T> {
152
        Paint::new(item).fg(Color::Magenta)
153
    }
154
155
    /// Constructs white foreground text.
156
    pub const fn white(item: T) -> Paint<T> {
157
        Paint::new(item).fg(Color::White)
158
    }
159
160
    /// Retrieves the style currently set on `self`.
161
    #[inline]
162
    pub const fn style(&self) -> Style {
163
        self.style
164
    }
165
166
    /// Retrieves a borrow to the inner item.
167
    #[inline]
168
    pub const fn inner(&self) -> &T {
169
        &self.item
170
    }
171
172
    /// Sets the style of `self` to `style`.
173
    #[inline]
174
    pub fn with_style(mut self, style: Style) -> Paint<T> {
175
        self.style = style;
176
        self
177
    }
178
179
    /// Makes `self` a _wrapping_ `Paint`.
180
    ///
181
    /// A wrapping `Paint` converts all color resets written out by the internal
182
    /// value to the styling of itself. This allows for seamless color wrapping
183
    /// of other colored text.
184
    ///
185
    /// # Performance
186
    ///
187
    /// In order to wrap an internal value, the internal value must first be
188
    /// written out to a local buffer and examined. As a result, displaying a
189
    /// wrapped value is likely to result in a heap allocation and copy.
190
    #[inline]
191
    pub const fn wrap(mut self) -> Paint<T> {
192
        self.style.wrap = true;
193
        self
194
    }
195
196
    /// Sets the foreground to `color`.
197
    #[inline]
198
    pub const fn fg(mut self, color: Color) -> Paint<T> {
199
        self.style.foreground = color;
200
        self
201
    }
202
203
    /// Sets the background to `color`.
204
    #[inline]
205
    pub const fn bg(mut self, color: Color) -> Paint<T> {
206
        self.style.background = color;
207
        self
208
    }
209
210
    /// Adds bold styling.
211
    pub fn bold(mut self) -> Self {
212
        self.style.properties.set(Property::BOLD);
213
        self
214
    }
215
216
    /// Adds dim styling.
217
    pub fn dim(mut self) -> Self {
218
        self.style.properties.set(Property::DIM);
219
        self
220
    }
221
222
    /// Adds italic styling.
223
    pub fn italic(mut self) -> Self {
224
        self.style.properties.set(Property::ITALIC);
225
        self
226
    }
227
228
    /// Adds underline styling.
229
    pub fn underline(mut self) -> Self {
230
        self.style.properties.set(Property::UNDERLINE);
231
        self
232
    }
233
234
    /// Adds inverse-video styling.
235
    pub fn invert(mut self) -> Self {
236
        self.style.properties.set(Property::INVERT);
237
        self
238
    }
239
240
    /// Adds strikethrough styling.
241
    pub fn strikethrough(mut self) -> Self {
242
        self.style.properties.set(Property::STRIKETHROUGH);
243
        self
244
    }
245
246
    /// Adds blink styling.
247
    pub fn blink(mut self) -> Self {
248
        self.style.properties.set(Property::BLINK);
249
        self
250
    }
251
252
    /// Adds hidden styling.
253
    pub fn hidden(mut self) -> Self {
254
        self.style.properties.set(Property::HIDDEN);
255
        self
256
    }
257
258
    /// Return a display adapter using `mode`.
259
    pub const fn rendered(&self, mode: PaintMode) -> Painted<'_, T> {
260
        Painted { paint: self, mode }
261
    }
262
263
    /// Return a display adapter that writes styled text.
264
    pub const fn styled(&self) -> Painted<'_, T> {
265
        self.rendered(PaintMode::Styled)
266
    }
267
268
    /// Return a display adapter that writes plain text.
269
    pub const fn plain(&self) -> Painted<'_, T> {
270
        self.rendered(PaintMode::Plain)
271
    }
272
}
273
274
impl<T: fmt::Display> fmt::Display for Paint<T> {
275
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
276
        fmt::Display::fmt(&self.item, f)
277
    }
278
}
279
280
impl<T: fmt::Display> fmt::Display for Painted<'_, T> {
281
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
282
        match self.mode {
283
            PaintMode::Plain => fmt::Display::fmt(&self.paint.item, f),
284
            PaintMode::Styled => self.paint.fmt_ansi(f),
285
        }
286
    }
287
}
288
289
impl<T: fmt::Display> Paint<T> {
290
    /// Write the item with ANSI styling.
291
    pub fn fmt_ansi(&self, f: &mut dyn fmt::Write) -> fmt::Result {
292
        if self.style.wrap {
293
            let mut prefix = String::new();
294
            prefix.push_str("\x1B[0m");
295
            self.style.fmt_prefix(&mut prefix)?;
296
            self.style.fmt_prefix(f)?;
297
298
            let item = format!("{}", &self.item).replace("\x1B[0m", &prefix);
299
            write!(f, "{item}")?;
300
            self.style.fmt_suffix(f)
301
        } else {
302
            self.style.fmt_prefix(f)?;
303
            write!(f, "{}", &self.item)?;
304
            self.style.fmt_suffix(f)
305
        }
306
    }
307
}
308
309
impl Paint<()> {
310
    /// Check 24-bit RGB color support.
311
    pub fn truecolor() -> bool {
312
        std::env::var("COLORTERM").is_ok_and(|term| term.eq_ignore_ascii_case("truecolor"))
313
    }
314
}
315
316
/// An object filled with a background color.
317
#[derive(Debug, Clone)]
318
pub struct Filled<T> {
319
    /// Wrapped display item.
320
    pub item: T,
321
    /// Background fill color.
322
    pub color: Color,
323
}
324
325
impl<T: fmt::Display> fmt::Display for Filled<T> {
326
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327
        write!(f, "{}", Paint::wrapping(&self.item).bg(self.color))
328
    }
329
}
330
331
/// Shorthand for [`Paint::new`].
332
pub fn paint<T>(item: T) -> Paint<T> {
333
    Paint::new(item)
334
}
335
336
#[cfg(test)]
337
mod tests {
338
    use super::*;
339
340
    #[test]
341
    fn paint_constructors_set_expected_colors() {
342
        assert_eq!(Paint::red("x").style().fg_color(), Color::Red);
343
        assert_eq!(Paint::black("x").style().fg_color(), Color::Black);
344
        assert_eq!(Paint::yellow("x").style().fg_color(), Color::Yellow);
345
        assert_eq!(Paint::green("x").style().fg_color(), Color::Green);
346
        assert_eq!(Paint::cyan("x").style().fg_color(), Color::Cyan);
347
        assert_eq!(Paint::blue("x").style().fg_color(), Color::Blue);
348
        assert_eq!(Paint::magenta("x").style().fg_color(), Color::Magenta);
349
        assert_eq!(Paint::white("x").style().fg_color(), Color::White);
350
        assert_eq!(Paint::fixed(42, "x").style().fg_color(), Color::Fixed(42));
351
        assert_eq!(
352
            Paint::rgb(1, 2, 3, "x").style().fg_color(),
353
            Color::RGB(1, 2, 3)
354
        );
355
    }
356
357
    #[test]
358
    fn paint_records_background_and_wrapping() {
359
        let paint = Paint::wrapping("x").bg(Color::Blue);
360
361
        assert_eq!(paint.style().bg_color(), Color::Blue);
362
        assert!(paint.style().is_wrapping());
363
    }
364
365
    #[test]
366
    fn paint_from_conversions_preserve_content_and_style() {
367
        let borrowed = Paint::red("content");
368
        let owned = Paint::<String>::from(borrowed);
369
370
        assert_eq!(owned.content(), "content");
371
        assert_eq!(owned.style().fg_color(), Color::Red);
372
        assert_eq!(String::from(owned), "content");
373
        assert_eq!(Paint::<String>::from("other").content(), "other");
374
    }
375
376
    #[test]
377
    fn display_is_plain_and_styled_adapter_is_explicit() {
378
        let paint = Paint::red("content");
379
380
        assert_eq!(paint.to_string(), "content");
381
        assert_eq!(paint.plain().to_string(), "content");
382
        assert_eq!(paint.styled().to_string(), "\x1B[31mcontent\x1B[0m");
383
        assert_eq!(
384
            paint.rendered(PaintMode::Styled).to_string(),
385
            "\x1B[31mcontent\x1B[0m"
386
        );
387
    }
388
389
    #[test]
390
    fn styled_adapter_reapplies_wrapping_style_after_reset() {
391
        let paint = Paint::wrapping("a\x1B[0mb").fg(Color::Red);
392
393
        assert_eq!(
394
            paint.styled().to_string(),
395
            "\x1B[31ma\x1B[0m\x1B[31mb\x1B[0m"
396
        );
397
    }
398
399
    #[test]
400
    fn filled_records_item_and_background_color() {
401
        let filled = Filled {
402
            item: "x",
403
            color: Color::Red,
404
        };
405
406
        assert_eq!(filled.item, "x");
407
        assert_eq!(filled.color, Color::Red);
408
    }
409
}