rat_widget/layout/
layout_form.rs

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
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
use crate::layout::generic_layout::GenericLayout;
use crate::util::block_padding;
use ratatui::layout::{Flex, Rect, Size};
use ratatui::widgets::{Block, Padding};
use std::borrow::Cow;
use std::cmp::{max, min};
use std::fmt::Debug;
use std::hash::Hash;
use std::ops::Range;

/// Label constraints.
///
/// Any given widths and heights will be reduced if there is not enough space.
#[derive(Debug, Default)]
pub enum FormLabel {
    /// No label, just the widget.
    #[default]
    None,
    /// Label by example.
    /// Line breaks in the text don't work.
    ///
    /// Will create a label area with the max width of all labels and a height of 1.
    /// The area will be top aligned with the widget.
    Str(&'static str),
    /// Label by example.
    /// Line breaks in the text don't work.
    ///
    /// Will create a label area with the max width of all labels and a height of 1.
    /// The area will be top aligned with the widget.
    String(String),
    /// Label by width.
    ///
    /// Will create a label area with the max width of all labels and a height of 1.
    /// The area will be top aligned with the widget.
    ///
    ///  __unit: cols__
    Width(u16),
    /// Label by height+width.
    ///
    /// Will create a label area with the max width of all labels and a height of rows.
    /// The area will be top aligned with the widget.
    ///
    ///  __unit: cols,rows__
    Size(u16, u16),
}

/// Widget constraints.
///
/// Any given widths and heights will be reduced if there is not enough space.
#[derive(Debug, Default)]
pub enum FormWidget {
    /// No widget, just a label.
    #[default]
    None,
    /// Widget aligned with the label.
    ///
    /// Will create an area with the given width and height 1.
    /// The area will be top aligned with the label.
    ///
    /// __unit: cols__
    Width(u16),
    /// Widget aligned with the label.
    ///
    /// Will create an area with the given width and height.
    /// The area will be top aligned with the label.
    ///
    /// __unit: cols,rows__
    Size(u16, u16),
    /// Widget aligned with the label.
    ///
    /// The widget will start with the given number of rows.
    /// If there is remaining vertical space left after a page-break this
    /// widget will get it. If there are more than one such widget
    /// the remainder will be evenly distributed.
    ///
    /// Will create an area with the given width and height.
    /// The area will be top aligned with the label.
    ///
    /// __unit: cols,rows__
    StretchY(u16, u16),
    /// Fill the total width of labels+widget.
    /// Any label that is not FormLabel::None will be placed above
    /// the widget.
    ///
    /// Will create an area with the full width of labels + widgets
    /// and the given height.
    ///
    /// __unit: cols,rows__
    Wide(u16, u16),

    /// Stretch the widget to the maximum extent horizontally.
    ///
    /// Will create an area with the full width of the given area,
    /// still respecting labels, borders and blocks.
    ///
    /// __unit: cols,rows__
    StretchX(u16, u16),

    /// Stretch the widget to the maximum extend horizontally,
    /// including the label. (rows).
    ///
    /// Will create an area with the full width of the given area,
    /// still respecting borders and blocks.
    ///
    /// __unit: cols,rows__
    WideStretchX(u16, u16),

    /// Stretch the widget to the maximum extent horizontally and vertically.
    ///
    /// The widget will start with the given number of rows.
    /// If there is remaining vertical space left after a page-break this
    /// widget will get it. If there are more than one such widget
    /// the remainder will be evenly distributed.
    ///
    /// __unit: cols,rows__
    StretchXY(u16, u16),

