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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
//! Linear layout
//!
//! A linear layout is a list of [`View`]s that are placed one after the other along
//! the horizontal or vertical axis.
//!
//! The main flow when working with a [`LinearLayout`] is the following:
//!  - Create the layout
//!    * you need to choose which orientation you want your views arranged in
//!    * pass in your views wrapped in a [`ViewGroup`].
//!  - Optionally, set [secondary alignment]
//!  - Optionally, set [element spacing]
//!  - Call [`LinearLayout::arrange`] to finalize view placement
//!  - Align the layout object to where you want it to be displayed
//!  - Call `draw` to display the views
//!
//! # Orientation
//!
//! When constructing a [`LinearLayout`] object, you need to choose an orientation along which
//! the views will be arranged. This can either be horizontal or vertical.
//!
//! ## Examples:
//!
//! Create a [`LinearLayout`] with two pieces of text, where one is below the other:
//!
//! ```rust
//! # use embedded_layout::prelude::*;
//! # use embedded_layout::layout::linear::LinearLayout;
//! # use embedded_graphics::{
//! #     mono_font::{ascii::FONT_6X9, MonoTextStyle},
//! #     pixelcolor::BinaryColor,
//! #     text::Text,
//! #     prelude::*,
//! # };
//! let text_style = MonoTextStyle::new(&FONT_6X9, BinaryColor::On);
//! let _ = LinearLayout::vertical(
//!     Chain::new(Text::new("Hello,", Point::zero(), text_style))
//!         .append(Text::new("World!", Point::zero(), text_style)),
//! )
//! .arrange();
//! ```
//!
//! # Secondary alignment
//!
//! Secondary alignment means the alignment on the "other" axis:
//!  - horizontal alignment in vertical linear layouts
//!  - vertical alignment in horizontal linear layouts
//!
//! By default, the secondary alignments are the following:
//!  - Horizontal orientation: [`vertical::Bottom`]
//!  - Vertical orientation: [`horizontal::Left`]
//!
//! Except for using the cascading (`XtoY`) secondary alignments, the [`LinearLayout`] will take up
//! as much space along the secondary alignment as the biggest element, i.e. vertical layouts
//! will be as wide as the widest view inside them.
//!
//! # Element spacing
//!
//! It's possible to modify how views are placed relative to one another.
//!  * The default is [`Tight`] which is equivalent to [`FixedMargin(0)`]
//!  * [`FixedMargin(margin)`]: `margin` px distance between views, where `margin` can be negative to overlap views
//!  * [`DistributeFill(size)`]: force the primary layout size to `size`, distribute views evenly
//!
//! [`View`]: crate::View
//! [`ViewGroup`]: crate::view_group::ViewGroup
//! [secondary alignment]: LinearLayout::with_alignment
//! [element spacing]: LinearLayout::with_spacing
//! [`Tight`]: crate::layout::linear::spacing::Tight
//! [`FixedMargin(0)`]: crate::layout::linear::spacing::FixedMargin
//! [`FixedMargin(margin)`]: crate::layout::linear::spacing::FixedMargin
//! [`DistributeFill(size)`]: crate::layout::linear::spacing::DistributeFill
//! [`vertical::Bottom`]: crate::align::vertical::Bottom
//! [`horizontal::Left`]: crate::align::horizontal::Left

use crate::{
    align::{horizontal, vertical},
    align::{HorizontalAlignment, VerticalAlignment},
    view_group::{EmptyViewGroup, ViewGroup},
    View,
};

mod orientation;
mod secondary_alignment;
pub mod spacing;

use embedded_graphics::{
    draw_target::DrawTarget,
    prelude::{PixelColor, Point},
    primitives::Rectangle,
    Drawable,
};
pub use orientation::{Horizontal, Orientation, Vertical};
pub use secondary_alignment::SecondaryAlignment;
pub use spacing::{ElementSpacing, FixedMargin};

use spacing::Tight;

/// `LinearLayout`
///
/// [`LinearLayout`] is used to arrange views along the horizontal or vertical axis.
///
/// For more information and examples see the [module level documentation](crate::layout::linear).
pub struct LinearLayout<LD, VG> {
    position: Point,
    direction: LD,
    views: VG,
}

impl<LD, VG> LinearLayout<LD, VG> {
    /// Returns a reference to the contained views.
    #[inline]
    pub fn inner(&self) -> &VG {
        &self.views
    }

