console_display/
color.rs

1//! Provides abstractions over colors that are used in terminal context.
2
3// TODO: Check if this can be const
4/// Defines a color used to color text.
5pub trait Color
6where
7    Self: Sized,
8{
9    /// Blends the top with the bottom color.
10    /// In the case of opaque colors this simply returns the top color.
11    /// If the top color is completely transparent it returns the bottom color.
12    /// For a translucent top color this returns a mix of both colors weighted by their opacity.
13    ///
14    /// # Examples
15    ///
16    /// ```
17    /// use console_display::color::{
18    ///     Color,
19    ///     RGBColor,
20    /// };
21    /// use rand::{
22    ///     Rng,
23    ///     thread_rng,
24    /// };
25    ///
26    /// let top = RGBColor {
27    ///     r: thread_rng().gen_range(0..=255),
28    ///     g: thread_rng().gen_range(0..=255),
29    ///     b: thread_rng().gen_range(0..=255),
30    /// };
31    /// let bottom = RGBColor {
32    ///     r: thread_rng().gen_range(0..=255),
33    ///     g: thread_rng().gen_range(0..=255),
34    ///     b: thread_rng().gen_range(0..=255),
35    /// };
36    ///
37    /// // Opaque top color is returned.
38    /// assert_eq!(top, RGBColor::blend(&top, &bottom));
39    /// ```
40    #[must_use]
41    fn blend(color_top: &Self, color_bottom: &Self) -> Self;
42
43    /// Colors a text with a foreground and background color.
44    ///
45    /// # Examples
46    ///
47    /// ```
48    /// use console_display::color::{
49    ///     Color,
50    ///     RGBColor,
51    /// };
52    ///
53    /// let msg =
54    ///     RGBColor::color("test", &RGBColor::RED, &RGBColor::BLACK);
55    ///
56    /// // msg contains escape sequences containing color information.
57    /// assert!(msg.chars().count() > 4);
58    /// ```
59    #[must_use]
60    fn color(
61        text: &str,
62        foreground_color: &Self,
63        background_color: &Self,
64    ) -> String;
65
66    /// Calculates the relative distance between two colors.
67    /// For smaller distances the returned value is smaller.
68    /// There are no guarantees for the exact return value, so this has only meaning in comparisons.
69    ///
70    /// # Examples
71    ///
72    /// ```
73    /// use console_display::color::{
74    ///     Color,
75    ///     RGBColor,
76    ///     TerminalColor,
77    /// };
78    ///
79    /// let dist_prio = TerminalColor::distance(
80    ///     &RGBColor::BLACK.into(),
81    ///     &TerminalColor::Default,
82    /// );
83    /// let dist_min = TerminalColor::distance(
84    ///     &RGBColor::BLACK.into(),
85    ///     &RGBColor::BLACK.into(),
86    /// );
87    /// let dist = TerminalColor::distance(
88    ///     &RGBColor::BLACK.into(),
89    ///     &RGBColor::RED.into(),
90    /// );
91    /// let dist_max = TerminalColor::distance(
92    ///     &RGBColor::BLACK.into(),
93    ///     &RGBColor::WHITE.into(),
94    /// );
95    ///
96    /// assert!(dist_prio <= dist_min);
97    /// assert!(dist_min < dist);
98    /// assert!(dist < dist_max);
99    /// ```
100    #[must_use]
101    fn distance(color1: &Self, color2: &Self) -> f32;
102
103    /// Mixes a list of colors into one.
104    ///
105    /// # Examples
106    ///
107    /// ```
108    /// use console_display::color::{
109    ///     Color,
110    ///     RGBColor,
111    ///     TerminalColor,
112    /// };
113    ///
114    /// let colors = [
115    ///     RGBColor::BLACK.into(),
116    ///     TerminalColor::Default,
117    ///     RGBColor::WHITE.into(),
118    /// ];
119    ///
120    /// let mix = TerminalColor::mix(&colors);
121    ///
122    /// assert_eq!(
123    ///     mix,
124    ///     // gray, Default is ignored in calculation
125    ///     RGBColor {
126    ///         r: 255 / 2,
127    ///         g: 255 / 2,
128    ///         b: 255 / 2
129    ///     }
130    ///     .into()
131    /// );
132    /// ```
133    #[must_use]
134    fn mix(colors: &[Self]) -> Self;
135
136    /// Groups a list of colors into two groups.
137    /// The groups are formed by finding the most distant colors.
138    /// All other colors are then put into a group with one of them depending on which distance is smaller.
139    /// Returns an array of the size of the input. True and false are used to map each color into one of two groups.
140    ///
141    /// # Examples
142    ///
143    /// ```
144    /// use console_display::color::{
145    ///     Color,
146    ///     RGBColor,
147    /// };
148    ///
149    /// let colors =
150    ///     [RGBColor::BLACK, RGBColor::WHITE, RGBColor::BLACK];
151    ///
152    /// let grouping = RGBColor::group(&colors);
153    ///
154    /// assert_ne!(grouping[0], grouping[1]);
155    /// assert_ne!(grouping[1], grouping[2]);
156    /// assert_eq!(grouping[0], grouping[2]);
157    /// ```
158    #[must_use]
159    fn group<const N: usize>(colors: &[Self; N]) -> [bool; N] {
160        let mut max = 0f32;
161        let mut col1 = 0;
162        let mut col2 = 0;
163        for i in 0..N {
164            for j in (i + 1)..N {
165                let dist = Self::distance(&colors[i], &colors[j]);
166                if dist > max {
167                    max = dist;
168                    col1 = i;
169                    col2 = j;
170                }
171            }
172        }
173        let mut groups = [false; N];
174        for i in 0..N {
175            if Self::distance(&colors[col1], &colors[i]) >
176                Self::distance(&colors[col2], &colors[i])
177            {
178                groups[i] = true;
179            }
180        }
181        groups
182    }
183}
184
185/// Defines a color used for foreground and background coloring of text.
186///
187/// `Default` - Uses the default color provided by the terminal for foreground or background respectively.\
188/// `ARGBColor` - Displays a color made of RGB components and an alpha/opacity channel.
189#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
190pub enum TerminalColor {
191    #[default]
192    Default,
193    ARGBColor(ARGBColor),
194}
195
196impl Color for TerminalColor {
197    fn blend(color_top: &Self, color_bottom: &Self) -> Self {
198        if let Self::ARGBColor(color_top) = color_top &&
199            let Self::ARGBColor(color_bottom) = color_bottom
200        {
201            return Self::ARGBColor(ARGBColor::blend(
202                color_top,
203                color_bottom,
204            ));
205        }
206        if let Self::ARGBColor(color) = color_top &&
207            color.opacity > 0
208        {
209            *color_top
210        }
211        else {
212            *color_bottom
213        }
214    }
215
216    fn color(
217        text: &str,
218        foreground_color: &Self,
219        background_color: &Self,
220    ) -> String {
221        let mut codes = Vec::new();
222
223        if let Self::ARGBColor(top_color) = foreground_color {
224            if let Self::ARGBColor(bottom_color) = *background_color {
225                let top_color = ARGBColor::blend(top_color, &bottom_color);
226                codes.push(format!(
227                    "\x1b[38;2;{};{};{}m",
228                    top_color.color.r,
229                    top_color.color.g,
230                    top_color.color.b, // foreground color
231                ));
232            }
233            codes.push(format!(
234                "\x1b[38;2;{};{};{}m",
235                top_color.color.r,
236                top_color.color.g,
237                top_color.color.b, // foreground color
238            ));
239        }
240        if let Self::ARGBColor(background_color) = background_color {
241            codes.push(format!(
242                "\x1b[48;2;{};{};{}m",
243                background_color.color.r,
244                background_color.color.g,
245                background_color.color.b, // background color
246            ));
247        }
248        if codes.is_empty() {
249            return text.to_owned();
250        }
251        format!("{}{text}{}", codes.join(""), "\x1b[0m")
252    }
253
254    fn distance(color1: &Self, color2: &Self) -> f32 {
255        if let Self::ARGBColor(col1) = color1 &&
256            let Self::ARGBColor(col2) = color2
257        {
258            return ARGBColor::distance(col1, col2);
259        }
260        0.
261    }
262
263    fn mix(colors: &[Self]) -> Self {
264        let mut argb_colors = Vec::with_capacity(colors.len());
265        for color in colors {
266            argb_colors.push(match color {
267                Self::Default => continue,
268                Self::ARGBColor(argbcolor) => *argbcolor,
269            });
270        }
271        if argb_colors.is_empty() {
272            return Self::Default;
273        }
274
275        Self::ARGBColor(ARGBColor::mix(argb_colors.as_slice()))
276    }
277}
278
279impl From<RGBColor> for TerminalColor {
280    fn from(value: RGBColor) -> Self {
281        Self::ARGBColor(value.into())
282    }
283}
284
285impl From<ARGBColor> for TerminalColor {
286    fn from(value: ARGBColor) -> Self {
287        Self::ARGBColor(value)
288    }
289}
290
291/// Defines an RGB color used for foreground and background coloring of text.
292/// `r`, `g`, `b` are the red, green and blue components of the color respectively.
293#[derive(Clone, Copy, PartialEq, Eq, Debug)]
294pub struct RGBColor {
295    pub r: u8,
296    pub g: u8,
297    pub b: u8,
298}
299
300impl Color for RGBColor {
301    fn blend(color_top: &Self, _color_bottom: &Self) -> Self {
302        *color_top
303    }
304
305    fn color(
306        text: &str,
307        foreground_color: &Self,
308        background_color: &Self,
309    ) -> String {
310        format!(
311            "\x1b[38;2;{};{};{}m\x1b[48;2;{};{};{}m{}\x1b[0m",
312            foreground_color.r,
313            foreground_color.g,
314            foreground_color.b, // foreground color
315            background_color.r,
316            background_color.g,
317            background_color.b, // background color
318            text
319        )
320    }
321
322    #[rustfmt::skip]
323    #[allow(clippy::suboptimal_flops)]
324    fn distance(color1: &Self, color2: &Self) -> f32 {
325        (
326            ((f32::from(color1.r) - f32::from(color2.r)) / 255.).powi(2) +
327            ((f32::from(color1.g) - f32::from(color2.g)) / 255.).powi(2) +
328            ((f32::from(color1.b) - f32::from(color2.b)) / 255.).powi(2)
329        )
330        .sqrt()
331    }
332
333    fn mix(colors: &[Self]) -> Self {
334        let mut sum = (0, 0, 0);
335        for color in colors {
336            sum.0 += u32::from(color.r);
337            sum.1 += u32::from(color.g);
338            sum.2 += u32::from(color.b);
339        }
340        let colors_len = u32::try_from(colors.len())
341            .expect("colors contains too many elements");
342
343        Self {
344            r: (sum.0 / colors_len).clamp(0, 255) as u8,
345            g: (sum.1 / colors_len).clamp(0, 255) as u8,
346            b: (sum.2 / colors_len).clamp(0, 255) as u8,
347        }
348    }
349}
350
351impl RGBColor {
352    pub const BLACK: Self = Self { r: 0, g: 0, b: 0 };
353    pub const DARK_GRAY: Self = Self {
354        r: 63,
355        g: 63,
356        b: 63,
357    };
358    pub const GRAY: Self = Self {
359        r: 127,
360        g: 127,
361        b: 127,
362    };
363    pub const LIGHT_GRAY: Self = Self {
364        r: 191,
365        g: 191,
366        b: 191,
367    };
368    pub const WHITE: Self = Self {
369        r: 255,
370        g: 255,
371        b: 255,
372    };
373    pub const RED: Self = Self { r: 255, g: 0, b: 0 };
374    pub const GREEN: Self = Self { r: 0, g: 255, b: 0 };
375    pub const BLUE: Self = Self { r: 0, g: 0, b: 255 };
376    pub const YELLOW: Self = Self {
377        r: 255,
378        g: 255,
379        b: 0,
380    };
381    pub const CYAN: Self = Self {
382        r: 0,
383        g: 255,
384        b: 255,
385    };
386    pub const MAGENTA: Self = Self {
387        r: 255,
388        g: 0,
389        b: 255,
390    };
391}
392
393/// Defines an ARGB color used for foreground and background coloring of text.
394/// `color` are the opaque RGB components of the color with an additional `opacity`.
395#[derive(Clone, Copy, PartialEq, Eq, Debug)]
396pub struct ARGBColor {
397    pub opacity: u8,
398    pub color: RGBColor,
399}
400
401impl Color for ARGBColor {
402    #[allow(clippy::cast_possible_truncation)]
403    #[allow(clippy::cast_sign_loss)]
404    fn blend(color_top: &Self, color_bottom: &Self) -> Self {
405        let opacity_top = f32::from(color_top.opacity) / 255.;
406        let opacity_bottom = f32::from(color_bottom.opacity) / 255.;
407        let opacity_res =
408            opacity_bottom.mul_add(1. - opacity_top, opacity_top);
409        let red = f32::from(color_top.color.r).mul_add(
410            opacity_top,
411            f32::from(color_bottom.color.r) *
412                (1. - opacity_top) *
413                opacity_bottom,
414        ) / opacity_res;
415        let green = f32::from(color_top.color.g).mul_add(
416            opacity_top,
417            f32::from(color_bottom.color.g) *
418                (1. - opacity_top) *
419                opacity_bottom,
420        ) / opacity_res;
421        let blue = f32::from(color_top.color.b).mul_add(
422            opacity_top,
423            f32::from(color_bottom.color.b) *
424                (1. - opacity_top) *
425                opacity_bottom,
426        ) / opacity_res;
427        Self {
428            opacity: (opacity_res * 255.).clamp(0., 255.) as u8,
429            color: RGBColor {
430                r: red.clamp(0., 255.) as u8,
431                g: green.clamp(0., 255.) as u8,
432                b: blue.clamp(0., 255.) as u8,
433            },
434        }
435    }
436
437    fn color(
438        text: &str,
439        foreground_color: &Self,
440        background_color: &Self,
441    ) -> String {
442        format!(
443            "\x1b[38;2;{};{};{}m\x1b[48;2;{};{};{}m{}\x1b[0m",
444            foreground_color.color.r,
445            foreground_color.color.g,
446            foreground_color.color.b, // foreground color
447            background_color.color.r,
448            background_color.color.g,
449            background_color.color.b, // background color
450            text
451        )
452    }
453
454    fn distance(color1: &Self, color2: &Self) -> f32 {
455        // Equivalent to d = sqrt(r²+g²+b²+a²)
456        RGBColor::distance(&color1.color, &color2.color).hypot(
457            (f32::from(color1.opacity) - f32::from(color2.opacity)) / 255.,
458        )
459    }
460
461    fn mix(colors: &[Self]) -> Self {
462        let mut sum_opacity = 0;
463        for color in colors {
464            sum_opacity += u32::from(color.opacity);
465        }
466        let colors_len = u32::try_from(colors.len())
467            .expect("colors contains too many elements");
468
469        Self {
470            opacity: (sum_opacity / colors_len).clamp(0, 255) as u8,
471            color: RGBColor::mix(
472                &colors.iter().map(|x| x.color).collect::<Vec<_>>(),
473            ),
474        }
475    }
476}
477
478impl ARGBColor {
479    pub const TRANSPARENT: Self = Self {
480        opacity: 0,
481        color: RGBColor::BLACK,
482    };
483}
484
485impl From<RGBColor> for ARGBColor {
486    fn from(value: RGBColor) -> Self {
487        Self {
488            opacity: u8::MAX,
489            color: value,
490        }
491    }
492}
493
494#[cfg(test)]
495mod tests {
496    use super::*;
497    mod rgb_color {
498        use super::*;
499        use rand::{
500            Rng,
501            thread_rng,
502        };
503
504        #[test]
505        fn blend() {
506            let top = RGBColor {
507                r: thread_rng().gen_range(0..=255),
508                g: thread_rng().gen_range(0..=255),
509                b: thread_rng().gen_range(0..=255),
510            };
511            let bottom = RGBColor {
512                r: thread_rng().gen_range(0..=255),
513                g: thread_rng().gen_range(0..=255),
514                b: thread_rng().gen_range(0..=255),
515            };
516            assert_eq!(top, RGBColor::blend(&top, &bottom));
517        }
518
519        #[test]
520        fn color() {
521            let msg =
522                RGBColor::color("test", &RGBColor::RED, &RGBColor::BLACK);
523            assert!(msg.chars().count() > 4);
524        }
525
526        #[test]
527        fn group() {
528            let colors =
529                [RGBColor::BLACK, RGBColor::WHITE, RGBColor::BLACK];
530            let grouping = RGBColor::group(&colors);
531            assert_ne!(grouping[0], grouping[1]);
532            assert_ne!(grouping[1], grouping[2]);
533            assert_eq!(grouping[0], grouping[2]);
534        }
535
536        #[test]
537        fn group_equal() {
538            let colors =
539                [RGBColor::BLACK, RGBColor::BLACK, RGBColor::BLACK];
540            let grouping = RGBColor::group(&colors);
541            assert_eq!(grouping[0], grouping[1]);
542            assert_eq!(grouping[1], grouping[2]);
543            assert_eq!(grouping[0], grouping[2]);
544        }
545    }
546
547    mod terminal_color {
548        use super::*;
549
550        #[test]
551        fn color_none() {
552            let msg = TerminalColor::color(
553                "test",
554                &TerminalColor::Default,
555                &TerminalColor::Default,
556            );
557            assert_eq!(msg, "test");
558        }
559
560        #[test]
561        fn color_default() {
562            let msg = TerminalColor::color(
563                "test",
564                &RGBColor::RED.into(),
565                &TerminalColor::Default,
566            );
567            assert!(msg.chars().count() > 4);
568        }
569
570        #[test]
571        fn distance() {
572            let dist_prio = TerminalColor::distance(
573                &RGBColor::BLACK.into(),
574                &TerminalColor::Default,
575            );
576            let dist_min = TerminalColor::distance(
577                &RGBColor::BLACK.into(),
578                &RGBColor::BLACK.into(),
579            );
580            let dist = TerminalColor::distance(
581                &RGBColor::BLACK.into(),
582                &RGBColor::RED.into(),
583            );
584            let dist_max = TerminalColor::distance(
585                &RGBColor::BLACK.into(),
586                &RGBColor::WHITE.into(),
587            );
588
589            assert!(dist_prio <= dist_min);
590            assert!(dist_min < dist);
591            assert!(dist < dist_max);
592        }
593
594        #[test]
595        fn mix() {
596            let colors = [RGBColor::BLACK, RGBColor::RED, RGBColor::GREEN]
597                .map(Into::into);
598            let mix = TerminalColor::mix(&colors);
599            assert_eq!(
600                mix,
601                RGBColor {
602                    r: 255 / 3,
603                    g: 255 / 3,
604                    b: 0
605                }
606                .into()
607            );
608        }
609
610        #[test]
611        fn mix_empty() {
612            let colors = [];
613            let mix = TerminalColor::mix(&colors);
614            assert_eq!(mix, TerminalColor::Default);
615        }
616
617        #[test]
618        fn mix_only_default() {
619            let colors = [TerminalColor::Default, TerminalColor::Default];
620            let mix = TerminalColor::mix(&colors);
621            assert_eq!(mix, TerminalColor::Default);
622        }
623
624        #[test]
625        fn mix_default() {
626            let colors = [
627                RGBColor::BLACK.into(),
628                TerminalColor::Default,
629                RGBColor::WHITE.into(),
630            ];
631            let mix = TerminalColor::mix(&colors);
632            assert_eq!(mix, RGBColor::GRAY.into());
633        }
634
635        #[test]
636        fn blend_translucent_default() {
637            let translucent_red = ARGBColor::mix(&[
638                RGBColor::RED.into(),
639                ARGBColor::TRANSPARENT,
640            ])
641            .into();
642            let color = TerminalColor::blend(
643                &translucent_red,
644                &TerminalColor::Default,
645            );
646            assert_eq!(color, translucent_red);
647        }
648
649        #[test]
650        fn blend_transparent_default() {
651            let color = TerminalColor::blend(
652                &ARGBColor::TRANSPARENT.into(),
653                &TerminalColor::Default,
654            );
655            assert_eq!(color, TerminalColor::Default);
656        }
657
658        #[test]
659        fn from_argb() {
660            let color: TerminalColor = ARGBColor::TRANSPARENT.into();
661            assert_eq!(
662                color,
663                TerminalColor::ARGBColor(ARGBColor::TRANSPARENT)
664            );
665        }
666    }
667
668    mod argb_color {
669        use super::*;
670
671        #[test]
672        fn color() {
673            let msg = ARGBColor::color(
674                "test",
675                &RGBColor::RED.into(),
676                &RGBColor::BLACK.into(),
677            );
678            assert!(msg.chars().count() > 4);
679        }
680    }
681}