    /// Stretch the widget to the maximum extent horizontally and vertically,
    /// including the label.
    ///
    /// The widget will start with the given number of rows.
    /// If there is remaining vertical space left after a page-break this
    /// widget will get it. If there are more than one such widget
    /// the remainder will be evenly distributed.
    ///
    /// __unit: rows__
    WideStretchXY(u16, u16),
}

/// Create a layout with a single column of label+widget.
///
/// There are a number of possible constraints that influence
/// the exact layout: [FormLabel] and [FormWidget].
///
/// * This layout can page break the form, if there is not enough
///   space on one page. This can be used with [SinglePager](crate::pager::SinglePager)
///   and friends.
///
/// * Or it can generate an endless layout that will be used
///   with scrolling logic like [Clipper](crate::clipper::Clipper).
///
/// * There is currently no functionality to shrink-fit the layout
///   to a given page size.
///
/// The widgets can be grouped together and a [Block] can be set
/// to highlight this grouping. Groups can cascade. Groups will
/// be correctly broken by the page break logic. There is no
/// special handling for orphans and widows.
///
/// Other features:
/// * Spacing/Line spacing.
/// * Supports Flex.
/// * Manual page breaks.
///
#[derive(Debug)]
pub struct LayoutForm<W>
where
    W: Eq + Hash + Clone + Debug,
{
    /// Column spacing.
    spacing: u16,
    /// Line spacing.
    line_spacing: u16,
    /// Mirror the borders between even/odd pages.
    mirror: bool,
    /// Flex
    flex: Flex,
    /// Areas
    widgets: Vec<WidgetDef<W>>,
    /// Containers/Blocks
    blocks: Vec<BlockDef>,
    /// Page breaks.
    page_breaks: Vec<usize>,

    /// maximum width
    max_label: u16,
    max_widget: u16,

    /// maximum padding due to containers.
    max_left_padding: u16,
    max_right_padding: u16,

    /// container padding, accumulated.
    /// current active top-padding. valid for 1 widget.
    c_top: u16,
    /// current active bottom-padding.
    /// valid for every contained widget to calculate a page-break.
    c_bottom: u16,
    /// current left indent.
    c_left: u16,
    /// current right indent.
    c_right: u16,
}

#[derive(Debug)]
struct WidgetDef<W>
where
    W: Debug + Clone,
{
    // widget id
    id: W,
    // label constraint
    label: FormLabel,
    // label text
    label_str: Option<Cow<'static, str>>,
    // widget constraint
    widget: FormWidget,
    // effective top border due to container padding.
    top_border: u16,
    // effective bottom border due to container padding.
    bottom_border: u16,
    // optional bottom border. all containers that
    // do not end exactly at this widget contribute.
    opt_bottom_border: u16,
}

/// Tag for a group/block.
#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
pub struct BlockTag(usize);

#[derive(Debug)]
struct BlockDef {
    id: BlockTag,
    // block
    block: Option<Block<'static>>,
    // padding due to block
    padding: Padding,
    // under construction
    constructing: bool,
    // range into the widget vec
    range: Range<usize>,
    // calculated container area.
    area: Rect,
}

#[derive(Debug)]
struct BlockOut {
    // block
    block: Option<Block<'static>>,
    // area
    area: Rect,
}

// effective positions for layout construction.
#[derive(Debug, Default, Clone, Copy)]
struct Positions {
    // label position
    label_x: u16,
    // label width, max.
    label_width: u16,
    // widget position
    widget_x: u16,
    // widget width, max.
    widget_width: u16,
    // left position for container blocks.
    container_left: u16,
    // right position for container blocks.
    container_right: u16,
    // total width label+spacing+widget
    total_width: u16,
}

// Current page data
#[derive(Debug, Default, Clone, Copy)]
struct Page {
    // page width
    #[allow(dead_code)]
    width: u16,
    // page height
    height: u16,
    // top border
    top: u16,
    // bottom border
    bottom: u16,
    // maximum widget + label height
    max_height: u16,

    // page number
    page_no: u16,
    // page start y
    y_page: u16,
    // current y
    y: u16,

    // current line spacing.
    // set to zero on page-break and restored after the first widget.
    line_spacing: u16,