    /// Returns a mutable reference to the contained views.
    #[inline]
    pub fn inner_mut(&mut self) -> &mut VG {
        &mut self.views
    }
}

impl<VG> LinearLayout<Horizontal<vertical::Bottom, Tight>, VG>
where
    VG: ViewGroup,
{
    /// Create a new [`LinearLayout`] that places views left to right
    #[inline]
    #[must_use]
    pub fn horizontal(views: VG) -> Self {
        Self {
            position: Point::new(0, 0),
            direction: Horizontal::default(),
            views,
        }
    }
}

impl<VG> LinearLayout<Vertical<horizontal::Left, Tight>, VG>
where
    VG: ViewGroup,
{
    /// Create a new [`LinearLayout`] that places views top to bottom
    #[inline]
    #[must_use]
    pub fn vertical(views: VG) -> Self {
        Self {
            position: Point::new(0, 0),
            direction: Vertical::default(),
            views,
        }
    }
}

impl<S, ELS, VG> LinearLayout<Horizontal<S, ELS>, VG>
where
    S: SecondaryAlignment + VerticalAlignment,
    ELS: ElementSpacing,
    VG: ViewGroup,
{
    /// Change the secondary alignment for this [`LinearLayout`] object.
    ///
    /// For layouts created using [`LinearLayout::horizontal`] the secondary alignment is [`vertical`].
    ///
    /// [`LinearLayout::horizontal`]: crate::layout::linear::LinearLayout::horizontal
    /// [`vertical`]: crate::align::vertical
    #[inline]
    pub fn with_alignment<Sec>(self, alignment: Sec) -> LinearLayout<Horizontal<Sec, ELS>, VG>
    where
        Sec: SecondaryAlignment + VerticalAlignment,
    {
        LinearLayout {
            position: self.position,
            direction: self.direction.with_secondary_alignment(alignment),
            views: self.views,
        }
    }

    /// Change the element spacing
    ///
    /// For available values and their properties, see [spacing]
    ///
    /// [spacing]: crate::layout::linear::spacing
    #[inline]
    pub fn with_spacing<ES>(self, spacing: ES) -> LinearLayout<Horizontal<S, ES>, VG>
    where
        ES: ElementSpacing,
    {
        LinearLayout {
            position: self.position,
            direction: self.direction.with_spacing(spacing),
            views: self.views,
        }
    }
}

impl<S, ELS, VG> LinearLayout<Vertical<S, ELS>, VG>
where
    S: SecondaryAlignment + HorizontalAlignment,
    ELS: ElementSpacing,
    VG: ViewGroup,
{
    /// Change the secondary alignment for this [`LinearLayout`] object.
    ///
    /// For layouts created using [`LinearLayout::vertical`] the secondary alignment is [`horizontal`].
    ///
    /// [`LinearLayout::vertical`]: crate::layout::linear::LinearLayout::vertical
    /// [`horizontal`]: crate::align::horizontal
    #[inline]
    pub fn with_alignment<Sec>(self, alignment: Sec) -> LinearLayout<Vertical<Sec, ELS>, VG>
    where
        Sec: SecondaryAlignment + HorizontalAlignment,
    {
        LinearLayout {
            position: self.position,
            direction: self.direction.with_secondary_alignment(alignment),
            views: self.views,
        }
    }

    /// Change the element spacing
    ///
    /// For available values and their properties, see [spacing]
    ///
    /// [spacing]: crate::layout::linear::spacing
    #[inline]
    pub fn with_spacing<ES>(self, spacing: ES) -> LinearLayout<Vertical<S, ES>, VG>
    where
        ES: ElementSpacing,
    {
        LinearLayout {
            position: self.position,
            direction: self.direction.with_spacing(spacing),
            views: self.views,
        }
    }
}

impl<LD, VG> Clone for LinearLayout<LD, VG>
where
    LD: Orientation,
    VG: ViewGroup + Clone,
{
    fn clone(&self) -> Self {
        Self {
            position: self.position,
            direction: self.direction,
            views: self.views.clone(),
        }
    }
}

