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
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
use std::time::Instant;
#[cfg(feature = "layout-cache")]
use std::{cell::RefCell, collections::HashMap};
use cassowary::strength::{MEDIUM, REQUIRED, STRONG, WEAK};
use cassowary::WeightedRelation::*;
use cassowary::{Constraint as CassowaryConstraint, Solver};
use crate::layout::elements::{LineBox, Variables};
use crate::layout::{
elements::{ElConstraint, Element},
flex::Flex,
rect::Rect,
};
const SUPER: f64 = 1_001_001_001_000.0;
#[derive(Default)]
struct Line {
elements: Vec<Element>,
}
#[derive(Copy, Clone)]
pub(crate) enum Attr {
Start,
CrossStart,
Size,
CrossSize,
Gap,
}
#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
pub enum Corner {
TopLeft,
TopRight,
BottomRight,
BottomLeft,
}
#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
Horizontal,
Vertical,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Constraint {
// TODO: enforce range 0 - 100
Percentage(u16),
Ratio(u32, u32),
Length(u16),
Max(u16),
Min(u16),
}
impl Constraint {
pub fn apply(&self, length: u16) -> u16 {
match *self {
Constraint::Percentage(p) => length * p / 100,
Constraint::Ratio(num, den) => {
let r = num * u32::from(length) / den;
r as u16
}
Constraint::Length(l) => length.min(l),
Constraint::Max(m) => length.min(m),
Constraint::Min(m) => length.max(m),
}
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Margin {
pub vertical: u16,
pub horizontal: u16,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Alignment {
Left,
Center,
Right,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Layout {
direction: Direction,
margin: Margin,
constraints: Vec<Constraint>,
flex: Flex,
cross_flex: Flex,
cross_size: Constraint,
overlap: u16,
cross_overlap: u16,
boxed: bool,
external_scroll: bool,
wrap: bool,
}
#[cfg(feature = "layout-cache")]
thread_local! {
static LAYOUT_CACHE: RefCell<HashMap<(Rect, Layout, u16), Vec<Rect>>> = RefCell::new(HashMap::new());
}
impl Default for Layout {
fn default() -> Layout {
Layout {
direction: Direction::Vertical,
margin: Margin {
horizontal: 0,
vertical: 0,
},
constraints: Vec::new(),
flex: Flex::Start,
cross_flex: Flex::Start,
cross_size: Constraint::Percentage(100),
overlap: 0,
cross_overlap: 0,
boxed: false,
external_scroll: false,
wrap: false,
}
}
}
impl Layout {
/// Creates a vertical layout with the given constraints.
///
/// A vertical layout splits the available area from top to bottom
/// into multiple horizontal slices.
///
/// In other words:
/// * `Constraint` values are applied to the `height`
/// * All resulting rectangles share the same `x` and `width`
/// * Rectangles are stacked along the `Y axis`
///
/// This method is equivalent to `Layout::default().direction(Direction::Vertical)`
/// and effectively replaces the use of `Layout::new(...)` for vertical layouts.
///
/// ## Visual representation
/// ```text
/// +----------------------+
/// | Rect 0 | ← Constraint[0]
/// +----------------------+
/// | Rect 1 | ← Constraint[1]
/// +----------------------+
/// | Rect 2 | ← Constraint[2]
/// +----------------------+
/// ```
///
/// ## Example
///
/// ```
/// use altui_core::layout::{Rect, Constraint::*, Layout};
///
/// let chunks = Layout::vertical([Length(2),Min(0)])
/// .split(Rect {
/// x: 0,
/// y: 0,
/// width: 10,
/// height: 6,
/// });
///
/// // Splits the area into two rows:
/// // height = 2 and height = 4
/// assert_eq!(chunks.len(), 2);
/// assert_eq!(chunks[0].height, 2);
/// assert_eq!(chunks[1].height, 4);
/// ```
/// See also [`Layout::horizontal`] for left-to-right layouts.
pub fn vertical<C>(constraints: C) -> Self
where
C: Into<Vec<Constraint>>,
{
Layout {
constraints: constraints.into(),
..Default::default()
}
}
/// Creates a horizontal layout with the given constraints.
///
/// A horizontal layout splits the available area from left to right
/// into multiple vertical slices.
///
/// In other words:
/// * Constraint values are applied to the `width`
/// * All resulting rectangles share the same `y` and `height`
/// * Rectangles are stacked along the `X axis`
///
/// This method is equivalent to
/// `Layout::default().direction(Direction::Horizontal)`
/// and effectively replaces the use of `Layout::new(...)` for horizontal layouts.
///
/// ## Visual representation
/// ```text
/// +---------+---------+---------+
/// | Rect 0 | Rect 1 | Rect 2 |
/// | | | |
/// +---------+---------+---------+
/// ↑ ↑
/// Constraint[0] Constraint[1]
/// ```
///
/// ## Example
///
/// ```
/// use altui_core::layout::{Rect, Constraint::*, Layout};
///
/// let chunks = Layout::horizontal([Length(3),Min(0)])
/// .split(Rect {
/// x: 0,
/// y: 0,
/// width: 10,
/// height: 4,
/// });
///
/// // Splits the area into two columns:
/// // width = 3 and width = 7
/// assert_eq!(chunks.len(), 2);
/// assert_eq!(chunks[0].width, 3);
/// assert_eq!(chunks[1].width, 7);
/// ```
/// See also [`Layout::vertical`] for top-to-bottom layouts.
pub fn horizontal<C>(constraints: C) -> Self
where
C: Into<Vec<Constraint>>,
{
Layout {
direction: Direction::Horizontal,
constraints: constraints.into(),
..Default::default()
}
}
pub fn constraints<C>(mut self, constraints: C) -> Layout
where
C: Into<Vec<Constraint>>,
{
self.constraints = constraints.into();
self
}
pub fn margin(mut self, margin: u16) -> Layout {
self.margin = Margin {
horizontal: margin,
vertical: margin,
};
self
}
pub fn horizontal_margin(mut self, horizontal: u16) -> Layout {
self.margin.horizontal = horizontal;
self
}
pub fn vertical_margin(mut self, vertical: u16) -> Layout {
self.margin.vertical = vertical;
self
}
pub fn direction(mut self, direction: Direction) -> Layout {
self.direction = direction;
self
}
/// Sets the amount of allowed overlap between adjacent elements
/// along the main axis.
///
/// The `overlap` value specifies how many neighboring characters are
/// allowed to overlap between adjacent layout items.
///
/// Useful for compact layouts with shared borders.
///
/// ```text
/// ┌────────┌────────┌────────┐
/// │ Item 1 │ Item 2 │ Item 3 │
/// └────────└────────└────────┘
/// ```
///
/// # Warning: Unstable API
///
/// ⚠️ **Known Issue**: This method may cause incorrect rendering
/// when used together with [`Layout::split_ext`], [`Flex::SpaceBetween`]
/// or [`Flex::SpaceAround`].
pub fn overlap(mut self, overlap: u16) -> Layout {
self.overlap = overlap;
self
}
/// Sets the amount of allowed overlap between adjacent elements
/// along the cross axis.
///
/// The `overlap` value specifies how many neighboring symbols are
/// allowed to overlap between adjacent layout items.
///
/// Useful for compact layouts with shared borders.
///
/// ```text
/// ┌────────┐
/// │ Item 1 │
/// ┌────────┐
/// │ Item 2 │
/// ┌────────┐
/// │ Item 3 │
/// └────────┘
/// ```
///
/// # Warning: Unstable API
///
/// ⚠️ **Known Issue**: This method may cause incorrect rendering
/// when used together with [`Layout::split_ext`], [`Flex::SpaceBetween`]
/// or [`Flex::SpaceAround`].
pub fn cross_overlap(mut self, cross_overlap: u16) -> Layout {
self.cross_overlap = cross_overlap;
self
}
/// Sets how free space is distributed between elements along the main axis.
///
/// `Flex` controls the alignment and spacing of elements **after all constraints
/// have been resolved**.
///
/// This affects only the main axis:
/// * horizontal layouts → X axis
/// * vertical layouts → Y axis
///
/// The default value is [`Flex::Start`].
///
/// See [`Flex`] for a detailed description of each mode.
pub fn flex(mut self, flex: Flex) -> Layout {
self.flex = flex;
self
}
/// Sets how free space is distributed between elements along the cross axis.
///
/// `Flex` controls the alignment and spacing of elements **after all constraints
/// have been resolved**.
///
/// This affects only the cross axis:
/// * horizontal layouts → Y axis
/// * vertical layouts → X axis
///
/// The default value is [`Flex::Start`].
pub fn cross_flex(mut self, flex: Flex) -> Layout {
self.cross_flex = flex;
self
}
/// Enables or disables *boxed layout mode*.
///
/// When `boxed` is set to `true`, fixed-size constraints
/// (`Constraint::Length`, `Constraint::Min`) take precedence and are resolved first.
///
/// Remaining space is then distributed between:
/// * `Constraint::Ratio`
/// * `Constraint::Percentage`
///
/// When boxed is `false` (default), all constraints participate in layout
/// solving on equal terms.
///
/// ## Important notes
///
/// * Using `boxed = true` together with scrolling or wrapping may produce
/// unintuitive results.
/// * Percentage and ratio constraints are strongly discouraged when
/// `boxed` is enabled.
///
/// ## Default
///
/// `false`
pub fn boxed(mut self, boxed: bool) -> Layout {
self.boxed = boxed;
self
}
/// Marks the layout as externally scroll-controlled.
///
/// When enabled, the layout does not compute its own scroll bounds.
/// Instead, the scroll size is assumed to be managed by the caller.
///
/// This is mainly useful when:
/// * multiple layouts share a single scroll state
/// * scroll limits are computed elsewhere
///
/// This option is only meaningful when using [`Layout::split_ext`].
pub fn external_scroll(mut self) -> Layout {
self.external_scroll = true;
self
}
/// Enables wrapping into multiple lines when the accumulated main-axis length
/// exceeds the given value. Sets line/column size on cross-axis.
///
/// Wrapping splits elements into multiple lines/columns, similar to text wrapping.
///
/// * Wrapping is performed based on main-axis length
/// * Line/column size along the cross-axis is fixed (Min/Max Constraints work as Length)
/// * Enabling wrapping implicitly changes the scroll direction
///
/// ## Scroll direction
///
/// * Without wrapping:
/// * horizontal layout → horizontal scroll
/// * vertical layout → vertical scroll
///
/// * With wrapping enabled:
/// * horizontal layout → vertical scroll
/// * vertical layout → horizontal scroll
///
/// ## Example
///
/// Wrapping a horizontal layout into multiple rows:
///
/// ```text
/// [A][B][C] → wrap
/// [A][B]
/// [C]
/// ```
/// See also [`cross_size`](Layout::cross_size).
pub fn wrap(mut self, cross_size: Constraint) -> Layout {
self.wrap = true;
self.cross_size = cross_size;
self
}
/// Sets the size of Rect along the cross-axis (or cross-direction) without wrapping
///
/// Note!
/// * `Min/Max` constraints work as `Length`
/// * Default is `Percentage(100)`
pub fn cross_size(mut self, cross_size: Constraint) -> Layout {
self.cross_size = cross_size;
self
}
#[cfg(not(feature = "layout-cache"))]
pub fn cache_eq(&self, other: &Layout) -> bool {
self.constraints == other.constraints
&& self.cross_size == other.cross_size
&& self.flex == other.flex
&& self.cross_flex == other.cross_flex
&& self.direction == other.direction
&& self.margin == other.margin
&& self.boxed == other.boxed
&& self.wrap == other.wrap
&& self.external_scroll == other.external_scroll
}
/// Splits the given area into multiple [`Rect`]s according to the layout
/// configuration, direction, wrapping rules and constraints.
///
/// This function is a high-level wrapper around an internal Cassowary-based
/// solver. The layout process consists of two distinct phases:
///
/// 1. Line/column construction (preparation phase)
/// 2. Constraint solving (layout phase)
///
/// ## Wrapping behavior
///
/// * Wrapping is enabled when [`Layout::wrap`] method is used.
/// * Each line/column has a fixed cross size determined in the method parameter.
/// * When wrapping is enabled, a new line/column is started whenever adding the
/// next constraint would exceed the available main axis (direction) size.
/// * Elements with `Max` constraint and `Percentage` and `Ratio` constraints
/// if layout is `boxed` do not contribute to line/column size and will be
/// collapsed by the solver.
///
/// # Examples
///
/// ### Vertical layout
/// ```
/// use altui_core::layout::{Rect, Constraint, Layout};
///
/// let chunks = Layout::vertical([Constraint::Length(5), Constraint::Min(0)])
/// .split(Rect {
/// x: 2,
/// y: 2,
/// width: 10,
/// height: 10,
/// });
/// assert_eq!(
/// chunks,
/// vec![
/// Rect {
/// x: 2,
/// y: 2,
/// width: 10,
/// height: 5
/// },
/// Rect {
/// x: 2,
/// y: 7,
/// width: 10,
/// height: 5
/// }
/// ]
/// );
/// ```
///
/// ## Horizontal layout with ratios
/// ```
/// use altui_core::layout::{Rect, Constraint, Layout};
///
/// let chunks = Layout::horizontal([Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)])
/// .split(Rect {
/// x: 0,
/// y: 0,
/// width: 9,
/// height: 2,
/// });
/// assert_eq!(
/// chunks,
/// vec![
/// Rect {
/// x: 0,
/// y: 0,
/// width: 3,
/// height: 2
/// },
/// Rect {
/// x: 3,
/// y: 0,
/// width: 6,
/// height: 2
/// }
/// ]
/// );
/// ```
///
/// ### Wrapping into multiple lines by length
/// ```
/// use altui_core::layout::{Rect, Constraint, Layout};
///
/// let chunks = Layout::horizontal([
/// Constraint::Length(3),
/// Constraint::Length(3),
/// Constraint::Length(3),
/// ])
/// .wrap(Constraint::Length(2))
/// .split(Rect {
/// x: 0,
/// y: 0,
/// width: 6,
/// height: 4,
/// });
///
/// // Produces two rows with height `2` each:
/// // [3][3]
/// // [3]
///
/// assert_eq!(
/// chunks,
/// vec![
/// Rect { x: 0, y: 0, width: 3, height: 2 },
/// Rect { x: 3, y: 0, width: 3, height: 2 },
/// Rect { x: 0, y: 2, width: 3, height: 2 },
/// ]
/// );
/// ```
///
/// ### Wrapping into multiple lines by percentage
/// ```
/// use altui_core::layout::{Rect, Constraint, Layout};
///
/// let chunks = Layout::horizontal([
/// Constraint::Length(3),
/// Constraint::Length(3),
/// Constraint::Length(3),
/// ])
/// .wrap(Constraint::Percentage(50))
/// .split(Rect {
/// x: 0,
/// y: 0,
/// width: 6,
/// height: 8,
/// });
///
/// // Produces two rows with height `4` each:
/// // [3][3]
/// // [3]
///
/// assert_eq!(
/// chunks,
/// vec![
/// Rect { x: 0, y: 0, width: 3, height: 4 },
/// Rect { x: 3, y: 0, width: 3, height: 4 },
/// Rect { x: 0, y: 4, width: 3, height: 4 },
/// ]
/// );
/// ```
pub fn split(&self, area: Rect) -> Vec<Rect> {
let dest_area = area.inner(&self.margin);
// TODO: Maybe use a fixed size cache ?
#[cfg(feature = "layout-cache")]
{
LAYOUT_CACHE.with(|c| {
c.borrow_mut()
.entry((dest_area, self.clone(), 0))
.or_insert_with(|| self.split_inner(dest_area))
.clone()
})
}
#[cfg(not(feature = "layout-cache"))]
self.split_inner(dest_area)
}
fn split_inner(&self, dest_area: Rect) -> Vec<Rect> {
let stopwatch = Instant::now();
let (lines, _, line_cross_size, _, variables) = self.split_preparations(&dest_area);
let result = Results::new(self.direction, self.constraints.len()).split(
dest_area,
self,
0.0,
lines,
line_cross_size,
variables,
);
tracing::trace!(
"Altui split: {} µs",
stopwatch.elapsed().as_nanos() as f64 / 1_000.0
);
result
}
/// Splits the given area into multiple [`Rect`]s with scrolling support.
///
/// This method extends [`Layout::split`] by introducing a scroll offset and
/// automatically computing the scrollable range based on the layout
/// configuration.
///
/// The layout process is identical to split, but the final positioning
/// is shifted by a computed scroll offset along the active scroll axis.
///
/// ## Scrolling model
///
/// Scrolling is single-axis and its direction depends on whether wrapping
/// is enabled:
///
/// * Without wrapping:
/// * Scrolling occurs along the main axis of the layout.
/// * For example:
/// * Direction::Horizontal → horizontal scrolling
/// * Direction::Vertical → vertical scrolling
///
/// * With wrapping enabled:
/// * Scrolling occurs along the cross axis.
/// * The layout grows by adding multiple lines/columns, and scrolling moves
/// between those lines/columns.
///
/// This behavior mirrors common UI patterns where wrapping turns a
/// one-dimensional layout into a multi-line structure with perpendicular
/// scrolling.
///
/// ## Scroll parameters
///
/// * scroll — total scrollable length (output)
/// * Updated by this function unless external_scroll is enabled.
/// * Represents the full scroll range in layout units.
///
/// * scrollstate — current scroll position (input/output)
/// * Clamped automatically to the valid scroll range.
/// * Used to compute the effective scroll offset.
///
/// ## Wrapping and scrolling interaction
///
/// * When wrapping is enabled:
/// * The scroll range is computed from the total cross-axis size of all
/// lines/columns.
///
/// * When wrapping is disabled:
/// * The scroll range is computed from the total content length along the
/// main axis.
///
/// ## External scrolling
///
/// If external_scroll is enabled:
/// * The scroll range is taken from the scroll parameter.
/// * This allows integrating the layout with an external scrolling container.
///
/// ## Constraints and limitations
///
/// ⚠️ Important:
/// Do not use the following constraint combinations with split_ext:
///
/// * [`Constraint::Percentage`] or [`Constraint::Ratio`] when the layout is boxed
/// * [`Constraint::Max`] when relying on internal scrolling
///
/// These combinations may produce undefined or unintuitive scrolling behavior.
///
/// ## Notes
///
/// * Line construction and wrapping are performed before scrolling is
/// applied.
/// * The solver does not decide the scroll direction.
/// * Margins are applied before layout and scrolling.
/// * Scrolling offsets are quantized to integer values.
///
/// # Examples
///
/// ### Horizontal scrolling without wrapping
///
///```
/// use altui_core::layout::{Rect, Constraint, Layout};
///
/// let mut scroll = 0;
/// let mut scrollstate = 0;
///
/// let chunks = Layout::horizontal([
/// Constraint::Length(5),
/// Constraint::Length(5),
/// Constraint::Length(5),
/// ])
/// .split_ext(
/// Rect { x: 0, y: 0, width: 8, height: 2 },
/// &mut scrollstate,
/// &mut scroll,
/// );
///
/// // Content width exceeds available width, so scrolling is horizontal.
/// assert!(scroll == 15);
/// ```
///
/// ### Vertical scrolling with wrapping enabled
/// ```
/// use altui_core::layout::{Rect, Constraint, Layout};
///
/// let mut scroll = 0;
/// let mut scrollstate = 0;
///
/// let chunks = Layout::horizontal([
/// Constraint::Length(3),
/// Constraint::Length(3),
/// Constraint::Length(3),
/// ])
/// .wrap(Constraint::Length(8))
/// .split_ext(
/// Rect { x: 0, y: 0, width: 6, height: 8 },
/// &mut scrollstate,
/// &mut scroll,
/// );
///
/// // Wrapping creates multiple rows; scrolling is now vertical.
/// assert!(scroll == 16);
/// ```
/// See [`Layout::split`] for a non-scrolling variant.
pub fn split_ext(&self, area: Rect, scrollstate: &mut u16, scroll: &mut u16) -> Vec<Rect> {
let dest_area = area.inner(&self.margin);
if *scroll > 0 && scrollstate > scroll {
*scrollstate = *scroll;
}
// TODO: Maybe use a fixed size cache ?
#[cfg(feature = "layout-cache")]
{
LAYOUT_CACHE.with(|c| {
c.borrow_mut()
.entry((dest_area, self.clone(), *scrollstate))
.or_insert_with(|| self.split_ext_inner(dest_area, scrollstate, scroll))
.clone()
})
}
#[cfg(not(feature = "layout-cache"))]
self.split_ext_inner(dest_area, scrollstate, scroll)
}
fn split_ext_inner(
&self,
dest_area: Rect,
scrollstate: &mut u16,
scroll: &mut u16,
) -> Vec<Rect> {
let stopwatch = std::time::Instant::now();
let gap: f64;
let (lines, size, line_cross_size, content_length, variables) =
self.split_preparations(&dest_area);
if !self.external_scroll && !self.wrap {
gap = (content_length - size).max(0.0).floor();
*scroll = content_length.max(size).floor() as u16;
} else if !self.external_scroll {
let cross_size = dest_area.cross_end(self.direction);
let cross_length = *line_cross_size * lines.len() as f64;
gap = (cross_length - cross_size).max(0.0).floor();
*scroll = cross_length.max(cross_size).floor() as u16;
} else {
gap = (f64::from(*scroll) - size).max(0.0);
}
let scroll_inner = match gap == 0.0 {
true => 0.0,
false => f64::from(*scrollstate) / f64::from(*scroll) * gap,
};
let result = Results::new(self.direction, self.constraints.len()).split(
dest_area,
self,
scroll_inner.floor(),
lines,
line_cross_size,
variables,
);
tracing::trace!(
"Altui scrollable split: {} µs",
stopwatch.elapsed().as_nanos() as f64 / 1_000.0
);
result
}
#[inline(always)]
fn split_preparations(
&self,
dest_area: &Rect,
) -> (Vec<Line>, f64, ElConstraint, f64, Variables) {
use Constraint::*;
let mut content_length = 0.0;
let mut variables = Variables::default();
let size = dest_area.size(self.direction);
let line_cross_size = match self.cross_size {
Percentage(100) => ElConstraint::Length(dest_area.cross_size(self.direction)),
Percentage(v) => {
ElConstraint::Length(dest_area.cross_size(self.direction) * v as f64 / 100.0)
}
Ratio(n, d) => ElConstraint::Ratio(size * f64::from(n) / f64::from(d)),
Length(v) | Min(v) | Max(v) => ElConstraint::Length(f64::from(v)),
};
let mut lines = Vec::new();
let mut line = Line::default();
let boxedf64 = if self.boxed { STRONG } else { MEDIUM };
let mut used = 0.0;
for el in &self.constraints {
let (boxed, strength, constraint) = match el {
Length(v) => (false, boxedf64, ElConstraint::Length(f64::from(*v))),
Min(v) => (false, boxedf64, ElConstraint::Min(f64::from(*v))),
Percentage(v) => (
self.boxed,
MEDIUM,
ElConstraint::Percentage(size * f64::from(*v) / 100.0),
),
Max(v) => (true, WEAK, ElConstraint::Max(f64::from(*v))),
Ratio(n, d) => (
self.boxed,
MEDIUM,
ElConstraint::Ratio(size * f64::from(*n) / f64::from(*d)),
),
};
let w = if boxed { 0.0 } else { *constraint };
content_length += w;
if self.wrap && used > 0.0 && used + w > size {
lines.push(std::mem::take(&mut line));
used = 0.0;
}
line.elements
.push(Element::new(strength, constraint, &mut variables));
used += w;
}
if !line.elements.is_empty() {
lines.push(line);
}
(lines, size, line_cross_size, content_length, variables)
}
}
#[derive(Debug)]
struct Results {
v: Vec<Rect>,
axis: Direction,
}
impl Results {
fn new(axis: Direction, len: usize) -> Self {
Results {
v: vec![Rect::default(); len],
axis,
}
}
#[inline(always)]
fn main_axis(&mut self, index: usize, attr: Attr, value: u16) {
let r = &mut self.v[index];
match (self.axis, attr) {
(Direction::Horizontal, Attr::Start) => r.x = value,
(Direction::Horizontal, Attr::Size) => r.width = value,
(Direction::Vertical, Attr::Start) => r.y = value,
(Direction::Vertical, Attr::Size) => r.height = value,
_ => {}
}
}
#[inline(always)]
fn cross_axis(&mut self, index: usize, line: usize, lines: &[(u16, u16)]) {
let r = &mut self.v[index];
let (start, size) = lines[line];
match self.axis {
Direction::Horizontal => {
r.y = start;
r.height = size;
}
Direction::Vertical => {
r.x = start;
r.width = size;
}
}
}
#[inline(always)]
fn split(
mut self,
dest_area: Rect,
layout: &Layout,
mut offset: f64,
lines: Vec<Line>,
cross_size: ElConstraint,
mut variables: Variables,
) -> Vec<Rect> {
use crate::layout::Flex::*;
// Gap constraints for each line + rows constraints + flex constraints
let mut ccs: Vec<CassowaryConstraint> =
Vec::with_capacity(lines.len() + layout.constraints.len() * 6 + lines.len() * 2);
// Cross gap + line/column constraints + flex constraints
let mut cross_ccs: Vec<CassowaryConstraint> = Vec::with_capacity(1 + lines.len() * 5 + 2);
// Calc quantity of Cassowary Variables, that must be eq with the index of the last Variable:
// Constraints Variables + Lines Variables + Gaps Variables + Cross gap variable
let vars_indexes = layout.constraints.len() * 2 + lines.len() * 2 + lines.len() + 1;
// Line, index, attr
let mut ivars: Vec<Option<(usize, usize, Attr)>> = vec![None; vars_indexes];
// Lines processing
let elmlines = &lines
.iter()
.map(|_| LineBox::new(&mut variables))
.collect::<Vec<LineBox>>();
let overlap = (layout.overlap as f64).min(dest_area.size(self.axis));
let cross_overlap = (layout.cross_overlap as f64).min(dest_area.cross_size(self.axis));
// Cross axis gap for lines
let cross_gap = variables.add();
ivars[variables.get_id(cross_gap)] = Some((0, 0, Attr::Gap));
cross_ccs.push(match layout.cross_flex {
SpaceBetween | SpaceAround => cross_gap | GE(REQUIRED) | 0f64,
_ => cross_gap | EQ(REQUIRED) | 0f64,
});
let mut j: usize = 0;
// Lines
for ((l, line), elmline) in lines.iter().enumerate().zip(elmlines) {
elmline.vars(&mut ivars, l, &variables);
// Main axis gap constraint for SpaceBetween or SpaceAround
let gap = variables.add();
ivars[variables.get_id(gap)] = Some((0, 0, Attr::Gap));
ccs.push(match layout.flex {
SpaceBetween | SpaceAround => gap | GE(REQUIRED) | 0f64,
_ => gap | EQ(SUPER) | 0f64,
});
// calc offset for cross axis scroll
let cross_size_with_offset = if layout.wrap {
scroll(*cross_size, &mut offset)
} else {
*cross_size
};
// spacing between lines
if let Some(next) = elmlines.get(l + 1) {
cross_ccs.push(
next.cross_start - elmline.cross_end()
| EQ(REQUIRED)
| cross_gap - cross_overlap,
);
}
cross_ccs.extend([
elmline.cross_size | GE(REQUIRED) | 0.0,
elmline.cross_start | GE(REQUIRED) | dest_area.cross_start(self.axis),
elmline.cross_end() | LE(REQUIRED) | dest_area.cross_end(self.axis),
elmline.cross_size | EQ(MEDIUM) | cross_size_with_offset,
]);
// Elements
for (i, elm) in line.elements.iter().enumerate() {
elm.vars(&mut ivars, l, j, &variables);
// calc offset for main axis scroll
let v = match elm.constraint {
ElConstraint::Min(v) => {
ccs.push(elm.size | EQ(WEAK) | dest_area.size(self.axis));
if layout.wrap {
v
} else {
scroll(v, &mut offset)
}
}
ElConstraint::Percentage(v)
| ElConstraint::Ratio(v)
| ElConstraint::Length(v) => {
if layout.wrap {
v
} else {
scroll(v, &mut offset)
}
}
ElConstraint::Max(v) => v,
};
// spacing between elements
if let Some(next_elm) = line.elements.get(i + 1) {
ccs.push(next_elm.start - elm.end() | EQ(REQUIRED) | gap - overlap);
}
ccs.extend([
elm.size | GE(REQUIRED) | 0.0,
elm.start | GE(REQUIRED) | dest_area.start(self.axis),
elm.end() | LE(REQUIRED) | dest_area.end(self.axis),
match elm.constraint {
ElConstraint::Min(_) => elm.size | GE(elm.strength) | v,
_ => elm.size | EQ(elm.strength) | v,
},
]);
j += 1;
}
// flex constraints
if let (Some(first), Some(last)) = (line.elements.first(), line.elements.last()) {
match layout.flex {
Legacy | SpaceBetween => ccs.extend([
first.start | EQ(SUPER) | dest_area.start(self.axis),
last.end() | EQ(SUPER) | dest_area.end(self.axis),
]),
Start => ccs.push(first.start | EQ(SUPER) | dest_area.start(self.axis)),
End => ccs.push(last.end() | EQ(SUPER) | dest_area.end(self.axis)),
Center => ccs.push(
first.start + last.size + last.start
| EQ(SUPER)
| dest_area.start(self.axis) + dest_area.end(self.axis),
),
SpaceAround => ccs.extend([
first.start - dest_area.start(self.axis) | EQ(SUPER) | gap,
dest_area.end(self.axis) - last.end() | EQ(SUPER) | gap,
]),
}
}
}
if let (Some(first), Some(last)) = (elmlines.first(), elmlines.last()) {
match layout.cross_flex {
Legacy | Start => {
cross_ccs.push(first.cross_start | EQ(SUPER) | dest_area.cross_start(self.axis))
}
End => {
cross_ccs.push(last.cross_end() | EQ(SUPER) | dest_area.cross_end(self.axis))
}
Center => cross_ccs.push(
first.cross_start + last.cross_size + last.cross_start
| EQ(SUPER)
| dest_area.cross_start(self.axis) + dest_area.cross_end(self.axis),
),
SpaceBetween => cross_ccs.extend([
first.cross_start | EQ(SUPER) | dest_area.cross_start(self.axis),
last.cross_end() | EQ(SUPER) | dest_area.cross_end(self.axis),
]),
SpaceAround => cross_ccs.extend([
first.cross_start - dest_area.cross_start(self.axis) | EQ(SUPER) | cross_gap,
dest_area.cross_end(self.axis) - last.cross_end() | EQ(SUPER) | cross_gap,
]),
}
}
assert!(ccs.len() < layout.constraints.len() * 13 + lines.len() + 1);
let mut solver = Solver::new();
solver.add_constraints(&cross_ccs).unwrap();
// (Start, Size)
let mut lines = vec![(0, 0); lines.len()];
for &(var, value) in solver.fetch_changes() {
let (line, index, attr) = ivars
.get(variables.get_id(var))
.expect("Cassowary variable and usize must have the same size and alignment")
.expect("Total quantity of Cassowary Variables used in altui must be eq the last Variable index");
// We have one gap var in line, that can be eq 0, but indexs can not
assert!(index == 0);
let value = norm(value);
match attr {
Attr::CrossStart => lines[line].0 = value,
Attr::CrossSize => lines[line].1 = value,
_ => {}
}
}
solver.reset();
solver.add_constraints(&ccs).unwrap();
for &(var, value) in solver.fetch_changes() {
let (line, index, attr) = ivars
.get(variables.get_id(var))
.expect("Cassowary variable and usize must have the same size and alignment")
.expect("Total quantity of Cassowary Variables used in altui must be eq the last Variable index");
let value = norm(value);
self.main_axis(index, attr, value);
self.cross_axis(index, line, &lines);
}
self.v
}
}
#[inline]
fn norm(v: f64) -> u16 {
if v.is_sign_negative() {
0
} else {
v as u16
}
}
#[inline(always)]
fn scroll(mut x: f64, scroll: &mut f64) -> f64 {
if *scroll > 0.0 {
if *scroll >= x {
*scroll -= x;
return 0.0;
} else {
x -= *scroll;
*scroll = 0.0;
}
}
x
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_boxed() {
let err_msg = "Failed to resolve area with boxed param in Layout";
let area = Rect {
x: 0,
y: 0,
width: 10,
height: 10,
};
let layout = Layout::vertical([Constraint::Percentage(50), Constraint::Length(8)])
.boxed(true)
.split(area);
assert_eq!(layout[0].height, 2, "{}, {}", err_msg, "Percentage");
assert_eq!(layout[1].height, 8, "{}, {}", err_msg, "Length");
}
#[test]
fn test_vertical_split_by_height() {
let target = Rect {
x: 2,
y: 2,
width: 10,
height: 10,
};
let chunks = Layout::vertical([
Constraint::Percentage(10),
Constraint::Max(5),
Constraint::Min(1),
])
.split(target);
assert_eq!(target.height, chunks.iter().map(|r| r.height).sum::<u16>());
chunks.windows(2).for_each(|w| assert!(w[0].y <= w[1].y));
}
#[test]
fn test_rect_size_truncation() {
for width in 256u16..300u16 {
for height in 256u16..300u16 {
let rect = Rect::new(0, 0, width, height);
rect.area(); // Should not panic.
assert!(rect.width < width || rect.height < height);
// The target dimensions are rounded down so the math will not be too precise
// but let's make sure the ratios don't diverge crazily.
assert!(
(f64::from(rect.width) / f64::from(rect.height)
- f64::from(width) / f64::from(height))
.abs()
< 1.0
)
}
}
// One dimension below 255, one above. Area above max u16.
let width = 900;
let height = 100;
let rect = Rect::new(0, 0, width, height);
assert_ne!(rect.width, 900);
assert_ne!(rect.height, 100);
assert!(rect.width < width || rect.height < height);
}
#[test]
fn test_rect_size_preservation() {
for width in 0..256u16 {
for height in 0..256u16 {
let rect = Rect::new(0, 0, width, height);
rect.area(); // Should not panic.
assert_eq!(rect.width, width);
assert_eq!(rect.height, height);
}
}
// One dimension below 255, one above. Area below max u16.
let rect = Rect::new(0, 0, 300, 100);
assert_eq!(rect.width, 300);
assert_eq!(rect.height, 100);
}
}