console-display 0.1.0

A tui library that focuses primarily on providing high resolution display functionality in the console.
Documentation
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
//! Provides abstractions over colors that are used in terminal context.

// TODO: Check if this can be const
/// Defines a color used to color text.
pub trait Color
where
    Self: Sized,
{
    /// Blends the top with the bottom color.
    /// In the case of opaque colors this simply returns the top color.
    /// If the top color is completely transparent it returns the bottom color.
    /// For a translucent top color this returns a mix of both colors weighted by their opacity.
    ///
    /// # Examples
    ///
    /// ```
    /// use console_display::color::{
    ///     Color,
    ///     RGBColor,
    /// };
    /// use rand::{
    ///     Rng,
    ///     thread_rng,
    /// };
    ///
    /// let top = RGBColor {
    ///     r: thread_rng().gen_range(0..=255),
    ///     g: thread_rng().gen_range(0..=255),
    ///     b: thread_rng().gen_range(0..=255),
    /// };
    /// let bottom = RGBColor {
    ///     r: thread_rng().gen_range(0..=255),
    ///     g: thread_rng().gen_range(0..=255),
    ///     b: thread_rng().gen_range(0..=255),
    /// };
    ///
    /// // Opaque top color is returned.
    /// assert_eq!(top, RGBColor::blend(&top, &bottom));
    /// ```
    #[must_use]
    fn blend(color_top: &Self, color_bottom: &Self) -> Self;

    /// Colors a text with a foreground and background color.
    ///
    /// # Examples
    ///
    /// ```
    /// use console_display::color::{
    ///     Color,
    ///     RGBColor,
    /// };
    ///
    /// let msg =
    ///     RGBColor::color("test", &RGBColor::RED, &RGBColor::BLACK);
    ///
    /// // msg contains escape sequences containing color information.
    /// assert!(msg.chars().count() > 4);
    /// ```
    #[must_use]
    fn color(
        text: &str,
        foreground_color: &Self,
        background_color: &Self,
    ) -> String;

    /// Calculates the relative distance between two colors.
    /// For smaller distances the returned value is smaller.
    /// There are no guarantees for the exact return value, so this has only meaning in comparisons.
    ///
    /// # Examples
    ///
    /// ```
    /// use console_display::color::{
    ///     Color,
    ///     RGBColor,
    ///     TerminalColor,
    /// };
    ///
    /// let dist_prio = TerminalColor::distance(
    ///     &RGBColor::BLACK.into(),
    ///     &TerminalColor::Default,
    /// );
    /// let dist_min = TerminalColor::distance(
    ///     &RGBColor::BLACK.into(),
    ///     &RGBColor::BLACK.into(),
    /// );
    /// let dist = TerminalColor::distance(
    ///     &RGBColor::BLACK.into(),
    ///     &RGBColor::RED.into(),
    /// );
    /// let dist_max = TerminalColor::distance(
    ///     &RGBColor::BLACK.into(),
    ///     &RGBColor::WHITE.into(),
    /// );
    ///
    /// assert!(dist_prio <= dist_min);
    /// assert!(dist_min < dist);
    /// assert!(dist < dist_max);
    /// ```
    #[must_use]
    fn distance(color1: &Self, color2: &Self) -> f32;

    /// Mixes a list of colors into one.
    ///
    /// # Examples
    ///
    /// ```
    /// use console_display::color::{
    ///     Color,
    ///     RGBColor,
    ///     TerminalColor,
    /// };
    ///
    /// let colors = [
    ///     RGBColor::BLACK.into(),
    ///     TerminalColor::Default,
    ///     RGBColor::WHITE.into(),
    /// ];
    ///
    /// let mix = TerminalColor::mix(&colors);
    ///
    /// assert_eq!(
    ///     mix,
    ///     // gray, Default is ignored in calculation
    ///     RGBColor {
    ///         r: 255 / 2,
    ///         g: 255 / 2,
    ///         b: 255 / 2
    ///     }
    ///     .into()
    /// );
    /// ```
    #[must_use]
    fn mix(colors: &[Self]) -> Self;

    /// Groups a list of colors into two groups.
    /// The groups are formed by finding the most distant colors.
    /// All other colors are then put into a group with one of them depending on which distance is smaller.
    /// Returns an array of the size of the input. True and false are used to map each color into one of two groups.
    ///
    /// # Examples
    ///
    /// ```
    /// use console_display::color::{
    ///     Color,
    ///     RGBColor,
    /// };
    ///
    /// let colors =
    ///     [RGBColor::BLACK, RGBColor::WHITE, RGBColor::BLACK];
    ///
    /// let grouping = RGBColor::group(&colors);
    ///
    /// assert_ne!(grouping[0], grouping[1]);
    /// assert_ne!(grouping[1], grouping[2]);
    /// assert_eq!(grouping[0], grouping[2]);
    /// ```
    #[must_use]
    fn group<const N: usize>(colors: &[Self; N]) -> [bool; N] {
        let mut max = 0f32;
        let mut col1 = 0;
        let mut col2 = 0;
        for i in 0..N {
            for j in (i + 1)..N {
                let dist = Self::distance(&colors[i], &colors[j]);
                if dist > max {
                    max = dist;
                    col1 = i;
                    col2 = j;
                }
            }
        }
        let mut groups = [false; N];
        for i in 0..N {
            if Self::distance(&colors[col1], &colors[i]) >
                Self::distance(&colors[col2], &colors[i])
            {
                groups[i] = true;
            }
        }
        groups
    }
}