impl<LD, VG> LinearLayout<LD, VG>
where
    LD: Orientation,
    VG: ViewGroup,
{
    /// Consume the layout object and return the wrapped [`ViewGroup`].
    ///
    /// After calling `arrange()` it is no longer necessary to hold the views in a `LinearLayout`.
    /// Use this method to extract the original view group object if you need to work with the
    /// arranged views.
    ///
    /// # Example
    ///
    /// Arrange an array of `StyledText` objects, then check the second object's position.
    ///
    /// ```rust
    /// # use embedded_layout::prelude::*;
    /// # use embedded_layout::layout::linear::LinearLayout;
    /// # use embedded_graphics::{
    /// #     mono_font::{ascii::FONT_6X9, MonoTextStyle},
    /// #     pixelcolor::BinaryColor,
    /// #     prelude::*,
    /// #     mock_display::MockDisplay,
    /// #     text::Text,
    /// # };
    /// # let mut display: MockDisplay<BinaryColor> = MockDisplay::new();
    /// #
    /// let text_style = MonoTextStyle::new(&FONT_6X9, BinaryColor::On);
    ///
    /// // First, wrap out views in a `ViewGroup`.
    /// let mut texts = [
    ///     Text::new("Hello,", Point::zero(), text_style),
    ///     Text::new("World!", Point::zero(), text_style)
    /// ];
    /// let mut views = Views::new(&mut texts);
    ///
    /// // Arrange our views and extract our original view group.
    /// let views = LinearLayout::vertical(views).arrange().into_inner();
    ///
    /// // We can access our `StyledText` objects now. Note that `Views` works like a slice!
    /// assert_eq!(Point::new(0, 9), views[1].bounds().top_left);
    ///
    /// // `Views` is also a drawable `ViewGroup`, so let's display our arranged text!
    /// views.draw(&mut display).unwrap();
    /// ```
    #[inline]
    #[must_use]
    pub fn into_inner(self) -> VG {
        self.views
    }

    /// Arrange the views according to the layout properties and return the views as a [`ViewGroup`].
    #[inline]
    #[must_use]
    pub fn arrange(mut self) -> Self {
        // Place first child to the layout's position.
        self.views
            .translate_child(0, self.position - self.views.bounds_of(0).top_left);

        // We can't use `self` because we borrow parts of it mutably.
        LinearLayout {
            position: Point::zero(),
            direction: self.direction,
            views: EmptyViewGroup,
        }
        .arrange_view_group(&mut self.views);

        self
    }

    /// Arrange a [`ViewGroup`] according to the layout properties.
    #[inline]
    pub fn arrange_view_group(&self, view_group: &mut impl ViewGroup) {
        let view_count = view_group.len();

        // measure
        let bounds = view_group.bounds_of(0);
        let position = bounds.top_left;
        let mut size = bounds.size();
        for i in 1..view_count {
            let current_el_size = view_group.bounds_of(i).size();
            size = LD::Secondary::measure(size, current_el_size);
        }

        // arrange
        let mut bounds = Rectangle::new(position, size);
        for i in 0..view_count {
            let offset =
                self.direction
                    .compute_offset(view_group.bounds_of(i), size, bounds, i, view_count);
            view_group.translate_child(i, offset);
            bounds = view_group.bounds_of(i);
        }
    }
}

impl<LD, VG> View for LinearLayout<LD, VG>
where
    LD: Orientation,
    VG: ViewGroup,
{
    #[inline]
    fn translate_impl(&mut self, by: Point) {
        self.position += by;
        View::translate_impl(&mut self.views, by);
    }

    #[inline]
    fn bounds(&self) -> Rectangle {
        let bounds = View::bounds(&self.views);
        let top_left = bounds.top_left;
        let correction = self.position - top_left;

        bounds.translate(correction)
    }
}

impl<LD, VG> ViewGroup for LinearLayout<LD, VG>
where
    LD: Orientation,
    VG: ViewGroup,
{
    #[inline]
    fn len(&self) -> usize {
        self.views.len()
    }

    #[inline]
    fn at(&self, idx: usize) -> &dyn View {
        self.views.at(idx)
    }

    #[inline]
    fn at_mut(&mut self, idx: usize) -> &mut dyn View {
        self.views.at_mut(idx)
    }

    #[inline]
    fn bounds_of(&self, idx: usize) -> Rectangle {
        self.views.bounds_of(idx)
    }

    #[inline]
    fn translate_child(&mut self, idx: usize, by: Point) {
        self.views.translate_child(idx, by)
    }
}

