console_display/widget/
two_widget.rs

1use std::ops::{
2    Deref,
3    DerefMut,
4};
5
6use console_display_macros::{
7    StaticWidget,
8    TwoWidget,
9};
10
11use crate::{
12    color::{
13        Color,
14        TerminalColor,
15    },
16    constraint,
17    impl_getters,
18    impl_setters,
19    widget::{
20        DynamicWidget,
21        StringData,
22    },
23};
24
25use super::StaticWidget;
26
27#[const_trait]
28pub trait TwoWidget<S: DynamicWidget, T: DynamicWidget>:
29    DynamicWidget + Deref + DerefMut
30{
31    fn children(&self) -> (&S, &T);
32    fn children_mut(&mut self) -> (&mut S, &mut T);
33}
34
35#[derive(StaticWidget, TwoWidget)]
36pub struct AlternativeWidget<S: DynamicWidget, T: DynamicWidget> {
37    child1_on_top: bool,
38    children: (S, T),
39}
40
41impl<S: StaticWidget, T: StaticWidget> AlternativeWidget<S, T> {
42    pub const fn new(child1: S, child2: T, child1_on_top: bool) -> Self
43    where
44        constraint!(S::WIDTH_CHARACTERS == T::WIDTH_CHARACTERS):,
45        constraint!(S::HEIGHT_CHARACTERS == T::HEIGHT_CHARACTERS):,
46    {
47        Self {
48            child1_on_top,
49            children: (child1, child2),
50        }
51    }
52}
53
54impl<S: DynamicWidget, T: DynamicWidget> AlternativeWidget<S, T> {
55    /// Builds an alternative widget with two children.
56    /// The `child1_on_top` parameter determines whether the first child should be
57    /// displayed instead of the second child and vice versa.
58    ///
59    /// # Errors
60    ///
61    /// Returns an error if the dimensions of both children don't match.
62    pub fn build(
63        child1: S,
64        child2: T,
65        child1_on_top: bool,
66    ) -> Result<Self, String> {
67        if child1.width_characters() != child2.width_characters() ||
68            child1.height_characters() != child2.height_characters()
69        {
70            return Err(format!(
71                "Height and/or width in characters of arguments does not match. Height {} and {}. Width: {} and {}",
72                child1.height_characters(),
73                child2.height_characters(),
74                child1.width_characters(),
75                child2.width_characters(),
76            ));
77        }
78        Ok(Self {
79            child1_on_top,
80            children: (child1, child2),
81        })
82    }
83
84    impl_getters!(pub const child1_on_top: bool);
85
86    impl_setters!(pub const child1_on_top: bool);
87}
88
89impl<S: [const] DynamicWidget, T: [const] DynamicWidget> const
90    DynamicWidget for AlternativeWidget<S, T>
91{
92    fn width_characters(&self) -> usize {
93        self.children.0.width_characters()
94    }
95
96    fn height_characters(&self) -> usize {
97        self.children.0.height_characters()
98    }
99
100    fn string_data(&self) -> StringData {
101        if self.child1_on_top {
102            self.children.0.string_data()
103        }
104        else {
105            self.children.1.string_data()
106        }
107    }
108}
109
110impl<S: DynamicWidget, T: DynamicWidget> const Deref
111    for AlternativeWidget<S, T>
112{
113    type Target = (S, T);
114
115    fn deref(&self) -> &Self::Target {
116        &self.children
117    }
118}
119
120impl<S: DynamicWidget, T: DynamicWidget> const DerefMut
121    for AlternativeWidget<S, T>
122{
123    fn deref_mut(&mut self) -> &mut Self::Target {
124        &mut self.children
125    }
126}
127
128#[derive(TwoWidget)]
129pub struct HorizontalTilingWidget<S: DynamicWidget, T: DynamicWidget> {
130    children: (S, T),
131}
132
133impl<S: DynamicWidget, T: DynamicWidget> HorizontalTilingWidget<S, T> {
134    /// Builds horizontal tiling widget with two children.
135    /// `child1` will be displayed on the left, `child2` on the right.
136    ///
137    /// # Errors
138    ///
139    /// Returns an error if the height of both children does not match.
140    pub fn build(child1: S, child2: T) -> Result<Self, String> {
141        if child1.height_characters() != child2.height_characters() {
142            return Err(format!(
143                "Height in characters of arguments does not match. {} and {}.",
144                child1.height_characters(),
145                child2.height_characters()
146            ));
147        }
148        Ok(Self {
149            children: (child1, child2),
150        })
151    }
152
153    pub const fn left(&self) -> &S {
154        &self.0
155    }
156
157    pub const fn left_mut(&mut self) -> &mut S {
158        &mut self.0
159    }
160
161    pub const fn right(&self) -> &T {
162        &self.1
163    }
164
165    pub const fn right_mut(&mut self) -> &mut T {
166        &mut self.1
167    }
168}
169
170impl<S: StaticWidget, T: StaticWidget> HorizontalTilingWidget<S, T> {
171    pub const fn new(child1: S, child2: T) -> Self
172    where
173        constraint!(S::HEIGHT_CHARACTERS == T::HEIGHT_CHARACTERS):,
174    {
175        Self {
176            children: (child1, child2),
177        }
178    }
179}
180
181impl<S: StaticWidget, T: StaticWidget> const StaticWidget
182    for HorizontalTilingWidget<S, T>
183{
184    const WIDTH_CHARACTERS: usize =
185        S::WIDTH_CHARACTERS + T::WIDTH_CHARACTERS;
186
187    const HEIGHT_CHARACTERS: usize = S::HEIGHT_CHARACTERS;
188}
189
190impl<S: DynamicWidget, T: DynamicWidget> DynamicWidget
191    for HorizontalTilingWidget<S, T>
192{
193    fn width_characters(&self) -> usize {
194        self.children.0.width_characters() +
195            self.children.1.width_characters()
196    }
197
198    fn height_characters(&self) -> usize {
199        self.children.0.height_characters()
200    }
201
202    fn string_data(&self) -> StringData {
203        StringData {
204            data: self
205                .0
206                .string_data()
207                .data
208                .into_iter()
209                .zip(self.children.1.string_data().data)
210                .map(|lines| [lines.0, lines.1].concat())
211                .collect(),
212        }
213    }
214}
215
216impl<S: DynamicWidget, T: DynamicWidget> const Deref
217    for HorizontalTilingWidget<S, T>
218{
219    type Target = (S, T);
220
221    fn deref(&self) -> &Self::Target {
222        &self.children
223    }
224}
225
226impl<S: DynamicWidget, T: DynamicWidget> const DerefMut
227    for HorizontalTilingWidget<S, T>
228{
229    fn deref_mut(&mut self) -> &mut Self::Target {
230        &mut self.children
231    }
232}
233
234#[derive(TwoWidget)]
235pub struct VerticalTilingWidget<S: DynamicWidget, T: DynamicWidget> {
236    children: (S, T),
237}
238
239impl<S: DynamicWidget, T: DynamicWidget> VerticalTilingWidget<S, T> {
240    /// Builds vertical tiling widget with two children.
241    /// `child1` will be displayed on the top, `child2` on the bottom.
242    ///
243    /// # Errors
244    ///
245    /// Returns an error if the width of both children does not match.
246    pub fn build(child1: S, child2: T) -> Result<Self, String> {
247        if child1.width_characters() != child2.width_characters() {
248            return Err(format!(
249                "Width in characters of arguments does not match. {} and {}.",
250                child1.width_characters(),
251                child2.width_characters()
252            ));
253        }
254        Ok(Self {
255            children: (child1, child2),
256        })
257    }
258
259    pub const fn top(&self) -> &S {
260        &self.0
261    }
262
263    pub const fn top_mut(&mut self) -> &mut S {
264        &mut self.0
265    }
266
267    pub const fn bottom(&self) -> &T {
268        &self.1
269    }
270
271    pub const fn bottom_mut(&mut self) -> &mut T {
272        &mut self.1
273    }
274}
275
276impl<S: StaticWidget, T: StaticWidget> VerticalTilingWidget<S, T> {
277    pub const fn new(child1: S, child2: T) -> Self
278    where
279        constraint!(S::WIDTH_CHARACTERS == T::WIDTH_CHARACTERS):,
280    {
281        Self {
282            children: (child1, child2),
283        }
284    }
285}
286
287impl<S: StaticWidget, T: StaticWidget> const StaticWidget
288    for VerticalTilingWidget<S, T>
289{
290    const WIDTH_CHARACTERS: usize = S::WIDTH_CHARACTERS;
291
292    const HEIGHT_CHARACTERS: usize =
293        S::HEIGHT_CHARACTERS + T::HEIGHT_CHARACTERS;
294}
295
296impl<S: DynamicWidget, T: DynamicWidget> DynamicWidget
297    for VerticalTilingWidget<S, T>
298{
299    fn width_characters(&self) -> usize {
300        self.children.0.width_characters()
301    }
302
303    fn height_characters(&self) -> usize {
304        self.children.0.height_characters() +
305            self.children.1.height_characters()
306    }
307
308    fn string_data(&self) -> StringData {
309        StringData {
310            data: [self.0.string_data().data, self.1.string_data().data]
311                .concat(),
312        }
313    }
314}
315
316impl<S: DynamicWidget, T: DynamicWidget> const Deref
317    for VerticalTilingWidget<S, T>
318{
319    type Target = (S, T);
320
321    fn deref(&self) -> &Self::Target {
322        &self.children
323    }
324}
325
326impl<S: DynamicWidget, T: DynamicWidget> const DerefMut
327    for VerticalTilingWidget<S, T>
328{
329    fn deref_mut(&mut self) -> &mut Self::Target {
330        &mut self.children
331    }
332}
333
334#[derive(StaticWidget)]
335pub struct OverlayWidget<S: DynamicWidget, T: DynamicWidget> {
336    children: (S, T),
337}
338
339impl<S: StaticWidget, T: StaticWidget> OverlayWidget<S, T> {
340    pub const fn new(overlay: S, base: T) -> Self
341    where
342        constraint!(S::WIDTH_CHARACTERS == T::WIDTH_CHARACTERS):,
343        constraint!(S::HEIGHT_CHARACTERS == T::HEIGHT_CHARACTERS):,
344    {
345        Self {
346            children: (overlay, base),
347        }
348    }
349
350    pub const fn overlay(&self) -> &S {
351        &self.0
352    }
353
354    pub const fn overlay_mut(&mut self) -> &mut S {
355        &mut self.0
356    }
357
358    pub const fn base(&self) -> &T {
359        &self.1
360    }
361
362    pub const fn base_mut(&mut self) -> &mut T {
363        &mut self.1
364    }
365}
366
367impl<S: DynamicWidget, T: DynamicWidget> OverlayWidget<S, T> {
368    /// Builds an overlay widget with two children.
369    ///
370    /// # Errors
371    ///
372    /// Returns an error if the dimensions of both children don't match.
373    pub fn build(overlay: S, base: T) -> Result<Self, String> {
374        if overlay.width_characters() != base.width_characters() ||
375            overlay.height_characters() != base.height_characters()
376        {
377            return Err(format!(
378                "Height and/or width in characters of arguments does not match. Height {} and {}. Width: {} and {}",
379                overlay.height_characters(),
380                base.height_characters(),
381                overlay.width_characters(),
382                base.width_characters(),
383            ));
384        }
385        Ok(Self {
386            children: (overlay, base),
387        })
388    }
389}
390
391impl<S: DynamicWidget, T: DynamicWidget> DynamicWidget
392    for OverlayWidget<S, T>
393{
394    fn width_characters(&self) -> usize {
395        self.children.0.width_characters()
396    }
397
398    fn height_characters(&self) -> usize {
399        self.children.0.height_characters()
400    }
401
402    fn string_data(&self) -> StringData {
403        let overlay = self.0.string_data().data;
404        let display = self.1.string_data().data;
405        StringData {
406            data: overlay
407                .into_iter()
408                .zip(display)
409                .map(|(overlay_row, display_row)| {
410                    overlay_row
411                        .into_iter()
412                        .zip(display_row)
413                        .map(|(cell_top, cell_bottom)| {
414                            let mut cell = cell_top;
415                            // TODO: Rework this blending
416                            if let TerminalColor::ARGBColor(foreground) =
417                                cell.foreground &&
418                                let TerminalColor::ARGBColor(background) =
419                                    cell.background &&
420                                background.opacity < u8::MAX / 2 &&
421                                foreground.opacity < u8::MAX / 2
422                            {
423                                cell.character = cell_bottom.character;
424
425                                cell.background = TerminalColor::blend(
426                                    &cell.background,
427                                    &cell_bottom.background,
428                                );
429                                cell.foreground = TerminalColor::blend(
430                                    &cell.foreground,
431                                    &cell_bottom.foreground,
432                                );
433                            }
434                            else if cell.background ==
435                                TerminalColor::Default ||
436                                cell.foreground ==
437                                    TerminalColor::Default
438                            {
439                                cell.character = cell_bottom.character;
440
441                                cell.background = TerminalColor::blend(
442                                    &cell.background,
443                                    &cell_bottom.background,
444                                );
445                                cell.foreground = TerminalColor::blend(
446                                    &cell.foreground,
447                                    &cell_bottom.foreground,
448                                );
449                            }
450                            cell
451                        })
452                        .collect()
453                })
454                .collect(),
455        }
456    }
457}
458
459impl<S: DynamicWidget, T: DynamicWidget> const Deref
460    for OverlayWidget<S, T>
461{
462    type Target = (S, T);
463
464    fn deref(&self) -> &Self::Target {
465        &self.children
466    }
467}
468
469impl<S: DynamicWidget, T: DynamicWidget> const DerefMut
470    for OverlayWidget<S, T>
471{
472    fn deref_mut(&mut self) -> &mut Self::Target {
473        &mut self.children
474    }
475}
476
477// TODO: Add more tests for functionality rather than initialization
478#[cfg(test)]
479mod tests {
480    use crate::{
481        pixel::{
482            color_pixel::ColorSinglePixel,
483            monochrome_pixel::SinglePixel,
484        },
485        pixel_display::StaticPixelDisplay,
486    };
487
488    use super::*;
489
490    mod alternative_widget {
491        use super::*;
492
493        #[test]
494        fn build_success() {
495            let alternative = AlternativeWidget::build(
496                StaticPixelDisplay::<SinglePixel, 1, 1>::new(false),
497                StaticPixelDisplay::<SinglePixel, 1, 1>::new(true),
498                true,
499            );
500            assert!(alternative.is_ok());
501        }
502
503        #[test]
504        fn build_failure() {
505            let alternative = AlternativeWidget::build(
506                StaticPixelDisplay::<SinglePixel, 1, 1>::new(false),
507                StaticPixelDisplay::<SinglePixel, 1, 2>::new(true),
508                true,
509            );
510            assert!(alternative.is_err());
511        }
512
513        #[test]
514        fn dimensions() {
515            let alternative = AlternativeWidget::new(
516                StaticPixelDisplay::<SinglePixel, 37, 63>::new(false),
517                StaticPixelDisplay::<SinglePixel, 37, 63>::new(true),
518                true,
519            );
520            assert_eq!(alternative.width_characters(), 37);
521            assert_eq!(alternative.height_characters(), 63);
522        }
523    }
524
525    mod horizontal_tiling {
526        use super::*;
527
528        #[test]
529        fn build_success() {
530            let overlay = HorizontalTilingWidget::build(
531                StaticPixelDisplay::<SinglePixel, 3, 10>::new(false),
532                StaticPixelDisplay::<SinglePixel, 2, 10>::new(true),
533            );
534            assert!(overlay.is_ok());
535        }
536
537        #[test]
538        fn build_failure() {
539            let overlay = HorizontalTilingWidget::build(
540                StaticPixelDisplay::<SinglePixel, 10, 3>::new(false),
541                StaticPixelDisplay::<SinglePixel, 10, 2>::new(true),
542            );
543            assert!(overlay.is_err());
544        }
545
546        #[test]
547        fn dimensions() {
548            let overlay = HorizontalTilingWidget::new(
549                StaticPixelDisplay::<SinglePixel, 37, 20>::new(false),
550                StaticPixelDisplay::<SinglePixel, 63, 20>::new(true),
551            );
552            assert_eq!(overlay.width_characters(), 100);
553            assert_eq!(overlay.height_characters(), 20);
554        }
555    }
556
557    mod vertical_tiling {
558        use super::*;
559
560        #[test]
561        fn build_success() {
562            let overlay = VerticalTilingWidget::build(
563                StaticPixelDisplay::<SinglePixel, 20, 5>::new(false),
564                StaticPixelDisplay::<SinglePixel, 20, 4>::new(true),
565            );
566            assert!(overlay.is_ok());
567        }
568
569        #[test]
570        fn build_failure() {
571            let overlay = VerticalTilingWidget::build(
572                StaticPixelDisplay::<SinglePixel, 5, 20>::new(false),
573                StaticPixelDisplay::<SinglePixel, 4, 20>::new(true),
574            );
575            assert!(overlay.is_err());
576        }
577
578        #[test]
579        fn dimensions() {
580            let overlay = VerticalTilingWidget::new(
581                StaticPixelDisplay::<SinglePixel, 30, 45>::new(false),
582                StaticPixelDisplay::<SinglePixel, 30, 54>::new(true),
583            );
584            assert_eq!(overlay.width_characters(), 30);
585            assert_eq!(overlay.height_characters(), 99);
586        }
587    }
588
589    mod overlay_widget {
590        use crate::{
591            color::{
592                ARGBColor,
593                RGBColor,
594            },
595            drawing::DynamicCanvas,
596            pixel_display::DynamicPixelDisplay,
597        };
598
599        use super::*;
600
601        #[test]
602        fn build_success() {
603            let overlay = OverlayWidget::build(
604                StaticPixelDisplay::<SinglePixel, 1, 1>::new(false),
605                StaticPixelDisplay::<SinglePixel, 1, 1>::new(true),
606            );
607            assert!(overlay.is_ok());
608        }
609
610        #[test]
611        fn build_failure() {
612            let overlay = OverlayWidget::build(
613                StaticPixelDisplay::<SinglePixel, 1, 1>::new(false),
614                StaticPixelDisplay::<SinglePixel, 1, 2>::new(true),
615            );
616            assert!(overlay.is_err());
617        }
618
619        #[test]
620        fn dimensions() {
621            let overlay = OverlayWidget::new(
622                StaticPixelDisplay::<SinglePixel, 37, 63>::new(false),
623                StaticPixelDisplay::<SinglePixel, 37, 63>::new(true),
624            );
625            assert_eq!(overlay.width_characters(), 37);
626            assert_eq!(overlay.height_characters(), 63);
627        }
628
629        #[test]
630        fn transparency() {
631            let top = DynamicPixelDisplay::<ColorSinglePixel>::new(
632                37,
633                63,
634                TerminalColor::ARGBColor(ARGBColor {
635                    opacity: 0,
636                    color: RGBColor::BLACK,
637                }),
638            );
639
640            let bottom =
641                StaticPixelDisplay::<ColorSinglePixel, 37, 63>::new(
642                    RGBColor::WHITE.into(),
643                );
644
645            let mut overlay = OverlayWidget::build(top, bottom).unwrap();
646
647            assert_eq!(
648                overlay.string_data().to_string(),
649                overlay.1.string_data().to_string()
650            );
651
652            overlay.0.set_pixel(10, 10, RGBColor::BLACK.into()).unwrap();
653
654            assert_ne!(
655                overlay.string_data().to_string(),
656                overlay.1.string_data().to_string()
657            );
658        }
659    }
660}