/// Defines a color used for foreground and background coloring of text.
///
/// `Default` - Uses the default color provided by the terminal for foreground or background respectively.\
/// `ARGBColor` - Displays a color made of RGB components and an alpha/opacity channel.
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
pub enum TerminalColor {
    #[default]
    Default,
    ARGBColor(ARGBColor),
}

impl Color for TerminalColor {
    fn blend(color_top: &Self, color_bottom: &Self) -> Self {
        if let Self::ARGBColor(color_top) = color_top &&
            let Self::ARGBColor(color_bottom) = color_bottom
        {
            return Self::ARGBColor(ARGBColor::blend(
                color_top,
                color_bottom,
            ));
        }
        if let Self::ARGBColor(color) = color_top &&
            color.opacity > 0
        {
            *color_top
        }
        else {
            *color_bottom
        }
    }

    fn color(
        text: &str,
        foreground_color: &Self,
        background_color: &Self,
    ) -> String {
        let mut codes = Vec::new();

        if let Self::ARGBColor(top_color) = foreground_color {
            if let Self::ARGBColor(bottom_color) = *background_color {
                let top_color = ARGBColor::blend(top_color, &bottom_color);
                codes.push(format!(
                    "\x1b[38;2;{};{};{}m",
                    top_color.color.r,
                    top_color.color.g,
                    top_color.color.b, // foreground color
                ));
            }
            codes.push(format!(
                "\x1b[38;2;{};{};{}m",
                top_color.color.r,
                top_color.color.g,
                top_color.color.b, // foreground color
            ));
        }
        if let Self::ARGBColor(background_color) = background_color {
            codes.push(format!(
                "\x1b[48;2;{};{};{}m",
                background_color.color.r,
                background_color.color.g,
                background_color.color.b, // background color
            ));
        }
        if codes.is_empty() {
            return text.to_owned();
        }
        format!("{}{text}{}", codes.join(""), "\x1b[0m")
    }

    fn distance(color1: &Self, color2: &Self) -> f32 {
        if let Self::ARGBColor(col1) = color1 &&
            let Self::ARGBColor(col2) = color2
        {
            return ARGBColor::distance(col1, col2);
        }
        0.
    }