    // container left pos
    container_left: u16,
    // container right pos
    container_right: u16,
}

impl BlockDef {
    fn as_out(&self) -> BlockOut {
        BlockOut {
            block: self.block.clone(),
            area: self.area,
        }
    }
}

impl FormWidget {
    #[inline(always)]
    fn is_stretch_y(&self) -> bool {
        match self {
            FormWidget::None => false,
            FormWidget::Width(_) => false,
            FormWidget::Size(_, _) => false,
            FormWidget::Wide(_, _) => false,
            FormWidget::StretchX(_, _) => false,
            FormWidget::WideStretchX(_, _) => false,
            FormWidget::StretchXY(_, _) => true,
            FormWidget::WideStretchXY(_, _) => true,
            FormWidget::StretchY(_, _) => true,
        }
    }
}

impl<W> Default for LayoutForm<W>
where
    W: Eq + Clone + Hash + Debug,
{
    fn default() -> Self {
        Self {
            spacing: 1,
            line_spacing: Default::default(),
            mirror: Default::default(),
            flex: Default::default(),
            widgets: Default::default(),
            page_breaks: Default::default(),
            max_label: Default::default(),
            max_widget: Default::default(),
            blocks: Default::default(),
            max_left_padding: Default::default(),
            max_right_padding: Default::default(),
            c_top: Default::default(),
            c_bottom: Default::default(),
            c_left: Default::default(),
            c_right: Default::default(),
        }
    }
}

impl<W> LayoutForm<W>
where
    W: Eq + Hash + Clone + Debug,
{
    pub fn new() -> Self {
        Self::default()
    }

    /// Spacing between label and widget.
    #[inline]
    pub fn spacing(mut self, spacing: u16) -> Self {
        self.spacing = spacing;
        self
    }

    /// Empty lines between widgets.
    #[inline]
    pub fn line_spacing(mut self, spacing: u16) -> Self {
        self.line_spacing = spacing;
        self
    }

    /// Mirror the border given to layout between even and odd pages.
    /// The layout starts with page 0 which is even.
    #[inline]
    pub fn mirror_odd_border(mut self) -> Self {
        self.mirror = true;
        self
    }

    /// Flex.
    #[inline]
    pub fn flex(mut self, flex: Flex) -> Self {
        self.flex = flex;
        self
    }

    /// Set a reference label width
    pub fn min_label(mut self, width: u16) -> Self {
        self.max_label = width;
        self
    }

    /// Set a reference widget width
    pub fn min_widget(mut self, width: u16) -> Self {
        self.max_widget = width;
        self
    }

    /// Start a group/block.
    ///
    /// This will create a block that covers all widgets added
    /// before calling `end()`.
    ///
    /// Groups/blocks can be stacked, but they cannot interleave.
    /// An inner group/block must be closed before an outer one.
    pub fn start(&mut self, block: Option<Block<'static>>) -> BlockTag {
        let max_idx = self.widgets.len();
        let padding = block_padding(&block);

        let tag = BlockTag(self.blocks.len());
        self.blocks.push(BlockDef {
            id: tag,
            block,
            padding,
            constructing: true,
            range: max_idx..max_idx,
            area: Rect::default(),
        });

        self.c_top += padding.top;
        self.c_bottom += padding.bottom;
        self.c_left += padding.left;
        self.c_right += padding.right;

        self.max_left_padding = max(self.max_left_padding, self.c_left);
        self.max_right_padding = max(self.max_right_padding, self.c_right);

        tag
    }

    /// Closes the group/block with the given tag.
    ///
    /// __Panic__
    /// Groups must be closed in reverse start order, otherwise
    /// this function will panic. It will also panic if there
    /// is no open group for the given tag.
    pub fn end(&mut self, tag: BlockTag) {
        let max = self.widgets.len();
        for cc in self.blocks.iter_mut().rev() {
            if cc.id == tag && cc.constructing {
                cc.range.end = max;
                cc.constructing = false;

                // might have been used by a widget.
                if self.c_top > 0 {
                    self.c_top -= cc.padding.top;
                }
                self.c_bottom -= cc.padding.bottom;
                self.c_left -= cc.padding.left;
                self.c_right -= cc.padding.right;

                if let Some(last) = self.widgets.last_mut() {
                    last.opt_bottom_border -= cc.padding.bottom;
                }

                return;
            }
            if cc.constructing {
                panic!("Unclosed container {:?}", cc.id);
            }
        }

        panic!("No open container.");
    }

    fn validate_containers(&self) {
        for cc in self.blocks.iter() {
            if cc.constructing {
                panic!("Unclosed container {:?}", cc.id);
            }
        }
    }

    /// Add label + widget constraint.
    /// Key must be a unique identifier.
    pub fn widget(&mut self, key: W, label: FormLabel, widget: FormWidget) {
        // split label by sample
        let (label, label_str) = match label {
            FormLabel::Str(s) => {
                let width = unicode_display_width::width(s) as u16;
                (FormLabel::Width(width), Some(Cow::Borrowed(s)))
            }
            FormLabel::String(s) => {
                let width = unicode_display_width::width(&s) as u16;
                (FormLabel::Width(width), Some(Cow::Owned(s)))
            }
            FormLabel::Width(w) => (FormLabel::Width(w), None),
            FormLabel::Size(w, h) => (FormLabel::Size(w, h), None),
            FormLabel::None => (FormLabel::None, None),
        };

        let w = match &label {
            FormLabel::None => 0,
            FormLabel::Str(_) | FormLabel::String(_) => {
                unreachable!()
            }
            FormLabel::Width(w) => *w,
            FormLabel::Size(w, _) => *w,
        };
        self.max_label = max(self.max_label, w);

        let w = match &widget {
            FormWidget::None => 0,
            FormWidget::Width(w) => *w,
            FormWidget::Size(w, _) => *w,
            FormWidget::StretchY(w, _) => *w,
            FormWidget::Wide(w, _) => *w,
            FormWidget::StretchX(w, _) => *w,
            FormWidget::WideStretchX(w, _) => *w,
            FormWidget::StretchXY(w, _) => *w,
            FormWidget::WideStretchXY(w, _) => *w,
        };
        self.max_widget = max(self.max_widget, w);

        self.widgets.push(WidgetDef {
            id: key,
            label,
            label_str,
            widget,
            top_border: self.c_top,
            bottom_border: self.c_bottom,
            opt_bottom_border: self.c_bottom,
        });

        // top padding is only used once.
        // bottom padding may apply for every contained widget
        // in case of page-break.
        self.c_top = 0;
    }

    /// Add a manual page break after the last widget.
    ///
    /// This will panic if the widget list is empty.
    pub fn page_break(&mut self) {
        self.page_breaks.push(self.widgets.len() - 1);
    }

    // Adjust widths to the available sapce.
    fn adjust_widths(&mut self, page_width: u16, border: Padding) {
        // cut excess
        let page_width = page_width.saturating_sub(
            border.left + self.max_left_padding + self.max_right_padding + border.right,
        );
        if self.max_label + self.spacing + self.max_widget > page_width {
            let mut reduce = self.max_label + self.spacing + self.max_widget - page_width;

            if self.spacing > reduce {
                self.spacing -= reduce;
                reduce = 0;
            } else {
                reduce -= self.spacing;
                self.spacing = 0;
            }
            if self.max_label > 5 {
                if self.max_label - 5 > reduce {
                    self.max_label -= reduce;
                    reduce = 0;
                } else {
                    reduce -= self.max_label - 5;
                    self.max_label = 5;
                }
            }
            if self.max_widget > 5 {
                if self.max_widget - 5 > reduce {
                    self.max_widget -= reduce;
                    reduce = 0;
                } else {
                    reduce -= self.max_widget - 5;
                    self.max_widget = 5;
                }
            }
            if self.max_label > reduce {
                self.max_label -= reduce;
                reduce = 0;
            } else {
                reduce -= self.max_label;
                self.max_label = 0;
            }
            if self.max_widget > reduce {
                self.max_widget -= reduce;
                // reduce = 0;
            } else {
                // reduce -= max_widget;
                self.max_widget = 0;
            }
        }
    }

    // Find horizontal positions for label and widget.
    fn find_pos(&self, layout_width: u16, border: Padding) -> Positions {
        let label_x;
        let widget_x;
        let container_left;
        let container_right;
        let total_width;

        match self.flex {
            Flex::Legacy => {
                label_x = border.left + self.max_left_padding;
                widget_x = label_x + self.max_label + self.spacing;

                container_left = label_x.saturating_sub(self.max_left_padding);
                container_right = layout_width.saturating_sub(border.right);

                total_width = self.max_label + self.spacing + self.max_widget;
            }
            Flex::Start => {
                label_x = border.left + self.max_left_padding;
                widget_x = label_x + self.max_label + self.spacing;

                container_left = label_x.saturating_sub(self.max_left_padding);
                container_right = widget_x + self.max_widget + self.max_right_padding;

                total_width = self.max_label + self.spacing + self.max_widget;
            }
            Flex::Center => {
                let rest = layout_width.saturating_sub(
                    border.left
                        + self.max_left_padding
                        + self.max_label
                        + self.spacing
                        + self.max_widget
                        + self.max_right_padding
                        + border.right,
                );
                label_x = border.left + self.max_left_padding + rest / 2;
                widget_x = label_x + self.max_label + self.spacing;

                container_left = label_x.saturating_sub(self.max_left_padding);
                container_right = widget_x + self.max_widget + self.max_right_padding;

                total_width = self.max_label + self.spacing + self.max_widget;
            }
            Flex::End => {
                widget_x = layout_width
                    .saturating_sub(border.right + self.max_right_padding + self.max_widget);
                label_x = widget_x.saturating_sub(self.spacing + self.max_label);

                container_left = label_x.saturating_sub(self.max_left_padding);
                container_right = layout_width.saturating_sub(border.right);

                total_width = self.max_label + self.spacing + self.max_widget;
            }
            Flex::SpaceAround => {
                let rest = layout_width.saturating_sub(
                    border.left
                        + self.max_left_padding
                        + self.max_label
                        + self.max_widget
                        + self.max_right_padding
                        + border.right,
                );
                let spacing = rest / 3;

                label_x = border.left + self.max_left_padding + spacing;
                widget_x = label_x + self.max_label + spacing;

                container_left = border.left;
                container_right = layout_width.saturating_sub(border.right);

                total_width = self.max_label + spacing + self.max_widget;
            }
            Flex::SpaceBetween => {
                label_x = border.left + self.max_left_padding;
                widget_x = layout_width
                    .saturating_sub(border.right + self.max_right_padding + self.max_widget);

                container_left = label_x.saturating_sub(self.max_left_padding);
                container_right = layout_width.saturating_sub(border.right);

                total_width = layout_width.saturating_sub(
                    border.left + self.max_left_padding + border.right + self.max_right_padding,
                );
            }
        }

        Positions {
            container_left,
            label_x,
            label_width: self.max_label,
            widget_x,
            widget_width: self.max_widget,
            container_right,
            total_width,
        }
    }

    /// Calculate a layout without page-breaks using the given layout-width and padding.
    #[inline(always)]
    pub fn endless(self, width: u16, border: Padding) -> GenericLayout<W> {
        self._layout::<true>(Size::new(width, u16::MAX), border)
    }

    /// Calculate the layout for the given page size and padding.
    #[inline(always)]
    pub fn paged(self, page: Size, border: Padding) -> GenericLayout<W> {
        self._layout::<false>(page, border)
    }

    /// Calculate the layout for the given page size and padding.
    fn _layout<const ENDLESS: bool>(mut self, page: Size, border: Padding) -> GenericLayout<W> {
        self.validate_containers();
        self.adjust_widths(page.width, border);
        let pos_even = self.find_pos(page.width, border);
        let pos_odd = if self.mirror {
            self.find_pos(
                page.width,
                Padding::new(border.right, border.left, border.top, border.bottom),
            )
        } else {
            pos_even
        };

        let mut gen_layout = GenericLayout::with_capacity(self.widgets.len(), self.blocks.len());
        gen_layout.set_page_size(page);

        let mut tmp = Vec::new();

        let mut pos = &pos_even;
        let mut page_bak;
        let mut page = Page {
            width: page.width,
            height: page.height,
            top: border.top,
            bottom: border.bottom,
            max_height: page.height.saturating_sub(border.top + border.bottom),

            page_no: 0,
            y_page: 0,
            y: border.top,

            line_spacing: 0,

            container_left: pos.container_left,
            container_right: pos.container_right,
        };
        // indexes into gen_layout for any generated areas that need y adjustment.
        let mut stretch_y = Vec::new();

        for (idx, widget) in self.widgets.into_iter().enumerate() {
            // safe point
            page_bak = page;

            // line spacing
            page.next_widget(self.line_spacing);
            // start container
            for cc in self.blocks.iter_mut() {
                if cc.range.start == idx {
                    page.start_container(cc);
                }
            }
            // get areas + advance
            let (mut label_area, mut widget_area) = page.widget_area(&widget, pos);
            // end and push containers
            for cc in self.blocks.iter_mut().rev() {
                if idx + 1 == cc.range.end {
                    page.end_container(cc);
                    tmp.push(cc.as_out());
                }
            }

            let break_overflow = if ENDLESS {
                false
            } else {
                page.y.saturating_add(widget.opt_bottom_border)
                    >= page
                        .y_page
                        .saturating_add(page.height.saturating_sub(page.bottom))
            };
            let break_manual = if ENDLESS {
                false
            } else {
                self.page_breaks.contains(&idx)
            };

            // page overflow induces page-break
            if break_overflow {
                // reset safe-point
                page = page_bak;
                // any container areas are invalid
                tmp.clear();

                // close and push containers
                // rev() ensures closing from innermost to outermost container.
                for cc in self.blocks.iter_mut().rev() {
                    if idx > cc.range.start && idx < cc.range.end {
                        page.end_container(cc);
                        tmp.push(cc.as_out());
                        // restart on next page
                        cc.range.start = idx;
                    }
                }
                // pop reverts the ordering for render
                while let Some(cc) = tmp.pop() {
                    gen_layout.add_block(cc.area, cc.block);
                }

                // modify layout to add y-stretch
                Self::adjust_y_stretch(&page, &mut stretch_y, &mut gen_layout);

                // advance
                pos = page.next_page(&pos_even, &pos_odd);

                // redo current widget

                // line spacing
                page.next_widget(self.line_spacing);
                // start container
                for cc in self.blocks.iter_mut() {
                    if idx == cc.range.start {
                        page.start_container(cc);
                    }
                }
                // get areas + advance
                (label_area, widget_area) = page.widget_area(&widget, pos);
                // end and push containers
                // rev() ensures closing from innermost to outermost container.
                for cc in self.blocks.iter_mut().rev() {
                    if idx + 1 == cc.range.end {
                        page.end_container(cc);
                        tmp.push(cc.as_out());
                    }
                }
            }

            // remember stretch widget.
            if widget.widget.is_stretch_y() && !ENDLESS {
                stretch_y.push(gen_layout.widget_len());
            }
            // add label + widget
            gen_layout.add(widget.id.clone(), widget_area, widget.label_str, label_area);
            // pop reverts the ordering for render
            while let Some(cc) = tmp.pop() {
                gen_layout.add_block(cc.area, cc.block);
            }

            if break_manual {
                // page-break after widget

                // close and push containers
                // rev() ensures closing from innermost to outermost container.
                for cc in self.blocks.iter_mut().rev() {
                    if idx + 1 > cc.range.start && idx + 1 < cc.range.end {
                        page.end_container(cc);
                        tmp.push(cc.as_out());
                        // restart on next page
                        cc.range.start = idx + 1;
                    }
                }
                // pop reverts the ordering for render
                while let Some(cc) = tmp.pop() {
                    gen_layout.add_block(cc.area, cc.block);
                }

                // modify layout to add y-stretch
                Self::adjust_y_stretch(&page, &mut stretch_y, &mut gen_layout);

                // advance
                pos = page.next_page(&pos_even, &pos_odd);
            }
        }

        // modify layout to add y-stretch
        Self::adjust_y_stretch(&page, &mut stretch_y, &mut gen_layout);

        gen_layout.set_page_count((page.page_no + 1) as usize);

        gen_layout
    }

    // some stretching
    // stretch_y contains the recorded widget indexes that need adjustment.
    fn adjust_y_stretch(
        page: &Page,
        stretch_y: &mut Vec<usize>,
        gen_layout: &mut GenericLayout<W>,
    ) {
        let bottom_y = page
            .y_page
            .saturating_add(page.height.saturating_sub(page.bottom));

        let mut remainder = bottom_y.saturating_sub(page.y);
        if remainder == 0 {
            return;
        }
        let mut n = stretch_y.len() as u16;

        for y_idx in stretch_y.drain(..) {
            // calculate stretch as a new fraction every time.
            // this makes a better distribution.
            let stretch = remainder / n;
            remainder -= stretch;
            n -= 1;

            // stretch
            let mut area = gen_layout.widget(y_idx);
            let test_y = area.bottom();
            area.height += stretch;
            gen_layout.set_widget(y_idx, area);

            // shift everything after
            for idx in y_idx + 1..gen_layout.widget_len() {
                let mut area = gen_layout.widget(idx);
                if area.y >= test_y {
                    area.y += stretch;
                }
                gen_layout.set_widget(idx, area);

                let mut area = gen_layout.label(idx);
                if area.y >= test_y {
                    area.y += stretch;
                }
                gen_layout.set_label(idx, area);
            }

            // containers may be shifted or stretched.
            for idx in 0..gen_layout.block_len() {
                let mut area = gen_layout.block_area(idx);
                if area.y >= test_y {
                    area.y += stretch;
                }
                // may stretch the container
                if area.y <= test_y && area.bottom() > test_y {
                    area.height += stretch;
                }
                gen_layout.set_block_area(idx, area);
            }
        }
    }
}

impl Page {
    fn widget_area<W: Debug + Clone>(
        &mut self,
        widget: &WidgetDef<W>,
        pos: &Positions,
    ) -> (Rect, Rect) {
        let stacked = matches!(
            widget.widget,
            FormWidget::Wide(_, _)
                | FormWidget::WideStretchX(_, _)
                | FormWidget::WideStretchXY(_, _)
        );

        let mut label_height = match &widget.label {
            FormLabel::None => 0,
            FormLabel::Str(_) | FormLabel::String(_) => unreachable!(),
            FormLabel::Width(_) => 1,
            FormLabel::Size(_, h) => *h,
        };

        let mut widget_height = match &widget.widget {
            FormWidget::None => 0,
            FormWidget::Width(_) => 1,
            FormWidget::Size(_, h) => *h,
            FormWidget::StretchY(_, h) => *h,
            FormWidget::Wide(_, h) => *h,
            FormWidget::StretchX(_, h) => *h,
            FormWidget::WideStretchX(_, h) => *h,
            FormWidget::StretchXY(_, h) => *h,
            FormWidget::WideStretchXY(_, h) => *h,
        };

        let stretch_width = self.container_right.saturating_sub(pos.widget_x);
        let total_stretch_width = self.container_right.saturating_sub(pos.label_x);

        if stacked {
            let max_height = self
                .max_height
                .saturating_sub(widget.top_border + widget.bottom_border);
            if label_height + widget_height > max_height {
                label_height = min(1, max_height.saturating_sub(widget_height));
            }
            if label_height + widget_height > max_height {
                widget_height = min(1, max_height.saturating_sub(label_height));
            }
            if label_height + widget_height > max_height {
                label_height = 0;
            }
            if label_height + widget_height > max_height {
                widget_height = max_height;
            }

            let mut label_area = match &widget.label {
                FormLabel::None => Rect::default(),
                FormLabel::Str(_) | FormLabel::String(_) => {
                    unreachable!()
                }
                FormLabel::Width(_) => {
                    Rect::new(pos.label_x, self.y, pos.label_width, label_height)
                }
                FormLabel::Size(_, _) => {
                    Rect::new(pos.label_x, self.y, pos.label_width, label_height)
                }
            };
            match &widget.widget {
                FormWidget::Wide(_, _) => label_area.width = pos.total_width,
                FormWidget::WideStretchX(_, _) => label_area.width = total_stretch_width,
                FormWidget::WideStretchXY(_, _) => label_area.width = total_stretch_width,
                _ => {}
            }

            self.y = self.y.saturating_add(label_area.height);

            let widget_area = match &widget.widget {
                FormWidget::None => Rect::default(),
                FormWidget::Width(w) => Rect::new(
                    pos.widget_x,
                    self.y,
                    min(*w, pos.widget_width),
                    widget_height,
                ),
                FormWidget::Size(w, _) => Rect::new(
                    pos.widget_x,
                    self.y,
                    min(*w, pos.widget_width),
                    widget_height,
                ),
                FormWidget::StretchY(w, _) => Rect::new(
                    pos.widget_x,
                    self.y,
                    min(*w, pos.widget_width),
                    widget_height,
                ),
                FormWidget::Wide(_, _) => {
                    Rect::new(pos.label_x, self.y, pos.total_width, widget_height)
                }
                FormWidget::StretchX(_, _) => {
                    Rect::new(pos.widget_x, self.y, stretch_width, widget_height)
                }
                FormWidget::WideStretchX(_, _) => {
                    Rect::new(pos.label_x, self.y, total_stretch_width, widget_height)
                }
                FormWidget::StretchXY(_, _) => {
                    Rect::new(pos.widget_x, self.y, stretch_width, widget_height)
                }
                FormWidget::WideStretchXY(_, _) => {
                    Rect::new(pos.label_x, self.y, total_stretch_width, widget_height)
                }
            };

            self.y = self.y.saturating_add(widget_area.height);

            (label_area, widget_area)
        } else {
            let max_height = self
                .max_height
                .saturating_sub(widget.top_border + widget.bottom_border);
            label_height = min(label_height, max_height);
            widget_height = min(widget_height, max_height);

            let label_area = match &widget.label {
                FormLabel::None => Rect::default(),
                FormLabel::Str(_) | FormLabel::String(_) => {
                    unreachable!()
                }
                FormLabel::Width(_) => {
                    Rect::new(pos.label_x, self.y, pos.label_width, label_height)
                }
                FormLabel::Size(_, _) => {
                    Rect::new(pos.label_x, self.y, pos.label_width, label_height)
                }
            };

            let widget_area = match &widget.widget {
                FormWidget::None => Rect::default(),
                FormWidget::Width(w) => Rect::new(
                    pos.widget_x,
                    self.y,
                    min(*w, pos.widget_width),
                    widget_height,
                ),
                FormWidget::Size(w, _) => Rect::new(
                    pos.widget_x,
                    self.y,
                    min(*w, pos.widget_width),
                    widget_height,
                ),
                FormWidget::StretchY(w, _) => Rect::new(
                    pos.widget_x,
                    self.y,
                    min(*w, pos.widget_width),
                    widget_height,
                ),
                FormWidget::Wide(_, _) => {
                    unreachable!()
                }
                FormWidget::StretchX(_, _) => {
                    Rect::new(pos.widget_x, self.y, stretch_width, widget_height)
                }
                FormWidget::WideStretchX(_, _) => {
                    unreachable!()
                }
                FormWidget::StretchXY(_, _) => {
                    Rect::new(pos.widget_x, self.y, stretch_width, widget_height)
                }
                FormWidget::WideStretchXY(_, _) => {
                    unreachable!()
                }
            };

            self.y = self
                .y
                .saturating_add(max(label_area.height, widget_area.height));

            (label_area, widget_area)
        }
    }

