1#![forbid(unsafe_code)]
2
3pub mod cache;
43pub mod debug;
44pub mod dep_graph;
45pub mod direction;
46pub mod egraph;
47pub mod grid;
48pub mod incremental;
49pub mod pane;
50pub mod pane_command;
51pub mod pane_execution;
52pub mod pane_memory;
53pub mod pane_monitors;
54pub mod pane_persistent;
55pub mod pane_retention;
56#[cfg(test)]
57mod repro_max_constraint;
58#[cfg(test)]
59mod repro_space_around;
60pub mod responsive;
61pub mod responsive_layout;
62pub mod veb_tree;
63pub mod visibility;
64pub mod wide_prefix;
65pub mod workspace;
66
67#[cfg(feature = "experimental")]
68pub use cache::S3FifoLayoutCache;
69pub use cache::{CoherenceCache, CoherenceId, LayoutCache, LayoutCacheKey, LayoutCacheStats};
70pub use direction::{FlowDirection, LogicalAlignment, LogicalSides, mirror_rects_horizontal};
71pub use ftui_core::geometry::{Rect, Sides, Size};
72pub use grid::{Grid, GridArea, GridLayout};
73pub use pane::{
74 PANE_AFFORDANCE_EMPHASIS_FULL_BPS, PANE_DEFAULT_MARGIN_CELLS, PANE_DEFAULT_PADDING_CELLS,
75 PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS, PANE_DRAG_RESIZE_DEFAULT_THRESHOLD,
76 PANE_EDGE_GRIP_INSET_CELLS, PANE_MAGNETIC_FIELD_CELLS,
77 PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION, PANE_SEMANTIC_INPUT_TRACE_SCHEMA_VERSION,
78 PANE_SNAP_DEFAULT_HYSTERESIS_BPS, PANE_SNAP_DEFAULT_STEP_BPS, PANE_TREE_SCHEMA_VERSION,
79 PaneAffordanceMotion, PaneCancelReason, PaneConstraints, PaneCoordinateNormalizationError,
80 PaneCoordinateNormalizer, PaneCoordinateRoundingPolicy, PaneDockPreview, PaneDockZone,
81 PaneDragBehaviorTuning, PaneDragResizeEffect, PaneDragResizeMachine,
82 PaneDragResizeMachineError, PaneDragResizeNoopReason, PaneDragResizeState,
83 PaneDragResizeTransition, PaneEdgeResizePlan, PaneEdgeResizePlanError, PaneGroupTransformPlan,
84 PaneId, PaneIdAllocator, PaneInertialThrow, PaneInputCoordinate, PaneInteractionPolicyError,
85 PaneInteractionTimeline, PaneInteractionTimelineCheckpointDecision,
86 PaneInteractionTimelineEntry, PaneInteractionTimelineError,
87 PaneInteractionTimelineReplayDiagnostics, PaneInteractionTimelineRetentionDiagnostics,
88 PaneInvariantCode, PaneInvariantIssue, PaneInvariantReport, PaneInvariantSeverity, PaneLayout,
89 PaneLayoutIntelligenceMode, PaneLeaf, PaneModelError, PaneModifierSnapshot, PaneMotionVector,
90 PaneNodeKind, PaneNodeRecord, PaneNormalizedCoordinate, PaneOperation, PaneOperationError,
91 PaneOperationFailure, PaneOperationFamily, PaneOperationJournalEntry,
92 PaneOperationJournalResult, PaneOperationKind, PaneOperationOutcome, PanePlacement,
93 PanePointerButton, PanePointerPosition, PanePrecisionMode, PanePrecisionPolicy,
94 PanePressureSnapProfile, PaneReflowMovePlan, PaneReflowPlanError, PaneRepairAction,
95 PaneRepairError, PaneRepairFailure, PaneRepairOutcome, PaneResizeDirection, PaneResizeGrip,
96 PaneResizeTarget, PaneScaleFactor, PaneSelectionState, PaneSemanticInputEvent,
97 PaneSemanticInputEventError, PaneSemanticInputEventKind, PaneSemanticInputTrace,
98 PaneSemanticInputTraceError, PaneSemanticInputTraceMetadata,
99 PaneSemanticReplayConformanceArtifact, PaneSemanticReplayDiffArtifact,
100 PaneSemanticReplayDiffKind, PaneSemanticReplayError, PaneSemanticReplayFixture,
101 PaneSemanticReplayOutcome, PaneSnapDecision, PaneSnapReason, PaneSnapTuning, PaneSplit,
102 PaneSplitRatio, PaneTransaction, PaneTransactionOutcome, PaneTree, PaneTreeSnapshot, SplitAxis,
103};
104pub use pane_command::{
105 PaneAccessibilityPreferences, PaneAnnouncement, PaneAnnouncementCategory, PaneAnnouncer,
106 PaneCardinalDirection, PaneCommand, PaneCommandAcceleration, PaneCommandEffect,
107 PaneCommandNoopReason, PaneCommandResolution, PaneFocusContext, PaneFocusOrdinal,
108 PaneKeymapOwner, PaneKeymapPrecedence, announce_command, focus_cyclic, focus_directional,
109 focus_edge, focus_order, resolve as resolve_pane_command,
110};
111pub use pane_execution::{
112 PaneExecutionDecision, PaneExecutionEngine, PaneExecutionError, PaneExecutionPolicy,
113 PaneExecutionSample, PaneExecutionStatus, PaneHistory, PaneStrategyReason, PaneWorkloadProfile,
114};
115pub use pane_memory::{
116 PANE_MEMORY_TELEMETRY_SCHEMA_VERSION, PaneMemoryComparison, PaneMemoryDriver,
117 PaneMemoryStrategy, PaneMemoryStrategyFootprint, pane_memory_comparison,
118};
119pub use pane_monitors::{
120 PaneAssumption, PaneMonitorReport, PaneMonitorStatus, PaneMonitorThresholds,
121 PaneMonitorVerdict, monitor_fallback_frequency, monitor_latency_envelope, monitor_replay_depth,
122 monitor_retention_pressure, monitor_selector_churn,
123};
124pub use pane_persistent::{
125 PaneVersionRetention, PaneVersionStore, PaneVersioningReport, PersistentApplyError,
126 PersistentApplyStrategy, PersistentNode, VersionedPaneTree,
127};
128pub use pane_retention::{
129 PaneRetentionBudget, PaneRetentionDecision, PaneRetentionOutcome, PaneRetentionPolicy,
130 apply_to_timeline as apply_retention_to_timeline,
131 apply_to_version_store as apply_retention_to_version_store,
132};
133pub use responsive::Responsive;
134pub use responsive_layout::{ResponsiveLayout, ResponsiveSplit};
135pub use smallvec;
136use smallvec::SmallVec;
137use std::cmp::min;
138pub use visibility::Visibility;
139pub use wide_prefix::{WidePrefixError, WidePrefixSums};
140pub use workspace::{
141 MigrationResult, WORKSPACE_SCHEMA_VERSION, WorkspaceMetadata, WorkspaceMigrationError,
142 WorkspaceSnapshot, WorkspaceSnapshotJsonError, WorkspaceValidationError,
143 canonicalize_workspace_snapshot, decode_workspace_snapshot_json, migrate_workspace,
144 needs_migration, to_canonical_workspace_snapshot_json,
145};
146
147const LAYOUT_INLINE_CAP: usize = 8;
152
153pub type Rects = SmallVec<[Rect; LAYOUT_INLINE_CAP]>;
155
156type Sizes = SmallVec<[u16; LAYOUT_INLINE_CAP]>;
158
159type Constraints = SmallVec<[Constraint; LAYOUT_INLINE_CAP]>;
161
162#[derive(Debug, Clone, Copy, PartialEq)]
164pub enum Constraint {
165 Fixed(u16),
167 Percentage(f32),
169 Min(u16),
171 Max(u16),
173 Ratio(u32, u32),
175 Fill,
177 FitContent,
182 FitContentBounded {
187 min: u16,
189 max: u16,
191 },
192 FitMin,
196}
197
198#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
221pub struct LayoutSizeHint {
222 pub min: u16,
224 pub preferred: u16,
226 pub max: Option<u16>,
228}
229
230impl LayoutSizeHint {
231 pub const ZERO: Self = Self {
233 min: 0,
234 preferred: 0,
235 max: None,
236 };
237
238 #[inline]
240 pub const fn exact(size: u16) -> Self {
241 Self {
242 min: size,
243 preferred: size,
244 max: Some(size),
245 }
246 }
247
248 #[inline]
250 pub const fn at_least(min: u16, preferred: u16) -> Self {
251 Self {
252 min,
253 preferred,
254 max: None,
255 }
256 }
257
258 #[inline]
260 pub fn clamp(&self, value: u16) -> u16 {
261 let max = self.max.unwrap_or(u16::MAX);
262 value.min(max).max(self.min)
263 }
264}
265
266#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
268pub enum Direction {
269 #[default]
271 Vertical,
272 Horizontal,
274}
275
276#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
278pub enum Alignment {
279 #[default]
281 Start,
282 Center,
284 End,
286 SpaceAround,
288 SpaceBetween,
290}
291
292#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
305pub enum OverflowBehavior {
306 #[default]
310 Clip,
311 Visible,
314 Scroll {
318 max_content: Option<u16>,
321 },
322 Wrap,
325}
326
327#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
340pub enum Breakpoint {
341 Xs,
343 Sm,
345 Md,
347 Lg,
349 Xl,
351}
352
353impl Breakpoint {
354 pub const ALL: [Breakpoint; 5] = [
356 Breakpoint::Xs,
357 Breakpoint::Sm,
358 Breakpoint::Md,
359 Breakpoint::Lg,
360 Breakpoint::Xl,
361 ];
362
363 #[inline]
365 const fn index(self) -> u8 {
366 match self {
367 Breakpoint::Xs => 0,
368 Breakpoint::Sm => 1,
369 Breakpoint::Md => 2,
370 Breakpoint::Lg => 3,
371 Breakpoint::Xl => 4,
372 }
373 }
374
375 #[must_use]
377 pub const fn label(self) -> &'static str {
378 match self {
379 Breakpoint::Xs => "xs",
380 Breakpoint::Sm => "sm",
381 Breakpoint::Md => "md",
382 Breakpoint::Lg => "lg",
383 Breakpoint::Xl => "xl",
384 }
385 }
386}
387
388impl std::fmt::Display for Breakpoint {
389 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
390 f.write_str(self.label())
391 }
392}
393
394#[derive(Debug, Clone, Copy, PartialEq, Eq)]
399pub struct Breakpoints {
400 pub sm: u16,
402 pub md: u16,
404 pub lg: u16,
406 pub xl: u16,
408}
409
410impl Breakpoints {
411 pub const DEFAULT: Self = Self {
413 sm: 60,
414 md: 90,
415 lg: 120,
416 xl: 160,
417 };
418
419 pub const fn new(sm: u16, md: u16, lg: u16) -> Self {
423 let md = if md < sm { sm } else { md };
424 let lg = if lg < md { md } else { lg };
425 let xl = match lg.checked_add(40) {
427 Some(v) => v,
428 None => u16::MAX,
429 };
430 Self { sm, md, lg, xl }
431 }
432
433 pub const fn new_with_xl(sm: u16, md: u16, lg: u16, xl: u16) -> Self {
437 let md = if md < sm { sm } else { md };
438 let lg = if lg < md { md } else { lg };
439 let xl = if xl < lg { lg } else { xl };
440 Self { sm, md, lg, xl }
441 }
442
443 #[inline]
445 pub const fn classify_width(self, width: u16) -> Breakpoint {
446 if width >= self.xl {
447 Breakpoint::Xl
448 } else if width >= self.lg {
449 Breakpoint::Lg
450 } else if width >= self.md {
451 Breakpoint::Md
452 } else if width >= self.sm {
453 Breakpoint::Sm
454 } else {
455 Breakpoint::Xs
456 }
457 }
458
459 #[inline]
461 pub const fn classify_size(self, size: Size) -> Breakpoint {
462 self.classify_width(size.width)
463 }
464
465 #[inline]
467 pub const fn at_least(self, width: u16, min: Breakpoint) -> bool {
468 self.classify_width(width).index() >= min.index()
469 }
470
471 #[inline]
473 pub const fn between(self, width: u16, min: Breakpoint, max: Breakpoint) -> bool {
474 let idx = self.classify_width(width).index();
475 idx >= min.index() && idx <= max.index()
476 }
477
478 #[must_use]
480 pub const fn threshold(self, bp: Breakpoint) -> u16 {
481 match bp {
482 Breakpoint::Xs => 0,
483 Breakpoint::Sm => self.sm,
484 Breakpoint::Md => self.md,
485 Breakpoint::Lg => self.lg,
486 Breakpoint::Xl => self.xl,
487 }
488 }
489
490 #[must_use]
492 pub const fn thresholds(self) -> [(Breakpoint, u16); 5] {
493 [
494 (Breakpoint::Xs, 0),
495 (Breakpoint::Sm, self.sm),
496 (Breakpoint::Md, self.md),
497 (Breakpoint::Lg, self.lg),
498 (Breakpoint::Xl, self.xl),
499 ]
500 }
501}
502
503#[derive(Debug, Clone, Copy, Default)]
505pub struct Measurement {
506 pub min_width: u16,
508 pub min_height: u16,
510 pub max_width: Option<u16>,
512 pub max_height: Option<u16>,
514}
515
516impl Measurement {
517 #[must_use]
519 pub fn fixed(width: u16, height: u16) -> Self {
520 Self {
521 min_width: width,
522 min_height: height,
523 max_width: Some(width),
524 max_height: Some(height),
525 }
526 }
527
528 #[must_use]
530 pub fn flexible(min_width: u16, min_height: u16) -> Self {
531 Self {
532 min_width,
533 min_height,
534 max_width: None,
535 max_height: None,
536 }
537 }
538}
539
540#[derive(Debug, Clone, Default)]
542pub struct Flex {
543 direction: Direction,
544 constraints: Constraints,
545 margin: Sides,
546 gap: u16,
547 alignment: Alignment,
548 flow_direction: direction::FlowDirection,
549 overflow: OverflowBehavior,
550}
551
552impl Flex {
553 #[must_use]
555 pub fn vertical() -> Self {
556 Self {
557 direction: Direction::Vertical,
558 ..Default::default()
559 }
560 }
561
562 #[must_use]
564 pub fn horizontal() -> Self {
565 Self {
566 direction: Direction::Horizontal,
567 ..Default::default()
568 }
569 }
570
571 #[must_use]
573 pub fn direction(mut self, direction: Direction) -> Self {
574 self.direction = direction;
575 self
576 }
577
578 #[must_use]
580 pub fn constraints(mut self, constraints: impl IntoIterator<Item = Constraint>) -> Self {
581 self.constraints = constraints.into_iter().collect();
582 self
583 }
584
585 #[must_use]
587 pub fn margin(mut self, margin: Sides) -> Self {
588 self.margin = margin;
589 self
590 }
591
592 #[must_use]
594 pub fn gap(mut self, gap: u16) -> Self {
595 self.gap = gap;
596 self
597 }
598
599 #[must_use]
601 pub fn alignment(mut self, alignment: Alignment) -> Self {
602 self.alignment = alignment;
603 self
604 }
605
606 #[must_use]
612 pub fn flow_direction(mut self, flow: direction::FlowDirection) -> Self {
613 self.flow_direction = flow;
614 self
615 }
616
617 #[must_use]
619 pub fn overflow(mut self, overflow: OverflowBehavior) -> Self {
620 self.overflow = overflow;
621 self
622 }
623
624 #[must_use]
626 pub fn overflow_behavior(&self) -> OverflowBehavior {
627 self.overflow
628 }
629
630 #[must_use]
632 pub fn constraint_count(&self) -> usize {
633 self.constraints.len()
634 }
635
636 pub fn split(&self, area: Rect) -> Rects {
638 let inner = area.inner(self.margin);
640 if inner.is_empty() {
641 return self.constraints.iter().map(|_| Rect::default()).collect();
642 }
643
644 let total_size = match self.direction {
645 Direction::Horizontal => inner.width,
646 Direction::Vertical => inner.height,
647 };
648
649 let count = self.constraints.len();
650 if count == 0 {
651 return Rects::new();
652 }
653
654 let gap_count = count - 1;
656 let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
657 let available_size = total_size.saturating_sub(total_gap);
658
659 let sizes = solve_constraints(&self.constraints, available_size);
661
662 let mut rects = self.sizes_to_rects(inner, &sizes);
664
665 if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
667 direction::mirror_rects_horizontal(&mut rects, inner);
668 }
669
670 rects
671 }
672
673 pub fn split_in<'a>(&self, arena: &'a ftui_core::arena::FrameArena, area: Rect) -> &'a [Rect] {
677 let inner = area.inner(self.margin);
678 if inner.is_empty() {
679 let mut rects = arena.new_vec_with_capacity::<Rect>(self.constraints.len());
680 for _ in &self.constraints {
681 rects.push(Rect::default());
682 }
683 return rects.into_bump_slice();
684 }
685
686 let total_size = match self.direction {
687 Direction::Horizontal => inner.width,
688 Direction::Vertical => inner.height,
689 };
690
691 let count = self.constraints.len();
692 if count == 0 {
693 return &[];
694 }
695
696 let gap_count = count - 1;
697 let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
698 let available_size = total_size.saturating_sub(total_gap);
699
700 let mut sizes = arena.new_vec_with_capacity::<u16>(count);
701 sizes.resize(count, 0);
702 solve_constraints_with_hints_into(
703 &self.constraints,
704 available_size,
705 &|_, _| LayoutSizeHint::ZERO,
706 None,
707 &mut sizes,
708 );
709 let mut rects = self.sizes_to_rects_in(arena, inner, &sizes);
710
711 if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
712 direction::mirror_rects_horizontal(&mut rects, inner);
713 }
714
715 rects.into_bump_slice()
716 }
717
718 fn sizes_to_rects(&self, area: Rect, sizes: &[u16]) -> Rects {
719 let mut rects = SmallVec::with_capacity(sizes.len());
720 self.populate_rects_from_sizes(area, sizes, |r| rects.push(r));
721 rects
722 }
723
724 fn sizes_to_rects_in<'a>(
725 &self,
726 arena: &'a ftui_core::arena::FrameArena,
727 area: Rect,
728 sizes: &[u16],
729 ) -> ftui_core::arena::BumpVec<'a, Rect> {
730 let mut rects = arena.new_vec_with_capacity::<Rect>(sizes.len());
731 self.populate_rects_from_sizes(area, sizes, |r| rects.push(r));
732 rects
733 }
734
735 fn populate_rects_from_sizes<P: FnMut(Rect)>(&self, area: Rect, sizes: &[u16], mut push: P) {
736 if sizes.is_empty() {
737 return;
738 }
739
740 let total_items_size: u16 = sizes.iter().fold(0u16, |acc, &s| acc.saturating_add(s));
741 let total_available = match self.direction {
742 Direction::Horizontal => area.width,
743 Direction::Vertical => area.height,
744 };
745
746 let (start_shift, use_formula) = match self.alignment {
748 Alignment::Start => (0, None),
749 Alignment::End => {
750 let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
751 .min(u16::MAX as u64) as u16;
752 let used = total_items_size.saturating_add(gap_space);
753 (total_available.saturating_sub(used), None)
754 }
755 Alignment::Center => {
756 let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
757 .min(u16::MAX as u64) as u16;
758 let used = total_items_size.saturating_add(gap_space);
759 (total_available.saturating_sub(used) / 2, None)
760 }
761 Alignment::SpaceBetween => {
762 let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
763 .min(u16::MAX as u64) as u16;
764 let used = total_items_size.saturating_add(gap_space);
765 let leftover = total_available.saturating_sub(used);
766 let slots = sizes.len().saturating_sub(1);
767 if slots > 0 {
768 (0, Some((leftover, slots, 0))) } else {
770 (0, None)
771 }
772 }
773 Alignment::SpaceAround => {
774 let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
775 .min(u16::MAX as u64) as u16;
776 let used = total_items_size.saturating_add(gap_space);
777 let leftover = total_available.saturating_sub(used);
778 let slots = sizes.len() * 2;
779 if slots > 0 {
780 (0, Some((leftover, slots, 1))) } else {
782 (0, None)
783 }
784 }
785 };
786
787 let mut accumulated_size = 0;
788
789 for (i, &size) in sizes.iter().enumerate() {
790 let explicit_gap_so_far = if i > 0 {
791 (i as u64 * self.gap as u64).min(u16::MAX as u64) as u16
792 } else {
793 0
794 };
795
796 let gap_offset = if let Some((leftover, slots, mode)) = use_formula {
797 if mode == 0 {
798 if i == 0 {
800 0
801 } else {
802 explicit_gap_so_far
803 .saturating_add((leftover as u64 * i as u64 / slots as u64) as u16)
804 }
805 } else {
806 let numerator = leftover as u64 * (2 * i as u64 + 1);
808 let denominator = slots as u64;
809 let raw = (numerator + (denominator / 2)) / denominator;
810 explicit_gap_so_far.saturating_add(raw.min(u64::from(u16::MAX)) as u16)
811 }
812 } else {
813 explicit_gap_so_far
815 };
816
817 let pos = match self.direction {
818 Direction::Horizontal => area
819 .x
820 .saturating_add(start_shift)
821 .saturating_add(accumulated_size)
822 .saturating_add(gap_offset),
823 Direction::Vertical => area
824 .y
825 .saturating_add(start_shift)
826 .saturating_add(accumulated_size)
827 .saturating_add(gap_offset),
828 };
829
830 let rect = match self.direction {
831 Direction::Horizontal => Rect {
832 x: pos,
833 y: area.y,
834 width: size.min(area.right().saturating_sub(pos)),
835 height: area.height,
836 },
837 Direction::Vertical => Rect {
838 x: area.x,
839 y: pos,
840 width: area.width,
841 height: size.min(area.bottom().saturating_sub(pos)),
842 },
843 };
844 push(rect);
845 accumulated_size = accumulated_size.saturating_add(size);
846 }
847 }
848
849 pub fn split_with_measurer<F>(&self, area: Rect, measurer: F) -> Rects
873 where
874 F: Fn(usize, u16) -> LayoutSizeHint,
875 {
876 let inner = area.inner(self.margin);
878 if inner.is_empty() {
879 return self.constraints.iter().map(|_| Rect::default()).collect();
880 }
881
882 let total_size = match self.direction {
883 Direction::Horizontal => inner.width,
884 Direction::Vertical => inner.height,
885 };
886
887 let count = self.constraints.len();
888 if count == 0 {
889 return Rects::new();
890 }
891
892 let gap_count = count - 1;
894 let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
895 let available_size = total_size.saturating_sub(total_gap);
896
897 let sizes =
899 solve_constraints_with_hints(&self.constraints, available_size, &measurer, None);
900
901 let mut rects = self.sizes_to_rects(inner, &sizes);
903
904 if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
906 direction::mirror_rects_horizontal(&mut rects, inner);
907 }
908
909 rects
910 }
911
912 pub fn split_with_measurer_in<'a, F>(
914 &self,
915 arena: &'a ftui_core::arena::FrameArena,
916 area: Rect,
917 measurer: F,
918 ) -> &'a [Rect]
919 where
920 F: Fn(usize, u16) -> LayoutSizeHint,
921 {
922 let inner = area.inner(self.margin);
923 if inner.is_empty() {
924 let mut rects = arena.new_vec_with_capacity::<Rect>(self.constraints.len());
925 for _ in &self.constraints {
926 rects.push(Rect::default());
927 }
928 return rects.into_bump_slice();
929 }
930
931 let total_size = match self.direction {
932 Direction::Horizontal => inner.width,
933 Direction::Vertical => inner.height,
934 };
935
936 let count = self.constraints.len();
937 if count == 0 {
938 return &[];
939 }
940
941 let gap_count = count - 1;
942 let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
943 let available_size = total_size.saturating_sub(total_gap);
944
945 let mut sizes = arena.new_vec_with_capacity::<u16>(count);
946 sizes.resize(count, 0);
947 solve_constraints_with_hints_into(
948 &self.constraints,
949 available_size,
950 &measurer,
951 None,
952 &mut sizes,
953 );
954 let mut rects = self.sizes_to_rects_in(arena, inner, &sizes);
955
956 if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
957 direction::mirror_rects_horizontal(&mut rects, inner);
958 }
959
960 rects.into_bump_slice()
961 }
962 pub fn split_with_measurer_stably<F>(
967 &self,
968 area: Rect,
969 measurer: F,
970 cache: &mut CoherenceCache,
971 ) -> Rects
972 where
973 F: Fn(usize, u16) -> LayoutSizeHint,
974 {
975 let inner = area.inner(self.margin);
977 if inner.is_empty() {
978 return self.constraints.iter().map(|_| Rect::default()).collect();
979 }
980
981 let total_size = match self.direction {
982 Direction::Horizontal => inner.width,
983 Direction::Vertical => inner.height,
984 };
985
986 let count = self.constraints.len();
987 if count == 0 {
988 return Rects::new();
989 }
990
991 let gap_count = count - 1;
993 let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
994 let available_size = total_size.saturating_sub(total_gap);
995
996 let id = CoherenceId::new(&self.constraints, self.direction);
998 let sizes = solve_constraints_with_hints(
999 &self.constraints,
1000 available_size,
1001 &measurer,
1002 Some((cache, id)),
1003 );
1004
1005 let mut rects = self.sizes_to_rects(inner, &sizes);
1007
1008 if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
1010 direction::mirror_rects_horizontal(&mut rects, inner);
1011 }
1012
1013 rects
1014 }
1015
1016 pub fn split_with_measurer_stably_in<'a, F>(
1018 &self,
1019 arena: &'a ftui_core::arena::FrameArena,
1020 area: Rect,
1021 measurer: F,
1022 cache: &mut CoherenceCache,
1023 ) -> &'a [Rect]
1024 where
1025 F: Fn(usize, u16) -> LayoutSizeHint,
1026 {
1027 let inner = area.inner(self.margin);
1028 if inner.is_empty() {
1029 let mut rects = arena.new_vec_with_capacity::<Rect>(self.constraints.len());
1030 for _ in &self.constraints {
1031 rects.push(Rect::default());
1032 }
1033 return rects.into_bump_slice();
1034 }
1035
1036 let total_size = match self.direction {
1037 Direction::Horizontal => inner.width,
1038 Direction::Vertical => inner.height,
1039 };
1040
1041 let count = self.constraints.len();
1042 if count == 0 {
1043 return &[];
1044 }
1045
1046 let gap_count = count - 1;
1047 let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
1048 let available_size = total_size.saturating_sub(total_gap);
1049
1050 let id = CoherenceId::new(&self.constraints, self.direction);
1051 let mut sizes = arena.new_vec_with_capacity::<u16>(count);
1052 sizes.resize(count, 0);
1053 solve_constraints_with_hints_into(
1054 &self.constraints,
1055 available_size,
1056 &measurer,
1057 Some((cache, id)),
1058 &mut sizes,
1059 );
1060
1061 let mut rects = self.sizes_to_rects_in(arena, inner, &sizes);
1062
1063 if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
1064 direction::mirror_rects_horizontal(&mut rects, inner);
1065 }
1066
1067 rects.into_bump_slice()
1068 }
1069}
1070
1071pub(crate) fn solve_constraints(constraints: &[Constraint], available_size: u16) -> Sizes {
1076 solve_constraints_with_hints(
1078 constraints,
1079 available_size,
1080 &|_, _| LayoutSizeHint::ZERO,
1081 None,
1082 )
1083}
1084
1085pub(crate) fn solve_constraints_with_hints<F>(
1090 constraints: &[Constraint],
1091 available_size: u16,
1092 measurer: &F,
1093 coherence: Option<(&mut CoherenceCache, CoherenceId)>,
1094) -> Sizes
1095where
1096 F: Fn(usize, u16) -> LayoutSizeHint,
1097{
1098 let mut sizes: Sizes = smallvec::smallvec![0u16; constraints.len()];
1099 solve_constraints_with_hints_into(constraints, available_size, measurer, coherence, &mut sizes);
1100 sizes
1101}
1102
1103pub(crate) fn solve_constraints_with_hints_into<F>(
1104 constraints: &[Constraint],
1105 available_size: u16,
1106 measurer: &F,
1107 mut coherence: Option<(&mut CoherenceCache, CoherenceId)>,
1108 sizes: &mut [u16],
1109) where
1110 F: Fn(usize, u16) -> LayoutSizeHint,
1111{
1112 const WEIGHT_SCALE: u64 = 10_000;
1113
1114 let mut remaining = available_size;
1115 let mut grow_indices: SmallVec<[usize; LAYOUT_INLINE_CAP]> = SmallVec::new();
1116
1117 let grow_weight = |constraint: Constraint| -> u64 {
1118 match constraint {
1119 Constraint::Min(_) | Constraint::Max(_) | Constraint::Fill => WEIGHT_SCALE,
1120 _ => 0,
1121 }
1122 };
1123
1124 for (i, &constraint) in constraints.iter().enumerate() {
1127 match constraint {
1128 Constraint::Fixed(size) => {
1129 let size = min(size, remaining);
1130 sizes[i] = size;
1131 remaining = remaining.saturating_sub(size);
1132 }
1133 Constraint::Min(min_size) => {
1134 let size = min(min_size, remaining);
1135 sizes[i] = size;
1136 remaining = remaining.saturating_sub(size);
1137 }
1139 Constraint::FitMin => {
1140 let hint = measurer(i, remaining);
1141 let size = min(hint.min, remaining);
1142 sizes[i] = size;
1143 remaining = remaining.saturating_sub(size);
1144 }
1145 Constraint::FitContent => {
1146 let hint = measurer(i, remaining);
1147 let size = min(hint.min, remaining);
1148 sizes[i] = size;
1149 remaining = remaining.saturating_sub(size);
1150 }
1151 Constraint::FitContentBounded { min: min_bound, .. } => {
1152 let size = min(min_bound, remaining);
1154 sizes[i] = size;
1155 remaining = remaining.saturating_sub(size);
1156 }
1157 _ => {} }
1159 }
1160
1161 for (i, &constraint) in constraints.iter().enumerate() {
1164 match constraint {
1165 Constraint::Percentage(p) => {
1166 let target = (available_size as f32 * p / 100.0)
1167 .round()
1168 .min(u16::MAX as f32) as u16;
1169 let needed = target.saturating_sub(sizes[i]);
1170 let alloc = min(needed, remaining);
1171 sizes[i] = sizes[i].saturating_add(alloc);
1172 remaining = remaining.saturating_sub(alloc);
1173 }
1174 Constraint::Ratio(n, d) => {
1175 let target = if d == 0 {
1176 0
1177 } else {
1178 (u64::from(available_size) * u64::from(n) / u64::from(d)).min(u16::MAX as u64)
1179 as u16
1180 };
1181 let needed = target.saturating_sub(sizes[i]);
1182 let alloc = min(needed, remaining);
1183 sizes[i] = sizes[i].saturating_add(alloc);
1184 remaining = remaining.saturating_sub(alloc);
1185 }
1186 Constraint::FitContent => {
1187 let hint = measurer(i, remaining);
1188 let preferred = hint
1189 .preferred
1190 .max(sizes[i])
1191 .min(hint.max.unwrap_or(u16::MAX));
1192 let needed = preferred.saturating_sub(sizes[i]);
1193 let alloc = min(needed, remaining);
1194 sizes[i] = sizes[i].saturating_add(alloc);
1195 remaining = remaining.saturating_sub(alloc);
1196 }
1197 Constraint::FitContentBounded { max: max_bound, .. } => {
1198 let hint = measurer(i, remaining);
1199 let preferred = hint.preferred.max(sizes[i]).min(max_bound);
1200 let needed = preferred.saturating_sub(sizes[i]);
1201 let alloc = min(needed, remaining);
1202 sizes[i] = sizes[i].saturating_add(alloc);
1203 remaining = remaining.saturating_sub(alloc);
1204 }
1205 Constraint::Min(_) => {
1206 grow_indices.push(i);
1207 }
1208 Constraint::Max(_) => {
1209 grow_indices.push(i);
1210 }
1211 Constraint::Fill => {
1212 grow_indices.push(i);
1213 }
1214 _ => {} }
1216 }
1217
1218 loop {
1220 if remaining == 0 || grow_indices.is_empty() {
1221 break;
1222 }
1223
1224 let mut total_weight = 0u128;
1225 for &i in &grow_indices {
1226 let weight = grow_weight(constraints[i]);
1227 if weight > 0 {
1228 total_weight = total_weight.saturating_add(u128::from(weight));
1229 }
1230 }
1231
1232 if total_weight == 0 {
1233 break;
1234 }
1235
1236 let space_to_distribute = remaining;
1237
1238 let targets: SmallVec<[f64; LAYOUT_INLINE_CAP]> = grow_indices
1240 .iter()
1241 .map(|&i| {
1242 let weight = grow_weight(constraints[i]);
1243 (space_to_distribute as f64 * weight as f64) / total_weight as f64
1244 })
1245 .collect();
1246
1247 let prev_alloc = coherence
1249 .as_ref()
1250 .and_then(|(cache, id)| cache.get(id))
1251 .map(|full_prev| {
1252 grow_indices
1254 .iter()
1255 .map(|&i| full_prev.get(i).copied().unwrap_or(0))
1256 .collect()
1257 });
1258
1259 let distributed = round_layout_stable(&targets, space_to_distribute, prev_alloc);
1261
1262 let mut violations: SmallVec<[usize; LAYOUT_INLINE_CAP]> = SmallVec::new();
1264 for (k, &i) in grow_indices.iter().enumerate() {
1265 if let Constraint::Max(max_val) = constraints[i]
1266 && sizes[i].saturating_add(distributed[k]) > max_val
1267 {
1268 violations.push(i);
1269 }
1270 }
1271
1272 if violations.is_empty() {
1273 for (k, &i) in grow_indices.iter().enumerate() {
1275 sizes[i] = sizes[i].saturating_add(distributed[k]);
1276 }
1277 if let Some((cache, id)) = coherence.as_mut() {
1278 if distributed.len() == targets.len() {
1281 let mut full_shares: Sizes = smallvec::smallvec![0u16; constraints.len()];
1282 for (k, &i) in grow_indices.iter().enumerate() {
1283 full_shares[i] = distributed[k];
1284 }
1285 cache.store(*id, full_shares);
1286 }
1287 }
1288 break;
1289 }
1290
1291 for i in violations {
1293 if let Constraint::Max(max_val) = constraints[i] {
1294 let consumed = max_val.saturating_sub(sizes[i]);
1297 sizes[i] = max_val;
1298 remaining = remaining.saturating_sub(consumed);
1299
1300 if let Some(pos) = grow_indices.iter().position(|&x| x == i) {
1302 grow_indices.remove(pos);
1303 }
1304 }
1305 }
1306 }
1307}
1308
1309pub type PreviousAllocation = Option<Sizes>;
1319
1320pub fn round_layout_stable(targets: &[f64], total: u16, prev: PreviousAllocation) -> Sizes {
1382 let n = targets.len();
1383 if n == 0 {
1384 return Sizes::new();
1385 }
1386
1387 let floors: Sizes = targets
1389 .iter()
1390 .map(|&r| (r.max(0.0).floor() as u64).min(u16::MAX as u64) as u16)
1391 .collect();
1392
1393 let floor_sum: u64 = floors.iter().map(|&x| u64::from(x)).sum();
1394 let total_u64 = u64::from(total);
1395
1396 if floor_sum > total_u64 {
1398 return redistribute_overflow(&floors, total);
1399 }
1400
1401 let deficit = (total_u64 - floor_sum) as u16;
1402
1403 if deficit == 0 {
1404 return floors;
1406 }
1407
1408 let mut priority: SmallVec<[(usize, f64, bool); LAYOUT_INLINE_CAP]> = targets
1410 .iter()
1411 .enumerate()
1412 .map(|(i, &r)| {
1413 let raw_remainder = r - (floors[i] as f64);
1416 let remainder = if raw_remainder.is_finite() {
1417 raw_remainder
1418 } else {
1419 0.0
1420 };
1421 let ceil_val = floors[i].saturating_add(1);
1422 let prev_used_ceil = prev
1424 .as_ref()
1425 .is_some_and(|p| p.get(i).copied() == Some(ceil_val));
1426 (i, remainder, prev_used_ceil)
1427 })
1428 .collect();
1429
1430 priority.sort_by(|a, b| {
1436 b.1.total_cmp(&a.1)
1437 .then_with(|| {
1438 b.2.cmp(&a.2)
1440 })
1441 .then_with(|| {
1442 a.0.cmp(&b.0)
1444 })
1445 });
1446
1447 let mut result = floors;
1449 let mut remaining_deficit = deficit;
1450
1451 if remaining_deficit as usize >= n {
1457 let per_item = remaining_deficit / (n as u16);
1458 for val in result.iter_mut() {
1459 *val = val.saturating_add(per_item);
1460 }
1461 remaining_deficit %= n as u16;
1462 }
1463
1464 if remaining_deficit > 0 {
1465 for &(i, _, _) in priority.iter().take(remaining_deficit as usize) {
1466 result[i] = result[i].saturating_add(1);
1467 }
1468 }
1469
1470 result
1471}
1472
1473fn redistribute_overflow(floors: &[u16], total: u16) -> Sizes {
1478 let mut result: Sizes = floors.iter().copied().collect();
1479 let current_sum: u64 = result.iter().map(|&x| u64::from(x)).sum();
1480 let total_u64 = u64::from(total);
1481 let n = result.len();
1482
1483 if current_sum <= total_u64 || n == 0 {
1484 return result;
1485 }
1486
1487 let mut overflow = current_sum - total_u64;
1488
1489 while overflow > 0 {
1490 let &max_val = result.iter().max().unwrap_or(&0);
1491 if max_val == 0 {
1492 for val in result.iter_mut() {
1496 *val = 0;
1497 }
1498 break;
1499 }
1500
1501 let count_max = result.iter().filter(|&&v| v == max_val).count() as u64;
1502 let &next_max = result.iter().filter(|&&v| v < max_val).max().unwrap_or(&0);
1503
1504 let delta = (max_val - next_max) as u64;
1505 let required_per_item = overflow.div_ceil(count_max);
1506 let reduce_per_item = delta.min(required_per_item).max(1) as u16;
1507
1508 let mut reduced_any = false;
1509 for val in result.iter_mut() {
1510 if *val == max_val {
1511 let amount = u64::from(*val)
1512 .min(u64::from(reduce_per_item))
1513 .min(overflow) as u16;
1514 if amount > 0 {
1515 *val -= amount;
1516 overflow -= u64::from(amount);
1517 reduced_any = true;
1518 }
1519 if overflow == 0 {
1520 break;
1521 }
1522 }
1523 }
1524
1525 if !reduced_any {
1526 for val in result.iter_mut() {
1528 if overflow == 0 {
1529 break;
1530 }
1531 if *val > 0 {
1532 *val -= 1;
1533 overflow -= 1;
1534 }
1535 }
1536 break;
1537 }
1538 }
1539
1540 result
1541}
1542
1543#[cfg(test)]
1544mod tests {
1545 use super::*;
1546
1547 #[test]
1548 fn an_oversubscribed_row_shrinks_rather_than_overlapping() {
1549 for width in [120u16, 43, 42, 38, 20] {
1554 let rects = Flex::horizontal()
1555 .constraints([Constraint::Min(11), Constraint::Fixed(32)])
1556 .split(Rect::new(0, 0, width, 3));
1557 let total: u32 = rects.iter().map(|r| u32::from(r.width)).sum();
1558 assert_eq!(total, u32::from(width), "row {width} not fully used");
1559 assert!(
1560 rects.windows(2).all(|w| w[0].x + w[0].width <= w[1].x),
1561 "rects overlap at width {width}: {rects:?}"
1562 );
1563 assert!(
1564 rects
1565 .iter()
1566 .all(|r| u32::from(r.x) + u32::from(r.width) <= u32::from(width)),
1567 "rect past the end at width {width}: {rects:?}"
1568 );
1569 }
1570 }
1571
1572 #[test]
1573 fn round_layout_stable_nan_targets_do_not_panic_the_sort() {
1574 let mut targets: Vec<f64> = (0..64).map(|i| (i as f64) * 0.37 + 0.1).collect();
1579 targets[7] = f64::NAN;
1580 targets[23] = f64::INFINITY;
1581 targets[41] = f64::NEG_INFINITY;
1582
1583 let sizes = round_layout_stable(&targets, 120, None);
1586 assert_eq!(sizes.len(), 64);
1587
1588 let nan_targets = [f64::NAN; 8];
1591 let sizes = round_layout_stable(&nan_targets, 40, None);
1592 let sum: u64 = sizes.iter().map(|&x| u64::from(x)).sum();
1593 assert_eq!(sum, 40);
1594 }
1595
1596 #[test]
1597 fn fixed_split() {
1598 let flex = Flex::horizontal().constraints([Constraint::Fixed(10), Constraint::Fixed(20)]);
1599 let rects = flex.split(Rect::new(0, 0, 100, 10));
1600 assert_eq!(rects.len(), 2);
1601 assert_eq!(rects[0], Rect::new(0, 0, 10, 10));
1602 assert_eq!(rects[1], Rect::new(10, 0, 20, 10)); }
1604
1605 #[test]
1606 fn percentage_split() {
1607 let flex = Flex::horizontal()
1608 .constraints([Constraint::Percentage(50.0), Constraint::Percentage(50.0)]);
1609 let rects = flex.split(Rect::new(0, 0, 100, 10));
1610 assert_eq!(rects[0].width, 50);
1611 assert_eq!(rects[1].width, 50);
1612 }
1613
1614 #[test]
1615 fn gap_handling() {
1616 let flex = Flex::horizontal()
1617 .gap(5)
1618 .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1619 let rects = flex.split(Rect::new(0, 0, 100, 10));
1620 assert_eq!(rects[0], Rect::new(0, 0, 10, 10));
1624 assert_eq!(rects[1], Rect::new(15, 0, 10, 10));
1625 }
1626
1627 #[test]
1628 fn mixed_constraints() {
1629 let flex = Flex::horizontal().constraints([
1630 Constraint::Fixed(10),
1631 Constraint::Min(10), Constraint::Percentage(10.0), ]);
1634
1635 let rects = flex.split(Rect::new(0, 0, 100, 1));
1643 assert_eq!(rects[0].width, 10); assert_eq!(rects[2].width, 10); assert_eq!(rects[1].width, 80); }
1647
1648 #[test]
1649 fn measurement_fixed_constraints() {
1650 let fixed = Measurement::fixed(5, 7);
1651 assert_eq!(fixed.min_width, 5);
1652 assert_eq!(fixed.min_height, 7);
1653 assert_eq!(fixed.max_width, Some(5));
1654 assert_eq!(fixed.max_height, Some(7));
1655 }
1656
1657 #[test]
1658 fn measurement_flexible_constraints() {
1659 let flexible = Measurement::flexible(2, 3);
1660 assert_eq!(flexible.min_width, 2);
1661 assert_eq!(flexible.min_height, 3);
1662 assert_eq!(flexible.max_width, None);
1663 assert_eq!(flexible.max_height, None);
1664 }
1665
1666 #[test]
1667 fn breakpoints_classify_defaults() {
1668 let bp = Breakpoints::DEFAULT;
1669 assert_eq!(bp.classify_width(20), Breakpoint::Xs);
1670 assert_eq!(bp.classify_width(60), Breakpoint::Sm);
1671 assert_eq!(bp.classify_width(90), Breakpoint::Md);
1672 assert_eq!(bp.classify_width(120), Breakpoint::Lg);
1673 }
1674
1675 #[test]
1676 fn breakpoints_at_least_and_between() {
1677 let bp = Breakpoints::new(50, 80, 110);
1678 assert!(bp.at_least(85, Breakpoint::Sm));
1679 assert!(bp.between(85, Breakpoint::Sm, Breakpoint::Md));
1680 assert!(!bp.between(85, Breakpoint::Lg, Breakpoint::Lg));
1681 }
1682
1683 #[test]
1684 fn alignment_end() {
1685 let flex = Flex::horizontal()
1686 .alignment(Alignment::End)
1687 .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1688 let rects = flex.split(Rect::new(0, 0, 100, 10));
1689 assert_eq!(rects[0], Rect::new(80, 0, 10, 10));
1691 assert_eq!(rects[1], Rect::new(90, 0, 10, 10));
1692 }
1693
1694 #[test]
1695 fn alignment_center() {
1696 let flex = Flex::horizontal()
1697 .alignment(Alignment::Center)
1698 .constraints([Constraint::Fixed(20), Constraint::Fixed(20)]);
1699 let rects = flex.split(Rect::new(0, 0, 100, 10));
1700 assert_eq!(rects[0], Rect::new(30, 0, 20, 10));
1702 assert_eq!(rects[1], Rect::new(50, 0, 20, 10));
1703 }
1704
1705 #[test]
1706 fn alignment_space_between() {
1707 let flex = Flex::horizontal()
1708 .alignment(Alignment::SpaceBetween)
1709 .constraints([
1710 Constraint::Fixed(10),
1711 Constraint::Fixed(10),
1712 Constraint::Fixed(10),
1713 ]);
1714 let rects = flex.split(Rect::new(0, 0, 100, 10));
1715 assert_eq!(rects[0].x, 0);
1717 assert_eq!(rects[1].x, 45); assert_eq!(rects[2].x, 90); }
1720
1721 #[test]
1722 fn vertical_alignment() {
1723 let flex = Flex::vertical()
1724 .alignment(Alignment::End)
1725 .constraints([Constraint::Fixed(5), Constraint::Fixed(5)]);
1726 let rects = flex.split(Rect::new(0, 0, 10, 100));
1727 assert_eq!(rects[0], Rect::new(0, 90, 10, 5));
1729 assert_eq!(rects[1], Rect::new(0, 95, 10, 5));
1730 }
1731
1732 #[test]
1733 fn nested_flex_support() {
1734 let outer = Flex::horizontal()
1736 .constraints([Constraint::Percentage(50.0), Constraint::Percentage(50.0)]);
1737 let outer_rects = outer.split(Rect::new(0, 0, 100, 100));
1738
1739 let inner = Flex::vertical().constraints([Constraint::Fixed(30), Constraint::Min(10)]);
1741 let inner_rects = inner.split(outer_rects[0]);
1742
1743 assert_eq!(inner_rects[0], Rect::new(0, 0, 50, 30));
1744 assert_eq!(inner_rects[1], Rect::new(0, 30, 50, 70));
1745 }
1746
1747 #[test]
1749 fn invariant_total_size_does_not_exceed_available() {
1750 for total in [10u16, 50, 100, 255] {
1752 let flex = Flex::horizontal().constraints([
1753 Constraint::Fixed(30),
1754 Constraint::Percentage(50.0),
1755 Constraint::Min(20),
1756 ]);
1757 let rects = flex.split(Rect::new(0, 0, total, 10));
1758 let total_width: u16 = rects.iter().map(|r| r.width).sum();
1759 assert!(
1760 total_width <= total,
1761 "Total width {} exceeded available {} for constraints",
1762 total_width,
1763 total
1764 );
1765 }
1766 }
1767
1768 #[test]
1769 fn invariant_empty_area_produces_empty_rects() {
1770 let flex = Flex::horizontal().constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1771 let rects = flex.split(Rect::new(0, 0, 0, 0));
1772 assert!(rects.iter().all(|r| r.is_empty()));
1773 }
1774
1775 #[test]
1776 fn invariant_no_constraints_produces_empty_vec() {
1777 let flex = Flex::horizontal().constraints([]);
1778 let rects = flex.split(Rect::new(0, 0, 100, 100));
1779 assert!(rects.is_empty());
1780 }
1781
1782 #[test]
1783 fn flex_constraints_stay_inline_for_common_layouts() {
1784 let flex = Flex::horizontal().constraints([Constraint::Fixed(1); LAYOUT_INLINE_CAP]);
1785 assert_eq!(flex.constraint_count(), LAYOUT_INLINE_CAP);
1786 assert!(!flex.constraints.spilled());
1787
1788 let rects = flex.split(Rect::new(0, 0, LAYOUT_INLINE_CAP as u16, 1));
1789 assert_eq!(rects.len(), LAYOUT_INLINE_CAP);
1790 assert!(rects.iter().all(|rect| rect.width == 1));
1791 }
1792
1793 #[test]
1796 fn ratio_constraint_splits_proportionally() {
1797 let flex =
1798 Flex::horizontal().constraints([Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)]);
1799 let rects = flex.split(Rect::new(0, 0, 90, 10));
1800 assert_eq!(rects[0].width, 30);
1801 assert_eq!(rects[1].width, 60);
1802 }
1803
1804 #[test]
1805 fn ratio_constraint_with_zero_denominator() {
1806 let flex = Flex::horizontal().constraints([Constraint::Ratio(1, 0)]);
1808 let rects = flex.split(Rect::new(0, 0, 100, 10));
1809 assert_eq!(rects.len(), 1);
1810 }
1811
1812 #[test]
1813 fn ratio_is_absolute_fraction() {
1814 let area = Rect::new(0, 0, 100, 1);
1815
1816 let rects = Flex::horizontal()
1818 .constraints([Constraint::Percentage(25.0)])
1819 .split(area);
1820 assert_eq!(rects[0].width, 25);
1821
1822 let rects = Flex::horizontal()
1825 .constraints([Constraint::Ratio(1, 4)])
1826 .split(area);
1827 assert_eq!(rects[0].width, 25);
1828 }
1829
1830 #[test]
1831 fn ratio_is_independent_of_grow_items() {
1832 let area = Rect::new(0, 0, 100, 1);
1833
1834 let rects = Flex::horizontal()
1836 .constraints([Constraint::Ratio(1, 4), Constraint::Fill])
1837 .split(area);
1838 assert_eq!(rects[0].width, 25);
1839 assert_eq!(rects[1].width, 75);
1840 }
1841
1842 #[test]
1843 fn ratio_zero_numerator_should_be_zero() {
1844 let flex = Flex::horizontal().constraints([Constraint::Fill, Constraint::Ratio(0, 1)]);
1847 let rects = flex.split(Rect::new(0, 0, 100, 1));
1848
1849 assert_eq!(rects[0].width, 100, "Fill should take all space");
1851 assert_eq!(rects[1].width, 0, "Ratio(0, 1) should be width 0");
1852 }
1853
1854 #[test]
1857 fn max_constraint_clamps_size() {
1858 let flex = Flex::horizontal().constraints([Constraint::Max(20), Constraint::Fixed(30)]);
1859 let rects = flex.split(Rect::new(0, 0, 100, 10));
1860 assert!(rects[0].width <= 20);
1861 assert_eq!(rects[1].width, 30);
1862 }
1863
1864 #[test]
1865 fn percentage_rounding_never_exceeds_available() {
1866 let constraints = [
1867 Constraint::Percentage(33.4),
1868 Constraint::Percentage(33.3),
1869 Constraint::Percentage(33.3),
1870 ];
1871 let sizes = solve_constraints(&constraints, 7);
1872 let total: u16 = sizes.iter().sum();
1873 assert!(total <= 7, "percent rounding overflowed: {sizes:?}");
1874 assert!(sizes.iter().all(|size| *size <= 7));
1875 }
1876
1877 #[test]
1878 fn tiny_area_saturates_fixed_and_min() {
1879 let constraints = [Constraint::Fixed(5), Constraint::Min(3), Constraint::Max(2)];
1880 let sizes = solve_constraints(&constraints, 2);
1881 assert_eq!(sizes[0], 2);
1882 assert_eq!(sizes[1], 0);
1883 assert_eq!(sizes[2], 0);
1884 assert_eq!(sizes.iter().sum::<u16>(), 2);
1885 }
1886
1887 #[test]
1888 fn ratio_distribution_sums_to_available() {
1889 let constraints = [Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)];
1891 let sizes = solve_constraints(&constraints, 5);
1892 assert_eq!(sizes.iter().sum::<u16>(), 4);
1893 assert_eq!(sizes[0], 1);
1894 assert_eq!(sizes[1], 3);
1895 }
1896
1897 #[test]
1898 fn flex_gap_exceeds_area_yields_zero_widths() {
1899 let flex = Flex::horizontal()
1900 .gap(5)
1901 .constraints([Constraint::Fixed(1), Constraint::Fixed(1)]);
1902 let rects = flex.split(Rect::new(0, 0, 3, 1));
1903 assert_eq!(rects.len(), 2);
1904 assert_eq!(rects[0].width, 0);
1905 assert_eq!(rects[1].width, 0);
1906 }
1907
1908 #[test]
1911 fn alignment_space_around() {
1912 let flex = Flex::horizontal()
1913 .alignment(Alignment::SpaceAround)
1914 .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1915 let rects = flex.split(Rect::new(0, 0, 100, 10));
1916
1917 assert_eq!(rects[0].x, 20);
1920 assert_eq!(rects[1].x, 70);
1921 }
1922
1923 #[test]
1926 fn vertical_gap() {
1927 let flex = Flex::vertical()
1928 .gap(5)
1929 .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1930 let rects = flex.split(Rect::new(0, 0, 50, 100));
1931 assert_eq!(rects[0], Rect::new(0, 0, 50, 10));
1932 assert_eq!(rects[1], Rect::new(0, 15, 50, 10));
1933 }
1934
1935 #[test]
1938 fn vertical_center() {
1939 let flex = Flex::vertical()
1940 .alignment(Alignment::Center)
1941 .constraints([Constraint::Fixed(10)]);
1942 let rects = flex.split(Rect::new(0, 0, 50, 100));
1943 assert_eq!(rects[0].y, 45);
1945 assert_eq!(rects[0].height, 10);
1946 }
1947
1948 #[test]
1951 fn single_min_takes_all() {
1952 let flex = Flex::horizontal().constraints([Constraint::Min(5)]);
1953 let rects = flex.split(Rect::new(0, 0, 80, 24));
1954 assert_eq!(rects[0].width, 80);
1955 }
1956
1957 #[test]
1960 fn fixed_exceeds_available_clamped() {
1961 let flex = Flex::horizontal().constraints([Constraint::Fixed(60), Constraint::Fixed(60)]);
1962 let rects = flex.split(Rect::new(0, 0, 100, 10));
1963 assert_eq!(rects[0].width, 60);
1965 assert_eq!(rects[1].width, 40);
1966 }
1967
1968 #[test]
1971 fn percentage_overflow_clamped() {
1972 let flex = Flex::horizontal()
1973 .constraints([Constraint::Percentage(80.0), Constraint::Percentage(80.0)]);
1974 let rects = flex.split(Rect::new(0, 0, 100, 10));
1975 assert_eq!(rects[0].width, 80);
1976 assert_eq!(rects[1].width, 20); }
1978
1979 #[test]
1982 fn margin_reduces_split_area() {
1983 let flex = Flex::horizontal()
1984 .margin(Sides::all(10))
1985 .constraints([Constraint::Fixed(20), Constraint::Min(0)]);
1986 let rects = flex.split(Rect::new(0, 0, 100, 100));
1987 assert_eq!(rects[0].x, 10);
1989 assert_eq!(rects[0].y, 10);
1990 assert_eq!(rects[0].width, 20);
1991 assert_eq!(rects[0].height, 80);
1992 }
1993
1994 #[test]
1997 fn builder_methods_chain() {
1998 let flex = Flex::vertical()
1999 .direction(Direction::Horizontal)
2000 .gap(3)
2001 .margin(Sides::all(1))
2002 .alignment(Alignment::End)
2003 .constraints([Constraint::Fixed(10)]);
2004 let rects = flex.split(Rect::new(0, 0, 50, 50));
2005 assert_eq!(rects.len(), 1);
2006 }
2007
2008 #[test]
2011 fn space_between_single_item() {
2012 let flex = Flex::horizontal()
2013 .alignment(Alignment::SpaceBetween)
2014 .constraints([Constraint::Fixed(10)]);
2015 let rects = flex.split(Rect::new(0, 0, 100, 10));
2016 assert_eq!(rects[0].x, 0);
2018 assert_eq!(rects[0].width, 10);
2019 }
2020
2021 #[test]
2022 fn invariant_rects_within_bounds() {
2023 let area = Rect::new(10, 20, 80, 60);
2024 let flex = Flex::horizontal()
2025 .margin(Sides::all(5))
2026 .gap(2)
2027 .constraints([
2028 Constraint::Fixed(15),
2029 Constraint::Percentage(30.0),
2030 Constraint::Min(10),
2031 ]);
2032 let rects = flex.split(area);
2033
2034 let inner = area.inner(Sides::all(5));
2036 for rect in &rects {
2037 assert!(
2038 rect.x >= inner.x && rect.right() <= inner.right(),
2039 "Rect {:?} exceeds horizontal bounds of {:?}",
2040 rect,
2041 inner
2042 );
2043 assert!(
2044 rect.y >= inner.y && rect.bottom() <= inner.bottom(),
2045 "Rect {:?} exceeds vertical bounds of {:?}",
2046 rect,
2047 inner
2048 );
2049 }
2050 }
2051
2052 #[test]
2055 fn fill_takes_remaining_space() {
2056 let flex = Flex::horizontal().constraints([Constraint::Fixed(20), Constraint::Fill]);
2057 let rects = flex.split(Rect::new(0, 0, 100, 10));
2058 assert_eq!(rects[0].width, 20);
2059 assert_eq!(rects[1].width, 80); }
2061
2062 #[test]
2063 fn multiple_fills_share_space() {
2064 let flex = Flex::horizontal().constraints([Constraint::Fill, Constraint::Fill]);
2065 let rects = flex.split(Rect::new(0, 0, 100, 10));
2066 assert_eq!(rects[0].width, 50);
2067 assert_eq!(rects[1].width, 50);
2068 }
2069
2070 #[test]
2073 fn fit_content_uses_preferred_size() {
2074 let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
2075 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |idx, _| {
2076 if idx == 0 {
2077 LayoutSizeHint {
2078 min: 5,
2079 preferred: 30,
2080 max: None,
2081 }
2082 } else {
2083 LayoutSizeHint::ZERO
2084 }
2085 });
2086 assert_eq!(rects[0].width, 30); assert_eq!(rects[1].width, 70); }
2089
2090 #[test]
2091 fn fit_content_clamps_to_available() {
2092 let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::FitContent]);
2093 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
2094 min: 5,
2095 preferred: 80,
2096 max: None,
2097 });
2098 assert_eq!(rects[0].width, 80);
2100 assert_eq!(rects[1].width, 20);
2101 }
2102
2103 #[test]
2104 fn fit_content_without_measurer_gets_zero() {
2105 let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
2107 let rects = flex.split(Rect::new(0, 0, 100, 10));
2108 assert_eq!(rects[0].width, 0); assert_eq!(rects[1].width, 100); }
2111
2112 #[test]
2113 fn fit_content_zero_area_returns_empty_rects() {
2114 let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
2115 let rects = flex.split_with_measurer(Rect::new(0, 0, 0, 0), |_, _| LayoutSizeHint {
2116 min: 5,
2117 preferred: 10,
2118 max: None,
2119 });
2120 assert_eq!(rects.len(), 2);
2121 assert_eq!(rects[0].width, 0);
2122 assert_eq!(rects[0].height, 0);
2123 assert_eq!(rects[1].width, 0);
2124 assert_eq!(rects[1].height, 0);
2125 }
2126
2127 #[test]
2128 fn fit_content_tiny_available_clamps_to_remaining() {
2129 let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
2130 let rects = flex.split_with_measurer(Rect::new(0, 0, 1, 1), |_, _| LayoutSizeHint {
2131 min: 5,
2132 preferred: 10,
2133 max: None,
2134 });
2135 assert_eq!(rects[0].width, 1);
2136 assert_eq!(rects[1].width, 0);
2137 }
2138
2139 #[test]
2142 fn fit_content_bounded_clamps_to_min() {
2143 let flex = Flex::horizontal().constraints([
2144 Constraint::FitContentBounded { min: 20, max: 50 },
2145 Constraint::Fill,
2146 ]);
2147 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
2148 min: 5,
2149 preferred: 10, max: None,
2151 });
2152 assert_eq!(rects[0].width, 20); assert_eq!(rects[1].width, 80);
2154 }
2155
2156 #[test]
2157 fn fit_content_bounded_respects_small_available() {
2158 let flex = Flex::horizontal().constraints([
2159 Constraint::FitContentBounded { min: 20, max: 50 },
2160 Constraint::Fill,
2161 ]);
2162 let rects = flex.split_with_measurer(Rect::new(0, 0, 5, 2), |_, _| LayoutSizeHint {
2163 min: 5,
2164 preferred: 10,
2165 max: None,
2166 });
2167 assert_eq!(rects[0].width, 5);
2169 assert_eq!(rects[1].width, 0);
2170 }
2171
2172 #[test]
2173 fn fit_content_bounded_clamps_to_max() {
2174 let flex = Flex::horizontal().constraints([
2175 Constraint::FitContentBounded { min: 10, max: 30 },
2176 Constraint::Fill,
2177 ]);
2178 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
2179 min: 5,
2180 preferred: 50, max: None,
2182 });
2183 assert_eq!(rects[0].width, 30); assert_eq!(rects[1].width, 70);
2185 }
2186
2187 #[test]
2188 fn fit_content_bounded_uses_preferred_when_in_range() {
2189 let flex = Flex::horizontal().constraints([
2190 Constraint::FitContentBounded { min: 10, max: 50 },
2191 Constraint::Fill,
2192 ]);
2193 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
2194 min: 5,
2195 preferred: 35, max: None,
2197 });
2198 assert_eq!(rects[0].width, 35);
2199 assert_eq!(rects[1].width, 65);
2200 }
2201
2202 #[test]
2205 fn fit_min_uses_minimum_size() {
2206 let flex = Flex::horizontal().constraints([Constraint::FitMin, Constraint::Fill]);
2207 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |idx, _| {
2208 if idx == 0 {
2209 LayoutSizeHint {
2210 min: 15,
2211 preferred: 40,
2212 max: None,
2213 }
2214 } else {
2215 LayoutSizeHint::ZERO
2216 }
2217 });
2218 assert_eq!(rects[0].width, 15, "FitMin should strict size to min");
2221 assert_eq!(rects[1].width, 85, "Fill should take remaining space");
2222 }
2223
2224 #[test]
2225 fn fit_min_without_measurer_gets_zero() {
2226 let flex = Flex::horizontal().constraints([Constraint::FitMin, Constraint::Fill]);
2227 let rects = flex.split(Rect::new(0, 0, 100, 10));
2228 assert_eq!(rects[0].width, 0);
2231 assert_eq!(rects[1].width, 100);
2232 }
2233
2234 #[test]
2237 fn layout_size_hint_zero_is_default() {
2238 assert_eq!(LayoutSizeHint::default(), LayoutSizeHint::ZERO);
2239 }
2240
2241 #[test]
2242 fn layout_size_hint_exact() {
2243 let h = LayoutSizeHint::exact(25);
2244 assert_eq!(h.min, 25);
2245 assert_eq!(h.preferred, 25);
2246 assert_eq!(h.max, Some(25));
2247 }
2248
2249 #[test]
2250 fn layout_size_hint_at_least() {
2251 let h = LayoutSizeHint::at_least(10, 30);
2252 assert_eq!(h.min, 10);
2253 assert_eq!(h.preferred, 30);
2254 assert_eq!(h.max, None);
2255 }
2256
2257 #[test]
2258 fn layout_size_hint_clamp() {
2259 let h = LayoutSizeHint {
2260 min: 10,
2261 preferred: 20,
2262 max: Some(30),
2263 };
2264 assert_eq!(h.clamp(5), 10); assert_eq!(h.clamp(15), 15); assert_eq!(h.clamp(50), 30); }
2268
2269 #[test]
2270 fn layout_size_hint_clamp_unbounded() {
2271 let h = LayoutSizeHint::at_least(5, 10);
2272 assert_eq!(h.clamp(3), 5); assert_eq!(h.clamp(1000), 1000); }
2275
2276 #[test]
2277 fn layout_size_hint_clamp_min_greater_than_max() {
2278 let h = LayoutSizeHint {
2280 min: 20,
2281 preferred: 20,
2282 max: Some(10),
2283 };
2284 assert_eq!(h.clamp(5), 20); assert_eq!(h.clamp(15), 20); assert_eq!(h.clamp(25), 20); }
2288
2289 #[test]
2292 fn fit_content_with_fixed_and_fill() {
2293 let flex = Flex::horizontal().constraints([
2294 Constraint::Fixed(20),
2295 Constraint::FitContent,
2296 Constraint::Fill,
2297 ]);
2298 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |idx, _| {
2299 if idx == 1 {
2300 LayoutSizeHint {
2301 min: 5,
2302 preferred: 25,
2303 max: None,
2304 }
2305 } else {
2306 LayoutSizeHint::ZERO
2307 }
2308 });
2309 assert_eq!(rects[0].width, 20); assert_eq!(rects[1].width, 25); assert_eq!(rects[2].width, 55); }
2313
2314 #[test]
2315 fn total_allocation_never_exceeds_available_with_fit_content() {
2316 for available in [10u16, 50, 100, 255] {
2317 let flex = Flex::horizontal().constraints([
2318 Constraint::FitContent,
2319 Constraint::FitContent,
2320 Constraint::Fill,
2321 ]);
2322 let rects =
2323 flex.split_with_measurer(Rect::new(0, 0, available, 10), |_, _| LayoutSizeHint {
2324 min: 10,
2325 preferred: 40,
2326 max: None,
2327 });
2328 let total: u16 = rects.iter().map(|r| r.width).sum();
2329 assert!(
2330 total <= available,
2331 "Total {} exceeded available {} with FitContent",
2332 total,
2333 available
2334 );
2335 }
2336 }
2337
2338 mod rounding_tests {
2343 use super::super::*;
2344
2345 #[test]
2348 fn rounding_conserves_sum_exact() {
2349 let result = round_layout_stable(&[10.0, 20.0, 10.0], 40, None);
2350 assert_eq!(result.iter().copied().sum::<u16>(), 40);
2351 assert_eq!(result.as_slice(), &[10u16, 20u16, 10u16]);
2352 }
2353
2354 #[test]
2355 fn rounding_conserves_sum_fractional() {
2356 let result = round_layout_stable(&[10.4, 20.6, 9.0], 40, None);
2357 assert_eq!(
2358 result.iter().copied().sum::<u16>(),
2359 40,
2360 "Sum must equal total: {:?}",
2361 result
2362 );
2363 }
2364
2365 #[test]
2366 fn rounding_conserves_sum_many_fractions() {
2367 let targets = vec![20.2, 20.2, 20.2, 20.2, 19.2];
2368 let result = round_layout_stable(&targets, 100, None);
2369 assert_eq!(
2370 result.iter().copied().sum::<u16>(),
2371 100,
2372 "Sum must be exactly 100: {:?}",
2373 result
2374 );
2375 }
2376
2377 #[test]
2378 fn rounding_conserves_sum_all_half() {
2379 let targets = vec![10.5, 10.5, 10.5, 10.5];
2380 let result = round_layout_stable(&targets, 42, None);
2381 assert_eq!(
2382 result.iter().copied().sum::<u16>(),
2383 42,
2384 "Sum must be exactly 42: {:?}",
2385 result
2386 );
2387 }
2388
2389 #[test]
2392 fn rounding_displacement_bounded() {
2393 let targets = vec![33.33, 33.33, 33.34];
2394 let result = round_layout_stable(&targets, 100, None);
2395 assert_eq!(result.iter().copied().sum::<u16>(), 100);
2396
2397 for (i, (&x, &r)) in result.iter().zip(targets.iter()).enumerate() {
2398 let floor = r.floor() as u16;
2399 let ceil = floor + 1;
2400 assert!(
2401 x == floor || x == ceil,
2402 "Element {} = {} not in {{floor={}, ceil={}}} of target {}",
2403 i,
2404 x,
2405 floor,
2406 ceil,
2407 r
2408 );
2409 }
2410 }
2411
2412 #[test]
2415 fn temporal_tiebreak_stable_when_unchanged() {
2416 let targets = vec![10.5, 10.5, 10.5, 10.5];
2417 let first = round_layout_stable(&targets, 42, None);
2418 let second = round_layout_stable(&targets, 42, Some(first.clone()));
2419 assert_eq!(
2420 first, second,
2421 "Identical targets should produce identical results"
2422 );
2423 }
2424
2425 #[test]
2426 fn temporal_tiebreak_prefers_previous_direction() {
2427 let targets = vec![10.5, 10.5];
2428 let total = 21;
2429 let first = round_layout_stable(&targets, total, None);
2430 assert_eq!(first.iter().copied().sum::<u16>(), total);
2431 let second = round_layout_stable(&targets, total, Some(first.clone()));
2432 assert_eq!(first, second, "Should maintain rounding direction");
2433 }
2434
2435 #[test]
2436 fn temporal_tiebreak_adapts_to_changed_targets() {
2437 let targets_a = vec![10.5, 10.5];
2438 let result_a = round_layout_stable(&targets_a, 21, None);
2439 let targets_b = vec![15.7, 5.3];
2440 let result_b = round_layout_stable(&targets_b, 21, Some(result_a));
2441 assert_eq!(result_b.iter().copied().sum::<u16>(), 21);
2442 assert!(result_b[0] > result_b[1], "Should follow larger target");
2443 }
2444
2445 #[test]
2448 fn property_min_displacement_brute_force_small() {
2449 let targets = vec![3.3, 3.3, 3.4];
2450 let total: u16 = 10;
2451 let result = round_layout_stable(&targets, total, None);
2452 let our_displacement: f64 = result
2453 .iter()
2454 .zip(targets.iter())
2455 .map(|(&x, &r)| (x as f64 - r).abs())
2456 .sum();
2457
2458 let mut min_displacement = f64::MAX;
2459 let floors: Vec<u16> = targets.iter().map(|&r| r.floor() as u16).collect();
2460 let ceils: Vec<u16> = targets.iter().map(|&r| r.floor() as u16 + 1).collect();
2461
2462 for a in floors[0]..=ceils[0] {
2463 for b in floors[1]..=ceils[1] {
2464 for c in floors[2]..=ceils[2] {
2465 if a + b + c == total {
2466 let disp = (a as f64 - targets[0]).abs()
2467 + (b as f64 - targets[1]).abs()
2468 + (c as f64 - targets[2]).abs();
2469 if disp < min_displacement {
2470 min_displacement = disp;
2471 }
2472 }
2473 }
2474 }
2475 }
2476
2477 assert!(
2478 (our_displacement - min_displacement).abs() < 1e-10,
2479 "Our displacement {} should match optimal {}: {:?}",
2480 our_displacement,
2481 min_displacement,
2482 result
2483 );
2484 }
2485
2486 #[test]
2489 fn rounding_deterministic() {
2490 let targets = vec![7.7, 8.3, 14.0];
2491 let a = round_layout_stable(&targets, 30, None);
2492 let b = round_layout_stable(&targets, 30, None);
2493 assert_eq!(a, b, "Same inputs must produce identical outputs");
2494 }
2495
2496 #[test]
2499 fn rounding_empty_targets() {
2500 let result = round_layout_stable(&[], 0, None);
2501 assert!(result.is_empty());
2502 }
2503
2504 #[test]
2505 fn rounding_single_element() {
2506 let result = round_layout_stable(&[10.7], 11, None);
2507 assert_eq!(result.as_slice(), &[11u16]);
2508 }
2509
2510 #[test]
2511 fn rounding_zero_total() {
2512 let result = round_layout_stable(&[5.0, 5.0], 0, None);
2513 assert_eq!(result.iter().copied().sum::<u16>(), 0);
2514 }
2515
2516 #[test]
2517 fn rounding_zero_total_with_large_overflow_reaches_zero() {
2518 let result = round_layout_stable(&[65535.0, 65535.0], 0, None);
2519 assert_eq!(result.as_slice(), &[0u16, 0u16]);
2520 assert_eq!(result.iter().copied().sum::<u16>(), 0);
2521 }
2522
2523 #[test]
2524 fn rounding_all_zeros() {
2525 let result = round_layout_stable(&[0.0, 0.0, 0.0], 0, None);
2526 assert_eq!(result.as_slice(), &[0u16, 0u16, 0u16]);
2527 }
2528
2529 #[test]
2530 fn rounding_integer_targets() {
2531 let result = round_layout_stable(&[10.0, 20.0, 30.0], 60, None);
2532 assert_eq!(result.as_slice(), &[10u16, 20u16, 30u16]);
2533 }
2534
2535 #[test]
2536 fn rounding_large_deficit() {
2537 let result = round_layout_stable(&[0.9, 0.9, 0.9], 3, None);
2538 assert_eq!(result.iter().copied().sum::<u16>(), 3);
2539 assert_eq!(result.as_slice(), &[1u16, 1u16, 1u16]);
2540 }
2541
2542 #[test]
2543 fn rounding_with_prev_different_length() {
2544 let result = round_layout_stable(
2545 &[10.5, 10.5],
2546 21,
2547 Some(smallvec::smallvec![11u16, 10u16, 5u16]),
2548 );
2549 assert_eq!(result.iter().copied().sum::<u16>(), 21);
2550 }
2551
2552 #[test]
2553 fn rounding_very_small_fractions() {
2554 let targets = vec![10.001, 20.001, 9.998];
2555 let result = round_layout_stable(&targets, 40, None);
2556 assert_eq!(result.iter().copied().sum::<u16>(), 40);
2557 }
2558
2559 #[test]
2560 fn rounding_conserves_sum_stress() {
2561 let n = 50;
2562 let targets: Vec<f64> = (0..n).map(|i| 2.0 + (i as f64 * 0.037)).collect();
2563 let total = 120u16;
2564 let result = round_layout_stable(&targets, total, None);
2565 assert_eq!(
2566 result.iter().copied().sum::<u16>(),
2567 total,
2568 "Sum must be exactly {} for {} items: {:?}",
2569 total,
2570 n,
2571 result
2572 );
2573 }
2574 }
2575
2576 mod property_constraint_tests {
2581 use super::super::*;
2582
2583 struct Lcg(u64);
2585
2586 impl Lcg {
2587 fn new(seed: u64) -> Self {
2588 Self(seed)
2589 }
2590 fn next_u32(&mut self) -> u32 {
2591 self.0 = self
2592 .0
2593 .wrapping_mul(6_364_136_223_846_793_005)
2594 .wrapping_add(1);
2595 (self.0 >> 33) as u32
2596 }
2597 fn next_u16_range(&mut self, lo: u16, hi: u16) -> u16 {
2598 if lo >= hi {
2599 return lo;
2600 }
2601 lo + (self.next_u32() % (hi - lo) as u32) as u16
2602 }
2603 fn next_f32(&mut self) -> f32 {
2604 (self.next_u32() & 0x00FF_FFFF) as f32 / 16_777_216.0
2605 }
2606 }
2607
2608 fn random_constraint(rng: &mut Lcg) -> Constraint {
2610 match rng.next_u32() % 7 {
2611 0 => Constraint::Fixed(rng.next_u16_range(1, 80)),
2612 1 => Constraint::Percentage(rng.next_f32() * 100.0),
2613 2 => Constraint::Min(rng.next_u16_range(0, 40)),
2614 3 => Constraint::Max(rng.next_u16_range(5, 120)),
2615 4 => {
2616 let n = rng.next_u32() % 5 + 1;
2617 let d = rng.next_u32() % 5 + 1;
2618 Constraint::Ratio(n, d)
2619 }
2620 5 => Constraint::Fill,
2621 _ => Constraint::FitContent,
2622 }
2623 }
2624
2625 #[test]
2626 fn property_constraints_respected_fixed() {
2627 let mut rng = Lcg::new(0xDEAD_BEEF);
2628 for _ in 0..200 {
2629 let fixed_val = rng.next_u16_range(1, 60);
2630 let avail = rng.next_u16_range(10, 200);
2631 let flex = Flex::horizontal().constraints([Constraint::Fixed(fixed_val)]);
2632 let rects = flex.split(Rect::new(0, 0, avail, 10));
2633 assert!(
2634 rects[0].width <= fixed_val.min(avail),
2635 "Fixed({}) in avail {} -> width {}",
2636 fixed_val,
2637 avail,
2638 rects[0].width
2639 );
2640 }
2641 }
2642
2643 #[test]
2644 fn property_constraints_respected_max() {
2645 let mut rng = Lcg::new(0xCAFE_BABE);
2646 for _ in 0..200 {
2647 let max_val = rng.next_u16_range(5, 80);
2648 let avail = rng.next_u16_range(10, 200);
2649 let flex =
2650 Flex::horizontal().constraints([Constraint::Max(max_val), Constraint::Fill]);
2651 let rects = flex.split(Rect::new(0, 0, avail, 10));
2652 assert!(
2653 rects[0].width <= max_val,
2654 "Max({}) in avail {} -> width {}",
2655 max_val,
2656 avail,
2657 rects[0].width
2658 );
2659 }
2660 }
2661
2662 #[test]
2663 fn property_constraints_respected_min() {
2664 let mut rng = Lcg::new(0xBAAD_F00D);
2665 for _ in 0..200 {
2666 let min_val = rng.next_u16_range(0, 40);
2667 let avail = rng.next_u16_range(min_val.max(1), 200);
2668 let flex = Flex::horizontal().constraints([Constraint::Min(min_val)]);
2669 let rects = flex.split(Rect::new(0, 0, avail, 10));
2670 assert!(
2671 rects[0].width >= min_val,
2672 "Min({}) in avail {} -> width {}",
2673 min_val,
2674 avail,
2675 rects[0].width
2676 );
2677 }
2678 }
2679
2680 #[test]
2681 fn property_constraints_respected_ratio_proportional() {
2682 let mut rng = Lcg::new(0x1234_5678);
2683 for _ in 0..200 {
2684 let n1 = rng.next_u32() % 5 + 1;
2685 let n2 = rng.next_u32() % 5 + 1;
2686 let d = n1 + n2;
2687 let avail = rng.next_u16_range(20, 200);
2688 let flex = Flex::horizontal()
2689 .constraints([Constraint::Ratio(n1, d), Constraint::Ratio(n2, d)]);
2690 let rects = flex.split(Rect::new(0, 0, avail, 10));
2691 let w1 = rects[0].width as f64;
2692 let w2 = rects[1].width as f64;
2693 let total = w1 + w2;
2694 if total > 0.0 {
2695 let expected_ratio = n1 as f64 / d as f64;
2696 let actual_ratio = w1 / total;
2697 assert!(
2698 (actual_ratio - expected_ratio).abs() < 0.15 || total < 4.0,
2699 "Ratio({},{})/({}+{}) avail={}: ~{:.2} got {:.2} (w1={}, w2={})",
2700 n1,
2701 d,
2702 n1,
2703 n2,
2704 avail,
2705 expected_ratio,
2706 actual_ratio,
2707 w1,
2708 w2
2709 );
2710 }
2711 }
2712 }
2713
2714 #[test]
2715 fn property_total_allocation_never_exceeds_available() {
2716 let mut rng = Lcg::new(0xFACE_FEED);
2717 for _ in 0..500 {
2718 let n = (rng.next_u32() % 6 + 1) as usize;
2719 let constraints: Vec<Constraint> =
2720 (0..n).map(|_| random_constraint(&mut rng)).collect();
2721 let avail = rng.next_u16_range(5, 200);
2722 let dir = if rng.next_u32().is_multiple_of(2) {
2723 Direction::Horizontal
2724 } else {
2725 Direction::Vertical
2726 };
2727 let flex = Flex::default().direction(dir).constraints(constraints);
2728 let area = Rect::new(0, 0, avail, avail);
2729 let rects = flex.split(area);
2730 let total: u16 = rects
2731 .iter()
2732 .map(|r| match dir {
2733 Direction::Horizontal => r.width,
2734 Direction::Vertical => r.height,
2735 })
2736 .sum();
2737 assert!(
2738 total <= avail,
2739 "Total {} exceeded available {} with {} constraints",
2740 total,
2741 avail,
2742 n
2743 );
2744 }
2745 }
2746
2747 #[test]
2748 fn property_no_overlap_horizontal() {
2749 let mut rng = Lcg::new(0xABCD_1234);
2750 for _ in 0..300 {
2751 let n = (rng.next_u32() % 5 + 2) as usize;
2752 let constraints: Vec<Constraint> =
2753 (0..n).map(|_| random_constraint(&mut rng)).collect();
2754 let avail = rng.next_u16_range(20, 200);
2755 let flex = Flex::horizontal().constraints(constraints);
2756 let rects = flex.split(Rect::new(0, 0, avail, 10));
2757
2758 for i in 1..rects.len() {
2759 let prev_end = rects[i - 1].x + rects[i - 1].width;
2760 assert!(
2761 rects[i].x >= prev_end,
2762 "Overlap at {}: prev ends {}, next starts {}",
2763 i,
2764 prev_end,
2765 rects[i].x
2766 );
2767 }
2768 }
2769 }
2770
2771 #[test]
2772 fn property_deterministic_across_runs() {
2773 let mut rng = Lcg::new(0x9999_8888);
2774 for _ in 0..100 {
2775 let n = (rng.next_u32() % 5 + 1) as usize;
2776 let constraints: Vec<Constraint> =
2777 (0..n).map(|_| random_constraint(&mut rng)).collect();
2778 let avail = rng.next_u16_range(10, 200);
2779 let r1 = Flex::horizontal()
2780 .constraints(constraints.clone())
2781 .split(Rect::new(0, 0, avail, 10));
2782 let r2 = Flex::horizontal()
2783 .constraints(constraints)
2784 .split(Rect::new(0, 0, avail, 10));
2785 assert_eq!(r1, r2, "Determinism violation at avail={}", avail);
2786 }
2787 }
2788 }
2789
2790 mod property_temporal_tests {
2795 use super::super::*;
2796 use crate::cache::{CoherenceCache, CoherenceId};
2797
2798 struct Lcg(u64);
2800
2801 impl Lcg {
2802 fn new(seed: u64) -> Self {
2803 Self(seed)
2804 }
2805 fn next_u32(&mut self) -> u32 {
2806 self.0 = self
2807 .0
2808 .wrapping_mul(6_364_136_223_846_793_005)
2809 .wrapping_add(1);
2810 (self.0 >> 33) as u32
2811 }
2812 }
2813
2814 #[test]
2815 fn property_temporal_stability_small_resize() {
2816 let constraints = [
2817 Constraint::Percentage(33.3),
2818 Constraint::Percentage(33.3),
2819 Constraint::Fill,
2820 ];
2821 let mut coherence = CoherenceCache::new(64);
2822 let id = CoherenceId::new(&constraints, Direction::Horizontal);
2823
2824 for total in [80u16, 100, 120] {
2825 let flex = Flex::horizontal().constraints(constraints);
2826 let rects = flex.split(Rect::new(0, 0, total, 10));
2827 let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2828
2829 let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2830 let prev = coherence.get(&id);
2831 let rounded = round_layout_stable(&targets, total, prev);
2832
2833 if let Some(old) = coherence.get(&id) {
2834 let (sum_disp, max_disp) = coherence.displacement(&id, &rounded);
2835 assert!(
2836 max_disp <= total.abs_diff(old.iter().copied().sum()) as u32 + 1,
2837 "max_disp={} too large for size change {} -> {}",
2838 max_disp,
2839 old.iter().copied().sum::<u16>(),
2840 total
2841 );
2842 let _ = sum_disp;
2843 }
2844 coherence.store(id, rounded);
2845 }
2846 }
2847
2848 #[test]
2849 fn property_temporal_stability_random_walk() {
2850 let constraints = [
2851 Constraint::Ratio(1, 3),
2852 Constraint::Ratio(1, 3),
2853 Constraint::Ratio(1, 3),
2854 ];
2855 let id = CoherenceId::new(&constraints, Direction::Horizontal);
2856 let mut coherence = CoherenceCache::new(64);
2857 let mut rng = Lcg::new(0x5555_AAAA);
2858 let mut total: u16 = 90;
2859
2860 for step in 0..200 {
2861 let prev_total = total;
2862 let delta = (rng.next_u32() % 7) as i32 - 3;
2863 total = (total as i32 + delta).clamp(10, 250) as u16;
2864
2865 let flex = Flex::horizontal().constraints(constraints);
2866 let rects = flex.split(Rect::new(0, 0, total, 10));
2867 let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2868
2869 let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2870 let prev = coherence.get(&id);
2871 let rounded = round_layout_stable(&targets, total, prev);
2872
2873 if coherence.get(&id).is_some() {
2874 let (_, max_disp) = coherence.displacement(&id, &rounded);
2875 let size_change = total.abs_diff(prev_total);
2876 assert!(
2877 max_disp <= size_change as u32 + 2,
2878 "step {}: max_disp={} exceeds size_change={} + 2",
2879 step,
2880 max_disp,
2881 size_change
2882 );
2883 }
2884 coherence.store(id, rounded);
2885 }
2886 }
2887
2888 #[test]
2889 fn property_temporal_stability_identical_frames() {
2890 let constraints = [
2891 Constraint::Fixed(20),
2892 Constraint::Fill,
2893 Constraint::Fixed(15),
2894 ];
2895 let id = CoherenceId::new(&constraints, Direction::Horizontal);
2896 let mut coherence = CoherenceCache::new(64);
2897
2898 let flex = Flex::horizontal().constraints(constraints);
2899 let rects = flex.split(Rect::new(0, 0, 100, 10));
2900 let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2901 coherence.store(id, widths.iter().copied().collect());
2902
2903 for _ in 0..10 {
2904 let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2905 let prev = coherence.get(&id);
2906 let rounded = round_layout_stable(&targets, 100, prev);
2907 let (sum_disp, _) = coherence.displacement(&id, &rounded);
2908 assert_eq!(sum_disp, 0, "Identical frames: zero displacement");
2909 coherence.store(id, rounded);
2910 }
2911 }
2912
2913 #[test]
2914 fn property_temporal_coherence_sweep() {
2915 let constraints = [
2916 Constraint::Percentage(25.0),
2917 Constraint::Percentage(50.0),
2918 Constraint::Fill,
2919 ];
2920 let id = CoherenceId::new(&constraints, Direction::Horizontal);
2921 let mut coherence = CoherenceCache::new(64);
2922 let mut total_displacement: u64 = 0;
2923
2924 for total in 60u16..=140 {
2925 let flex = Flex::horizontal().constraints(constraints);
2926 let rects = flex.split(Rect::new(0, 0, total, 10));
2927 let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2928
2929 let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2930 let prev = coherence.get(&id);
2931 let rounded = round_layout_stable(&targets, total, prev);
2932
2933 if coherence.get(&id).is_some() {
2934 let (sum_disp, _) = coherence.displacement(&id, &rounded);
2935 total_displacement += sum_disp;
2936 }
2937 coherence.store(id, rounded);
2938 }
2939
2940 assert!(
2941 total_displacement <= 80 * 3,
2942 "Total displacement {} exceeds bound for 80-step sweep",
2943 total_displacement
2944 );
2945 }
2946 }
2947
2948 mod snapshot_layout_tests {
2953 use super::super::*;
2954 use crate::grid::{Grid, GridArea};
2955
2956 fn snapshot_flex(
2957 constraints: &[Constraint],
2958 dir: Direction,
2959 width: u16,
2960 height: u16,
2961 ) -> String {
2962 let flex = Flex::default()
2963 .direction(dir)
2964 .constraints(constraints.iter().copied());
2965 let rects = flex.split(Rect::new(0, 0, width, height));
2966 let mut out = format!(
2967 "Flex {:?} {}x{} ({} constraints)\n",
2968 dir,
2969 width,
2970 height,
2971 constraints.len()
2972 );
2973 for (i, r) in rects.iter().enumerate() {
2974 out.push_str(&format!(
2975 " [{}] x={} y={} w={} h={}\n",
2976 i, r.x, r.y, r.width, r.height
2977 ));
2978 }
2979 let total: u16 = rects
2980 .iter()
2981 .map(|r| match dir {
2982 Direction::Horizontal => r.width,
2983 Direction::Vertical => r.height,
2984 })
2985 .sum();
2986 out.push_str(&format!(" total={}\n", total));
2987 out
2988 }
2989
2990 fn snapshot_grid(
2991 rows: &[Constraint],
2992 cols: &[Constraint],
2993 areas: &[(&str, GridArea)],
2994 width: u16,
2995 height: u16,
2996 ) -> String {
2997 let mut grid = Grid::new()
2998 .rows(rows.iter().copied())
2999 .columns(cols.iter().copied());
3000 for &(name, area) in areas {
3001 grid = grid.area(name, area);
3002 }
3003 let layout = grid.split(Rect::new(0, 0, width, height));
3004
3005 let mut out = format!(
3006 "Grid {}x{} ({}r x {}c)\n",
3007 width,
3008 height,
3009 rows.len(),
3010 cols.len()
3011 );
3012 for r in 0..rows.len() {
3013 for c in 0..cols.len() {
3014 let rect = layout.cell(r, c);
3015 out.push_str(&format!(
3016 " [{},{}] x={} y={} w={} h={}\n",
3017 r, c, rect.x, rect.y, rect.width, rect.height
3018 ));
3019 }
3020 }
3021 for &(name, _) in areas {
3022 if let Some(rect) = layout.area(name) {
3023 out.push_str(&format!(
3024 " area({}) x={} y={} w={} h={}\n",
3025 name, rect.x, rect.y, rect.width, rect.height
3026 ));
3027 }
3028 }
3029 out
3030 }
3031
3032 #[test]
3035 fn snapshot_flex_thirds_80x24() {
3036 let snap = snapshot_flex(
3037 &[
3038 Constraint::Ratio(1, 3),
3039 Constraint::Ratio(1, 3),
3040 Constraint::Ratio(1, 3),
3041 ],
3042 Direction::Horizontal,
3043 80,
3044 24,
3045 );
3046 assert_eq!(
3047 snap,
3048 "\
3049Flex Horizontal 80x24 (3 constraints)
3050 [0] x=0 y=0 w=26 h=24
3051 [1] x=26 y=0 w=26 h=24
3052 [2] x=52 y=0 w=26 h=24
3053 total=78
3054"
3055 );
3056 }
3057
3058 #[test]
3059 fn snapshot_flex_sidebar_content_80x24() {
3060 let snap = snapshot_flex(
3061 &[Constraint::Fixed(20), Constraint::Fill],
3062 Direction::Horizontal,
3063 80,
3064 24,
3065 );
3066 assert_eq!(
3067 snap,
3068 "\
3069Flex Horizontal 80x24 (2 constraints)
3070 [0] x=0 y=0 w=20 h=24
3071 [1] x=20 y=0 w=60 h=24
3072 total=80
3073"
3074 );
3075 }
3076
3077 #[test]
3078 fn snapshot_flex_header_body_footer_80x24() {
3079 let snap = snapshot_flex(
3080 &[Constraint::Fixed(3), Constraint::Fill, Constraint::Fixed(1)],
3081 Direction::Vertical,
3082 80,
3083 24,
3084 );
3085 assert_eq!(
3086 snap,
3087 "\
3088Flex Vertical 80x24 (3 constraints)
3089 [0] x=0 y=0 w=80 h=3
3090 [1] x=0 y=3 w=80 h=20
3091 [2] x=0 y=23 w=80 h=1
3092 total=24
3093"
3094 );
3095 }
3096
3097 #[test]
3100 fn snapshot_flex_thirds_120x40() {
3101 let snap = snapshot_flex(
3102 &[
3103 Constraint::Ratio(1, 3),
3104 Constraint::Ratio(1, 3),
3105 Constraint::Ratio(1, 3),
3106 ],
3107 Direction::Horizontal,
3108 120,
3109 40,
3110 );
3111 assert_eq!(
3112 snap,
3113 "\
3114Flex Horizontal 120x40 (3 constraints)
3115 [0] x=0 y=0 w=40 h=40
3116 [1] x=40 y=0 w=40 h=40
3117 [2] x=80 y=0 w=40 h=40
3118 total=120
3119"
3120 );
3121 }
3122
3123 #[test]
3124 fn snapshot_flex_sidebar_content_120x40() {
3125 let snap = snapshot_flex(
3126 &[Constraint::Fixed(20), Constraint::Fill],
3127 Direction::Horizontal,
3128 120,
3129 40,
3130 );
3131 assert_eq!(
3132 snap,
3133 "\
3134Flex Horizontal 120x40 (2 constraints)
3135 [0] x=0 y=0 w=20 h=40
3136 [1] x=20 y=0 w=100 h=40
3137 total=120
3138"
3139 );
3140 }
3141
3142 #[test]
3143 fn snapshot_flex_percentage_mix_120x40() {
3144 let snap = snapshot_flex(
3145 &[
3146 Constraint::Percentage(25.0),
3147 Constraint::Percentage(50.0),
3148 Constraint::Fill,
3149 ],
3150 Direction::Horizontal,
3151 120,
3152 40,
3153 );
3154 assert_eq!(
3155 snap,
3156 "\
3157Flex Horizontal 120x40 (3 constraints)
3158 [0] x=0 y=0 w=30 h=40
3159 [1] x=30 y=0 w=60 h=40
3160 [2] x=90 y=0 w=30 h=40
3161 total=120
3162"
3163 );
3164 }
3165
3166 #[test]
3169 fn snapshot_grid_2x2_80x24() {
3170 let snap = snapshot_grid(
3171 &[Constraint::Fixed(3), Constraint::Fill],
3172 &[Constraint::Fixed(20), Constraint::Fill],
3173 &[
3174 ("header", GridArea::span(0, 0, 1, 2)),
3175 ("sidebar", GridArea::span(1, 0, 1, 1)),
3176 ("content", GridArea::cell(1, 1)),
3177 ],
3178 80,
3179 24,
3180 );
3181 assert_eq!(
3182 snap,
3183 "\
3184Grid 80x24 (2r x 2c)
3185 [0,0] x=0 y=0 w=20 h=3
3186 [0,1] x=20 y=0 w=60 h=3
3187 [1,0] x=0 y=3 w=20 h=21
3188 [1,1] x=20 y=3 w=60 h=21
3189 area(header) x=0 y=0 w=80 h=3
3190 area(sidebar) x=0 y=3 w=20 h=21
3191 area(content) x=20 y=3 w=60 h=21
3192"
3193 );
3194 }
3195
3196 #[test]
3197 fn snapshot_grid_3x3_80x24() {
3198 let snap = snapshot_grid(
3199 &[Constraint::Fixed(1), Constraint::Fill, Constraint::Fixed(1)],
3200 &[
3201 Constraint::Fixed(10),
3202 Constraint::Fill,
3203 Constraint::Fixed(10),
3204 ],
3205 &[],
3206 80,
3207 24,
3208 );
3209 assert_eq!(
3210 snap,
3211 "\
3212Grid 80x24 (3r x 3c)
3213 [0,0] x=0 y=0 w=10 h=1
3214 [0,1] x=10 y=0 w=60 h=1
3215 [0,2] x=70 y=0 w=10 h=1
3216 [1,0] x=0 y=1 w=10 h=22
3217 [1,1] x=10 y=1 w=60 h=22
3218 [1,2] x=70 y=1 w=10 h=22
3219 [2,0] x=0 y=23 w=10 h=1
3220 [2,1] x=10 y=23 w=60 h=1
3221 [2,2] x=70 y=23 w=10 h=1
3222"
3223 );
3224 }
3225
3226 #[test]
3229 fn snapshot_grid_2x2_120x40() {
3230 let snap = snapshot_grid(
3231 &[Constraint::Fixed(3), Constraint::Fill],
3232 &[Constraint::Fixed(20), Constraint::Fill],
3233 &[
3234 ("header", GridArea::span(0, 0, 1, 2)),
3235 ("sidebar", GridArea::span(1, 0, 1, 1)),
3236 ("content", GridArea::cell(1, 1)),
3237 ],
3238 120,
3239 40,
3240 );
3241 assert_eq!(
3242 snap,
3243 "\
3244Grid 120x40 (2r x 2c)
3245 [0,0] x=0 y=0 w=20 h=3
3246 [0,1] x=20 y=0 w=100 h=3
3247 [1,0] x=0 y=3 w=20 h=37
3248 [1,1] x=20 y=3 w=100 h=37
3249 area(header) x=0 y=0 w=120 h=3
3250 area(sidebar) x=0 y=3 w=20 h=37
3251 area(content) x=20 y=3 w=100 h=37
3252"
3253 );
3254 }
3255
3256 #[test]
3257 fn snapshot_grid_dashboard_120x40() {
3258 let snap = snapshot_grid(
3259 &[
3260 Constraint::Fixed(3),
3261 Constraint::Percentage(60.0),
3262 Constraint::Fill,
3263 ],
3264 &[Constraint::Percentage(30.0), Constraint::Fill],
3265 &[
3266 ("nav", GridArea::span(0, 0, 1, 2)),
3267 ("chart", GridArea::cell(1, 0)),
3268 ("detail", GridArea::cell(1, 1)),
3269 ("log", GridArea::span(2, 0, 1, 2)),
3270 ],
3271 120,
3272 40,
3273 );
3274 assert_eq!(
3275 snap,
3276 "\
3277Grid 120x40 (3r x 2c)
3278 [0,0] x=0 y=0 w=36 h=3
3279 [0,1] x=36 y=0 w=84 h=3
3280 [1,0] x=0 y=3 w=36 h=24
3281 [1,1] x=36 y=3 w=84 h=24
3282 [2,0] x=0 y=27 w=36 h=13
3283 [2,1] x=36 y=27 w=84 h=13
3284 area(nav) x=0 y=0 w=120 h=3
3285 area(chart) x=0 y=3 w=36 h=24
3286 area(detail) x=36 y=3 w=84 h=24
3287 area(log) x=0 y=27 w=120 h=13
3288"
3289 );
3290 }
3291 }
3292
3293 mod arena_flex_proptests {
3294 use super::*;
3295 use proptest::prelude::*;
3296
3297 fn arb_constraint() -> impl Strategy<Value = Constraint> {
3298 prop_oneof![
3299 (0u16..=60).prop_map(Constraint::Fixed),
3300 (0u16..=100).prop_map(|p| Constraint::Percentage(f32::from(p))),
3301 (0u16..=60).prop_map(Constraint::Min),
3302 (1u16..=60).prop_map(Constraint::Max),
3303 (0u32..=10, 1u32..=10).prop_map(|(n, d)| Constraint::Ratio(n, d)),
3304 Just(Constraint::Fill),
3305 Just(Constraint::FitContent),
3306 Just(Constraint::FitMin),
3307 ]
3308 }
3309
3310 fn arb_alignment() -> impl Strategy<Value = Alignment> {
3311 prop_oneof![
3312 Just(Alignment::Start),
3313 Just(Alignment::Center),
3314 Just(Alignment::End),
3315 Just(Alignment::SpaceBetween),
3316 Just(Alignment::SpaceAround),
3317 ]
3318 }
3319
3320 proptest! {
3321 #![proptest_config(ProptestConfig::with_cases(512))]
3322
3323 #[test]
3324 fn flex_split_in_equals_split(
3325 horiz in any::<bool>(),
3326 rtl in any::<bool>(),
3327 gap in 0u16..=4,
3328 w in 0u16..=200,
3329 h in 0u16..=80,
3330 alignment in arb_alignment(),
3331 constraints in prop::collection::vec(arb_constraint(), 0..=20),
3332 ) {
3333 let mut arena = ftui_core::arena::FrameArena::new(16 * 1024);
3334 let flex = if horiz { Flex::horizontal() } else { Flex::vertical() }
3335 .gap(gap)
3336 .alignment(alignment)
3337 .flow_direction(if rtl {
3338 direction::FlowDirection::Rtl
3339 } else {
3340 direction::FlowDirection::Ltr
3341 })
3342 .constraints(constraints);
3343
3344 let area = Rect::new(2, 3, w, h);
3345 let owned = flex.split(area);
3346 let in_arena = flex.split_in(&arena, area);
3347 prop_assert_eq!(in_arena, owned.as_slice());
3348
3349 arena.reset();
3350 let measurer = |idx: usize, avail: u16| LayoutSizeHint {
3351 min: ((idx as u16) * 2).min(avail),
3352 preferred: ((idx as u16) * 5 + 3).min(avail),
3353 max: Some(40),
3354 };
3355 let owned_m = flex.split_with_measurer(area, measurer);
3356 let in_arena_m = flex.split_with_measurer_in(&arena, area, measurer);
3357 prop_assert_eq!(in_arena_m, owned_m.as_slice());
3358 }
3359 }
3360 }
3361}