    fn mix(colors: &[Self]) -> Self {
        let mut argb_colors = Vec::with_capacity(colors.len());
        for color in colors {
            argb_colors.push(match color {
                Self::Default => continue,
                Self::ARGBColor(argbcolor) => *argbcolor,
            });
        }
        if argb_colors.is_empty() {
            return Self::Default;
        }

        Self::ARGBColor(ARGBColor::mix(argb_colors.as_slice()))
    }
}

impl From<RGBColor> for TerminalColor {
    fn from(value: RGBColor) -> Self {
        Self::ARGBColor(value.into())
    }
}

impl From<ARGBColor> for TerminalColor {
    fn from(value: ARGBColor) -> Self {
        Self::ARGBColor(value)
    }
}

/// Defines an RGB color used for foreground and background coloring of text.
/// `r`, `g`, `b` are the red, green and blue components of the color respectively.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct RGBColor {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

impl Color for RGBColor {
    fn blend(color_top: &Self, _color_bottom: &Self) -> Self {
        *color_top
    }

    fn color(
        text: &str,
        foreground_color: &Self,
        background_color: &Self,
    ) -> String {
        format!(
            "\x1b[38;2;{};{};{}m\x1b[48;2;{};{};{}m{}\x1b[0m",
            foreground_color.r,
            foreground_color.g,
            foreground_color.b, // foreground color
            background_color.r,
            background_color.g,
            background_color.b, // background color
            text
        )
    }

    #[rustfmt::skip]
    #[allow(clippy::suboptimal_flops)]
    fn distance(color1: &Self, color2: &Self) -> f32 {
        (
            ((f32::from(color1.r) - f32::from(color2.r)) / 255.).powi(2) +
            ((f32::from(color1.g) - f32::from(color2.g)) / 255.).powi(2) +
            ((f32::from(color1.b) - f32::from(color2.b)) / 255.).powi(2)
        )
        .sqrt()
    }

    fn mix(colors: &[Self]) -> Self {
        let mut sum = (0, 0, 0);
        for color in colors {
            sum.0 += u32::from(color.r);
            sum.1 += u32::from(color.g);
            sum.2 += u32::from(color.b);
        }
        let colors_len = u32::try_from(colors.len())
            .expect("colors contains too many elements");

        Self {
            r: (sum.0 / colors_len).clamp(0, 255) as u8,
            g: (sum.1 / colors_len).clamp(0, 255) as u8,
            b: (sum.2 / colors_len).clamp(0, 255) as u8,
        }
    }
}

impl RGBColor {
    pub const BLACK: Self = Self { r: 0, g: 0, b: 0 };
    pub const DARK_GRAY: Self = Self {
        r: 63,
        g: 63,
        b: 63,
    };
    pub const GRAY: Self = Self {
        r: 127,
        g: 127,
        b: 127,
    };
    pub const LIGHT_GRAY: Self = Self {
        r: 191,
        g: 191,
        b: 191,
    };
    pub const WHITE: Self = Self {
        r: 255,
        g: 255,
        b: 255,
    };
    pub const RED: Self = Self { r: 255, g: 0, b: 0 };
    pub const GREEN: Self = Self { r: 0, g: 255, b: 0 };
    pub const BLUE: Self = Self { r: 0, g: 0, b: 255 };
    pub const YELLOW: Self = Self {
        r: 255,
        g: 255,
        b: 0,
    };
    pub const CYAN: Self = Self {
        r: 0,
        g: 255,
        b: 255,
    };
    pub const MAGENTA: Self = Self {
        r: 255,
        g: 0,
        b: 255,
    };
}

/// Defines an ARGB color used for foreground and background coloring of text.
/// `color` are the opaque RGB components of the color with an additional `opacity`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct ARGBColor {
    pub opacity: u8,
    pub color: RGBColor,
}