impl<C, LD, VG> Drawable for LinearLayout<LD, VG>
where
    C: PixelColor,
    LD: Orientation,
    VG: ViewGroup + Drawable<Color = C>,
{
    type Color = C;
    type Output = ();

    #[inline]
    fn draw<D>(&self, display: &mut D) -> Result<(), D::Error>
    where
        D: DrawTarget<Color = C>,
    {
        self.views.draw(display)?;
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use crate::{
        layout::linear::{
            spacing::{DistributeFill, FixedMargin},
            LinearLayout,
        },
        object_chain::Chain,
        prelude::*,
    };
    use embedded_graphics::{
        mock_display::MockDisplay,
        pixelcolor::BinaryColor,
        prelude::{Point, Primitive, Size},
        primitives::{Circle, PrimitiveStyle, Rectangle},
        Drawable,
    };

    #[allow(dead_code)]
    fn compile_check() {
        let style = PrimitiveStyle::with_fill(BinaryColor::On);
        let rect = Rectangle::new(Point::zero(), Size::new(10, 20)).into_styled(style);
        let circ = Circle::new(Point::zero(), 10).into_styled(style);
        let _ = LinearLayout::horizontal(Chain::new(rect).append(circ));
    }

    #[test]
    fn layout_size() {
        let rect = Rectangle::new(Point::zero(), Size::new(10, 20));
        let rect2 = Rectangle::new(Point::zero(), Size::new(10, 20));
        let size = LinearLayout::horizontal(Chain::new(rect).append(rect2))
            .arrange()
            .size();

        assert_eq!(Size::new(20, 20), size);

        let rect = Rectangle::new(Point::zero(), Size::new(10, 20));
        let rect2 = Rectangle::new(Point::zero(), Size::new(10, 20));
        let size = LinearLayout::vertical(Chain::new(rect).append(rect2))
            .arrange()
            .size();

        assert_eq!(Size::new(10, 40), size);
    }

    #[test]
    fn layout_arrange_vertical() {
        let mut disp: MockDisplay<BinaryColor> = MockDisplay::new();

        let style = PrimitiveStyle::with_stroke(BinaryColor::On, 1);
        let rect = Rectangle::new(Point::new(10, 30), Size::new(10, 5)).into_styled(style);
        let rect2 = Rectangle::new(Point::new(-50, 10), Size::new(5, 10)).into_styled(style);

        LinearLayout::vertical(Chain::new(rect).append(rect2))
            .arrange()
            .translate(Point::new(1, 2))
            .draw(&mut disp)
            .unwrap();

        assert_eq!(
            disp,
            MockDisplay::from_pattern(&[
                "           ",
                "           ",
                " ##########",
                " #        #",
                " #        #",
                " #        #",
                " ##########",
                " #####     ",
                " #   #     ",
                " #   #     ",
                " #   #     ",
                " #   #     ",
                " #   #     ",
                " #   #     ",
                " #   #     ",
                " #   #     ",
                " #####     ",
            ])
        );
    }

    #[test]
    fn empty_rectangle_takes_up_no_vertical_space() {
        let mut disp: MockDisplay<BinaryColor> = MockDisplay::new();

        let style = PrimitiveStyle::with_stroke(BinaryColor::On, 1);
        let rect = Rectangle::new(Point::new(10, 30), Size::new(10, 5)).into_styled(style);
        let rect_empty = Rectangle::new(Point::new(-50, 10), Size::zero()).into_styled(style);
        let rect2 = Rectangle::new(Point::new(-50, 10), Size::new(5, 10)).into_styled(style);

        LinearLayout::vertical(Chain::new(rect).append(rect_empty).append(rect2))
            .arrange()
            .translate(Point::new(1, 2))
            .draw(&mut disp)
            .unwrap();

        assert_eq!(
            disp,
            MockDisplay::from_pattern(&[
                "           ",
                "           ",
                " ##########",
                " #        #",
                " #        #",
                " #        #",
                " ##########",
                " #####     ",
                " #   #     ",
                " #   #     ",
                " #   #     ",
                " #   #     ",
                " #   #     ",
                " #   #     ",
                " #   #     ",
                " #   #     ",
                " #####     ",
            ])
        );
    }

    #[test]
    fn layout_arrange_vertical_secondary() {
        let mut disp: MockDisplay<BinaryColor> = MockDisplay::new();

        let style = PrimitiveStyle::with_stroke(BinaryColor::On, 1);
        let rect = Rectangle::new(Point::new(10, 30), Size::new(10, 5)).into_styled(style);
        let rect2 = Rectangle::new(Point::new(-50, 10), Size::new(5, 10)).into_styled(style);

        LinearLayout::vertical(Chain::new(rect).append(rect2))
            .with_alignment(horizontal::Right)
            .arrange()
            .translate(Point::new(1, 2))
            .draw(&mut disp)
            .unwrap();

        assert_eq!(
            disp,
            MockDisplay::from_pattern(&[
                "           ",
                "           ",
                " ##########",
                " #        #",
                " #        #",
                " #        #",
                " ##########",
                "      #####",
                "      #   #",
                "      #   #",
                "      #   #",
                "      #   #",
                "      #   #",
                "      #   #",
                "      #   #",
                "      #   #",
                "      #####",
            ])
        );
    }

    #[test]
    fn layout_arrange_horizontal() {
        let mut disp: MockDisplay<BinaryColor> = MockDisplay::new();

        let style = PrimitiveStyle::with_stroke(BinaryColor::On, 1);
        let rect = Rectangle::new(Point::new(10, 30), Size::new(10, 5)).into_styled(style);
        let rect2 = Rectangle::new(Point::new(-50, 10), Size::new(5, 10)).into_styled(style);

        LinearLayout::horizontal(Chain::new(rect).append(rect2))
            .arrange()
            .translate(Point::new(1, 2))
            .draw(&mut disp)
            .unwrap();

        assert_eq!(
            disp,
            MockDisplay::from_pattern(&[
                "                ",
                "                ",
                "           #####",
                "           #   #",
                "           #   #",
                "           #   #",
                "           #   #",
                " ###########   #",
                " #        ##   #",
                " #        ##   #",
                " #        ##   #",
                " ###############",
            ])
        );
    }

    #[test]
    fn empty_rectangle_takes_up_no_horizontal_space() {
        let mut disp: MockDisplay<BinaryColor> = MockDisplay::new();

        let style = PrimitiveStyle::with_stroke(BinaryColor::On, 1);
        let rect = Rectangle::new(Point::new(10, 30), Size::new(10, 5)).into_styled(style);
        let rect_empty = Rectangle::new(Point::new(-50, 10), Size::zero()).into_styled(style);
        let rect2 = Rectangle::new(Point::new(-50, 10), Size::new(5, 10)).into_styled(style);

        LinearLayout::horizontal(Chain::new(rect).append(rect_empty).append(rect2))
            .arrange()
            .translate(Point::new(1, 2))
            .draw(&mut disp)
            .unwrap();

        assert_eq!(
            disp,
            MockDisplay::from_pattern(&[
                "                ",
                "                ",
                "           #####",
                "           #   #",
                "           #   #",
                "           #   #",
                "           #   #",
                " ###########   #",
                " #        ##   #",
                " #        ##   #",
                " #        ##   #",
                " ###############",
            ])
        );
    }

    #[test]
    fn layout_arrange_horizontal_secondary() {
        let mut disp: MockDisplay<BinaryColor> = MockDisplay::new();

        let style = PrimitiveStyle::with_stroke(BinaryColor::On, 1);
        let rect = Rectangle::new(Point::new(10, 30), Size::new(10, 5)).into_styled(style);
        let rect2 = Rectangle::new(Point::new(-50, 10), Size::new(5, 10)).into_styled(style);

        LinearLayout::horizontal(Chain::new(rect).append(rect2))
            .with_alignment(vertical::Top)
            .arrange()
            .translate(Point::new(1, 2))
            .draw(&mut disp)
            .unwrap();

        assert_eq!(
            disp,
            MockDisplay::from_pattern(&[
                "                ",
                "                ",
                " ###############",
                " #        ##   #",
                " #        ##   #",
                " #        ##   #",
                " ###########   #",
                "           #   #",
                "           #   #",
                "           #   #",
                "           #   #",
                "           #####",
            ])
        );
    }

    #[test]
    fn layout_spacing_size() {
        let style = PrimitiveStyle::with_stroke(BinaryColor::On, 1);

        let rect = Rectangle::new(Point::new(10, 30), Size::new(10, 5)).into_styled(style);
        let rect2 = Rectangle::new(Point::new(-50, 10), Size::new(5, 10)).into_styled(style);

        let size = LinearLayout::horizontal(Chain::new(rect).append(rect2))
            .with_spacing(FixedMargin(2))
            .with_alignment(vertical::Top)
            .arrange()
            .size();

        assert_eq!(Size::new(17, 10), size);

        let size = LinearLayout::vertical(Chain::new(rect).append(rect2))
            .with_spacing(FixedMargin(2))
            .arrange()
            .size();

        assert_eq!(Size::new(10, 17), size);
    }

    #[test]
    fn layout_spacing() {
        let mut disp: MockDisplay<BinaryColor> = MockDisplay::new();

        let style = PrimitiveStyle::with_stroke(BinaryColor::On, 1);

        let rect = Rectangle::new(Point::new(10, 30), Size::new(10, 5)).into_styled(style);
        let rect2 = Rectangle::new(Point::new(-50, 10), Size::new(5, 10)).into_styled(style);

        LinearLayout::horizontal(Chain::new(rect).append(rect2))
            .with_spacing(FixedMargin(2))
            .with_alignment(vertical::Top)
            .arrange()
            .translate(Point::new(1, 2))
            .draw(&mut disp)
            .unwrap();

        assert_eq!(
            disp,
            MockDisplay::from_pattern(&[
                "                  ",
                "                  ",
                " ##########  #####",
                " #        #  #   #",
                " #        #  #   #",
                " #        #  #   #",
                " ##########  #   #",
                "             #   #",
                "             #   #",
                "             #   #",
                "             #   #",
                "             #####",
            ])
        );
    }

    #[test]
    fn layout_spacing_distribute_overflow() {
        let style = PrimitiveStyle::with_stroke(BinaryColor::On, 1);

        let rect = Rectangle::new(Point::zero(), Size::new(5, 5)).into_styled(style);

        let layout = LinearLayout::horizontal(Chain::new(rect).append(rect).append(rect))
            .with_spacing(DistributeFill(11))
            .with_alignment(vertical::TopToBottom)
            .arrange();

        assert_eq!(Size::new(11, 15), layout.size());

        let mut disp: MockDisplay<BinaryColor> = MockDisplay::new();

        layout.arrange().draw(&mut disp).unwrap();
        assert_eq!(
            disp,
            MockDisplay::from_pattern(&[
                "#####      ",
                "#   #      ",
                "#   #      ",
                "#   #      ",
                "#####      ",
                "   #####   ",
                "   #   #   ",
                "   #   #   ",
                "   #   #   ",
                "   #####   ",
                "      #####",
                "      #   #",
                "      #   #",
                "      #   #",
                "      #####",
            ])
        );
    }

    #[test]
    fn layout_spacing_distribute_fill() {
        let style = PrimitiveStyle::with_stroke(BinaryColor::On, 1);

        let rect = Rectangle::new(Point::zero(), Size::new(2, 2)).into_styled(style);

        let view_group =
            LinearLayout::vertical(Chain::new(rect).append(rect).append(rect).append(rect))
                .with_spacing(DistributeFill(18))
                .arrange();

        let mut disp: MockDisplay<BinaryColor> = MockDisplay::new();

        view_group.draw(&mut disp).unwrap();
        assert_eq!(
            disp,
            MockDisplay::from_pattern(&[
                "##            ",
                "##            ",
                "              ",
                "              ",
                "              ",
                "              ",
                "##            ",
                "##            ",
                "              ",
                "              ",
                "              ",
                "##            ",
                "##            ",
                "              ",
                "              ",
                "              ",
                "##            ",
                "##            "
            ])
        );
    }

    #[test]
    fn layout_size_independent_of_view_location() {
        let rect = Rectangle::new(Point::zero(), Size::new(10, 20));
        let rect2 = Rectangle::new(Point::zero(), Size::new(10, 20));

        let size1 = LinearLayout::horizontal(Chain::new(rect).append(rect2))
            .arrange()
            .bounds()
            .size();

        let rect = rect.translate(Point::new(30, 50));

        let size2 = LinearLayout::horizontal(Chain::new(rect).append(rect2))
            .arrange()
            .bounds()
            .size();

        assert_eq!(size1, size2);
    }
}