    // advance to next page
    fn next_page<'a>(&mut self, pos_even: &'a Positions, pos_odd: &'a Positions) -> &'a Positions {
        self.page_no += 1;
        self.y_page = self.page_no.saturating_mul(self.height);
        self.y = self.y_page.saturating_add(self.top);
        self.line_spacing = 0;

        if self.page_no % 2 == 0 {
            pos_even
        } else {
            pos_odd
        }
    }

    // advance to next widget
    fn next_widget(&mut self, adjust_spacing: u16) {
        self.y = self.y.saturating_add(self.line_spacing);
        self.line_spacing = adjust_spacing;
    }

    // close the given container
    fn end_container(&mut self, cc: &mut BlockDef) {
        self.y = self.y.saturating_add(cc.padding.bottom);
        self.container_left = self.container_left.saturating_sub(cc.padding.left);
        self.container_right = self.container_right.saturating_add(cc.padding.right);

        cc.area.height = self.y.saturating_sub(cc.area.y);
    }

    // open the given container
    fn start_container(&mut self, cc: &mut BlockDef) {
        cc.area.x = self.container_left;
        cc.area.width = self.container_right.saturating_sub(self.container_left);
        cc.area.y = self.y;

        self.y = self.y.saturating_add(cc.padding.top);
        self.container_left = self.container_left.saturating_add(cc.padding.left);
        self.container_right = self.container_right.saturating_sub(cc.padding.right);
    }
}