impl Color for ARGBColor {
    #[allow(clippy::cast_possible_truncation)]
    #[allow(clippy::cast_sign_loss)]
    fn blend(color_top: &Self, color_bottom: &Self) -> Self {
        let opacity_top = f32::from(color_top.opacity) / 255.;
        let opacity_bottom = f32::from(color_bottom.opacity) / 255.;
        let opacity_res =
            opacity_bottom.mul_add(1. - opacity_top, opacity_top);
        let red = f32::from(color_top.color.r).mul_add(
            opacity_top,
            f32::from(color_bottom.color.r) *
                (1. - opacity_top) *
                opacity_bottom,
        ) / opacity_res;
        let green = f32::from(color_top.color.g).mul_add(
            opacity_top,
            f32::from(color_bottom.color.g) *
                (1. - opacity_top) *
                opacity_bottom,
        ) / opacity_res;
        let blue = f32::from(color_top.color.b).mul_add(
            opacity_top,
            f32::from(color_bottom.color.b) *
                (1. - opacity_top) *
                opacity_bottom,
        ) / opacity_res;
        Self {
            opacity: (opacity_res * 255.).clamp(0., 255.) as u8,
            color: RGBColor {
                r: red.clamp(0., 255.) as u8,
                g: green.clamp(0., 255.) as u8,
                b: blue.clamp(0., 255.) as u8,
            },
        }
    }

    fn color(
        text: &str,
        foreground_color: &Self,
        background_color: &Self,
    ) -> String {
        format!(
            "\x1b[38;2;{};{};{}m\x1b[48;2;{};{};{}m{}\x1b[0m",
            foreground_color.color.r,
            foreground_color.color.g,
            foreground_color.color.b, // foreground color
            background_color.color.r,
            background_color.color.g,
            background_color.color.b, // background color
            text
        )
    }

    fn distance(color1: &Self, color2: &Self) -> f32 {
        // Equivalent to d = sqrt(r²+g²+b²+a²)
        RGBColor::distance(&color1.color, &color2.color).hypot(
            (f32::from(color1.opacity) - f32::from(color2.opacity)) / 255.,
        )
    }

    fn mix(colors: &[Self]) -> Self {
        let mut sum_opacity = 0;
        for color in colors {
            sum_opacity += u32::from(color.opacity);
        }
        let colors_len = u32::try_from(colors.len())
            .expect("colors contains too many elements");

        Self {
            opacity: (sum_opacity / colors_len).clamp(0, 255) as u8,
            color: RGBColor::mix(
                &colors.iter().map(|x| x.color).collect::<Vec<_>>(),
            ),
        }
    }
}

impl ARGBColor {
    pub const TRANSPARENT: Self = Self {
        opacity: 0,
        color: RGBColor::BLACK,
    };
}

impl From<RGBColor> for ARGBColor {
    fn from(value: RGBColor) -> Self {
        Self {
            opacity: u8::MAX,
            color: value,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    mod rgb_color {
        use super::*;
        use rand::{
            Rng,
            thread_rng,
        };

        #[test]
        fn blend() {
            let top = RGBColor {
                r: thread_rng().gen_range(0..=255),
                g: thread_rng().gen_range(0..=255),
                b: thread_rng().gen_range(0..=255),
            };
            let bottom = RGBColor {
                r: thread_rng().gen_range(0..=255),
                g: thread_rng().gen_range(0..=255),
                b: thread_rng().gen_range(0..=255),
            };
            assert_eq!(top, RGBColor::blend(&top, &bottom));
        }

        #[test]
        fn color() {
            let msg =
                RGBColor::color("test", &RGBColor::RED, &RGBColor::BLACK);
            assert!(msg.chars().count() > 4);
        }

        #[test]
        fn group() {
            let colors =
                [RGBColor::BLACK, RGBColor::WHITE, RGBColor::BLACK];
            let grouping = RGBColor::group(&colors);
            assert_ne!(grouping[0], grouping[1]);
            assert_ne!(grouping[1], grouping[2]);
            assert_eq!(grouping[0], grouping[2]);
        }

        #[test]
        fn group_equal() {
            let colors =
                [RGBColor::BLACK, RGBColor::BLACK, RGBColor::BLACK];
            let grouping = RGBColor::group(&colors);
            assert_eq!(grouping[0], grouping[1]);
            assert_eq!(grouping[1], grouping[2]);
            assert_eq!(grouping[0], grouping[2]);
        }
    }

    mod terminal_color {
        use super::*;

        #[test]
        fn color_none() {
            let msg = TerminalColor::color(
                "test",
                &TerminalColor::Default,
                &TerminalColor::Default,
            );
            assert_eq!(msg, "test");
        }

        #[test]
        fn color_default() {
            let msg = TerminalColor::color(
                "test",
                &RGBColor::RED.into(),
                &TerminalColor::Default,
            );
            assert!(msg.chars().count() > 4);
        }

        #[test]
        fn distance() {
            let dist_prio = TerminalColor::distance(
                &RGBColor::BLACK.into(),
                &TerminalColor::Default,
            );
            let dist_min = TerminalColor::distance(
                &RGBColor::BLACK.into(),
                &RGBColor::BLACK.into(),
            );
            let dist = TerminalColor::distance(
                &RGBColor::BLACK.into(),
                &RGBColor::RED.into(),
            );
            let dist_max = TerminalColor::distance(
                &RGBColor::BLACK.into(),
                &RGBColor::WHITE.into(),
            );

            assert!(dist_prio <= dist_min);
            assert!(dist_min < dist);
            assert!(dist < dist_max);
        }

        #[test]
        fn mix() {
            let colors = [RGBColor::BLACK, RGBColor::RED, RGBColor::GREEN]
                .map(Into::into);
            let mix = TerminalColor::mix(&colors);
            assert_eq!(
                mix,
                RGBColor {
                    r: 255 / 3,
                    g: 255 / 3,
                    b: 0
                }
                .into()
            );
        }

        #[test]
        fn mix_empty() {
            let colors = [];
            let mix = TerminalColor::mix(&colors);
            assert_eq!(mix, TerminalColor::Default);
        }

        #[test]
        fn mix_only_default() {
            let colors = [TerminalColor::Default, TerminalColor::Default];
            let mix = TerminalColor::mix(&colors);
            assert_eq!(mix, TerminalColor::Default);
        }

        #[test]
        fn mix_default() {
            let colors = [
                RGBColor::BLACK.into(),
                TerminalColor::Default,
                RGBColor::WHITE.into(),
            ];
            let mix = TerminalColor::mix(&colors);
            assert_eq!(mix, RGBColor::GRAY.into());
        }

        #[test]
        fn blend_translucent_default() {
            let translucent_red = ARGBColor::mix(&[
                RGBColor::RED.into(),
                ARGBColor::TRANSPARENT,
            ])
            .into();
            let color = TerminalColor::blend(
                &translucent_red,
                &TerminalColor::Default,
            );
            assert_eq!(color, translucent_red);
        }

        #[test]
        fn blend_transparent_default() {
            let color = TerminalColor::blend(
                &ARGBColor::TRANSPARENT.into(),
                &TerminalColor::Default,
            );
            assert_eq!(color, TerminalColor::Default);
        }

        #[test]
        fn from_argb() {
            let color: TerminalColor = ARGBColor::TRANSPARENT.into();
            assert_eq!(
                color,
                TerminalColor::ARGBColor(ARGBColor::TRANSPARENT)
            );
        }
    }

    mod argb_color {
        use super::*;

        #[test]
        fn color() {
            let msg = ARGBColor::color(
                "test",
                &RGBColor::RED.into(),
                &RGBColor::BLACK.into(),
            );
            assert!(msg.chars().count() > 4);
        }
    }
}