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 fn sizes_to_rects(&self, area: Rect, sizes: &[u16]) -> Rects {
674 let mut rects = SmallVec::with_capacity(sizes.len());
675 if sizes.is_empty() {
676 return rects;
677 }
678
679 let total_items_size: u16 = sizes.iter().fold(0u16, |acc, &s| acc.saturating_add(s));
680 let total_available = match self.direction {
681 Direction::Horizontal => area.width,
682 Direction::Vertical => area.height,
683 };
684
685 let (start_shift, use_formula) = match self.alignment {
687 Alignment::Start => (0, None),
688 Alignment::End => {
689 let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
690 .min(u16::MAX as u64) as u16;
691 let used = total_items_size.saturating_add(gap_space);
692 (total_available.saturating_sub(used), None)
693 }
694 Alignment::Center => {
695 let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
696 .min(u16::MAX as u64) as u16;
697 let used = total_items_size.saturating_add(gap_space);
698 (total_available.saturating_sub(used) / 2, None)
699 }
700 Alignment::SpaceBetween => {
701 let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
702 .min(u16::MAX as u64) as u16;
703 let used = total_items_size.saturating_add(gap_space);
704 let leftover = total_available.saturating_sub(used);
705 let slots = sizes.len().saturating_sub(1);
706 if slots > 0 {
707 (0, Some((leftover, slots, 0))) } else {
709 (0, None)
710 }
711 }
712 Alignment::SpaceAround => {
713 let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
714 .min(u16::MAX as u64) as u16;
715 let used = total_items_size.saturating_add(gap_space);
716 let leftover = total_available.saturating_sub(used);
717 let slots = sizes.len() * 2;
718 if slots > 0 {
719 (0, Some((leftover, slots, 1))) } else {
721 (0, None)
722 }
723 }
724 };
725
726 let mut accumulated_size = 0;
727
728 for (i, &size) in sizes.iter().enumerate() {
729 let explicit_gap_so_far = if i > 0 {
730 (i as u64 * self.gap as u64).min(u16::MAX as u64) as u16
731 } else {
732 0
733 };
734
735 let gap_offset = if let Some((leftover, slots, mode)) = use_formula {
736 if mode == 0 {
737 if i == 0 {
739 0
740 } else {
741 explicit_gap_so_far
742 .saturating_add((leftover as u64 * i as u64 / slots as u64) as u16)
743 }
744 } else {
745 let numerator = leftover as u64 * (2 * i as u64 + 1);
747 let denominator = slots as u64;
748 let raw = (numerator + (denominator / 2)) / denominator;
749 explicit_gap_so_far.saturating_add(raw.min(u64::from(u16::MAX)) as u16)
750 }
751 } else {
752 explicit_gap_so_far
754 };
755
756 let pos = match self.direction {
757 Direction::Horizontal => area
758 .x
759 .saturating_add(start_shift)
760 .saturating_add(accumulated_size)
761 .saturating_add(gap_offset),
762 Direction::Vertical => area
763 .y
764 .saturating_add(start_shift)
765 .saturating_add(accumulated_size)
766 .saturating_add(gap_offset),
767 };
768
769 let rect = match self.direction {
770 Direction::Horizontal => Rect {
771 x: pos,
772 y: area.y,
773 width: size.min(area.right().saturating_sub(pos)),
774 height: area.height,
775 },
776 Direction::Vertical => Rect {
777 x: area.x,
778 y: pos,
779 width: area.width,
780 height: size.min(area.bottom().saturating_sub(pos)),
781 },
782 };
783 rects.push(rect);
784 accumulated_size = accumulated_size.saturating_add(size);
785 }
786
787 rects
788 }
789
790 pub fn split_with_measurer<F>(&self, area: Rect, measurer: F) -> Rects
814 where
815 F: Fn(usize, u16) -> LayoutSizeHint,
816 {
817 let inner = area.inner(self.margin);
819 if inner.is_empty() {
820 return self.constraints.iter().map(|_| Rect::default()).collect();
821 }
822
823 let total_size = match self.direction {
824 Direction::Horizontal => inner.width,
825 Direction::Vertical => inner.height,
826 };
827
828 let count = self.constraints.len();
829 if count == 0 {
830 return Rects::new();
831 }
832
833 let gap_count = count - 1;
835 let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
836 let available_size = total_size.saturating_sub(total_gap);
837
838 let sizes =
840 solve_constraints_with_hints(&self.constraints, available_size, &measurer, None);
841
842 let mut rects = self.sizes_to_rects(inner, &sizes);
844
845 if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
847 direction::mirror_rects_horizontal(&mut rects, inner);
848 }
849
850 rects
851 }
852 pub fn split_with_measurer_stably<F>(
857 &self,
858 area: Rect,
859 measurer: F,
860 cache: &mut CoherenceCache,
861 ) -> Rects
862 where
863 F: Fn(usize, u16) -> LayoutSizeHint,
864 {
865 let inner = area.inner(self.margin);
867 if inner.is_empty() {
868 return self.constraints.iter().map(|_| Rect::default()).collect();
869 }
870
871 let total_size = match self.direction {
872 Direction::Horizontal => inner.width,
873 Direction::Vertical => inner.height,
874 };
875
876 let count = self.constraints.len();
877 if count == 0 {
878 return Rects::new();
879 }
880
881 let gap_count = count - 1;
883 let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
884 let available_size = total_size.saturating_sub(total_gap);
885
886 let id = CoherenceId::new(&self.constraints, self.direction);
888 let sizes = solve_constraints_with_hints(
889 &self.constraints,
890 available_size,
891 &measurer,
892 Some((cache, id)),
893 );
894
895 let mut rects = self.sizes_to_rects(inner, &sizes);
897
898 if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
900 direction::mirror_rects_horizontal(&mut rects, inner);
901 }
902
903 rects
904 }
905}
906
907pub(crate) fn solve_constraints(constraints: &[Constraint], available_size: u16) -> Sizes {
912 solve_constraints_with_hints(
914 constraints,
915 available_size,
916 &|_, _| LayoutSizeHint::ZERO,
917 None,
918 )
919}
920
921pub(crate) fn solve_constraints_with_hints<F>(
926 constraints: &[Constraint],
927 available_size: u16,
928 measurer: &F,
929 mut coherence: Option<(&mut CoherenceCache, CoherenceId)>,
930) -> Sizes
931where
932 F: Fn(usize, u16) -> LayoutSizeHint,
933{
934 const WEIGHT_SCALE: u64 = 10_000;
935
936 let mut sizes: Sizes = smallvec::smallvec![0u16; constraints.len()];
937 let mut remaining = available_size;
938 let mut grow_indices: SmallVec<[usize; LAYOUT_INLINE_CAP]> = SmallVec::new();
939
940 let grow_weight = |constraint: Constraint| -> u64 {
941 match constraint {
942 Constraint::Min(_) | Constraint::Max(_) | Constraint::Fill => WEIGHT_SCALE,
943 _ => 0,
944 }
945 };
946
947 for (i, &constraint) in constraints.iter().enumerate() {
950 match constraint {
951 Constraint::Fixed(size) => {
952 let size = min(size, remaining);
953 sizes[i] = size;
954 remaining = remaining.saturating_sub(size);
955 }
956 Constraint::Min(min_size) => {
957 let size = min(min_size, remaining);
958 sizes[i] = size;
959 remaining = remaining.saturating_sub(size);
960 }
962 Constraint::FitMin => {
963 let hint = measurer(i, remaining);
964 let size = min(hint.min, remaining);
965 sizes[i] = size;
966 remaining = remaining.saturating_sub(size);
967 }
968 Constraint::FitContent => {
969 let hint = measurer(i, remaining);
970 let size = min(hint.min, remaining);
971 sizes[i] = size;
972 remaining = remaining.saturating_sub(size);
973 }
974 Constraint::FitContentBounded { min: min_bound, .. } => {
975 let size = min(min_bound, remaining);
977 sizes[i] = size;
978 remaining = remaining.saturating_sub(size);
979 }
980 _ => {} }
982 }
983
984 for (i, &constraint) in constraints.iter().enumerate() {
987 match constraint {
988 Constraint::Percentage(p) => {
989 let target = (available_size as f32 * p / 100.0)
990 .round()
991 .min(u16::MAX as f32) as u16;
992 let needed = target.saturating_sub(sizes[i]);
993 let alloc = min(needed, remaining);
994 sizes[i] = sizes[i].saturating_add(alloc);
995 remaining = remaining.saturating_sub(alloc);
996 }
997 Constraint::Ratio(n, d) => {
998 let target = if d == 0 {
999 0
1000 } else {
1001 (u64::from(available_size) * u64::from(n) / u64::from(d)).min(u16::MAX as u64)
1002 as u16
1003 };
1004 let needed = target.saturating_sub(sizes[i]);
1005 let alloc = min(needed, remaining);
1006 sizes[i] = sizes[i].saturating_add(alloc);
1007 remaining = remaining.saturating_sub(alloc);
1008 }
1009 Constraint::FitContent => {
1010 let hint = measurer(i, remaining);
1011 let preferred = hint
1012 .preferred
1013 .max(sizes[i])
1014 .min(hint.max.unwrap_or(u16::MAX));
1015 let needed = preferred.saturating_sub(sizes[i]);
1016 let alloc = min(needed, remaining);
1017 sizes[i] = sizes[i].saturating_add(alloc);
1018 remaining = remaining.saturating_sub(alloc);
1019 }
1020 Constraint::FitContentBounded { max: max_bound, .. } => {
1021 let hint = measurer(i, remaining);
1022 let preferred = hint.preferred.max(sizes[i]).min(max_bound);
1023 let needed = preferred.saturating_sub(sizes[i]);
1024 let alloc = min(needed, remaining);
1025 sizes[i] = sizes[i].saturating_add(alloc);
1026 remaining = remaining.saturating_sub(alloc);
1027 }
1028 Constraint::Min(_) => {
1029 grow_indices.push(i);
1030 }
1031 Constraint::Max(_) => {
1032 grow_indices.push(i);
1033 }
1034 Constraint::Fill => {
1035 grow_indices.push(i);
1036 }
1037 _ => {} }
1039 }
1040
1041 loop {
1043 if remaining == 0 || grow_indices.is_empty() {
1044 break;
1045 }
1046
1047 let mut total_weight = 0u128;
1048 for &i in &grow_indices {
1049 let weight = grow_weight(constraints[i]);
1050 if weight > 0 {
1051 total_weight = total_weight.saturating_add(u128::from(weight));
1052 }
1053 }
1054
1055 if total_weight == 0 {
1056 break;
1057 }
1058
1059 let space_to_distribute = remaining;
1060 let mut shares: SmallVec<[u16; LAYOUT_INLINE_CAP]> =
1061 smallvec::smallvec![0u16; constraints.len()];
1062
1063 let targets: Vec<f64> = grow_indices
1065 .iter()
1066 .map(|&i| {
1067 let weight = grow_weight(constraints[i]);
1068 (space_to_distribute as f64 * weight as f64) / total_weight as f64
1069 })
1070 .collect();
1071
1072 let prev_alloc = coherence
1074 .as_ref()
1075 .and_then(|(cache, id)| cache.get(id))
1076 .map(|full_prev| {
1077 grow_indices
1079 .iter()
1080 .map(|&i| full_prev.get(i).copied().unwrap_or(0))
1081 .collect()
1082 });
1083
1084 let distributed = round_layout_stable(&targets, space_to_distribute, prev_alloc);
1086
1087 for (k, &i) in grow_indices.iter().enumerate() {
1088 shares[i] = distributed[k];
1089 }
1090
1091 let mut violations = Vec::new();
1093 for &i in &grow_indices {
1094 if let Constraint::Max(max_val) = constraints[i]
1095 && sizes[i].saturating_add(shares[i]) > max_val
1096 {
1097 violations.push(i);
1098 }
1099 }
1100
1101 if violations.is_empty() {
1102 for &i in &grow_indices {
1104 sizes[i] = sizes[i].saturating_add(shares[i]);
1105 }
1106 if let Some((cache, id)) = coherence.as_mut() {
1107 if distributed.len() == targets.len() {
1110 let mut full_shares: Sizes = smallvec::smallvec![0u16; constraints.len()];
1111 for (k, &i) in grow_indices.iter().enumerate() {
1112 full_shares[i] = distributed[k];
1113 }
1114 cache.store(*id, full_shares);
1115 }
1116 }
1117 break;
1118 }
1119
1120 for i in violations {
1122 if let Constraint::Max(max_val) = constraints[i] {
1123 let consumed = max_val.saturating_sub(sizes[i]);
1126 sizes[i] = max_val;
1127 remaining = remaining.saturating_sub(consumed);
1128
1129 if let Some(pos) = grow_indices.iter().position(|&x| x == i) {
1131 grow_indices.remove(pos);
1132 }
1133 }
1134 }
1135 }
1136
1137 sizes
1138}
1139
1140pub type PreviousAllocation = Option<Sizes>;
1150
1151pub fn round_layout_stable(targets: &[f64], total: u16, prev: PreviousAllocation) -> Sizes {
1213 let n = targets.len();
1214 if n == 0 {
1215 return Sizes::new();
1216 }
1217
1218 let floors: Sizes = targets
1220 .iter()
1221 .map(|&r| (r.max(0.0).floor() as u64).min(u16::MAX as u64) as u16)
1222 .collect();
1223
1224 let floor_sum: u64 = floors.iter().map(|&x| u64::from(x)).sum();
1225 let total_u64 = u64::from(total);
1226
1227 if floor_sum > total_u64 {
1229 return redistribute_overflow(&floors, total);
1230 }
1231
1232 let deficit = (total_u64 - floor_sum) as u16;
1233
1234 if deficit == 0 {
1235 return floors;
1237 }
1238
1239 let mut priority: SmallVec<[(usize, f64, bool); LAYOUT_INLINE_CAP]> = targets
1241 .iter()
1242 .enumerate()
1243 .map(|(i, &r)| {
1244 let raw_remainder = r - (floors[i] as f64);
1247 let remainder = if raw_remainder.is_finite() {
1248 raw_remainder
1249 } else {
1250 0.0
1251 };
1252 let ceil_val = floors[i].saturating_add(1);
1253 let prev_used_ceil = prev
1255 .as_ref()
1256 .is_some_and(|p| p.get(i).copied() == Some(ceil_val));
1257 (i, remainder, prev_used_ceil)
1258 })
1259 .collect();
1260
1261 priority.sort_by(|a, b| {
1267 b.1.total_cmp(&a.1)
1268 .then_with(|| {
1269 b.2.cmp(&a.2)
1271 })
1272 .then_with(|| {
1273 a.0.cmp(&b.0)
1275 })
1276 });
1277
1278 let mut result = floors;
1280 let mut remaining_deficit = deficit;
1281
1282 if remaining_deficit as usize >= n {
1288 let per_item = remaining_deficit / (n as u16);
1289 for val in result.iter_mut() {
1290 *val = val.saturating_add(per_item);
1291 }
1292 remaining_deficit %= n as u16;
1293 }
1294
1295 if remaining_deficit > 0 {
1296 for &(i, _, _) in priority.iter().take(remaining_deficit as usize) {
1297 result[i] = result[i].saturating_add(1);
1298 }
1299 }
1300
1301 result
1302}
1303
1304fn redistribute_overflow(floors: &[u16], total: u16) -> Sizes {
1309 let mut result: Sizes = floors.iter().copied().collect();
1310 let current_sum: u64 = result.iter().map(|&x| u64::from(x)).sum();
1311 let total_u64 = u64::from(total);
1312 let n = result.len();
1313
1314 if current_sum <= total_u64 || n == 0 {
1315 return result;
1316 }
1317
1318 let mut overflow = current_sum - total_u64;
1319
1320 while overflow > 0 {
1321 let &max_val = result.iter().max().unwrap_or(&0);
1322 if max_val == 0 {
1323 for val in result.iter_mut() {
1327 *val = 0;
1328 }
1329 break;
1330 }
1331
1332 let count_max = result.iter().filter(|&&v| v == max_val).count() as u64;
1333 let &next_max = result.iter().filter(|&&v| v < max_val).max().unwrap_or(&0);
1334
1335 let delta = (max_val - next_max) as u64;
1336 let required_per_item = overflow.div_ceil(count_max);
1337 let reduce_per_item = delta.min(required_per_item).max(1) as u16;
1338
1339 let mut reduced_any = false;
1340 for val in result.iter_mut() {
1341 if *val == max_val {
1342 let amount = u64::from(*val)
1343 .min(u64::from(reduce_per_item))
1344 .min(overflow) as u16;
1345 if amount > 0 {
1346 *val -= amount;
1347 overflow -= u64::from(amount);
1348 reduced_any = true;
1349 }
1350 if overflow == 0 {
1351 break;
1352 }
1353 }
1354 }
1355
1356 if !reduced_any {
1357 for val in result.iter_mut() {
1359 if overflow == 0 {
1360 break;
1361 }
1362 if *val > 0 {
1363 *val -= 1;
1364 overflow -= 1;
1365 }
1366 }
1367 break;
1368 }
1369 }
1370
1371 result
1372}
1373
1374#[cfg(test)]
1375mod tests {
1376 use super::*;
1377
1378 #[test]
1379 fn an_oversubscribed_row_shrinks_rather_than_overlapping() {
1380 for width in [120u16, 43, 42, 38, 20] {
1385 let rects = Flex::horizontal()
1386 .constraints([Constraint::Min(11), Constraint::Fixed(32)])
1387 .split(Rect::new(0, 0, width, 3));
1388 let total: u32 = rects.iter().map(|r| u32::from(r.width)).sum();
1389 assert_eq!(total, u32::from(width), "row {width} not fully used");
1390 assert!(
1391 rects.windows(2).all(|w| w[0].x + w[0].width <= w[1].x),
1392 "rects overlap at width {width}: {rects:?}"
1393 );
1394 assert!(
1395 rects
1396 .iter()
1397 .all(|r| u32::from(r.x) + u32::from(r.width) <= u32::from(width)),
1398 "rect past the end at width {width}: {rects:?}"
1399 );
1400 }
1401 }
1402
1403 #[test]
1404 fn round_layout_stable_nan_targets_do_not_panic_the_sort() {
1405 let mut targets: Vec<f64> = (0..64).map(|i| (i as f64) * 0.37 + 0.1).collect();
1410 targets[7] = f64::NAN;
1411 targets[23] = f64::INFINITY;
1412 targets[41] = f64::NEG_INFINITY;
1413
1414 let sizes = round_layout_stable(&targets, 120, None);
1417 assert_eq!(sizes.len(), 64);
1418
1419 let nan_targets = [f64::NAN; 8];
1422 let sizes = round_layout_stable(&nan_targets, 40, None);
1423 let sum: u64 = sizes.iter().map(|&x| u64::from(x)).sum();
1424 assert_eq!(sum, 40);
1425 }
1426
1427 #[test]
1428 fn fixed_split() {
1429 let flex = Flex::horizontal().constraints([Constraint::Fixed(10), Constraint::Fixed(20)]);
1430 let rects = flex.split(Rect::new(0, 0, 100, 10));
1431 assert_eq!(rects.len(), 2);
1432 assert_eq!(rects[0], Rect::new(0, 0, 10, 10));
1433 assert_eq!(rects[1], Rect::new(10, 0, 20, 10)); }
1435
1436 #[test]
1437 fn percentage_split() {
1438 let flex = Flex::horizontal()
1439 .constraints([Constraint::Percentage(50.0), Constraint::Percentage(50.0)]);
1440 let rects = flex.split(Rect::new(0, 0, 100, 10));
1441 assert_eq!(rects[0].width, 50);
1442 assert_eq!(rects[1].width, 50);
1443 }
1444
1445 #[test]
1446 fn gap_handling() {
1447 let flex = Flex::horizontal()
1448 .gap(5)
1449 .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1450 let rects = flex.split(Rect::new(0, 0, 100, 10));
1451 assert_eq!(rects[0], Rect::new(0, 0, 10, 10));
1455 assert_eq!(rects[1], Rect::new(15, 0, 10, 10));
1456 }
1457
1458 #[test]
1459 fn mixed_constraints() {
1460 let flex = Flex::horizontal().constraints([
1461 Constraint::Fixed(10),
1462 Constraint::Min(10), Constraint::Percentage(10.0), ]);
1465
1466 let rects = flex.split(Rect::new(0, 0, 100, 1));
1474 assert_eq!(rects[0].width, 10); assert_eq!(rects[2].width, 10); assert_eq!(rects[1].width, 80); }
1478
1479 #[test]
1480 fn measurement_fixed_constraints() {
1481 let fixed = Measurement::fixed(5, 7);
1482 assert_eq!(fixed.min_width, 5);
1483 assert_eq!(fixed.min_height, 7);
1484 assert_eq!(fixed.max_width, Some(5));
1485 assert_eq!(fixed.max_height, Some(7));
1486 }
1487
1488 #[test]
1489 fn measurement_flexible_constraints() {
1490 let flexible = Measurement::flexible(2, 3);
1491 assert_eq!(flexible.min_width, 2);
1492 assert_eq!(flexible.min_height, 3);
1493 assert_eq!(flexible.max_width, None);
1494 assert_eq!(flexible.max_height, None);
1495 }
1496
1497 #[test]
1498 fn breakpoints_classify_defaults() {
1499 let bp = Breakpoints::DEFAULT;
1500 assert_eq!(bp.classify_width(20), Breakpoint::Xs);
1501 assert_eq!(bp.classify_width(60), Breakpoint::Sm);
1502 assert_eq!(bp.classify_width(90), Breakpoint::Md);
1503 assert_eq!(bp.classify_width(120), Breakpoint::Lg);
1504 }
1505
1506 #[test]
1507 fn breakpoints_at_least_and_between() {
1508 let bp = Breakpoints::new(50, 80, 110);
1509 assert!(bp.at_least(85, Breakpoint::Sm));
1510 assert!(bp.between(85, Breakpoint::Sm, Breakpoint::Md));
1511 assert!(!bp.between(85, Breakpoint::Lg, Breakpoint::Lg));
1512 }
1513
1514 #[test]
1515 fn alignment_end() {
1516 let flex = Flex::horizontal()
1517 .alignment(Alignment::End)
1518 .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1519 let rects = flex.split(Rect::new(0, 0, 100, 10));
1520 assert_eq!(rects[0], Rect::new(80, 0, 10, 10));
1522 assert_eq!(rects[1], Rect::new(90, 0, 10, 10));
1523 }
1524
1525 #[test]
1526 fn alignment_center() {
1527 let flex = Flex::horizontal()
1528 .alignment(Alignment::Center)
1529 .constraints([Constraint::Fixed(20), Constraint::Fixed(20)]);
1530 let rects = flex.split(Rect::new(0, 0, 100, 10));
1531 assert_eq!(rects[0], Rect::new(30, 0, 20, 10));
1533 assert_eq!(rects[1], Rect::new(50, 0, 20, 10));
1534 }
1535
1536 #[test]
1537 fn alignment_space_between() {
1538 let flex = Flex::horizontal()
1539 .alignment(Alignment::SpaceBetween)
1540 .constraints([
1541 Constraint::Fixed(10),
1542 Constraint::Fixed(10),
1543 Constraint::Fixed(10),
1544 ]);
1545 let rects = flex.split(Rect::new(0, 0, 100, 10));
1546 assert_eq!(rects[0].x, 0);
1548 assert_eq!(rects[1].x, 45); assert_eq!(rects[2].x, 90); }
1551
1552 #[test]
1553 fn vertical_alignment() {
1554 let flex = Flex::vertical()
1555 .alignment(Alignment::End)
1556 .constraints([Constraint::Fixed(5), Constraint::Fixed(5)]);
1557 let rects = flex.split(Rect::new(0, 0, 10, 100));
1558 assert_eq!(rects[0], Rect::new(0, 90, 10, 5));
1560 assert_eq!(rects[1], Rect::new(0, 95, 10, 5));
1561 }
1562
1563 #[test]
1564 fn nested_flex_support() {
1565 let outer = Flex::horizontal()
1567 .constraints([Constraint::Percentage(50.0), Constraint::Percentage(50.0)]);
1568 let outer_rects = outer.split(Rect::new(0, 0, 100, 100));
1569
1570 let inner = Flex::vertical().constraints([Constraint::Fixed(30), Constraint::Min(10)]);
1572 let inner_rects = inner.split(outer_rects[0]);
1573
1574 assert_eq!(inner_rects[0], Rect::new(0, 0, 50, 30));
1575 assert_eq!(inner_rects[1], Rect::new(0, 30, 50, 70));
1576 }
1577
1578 #[test]
1580 fn invariant_total_size_does_not_exceed_available() {
1581 for total in [10u16, 50, 100, 255] {
1583 let flex = Flex::horizontal().constraints([
1584 Constraint::Fixed(30),
1585 Constraint::Percentage(50.0),
1586 Constraint::Min(20),
1587 ]);
1588 let rects = flex.split(Rect::new(0, 0, total, 10));
1589 let total_width: u16 = rects.iter().map(|r| r.width).sum();
1590 assert!(
1591 total_width <= total,
1592 "Total width {} exceeded available {} for constraints",
1593 total_width,
1594 total
1595 );
1596 }
1597 }
1598
1599 #[test]
1600 fn invariant_empty_area_produces_empty_rects() {
1601 let flex = Flex::horizontal().constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1602 let rects = flex.split(Rect::new(0, 0, 0, 0));
1603 assert!(rects.iter().all(|r| r.is_empty()));
1604 }
1605
1606 #[test]
1607 fn invariant_no_constraints_produces_empty_vec() {
1608 let flex = Flex::horizontal().constraints([]);
1609 let rects = flex.split(Rect::new(0, 0, 100, 100));
1610 assert!(rects.is_empty());
1611 }
1612
1613 #[test]
1614 fn flex_constraints_stay_inline_for_common_layouts() {
1615 let flex = Flex::horizontal().constraints([Constraint::Fixed(1); LAYOUT_INLINE_CAP]);
1616 assert_eq!(flex.constraint_count(), LAYOUT_INLINE_CAP);
1617 assert!(!flex.constraints.spilled());
1618
1619 let rects = flex.split(Rect::new(0, 0, LAYOUT_INLINE_CAP as u16, 1));
1620 assert_eq!(rects.len(), LAYOUT_INLINE_CAP);
1621 assert!(rects.iter().all(|rect| rect.width == 1));
1622 }
1623
1624 #[test]
1627 fn ratio_constraint_splits_proportionally() {
1628 let flex =
1629 Flex::horizontal().constraints([Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)]);
1630 let rects = flex.split(Rect::new(0, 0, 90, 10));
1631 assert_eq!(rects[0].width, 30);
1632 assert_eq!(rects[1].width, 60);
1633 }
1634
1635 #[test]
1636 fn ratio_constraint_with_zero_denominator() {
1637 let flex = Flex::horizontal().constraints([Constraint::Ratio(1, 0)]);
1639 let rects = flex.split(Rect::new(0, 0, 100, 10));
1640 assert_eq!(rects.len(), 1);
1641 }
1642
1643 #[test]
1644 fn ratio_is_absolute_fraction() {
1645 let area = Rect::new(0, 0, 100, 1);
1646
1647 let rects = Flex::horizontal()
1649 .constraints([Constraint::Percentage(25.0)])
1650 .split(area);
1651 assert_eq!(rects[0].width, 25);
1652
1653 let rects = Flex::horizontal()
1656 .constraints([Constraint::Ratio(1, 4)])
1657 .split(area);
1658 assert_eq!(rects[0].width, 25);
1659 }
1660
1661 #[test]
1662 fn ratio_is_independent_of_grow_items() {
1663 let area = Rect::new(0, 0, 100, 1);
1664
1665 let rects = Flex::horizontal()
1667 .constraints([Constraint::Ratio(1, 4), Constraint::Fill])
1668 .split(area);
1669 assert_eq!(rects[0].width, 25);
1670 assert_eq!(rects[1].width, 75);
1671 }
1672
1673 #[test]
1674 fn ratio_zero_numerator_should_be_zero() {
1675 let flex = Flex::horizontal().constraints([Constraint::Fill, Constraint::Ratio(0, 1)]);
1678 let rects = flex.split(Rect::new(0, 0, 100, 1));
1679
1680 assert_eq!(rects[0].width, 100, "Fill should take all space");
1682 assert_eq!(rects[1].width, 0, "Ratio(0, 1) should be width 0");
1683 }
1684
1685 #[test]
1688 fn max_constraint_clamps_size() {
1689 let flex = Flex::horizontal().constraints([Constraint::Max(20), Constraint::Fixed(30)]);
1690 let rects = flex.split(Rect::new(0, 0, 100, 10));
1691 assert!(rects[0].width <= 20);
1692 assert_eq!(rects[1].width, 30);
1693 }
1694
1695 #[test]
1696 fn percentage_rounding_never_exceeds_available() {
1697 let constraints = [
1698 Constraint::Percentage(33.4),
1699 Constraint::Percentage(33.3),
1700 Constraint::Percentage(33.3),
1701 ];
1702 let sizes = solve_constraints(&constraints, 7);
1703 let total: u16 = sizes.iter().sum();
1704 assert!(total <= 7, "percent rounding overflowed: {sizes:?}");
1705 assert!(sizes.iter().all(|size| *size <= 7));
1706 }
1707
1708 #[test]
1709 fn tiny_area_saturates_fixed_and_min() {
1710 let constraints = [Constraint::Fixed(5), Constraint::Min(3), Constraint::Max(2)];
1711 let sizes = solve_constraints(&constraints, 2);
1712 assert_eq!(sizes[0], 2);
1713 assert_eq!(sizes[1], 0);
1714 assert_eq!(sizes[2], 0);
1715 assert_eq!(sizes.iter().sum::<u16>(), 2);
1716 }
1717
1718 #[test]
1719 fn ratio_distribution_sums_to_available() {
1720 let constraints = [Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)];
1722 let sizes = solve_constraints(&constraints, 5);
1723 assert_eq!(sizes.iter().sum::<u16>(), 4);
1724 assert_eq!(sizes[0], 1);
1725 assert_eq!(sizes[1], 3);
1726 }
1727
1728 #[test]
1729 fn flex_gap_exceeds_area_yields_zero_widths() {
1730 let flex = Flex::horizontal()
1731 .gap(5)
1732 .constraints([Constraint::Fixed(1), Constraint::Fixed(1)]);
1733 let rects = flex.split(Rect::new(0, 0, 3, 1));
1734 assert_eq!(rects.len(), 2);
1735 assert_eq!(rects[0].width, 0);
1736 assert_eq!(rects[1].width, 0);
1737 }
1738
1739 #[test]
1742 fn alignment_space_around() {
1743 let flex = Flex::horizontal()
1744 .alignment(Alignment::SpaceAround)
1745 .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1746 let rects = flex.split(Rect::new(0, 0, 100, 10));
1747
1748 assert_eq!(rects[0].x, 20);
1751 assert_eq!(rects[1].x, 70);
1752 }
1753
1754 #[test]
1757 fn vertical_gap() {
1758 let flex = Flex::vertical()
1759 .gap(5)
1760 .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1761 let rects = flex.split(Rect::new(0, 0, 50, 100));
1762 assert_eq!(rects[0], Rect::new(0, 0, 50, 10));
1763 assert_eq!(rects[1], Rect::new(0, 15, 50, 10));
1764 }
1765
1766 #[test]
1769 fn vertical_center() {
1770 let flex = Flex::vertical()
1771 .alignment(Alignment::Center)
1772 .constraints([Constraint::Fixed(10)]);
1773 let rects = flex.split(Rect::new(0, 0, 50, 100));
1774 assert_eq!(rects[0].y, 45);
1776 assert_eq!(rects[0].height, 10);
1777 }
1778
1779 #[test]
1782 fn single_min_takes_all() {
1783 let flex = Flex::horizontal().constraints([Constraint::Min(5)]);
1784 let rects = flex.split(Rect::new(0, 0, 80, 24));
1785 assert_eq!(rects[0].width, 80);
1786 }
1787
1788 #[test]
1791 fn fixed_exceeds_available_clamped() {
1792 let flex = Flex::horizontal().constraints([Constraint::Fixed(60), Constraint::Fixed(60)]);
1793 let rects = flex.split(Rect::new(0, 0, 100, 10));
1794 assert_eq!(rects[0].width, 60);
1796 assert_eq!(rects[1].width, 40);
1797 }
1798
1799 #[test]
1802 fn percentage_overflow_clamped() {
1803 let flex = Flex::horizontal()
1804 .constraints([Constraint::Percentage(80.0), Constraint::Percentage(80.0)]);
1805 let rects = flex.split(Rect::new(0, 0, 100, 10));
1806 assert_eq!(rects[0].width, 80);
1807 assert_eq!(rects[1].width, 20); }
1809
1810 #[test]
1813 fn margin_reduces_split_area() {
1814 let flex = Flex::horizontal()
1815 .margin(Sides::all(10))
1816 .constraints([Constraint::Fixed(20), Constraint::Min(0)]);
1817 let rects = flex.split(Rect::new(0, 0, 100, 100));
1818 assert_eq!(rects[0].x, 10);
1820 assert_eq!(rects[0].y, 10);
1821 assert_eq!(rects[0].width, 20);
1822 assert_eq!(rects[0].height, 80);
1823 }
1824
1825 #[test]
1828 fn builder_methods_chain() {
1829 let flex = Flex::vertical()
1830 .direction(Direction::Horizontal)
1831 .gap(3)
1832 .margin(Sides::all(1))
1833 .alignment(Alignment::End)
1834 .constraints([Constraint::Fixed(10)]);
1835 let rects = flex.split(Rect::new(0, 0, 50, 50));
1836 assert_eq!(rects.len(), 1);
1837 }
1838
1839 #[test]
1842 fn space_between_single_item() {
1843 let flex = Flex::horizontal()
1844 .alignment(Alignment::SpaceBetween)
1845 .constraints([Constraint::Fixed(10)]);
1846 let rects = flex.split(Rect::new(0, 0, 100, 10));
1847 assert_eq!(rects[0].x, 0);
1849 assert_eq!(rects[0].width, 10);
1850 }
1851
1852 #[test]
1853 fn invariant_rects_within_bounds() {
1854 let area = Rect::new(10, 20, 80, 60);
1855 let flex = Flex::horizontal()
1856 .margin(Sides::all(5))
1857 .gap(2)
1858 .constraints([
1859 Constraint::Fixed(15),
1860 Constraint::Percentage(30.0),
1861 Constraint::Min(10),
1862 ]);
1863 let rects = flex.split(area);
1864
1865 let inner = area.inner(Sides::all(5));
1867 for rect in &rects {
1868 assert!(
1869 rect.x >= inner.x && rect.right() <= inner.right(),
1870 "Rect {:?} exceeds horizontal bounds of {:?}",
1871 rect,
1872 inner
1873 );
1874 assert!(
1875 rect.y >= inner.y && rect.bottom() <= inner.bottom(),
1876 "Rect {:?} exceeds vertical bounds of {:?}",
1877 rect,
1878 inner
1879 );
1880 }
1881 }
1882
1883 #[test]
1886 fn fill_takes_remaining_space() {
1887 let flex = Flex::horizontal().constraints([Constraint::Fixed(20), Constraint::Fill]);
1888 let rects = flex.split(Rect::new(0, 0, 100, 10));
1889 assert_eq!(rects[0].width, 20);
1890 assert_eq!(rects[1].width, 80); }
1892
1893 #[test]
1894 fn multiple_fills_share_space() {
1895 let flex = Flex::horizontal().constraints([Constraint::Fill, Constraint::Fill]);
1896 let rects = flex.split(Rect::new(0, 0, 100, 10));
1897 assert_eq!(rects[0].width, 50);
1898 assert_eq!(rects[1].width, 50);
1899 }
1900
1901 #[test]
1904 fn fit_content_uses_preferred_size() {
1905 let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
1906 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |idx, _| {
1907 if idx == 0 {
1908 LayoutSizeHint {
1909 min: 5,
1910 preferred: 30,
1911 max: None,
1912 }
1913 } else {
1914 LayoutSizeHint::ZERO
1915 }
1916 });
1917 assert_eq!(rects[0].width, 30); assert_eq!(rects[1].width, 70); }
1920
1921 #[test]
1922 fn fit_content_clamps_to_available() {
1923 let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::FitContent]);
1924 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
1925 min: 5,
1926 preferred: 80,
1927 max: None,
1928 });
1929 assert_eq!(rects[0].width, 80);
1931 assert_eq!(rects[1].width, 20);
1932 }
1933
1934 #[test]
1935 fn fit_content_without_measurer_gets_zero() {
1936 let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
1938 let rects = flex.split(Rect::new(0, 0, 100, 10));
1939 assert_eq!(rects[0].width, 0); assert_eq!(rects[1].width, 100); }
1942
1943 #[test]
1944 fn fit_content_zero_area_returns_empty_rects() {
1945 let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
1946 let rects = flex.split_with_measurer(Rect::new(0, 0, 0, 0), |_, _| LayoutSizeHint {
1947 min: 5,
1948 preferred: 10,
1949 max: None,
1950 });
1951 assert_eq!(rects.len(), 2);
1952 assert_eq!(rects[0].width, 0);
1953 assert_eq!(rects[0].height, 0);
1954 assert_eq!(rects[1].width, 0);
1955 assert_eq!(rects[1].height, 0);
1956 }
1957
1958 #[test]
1959 fn fit_content_tiny_available_clamps_to_remaining() {
1960 let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
1961 let rects = flex.split_with_measurer(Rect::new(0, 0, 1, 1), |_, _| LayoutSizeHint {
1962 min: 5,
1963 preferred: 10,
1964 max: None,
1965 });
1966 assert_eq!(rects[0].width, 1);
1967 assert_eq!(rects[1].width, 0);
1968 }
1969
1970 #[test]
1973 fn fit_content_bounded_clamps_to_min() {
1974 let flex = Flex::horizontal().constraints([
1975 Constraint::FitContentBounded { min: 20, max: 50 },
1976 Constraint::Fill,
1977 ]);
1978 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
1979 min: 5,
1980 preferred: 10, max: None,
1982 });
1983 assert_eq!(rects[0].width, 20); assert_eq!(rects[1].width, 80);
1985 }
1986
1987 #[test]
1988 fn fit_content_bounded_respects_small_available() {
1989 let flex = Flex::horizontal().constraints([
1990 Constraint::FitContentBounded { min: 20, max: 50 },
1991 Constraint::Fill,
1992 ]);
1993 let rects = flex.split_with_measurer(Rect::new(0, 0, 5, 2), |_, _| LayoutSizeHint {
1994 min: 5,
1995 preferred: 10,
1996 max: None,
1997 });
1998 assert_eq!(rects[0].width, 5);
2000 assert_eq!(rects[1].width, 0);
2001 }
2002
2003 #[test]
2004 fn fit_content_bounded_clamps_to_max() {
2005 let flex = Flex::horizontal().constraints([
2006 Constraint::FitContentBounded { min: 10, max: 30 },
2007 Constraint::Fill,
2008 ]);
2009 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
2010 min: 5,
2011 preferred: 50, max: None,
2013 });
2014 assert_eq!(rects[0].width, 30); assert_eq!(rects[1].width, 70);
2016 }
2017
2018 #[test]
2019 fn fit_content_bounded_uses_preferred_when_in_range() {
2020 let flex = Flex::horizontal().constraints([
2021 Constraint::FitContentBounded { min: 10, max: 50 },
2022 Constraint::Fill,
2023 ]);
2024 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
2025 min: 5,
2026 preferred: 35, max: None,
2028 });
2029 assert_eq!(rects[0].width, 35);
2030 assert_eq!(rects[1].width, 65);
2031 }
2032
2033 #[test]
2036 fn fit_min_uses_minimum_size() {
2037 let flex = Flex::horizontal().constraints([Constraint::FitMin, Constraint::Fill]);
2038 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |idx, _| {
2039 if idx == 0 {
2040 LayoutSizeHint {
2041 min: 15,
2042 preferred: 40,
2043 max: None,
2044 }
2045 } else {
2046 LayoutSizeHint::ZERO
2047 }
2048 });
2049 assert_eq!(rects[0].width, 15, "FitMin should strict size to min");
2052 assert_eq!(rects[1].width, 85, "Fill should take remaining space");
2053 }
2054
2055 #[test]
2056 fn fit_min_without_measurer_gets_zero() {
2057 let flex = Flex::horizontal().constraints([Constraint::FitMin, Constraint::Fill]);
2058 let rects = flex.split(Rect::new(0, 0, 100, 10));
2059 assert_eq!(rects[0].width, 0);
2062 assert_eq!(rects[1].width, 100);
2063 }
2064
2065 #[test]
2068 fn layout_size_hint_zero_is_default() {
2069 assert_eq!(LayoutSizeHint::default(), LayoutSizeHint::ZERO);
2070 }
2071
2072 #[test]
2073 fn layout_size_hint_exact() {
2074 let h = LayoutSizeHint::exact(25);
2075 assert_eq!(h.min, 25);
2076 assert_eq!(h.preferred, 25);
2077 assert_eq!(h.max, Some(25));
2078 }
2079
2080 #[test]
2081 fn layout_size_hint_at_least() {
2082 let h = LayoutSizeHint::at_least(10, 30);
2083 assert_eq!(h.min, 10);
2084 assert_eq!(h.preferred, 30);
2085 assert_eq!(h.max, None);
2086 }
2087
2088 #[test]
2089 fn layout_size_hint_clamp() {
2090 let h = LayoutSizeHint {
2091 min: 10,
2092 preferred: 20,
2093 max: Some(30),
2094 };
2095 assert_eq!(h.clamp(5), 10); assert_eq!(h.clamp(15), 15); assert_eq!(h.clamp(50), 30); }
2099
2100 #[test]
2101 fn layout_size_hint_clamp_unbounded() {
2102 let h = LayoutSizeHint::at_least(5, 10);
2103 assert_eq!(h.clamp(3), 5); assert_eq!(h.clamp(1000), 1000); }
2106
2107 #[test]
2108 fn layout_size_hint_clamp_min_greater_than_max() {
2109 let h = LayoutSizeHint {
2111 min: 20,
2112 preferred: 20,
2113 max: Some(10),
2114 };
2115 assert_eq!(h.clamp(5), 20); assert_eq!(h.clamp(15), 20); assert_eq!(h.clamp(25), 20); }
2119
2120 #[test]
2123 fn fit_content_with_fixed_and_fill() {
2124 let flex = Flex::horizontal().constraints([
2125 Constraint::Fixed(20),
2126 Constraint::FitContent,
2127 Constraint::Fill,
2128 ]);
2129 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |idx, _| {
2130 if idx == 1 {
2131 LayoutSizeHint {
2132 min: 5,
2133 preferred: 25,
2134 max: None,
2135 }
2136 } else {
2137 LayoutSizeHint::ZERO
2138 }
2139 });
2140 assert_eq!(rects[0].width, 20); assert_eq!(rects[1].width, 25); assert_eq!(rects[2].width, 55); }
2144
2145 #[test]
2146 fn total_allocation_never_exceeds_available_with_fit_content() {
2147 for available in [10u16, 50, 100, 255] {
2148 let flex = Flex::horizontal().constraints([
2149 Constraint::FitContent,
2150 Constraint::FitContent,
2151 Constraint::Fill,
2152 ]);
2153 let rects =
2154 flex.split_with_measurer(Rect::new(0, 0, available, 10), |_, _| LayoutSizeHint {
2155 min: 10,
2156 preferred: 40,
2157 max: None,
2158 });
2159 let total: u16 = rects.iter().map(|r| r.width).sum();
2160 assert!(
2161 total <= available,
2162 "Total {} exceeded available {} with FitContent",
2163 total,
2164 available
2165 );
2166 }
2167 }
2168
2169 mod rounding_tests {
2174 use super::super::*;
2175
2176 #[test]
2179 fn rounding_conserves_sum_exact() {
2180 let result = round_layout_stable(&[10.0, 20.0, 10.0], 40, None);
2181 assert_eq!(result.iter().copied().sum::<u16>(), 40);
2182 assert_eq!(result.as_slice(), &[10u16, 20u16, 10u16]);
2183 }
2184
2185 #[test]
2186 fn rounding_conserves_sum_fractional() {
2187 let result = round_layout_stable(&[10.4, 20.6, 9.0], 40, None);
2188 assert_eq!(
2189 result.iter().copied().sum::<u16>(),
2190 40,
2191 "Sum must equal total: {:?}",
2192 result
2193 );
2194 }
2195
2196 #[test]
2197 fn rounding_conserves_sum_many_fractions() {
2198 let targets = vec![20.2, 20.2, 20.2, 20.2, 19.2];
2199 let result = round_layout_stable(&targets, 100, None);
2200 assert_eq!(
2201 result.iter().copied().sum::<u16>(),
2202 100,
2203 "Sum must be exactly 100: {:?}",
2204 result
2205 );
2206 }
2207
2208 #[test]
2209 fn rounding_conserves_sum_all_half() {
2210 let targets = vec![10.5, 10.5, 10.5, 10.5];
2211 let result = round_layout_stable(&targets, 42, None);
2212 assert_eq!(
2213 result.iter().copied().sum::<u16>(),
2214 42,
2215 "Sum must be exactly 42: {:?}",
2216 result
2217 );
2218 }
2219
2220 #[test]
2223 fn rounding_displacement_bounded() {
2224 let targets = vec![33.33, 33.33, 33.34];
2225 let result = round_layout_stable(&targets, 100, None);
2226 assert_eq!(result.iter().copied().sum::<u16>(), 100);
2227
2228 for (i, (&x, &r)) in result.iter().zip(targets.iter()).enumerate() {
2229 let floor = r.floor() as u16;
2230 let ceil = floor + 1;
2231 assert!(
2232 x == floor || x == ceil,
2233 "Element {} = {} not in {{floor={}, ceil={}}} of target {}",
2234 i,
2235 x,
2236 floor,
2237 ceil,
2238 r
2239 );
2240 }
2241 }
2242
2243 #[test]
2246 fn temporal_tiebreak_stable_when_unchanged() {
2247 let targets = vec![10.5, 10.5, 10.5, 10.5];
2248 let first = round_layout_stable(&targets, 42, None);
2249 let second = round_layout_stable(&targets, 42, Some(first.clone()));
2250 assert_eq!(
2251 first, second,
2252 "Identical targets should produce identical results"
2253 );
2254 }
2255
2256 #[test]
2257 fn temporal_tiebreak_prefers_previous_direction() {
2258 let targets = vec![10.5, 10.5];
2259 let total = 21;
2260 let first = round_layout_stable(&targets, total, None);
2261 assert_eq!(first.iter().copied().sum::<u16>(), total);
2262 let second = round_layout_stable(&targets, total, Some(first.clone()));
2263 assert_eq!(first, second, "Should maintain rounding direction");
2264 }
2265
2266 #[test]
2267 fn temporal_tiebreak_adapts_to_changed_targets() {
2268 let targets_a = vec![10.5, 10.5];
2269 let result_a = round_layout_stable(&targets_a, 21, None);
2270 let targets_b = vec![15.7, 5.3];
2271 let result_b = round_layout_stable(&targets_b, 21, Some(result_a));
2272 assert_eq!(result_b.iter().copied().sum::<u16>(), 21);
2273 assert!(result_b[0] > result_b[1], "Should follow larger target");
2274 }
2275
2276 #[test]
2279 fn property_min_displacement_brute_force_small() {
2280 let targets = vec![3.3, 3.3, 3.4];
2281 let total: u16 = 10;
2282 let result = round_layout_stable(&targets, total, None);
2283 let our_displacement: f64 = result
2284 .iter()
2285 .zip(targets.iter())
2286 .map(|(&x, &r)| (x as f64 - r).abs())
2287 .sum();
2288
2289 let mut min_displacement = f64::MAX;
2290 let floors: Vec<u16> = targets.iter().map(|&r| r.floor() as u16).collect();
2291 let ceils: Vec<u16> = targets.iter().map(|&r| r.floor() as u16 + 1).collect();
2292
2293 for a in floors[0]..=ceils[0] {
2294 for b in floors[1]..=ceils[1] {
2295 for c in floors[2]..=ceils[2] {
2296 if a + b + c == total {
2297 let disp = (a as f64 - targets[0]).abs()
2298 + (b as f64 - targets[1]).abs()
2299 + (c as f64 - targets[2]).abs();
2300 if disp < min_displacement {
2301 min_displacement = disp;
2302 }
2303 }
2304 }
2305 }
2306 }
2307
2308 assert!(
2309 (our_displacement - min_displacement).abs() < 1e-10,
2310 "Our displacement {} should match optimal {}: {:?}",
2311 our_displacement,
2312 min_displacement,
2313 result
2314 );
2315 }
2316
2317 #[test]
2320 fn rounding_deterministic() {
2321 let targets = vec![7.7, 8.3, 14.0];
2322 let a = round_layout_stable(&targets, 30, None);
2323 let b = round_layout_stable(&targets, 30, None);
2324 assert_eq!(a, b, "Same inputs must produce identical outputs");
2325 }
2326
2327 #[test]
2330 fn rounding_empty_targets() {
2331 let result = round_layout_stable(&[], 0, None);
2332 assert!(result.is_empty());
2333 }
2334
2335 #[test]
2336 fn rounding_single_element() {
2337 let result = round_layout_stable(&[10.7], 11, None);
2338 assert_eq!(result.as_slice(), &[11u16]);
2339 }
2340
2341 #[test]
2342 fn rounding_zero_total() {
2343 let result = round_layout_stable(&[5.0, 5.0], 0, None);
2344 assert_eq!(result.iter().copied().sum::<u16>(), 0);
2345 }
2346
2347 #[test]
2348 fn rounding_zero_total_with_large_overflow_reaches_zero() {
2349 let result = round_layout_stable(&[65535.0, 65535.0], 0, None);
2350 assert_eq!(result.as_slice(), &[0u16, 0u16]);
2351 assert_eq!(result.iter().copied().sum::<u16>(), 0);
2352 }
2353
2354 #[test]
2355 fn rounding_all_zeros() {
2356 let result = round_layout_stable(&[0.0, 0.0, 0.0], 0, None);
2357 assert_eq!(result.as_slice(), &[0u16, 0u16, 0u16]);
2358 }
2359
2360 #[test]
2361 fn rounding_integer_targets() {
2362 let result = round_layout_stable(&[10.0, 20.0, 30.0], 60, None);
2363 assert_eq!(result.as_slice(), &[10u16, 20u16, 30u16]);
2364 }
2365
2366 #[test]
2367 fn rounding_large_deficit() {
2368 let result = round_layout_stable(&[0.9, 0.9, 0.9], 3, None);
2369 assert_eq!(result.iter().copied().sum::<u16>(), 3);
2370 assert_eq!(result.as_slice(), &[1u16, 1u16, 1u16]);
2371 }
2372
2373 #[test]
2374 fn rounding_with_prev_different_length() {
2375 let result = round_layout_stable(
2376 &[10.5, 10.5],
2377 21,
2378 Some(smallvec::smallvec![11u16, 10u16, 5u16]),
2379 );
2380 assert_eq!(result.iter().copied().sum::<u16>(), 21);
2381 }
2382
2383 #[test]
2384 fn rounding_very_small_fractions() {
2385 let targets = vec![10.001, 20.001, 9.998];
2386 let result = round_layout_stable(&targets, 40, None);
2387 assert_eq!(result.iter().copied().sum::<u16>(), 40);
2388 }
2389
2390 #[test]
2391 fn rounding_conserves_sum_stress() {
2392 let n = 50;
2393 let targets: Vec<f64> = (0..n).map(|i| 2.0 + (i as f64 * 0.037)).collect();
2394 let total = 120u16;
2395 let result = round_layout_stable(&targets, total, None);
2396 assert_eq!(
2397 result.iter().copied().sum::<u16>(),
2398 total,
2399 "Sum must be exactly {} for {} items: {:?}",
2400 total,
2401 n,
2402 result
2403 );
2404 }
2405 }
2406
2407 mod property_constraint_tests {
2412 use super::super::*;
2413
2414 struct Lcg(u64);
2416
2417 impl Lcg {
2418 fn new(seed: u64) -> Self {
2419 Self(seed)
2420 }
2421 fn next_u32(&mut self) -> u32 {
2422 self.0 = self
2423 .0
2424 .wrapping_mul(6_364_136_223_846_793_005)
2425 .wrapping_add(1);
2426 (self.0 >> 33) as u32
2427 }
2428 fn next_u16_range(&mut self, lo: u16, hi: u16) -> u16 {
2429 if lo >= hi {
2430 return lo;
2431 }
2432 lo + (self.next_u32() % (hi - lo) as u32) as u16
2433 }
2434 fn next_f32(&mut self) -> f32 {
2435 (self.next_u32() & 0x00FF_FFFF) as f32 / 16_777_216.0
2436 }
2437 }
2438
2439 fn random_constraint(rng: &mut Lcg) -> Constraint {
2441 match rng.next_u32() % 7 {
2442 0 => Constraint::Fixed(rng.next_u16_range(1, 80)),
2443 1 => Constraint::Percentage(rng.next_f32() * 100.0),
2444 2 => Constraint::Min(rng.next_u16_range(0, 40)),
2445 3 => Constraint::Max(rng.next_u16_range(5, 120)),
2446 4 => {
2447 let n = rng.next_u32() % 5 + 1;
2448 let d = rng.next_u32() % 5 + 1;
2449 Constraint::Ratio(n, d)
2450 }
2451 5 => Constraint::Fill,
2452 _ => Constraint::FitContent,
2453 }
2454 }
2455
2456 #[test]
2457 fn property_constraints_respected_fixed() {
2458 let mut rng = Lcg::new(0xDEAD_BEEF);
2459 for _ in 0..200 {
2460 let fixed_val = rng.next_u16_range(1, 60);
2461 let avail = rng.next_u16_range(10, 200);
2462 let flex = Flex::horizontal().constraints([Constraint::Fixed(fixed_val)]);
2463 let rects = flex.split(Rect::new(0, 0, avail, 10));
2464 assert!(
2465 rects[0].width <= fixed_val.min(avail),
2466 "Fixed({}) in avail {} -> width {}",
2467 fixed_val,
2468 avail,
2469 rects[0].width
2470 );
2471 }
2472 }
2473
2474 #[test]
2475 fn property_constraints_respected_max() {
2476 let mut rng = Lcg::new(0xCAFE_BABE);
2477 for _ in 0..200 {
2478 let max_val = rng.next_u16_range(5, 80);
2479 let avail = rng.next_u16_range(10, 200);
2480 let flex =
2481 Flex::horizontal().constraints([Constraint::Max(max_val), Constraint::Fill]);
2482 let rects = flex.split(Rect::new(0, 0, avail, 10));
2483 assert!(
2484 rects[0].width <= max_val,
2485 "Max({}) in avail {} -> width {}",
2486 max_val,
2487 avail,
2488 rects[0].width
2489 );
2490 }
2491 }
2492
2493 #[test]
2494 fn property_constraints_respected_min() {
2495 let mut rng = Lcg::new(0xBAAD_F00D);
2496 for _ in 0..200 {
2497 let min_val = rng.next_u16_range(0, 40);
2498 let avail = rng.next_u16_range(min_val.max(1), 200);
2499 let flex = Flex::horizontal().constraints([Constraint::Min(min_val)]);
2500 let rects = flex.split(Rect::new(0, 0, avail, 10));
2501 assert!(
2502 rects[0].width >= min_val,
2503 "Min({}) in avail {} -> width {}",
2504 min_val,
2505 avail,
2506 rects[0].width
2507 );
2508 }
2509 }
2510
2511 #[test]
2512 fn property_constraints_respected_ratio_proportional() {
2513 let mut rng = Lcg::new(0x1234_5678);
2514 for _ in 0..200 {
2515 let n1 = rng.next_u32() % 5 + 1;
2516 let n2 = rng.next_u32() % 5 + 1;
2517 let d = n1 + n2;
2518 let avail = rng.next_u16_range(20, 200);
2519 let flex = Flex::horizontal()
2520 .constraints([Constraint::Ratio(n1, d), Constraint::Ratio(n2, d)]);
2521 let rects = flex.split(Rect::new(0, 0, avail, 10));
2522 let w1 = rects[0].width as f64;
2523 let w2 = rects[1].width as f64;
2524 let total = w1 + w2;
2525 if total > 0.0 {
2526 let expected_ratio = n1 as f64 / d as f64;
2527 let actual_ratio = w1 / total;
2528 assert!(
2529 (actual_ratio - expected_ratio).abs() < 0.15 || total < 4.0,
2530 "Ratio({},{})/({}+{}) avail={}: ~{:.2} got {:.2} (w1={}, w2={})",
2531 n1,
2532 d,
2533 n1,
2534 n2,
2535 avail,
2536 expected_ratio,
2537 actual_ratio,
2538 w1,
2539 w2
2540 );
2541 }
2542 }
2543 }
2544
2545 #[test]
2546 fn property_total_allocation_never_exceeds_available() {
2547 let mut rng = Lcg::new(0xFACE_FEED);
2548 for _ in 0..500 {
2549 let n = (rng.next_u32() % 6 + 1) as usize;
2550 let constraints: Vec<Constraint> =
2551 (0..n).map(|_| random_constraint(&mut rng)).collect();
2552 let avail = rng.next_u16_range(5, 200);
2553 let dir = if rng.next_u32().is_multiple_of(2) {
2554 Direction::Horizontal
2555 } else {
2556 Direction::Vertical
2557 };
2558 let flex = Flex::default().direction(dir).constraints(constraints);
2559 let area = Rect::new(0, 0, avail, avail);
2560 let rects = flex.split(area);
2561 let total: u16 = rects
2562 .iter()
2563 .map(|r| match dir {
2564 Direction::Horizontal => r.width,
2565 Direction::Vertical => r.height,
2566 })
2567 .sum();
2568 assert!(
2569 total <= avail,
2570 "Total {} exceeded available {} with {} constraints",
2571 total,
2572 avail,
2573 n
2574 );
2575 }
2576 }
2577
2578 #[test]
2579 fn property_no_overlap_horizontal() {
2580 let mut rng = Lcg::new(0xABCD_1234);
2581 for _ in 0..300 {
2582 let n = (rng.next_u32() % 5 + 2) as usize;
2583 let constraints: Vec<Constraint> =
2584 (0..n).map(|_| random_constraint(&mut rng)).collect();
2585 let avail = rng.next_u16_range(20, 200);
2586 let flex = Flex::horizontal().constraints(constraints);
2587 let rects = flex.split(Rect::new(0, 0, avail, 10));
2588
2589 for i in 1..rects.len() {
2590 let prev_end = rects[i - 1].x + rects[i - 1].width;
2591 assert!(
2592 rects[i].x >= prev_end,
2593 "Overlap at {}: prev ends {}, next starts {}",
2594 i,
2595 prev_end,
2596 rects[i].x
2597 );
2598 }
2599 }
2600 }
2601
2602 #[test]
2603 fn property_deterministic_across_runs() {
2604 let mut rng = Lcg::new(0x9999_8888);
2605 for _ in 0..100 {
2606 let n = (rng.next_u32() % 5 + 1) as usize;
2607 let constraints: Vec<Constraint> =
2608 (0..n).map(|_| random_constraint(&mut rng)).collect();
2609 let avail = rng.next_u16_range(10, 200);
2610 let r1 = Flex::horizontal()
2611 .constraints(constraints.clone())
2612 .split(Rect::new(0, 0, avail, 10));
2613 let r2 = Flex::horizontal()
2614 .constraints(constraints)
2615 .split(Rect::new(0, 0, avail, 10));
2616 assert_eq!(r1, r2, "Determinism violation at avail={}", avail);
2617 }
2618 }
2619 }
2620
2621 mod property_temporal_tests {
2626 use super::super::*;
2627 use crate::cache::{CoherenceCache, CoherenceId};
2628
2629 struct Lcg(u64);
2631
2632 impl Lcg {
2633 fn new(seed: u64) -> Self {
2634 Self(seed)
2635 }
2636 fn next_u32(&mut self) -> u32 {
2637 self.0 = self
2638 .0
2639 .wrapping_mul(6_364_136_223_846_793_005)
2640 .wrapping_add(1);
2641 (self.0 >> 33) as u32
2642 }
2643 }
2644
2645 #[test]
2646 fn property_temporal_stability_small_resize() {
2647 let constraints = [
2648 Constraint::Percentage(33.3),
2649 Constraint::Percentage(33.3),
2650 Constraint::Fill,
2651 ];
2652 let mut coherence = CoherenceCache::new(64);
2653 let id = CoherenceId::new(&constraints, Direction::Horizontal);
2654
2655 for total in [80u16, 100, 120] {
2656 let flex = Flex::horizontal().constraints(constraints);
2657 let rects = flex.split(Rect::new(0, 0, total, 10));
2658 let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2659
2660 let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2661 let prev = coherence.get(&id);
2662 let rounded = round_layout_stable(&targets, total, prev);
2663
2664 if let Some(old) = coherence.get(&id) {
2665 let (sum_disp, max_disp) = coherence.displacement(&id, &rounded);
2666 assert!(
2667 max_disp <= total.abs_diff(old.iter().copied().sum()) as u32 + 1,
2668 "max_disp={} too large for size change {} -> {}",
2669 max_disp,
2670 old.iter().copied().sum::<u16>(),
2671 total
2672 );
2673 let _ = sum_disp;
2674 }
2675 coherence.store(id, rounded);
2676 }
2677 }
2678
2679 #[test]
2680 fn property_temporal_stability_random_walk() {
2681 let constraints = [
2682 Constraint::Ratio(1, 3),
2683 Constraint::Ratio(1, 3),
2684 Constraint::Ratio(1, 3),
2685 ];
2686 let id = CoherenceId::new(&constraints, Direction::Horizontal);
2687 let mut coherence = CoherenceCache::new(64);
2688 let mut rng = Lcg::new(0x5555_AAAA);
2689 let mut total: u16 = 90;
2690
2691 for step in 0..200 {
2692 let prev_total = total;
2693 let delta = (rng.next_u32() % 7) as i32 - 3;
2694 total = (total as i32 + delta).clamp(10, 250) as u16;
2695
2696 let flex = Flex::horizontal().constraints(constraints);
2697 let rects = flex.split(Rect::new(0, 0, total, 10));
2698 let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2699
2700 let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2701 let prev = coherence.get(&id);
2702 let rounded = round_layout_stable(&targets, total, prev);
2703
2704 if coherence.get(&id).is_some() {
2705 let (_, max_disp) = coherence.displacement(&id, &rounded);
2706 let size_change = total.abs_diff(prev_total);
2707 assert!(
2708 max_disp <= size_change as u32 + 2,
2709 "step {}: max_disp={} exceeds size_change={} + 2",
2710 step,
2711 max_disp,
2712 size_change
2713 );
2714 }
2715 coherence.store(id, rounded);
2716 }
2717 }
2718
2719 #[test]
2720 fn property_temporal_stability_identical_frames() {
2721 let constraints = [
2722 Constraint::Fixed(20),
2723 Constraint::Fill,
2724 Constraint::Fixed(15),
2725 ];
2726 let id = CoherenceId::new(&constraints, Direction::Horizontal);
2727 let mut coherence = CoherenceCache::new(64);
2728
2729 let flex = Flex::horizontal().constraints(constraints);
2730 let rects = flex.split(Rect::new(0, 0, 100, 10));
2731 let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2732 coherence.store(id, widths.iter().copied().collect());
2733
2734 for _ in 0..10 {
2735 let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2736 let prev = coherence.get(&id);
2737 let rounded = round_layout_stable(&targets, 100, prev);
2738 let (sum_disp, _) = coherence.displacement(&id, &rounded);
2739 assert_eq!(sum_disp, 0, "Identical frames: zero displacement");
2740 coherence.store(id, rounded);
2741 }
2742 }
2743
2744 #[test]
2745 fn property_temporal_coherence_sweep() {
2746 let constraints = [
2747 Constraint::Percentage(25.0),
2748 Constraint::Percentage(50.0),
2749 Constraint::Fill,
2750 ];
2751 let id = CoherenceId::new(&constraints, Direction::Horizontal);
2752 let mut coherence = CoherenceCache::new(64);
2753 let mut total_displacement: u64 = 0;
2754
2755 for total in 60u16..=140 {
2756 let flex = Flex::horizontal().constraints(constraints);
2757 let rects = flex.split(Rect::new(0, 0, total, 10));
2758 let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2759
2760 let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2761 let prev = coherence.get(&id);
2762 let rounded = round_layout_stable(&targets, total, prev);
2763
2764 if coherence.get(&id).is_some() {
2765 let (sum_disp, _) = coherence.displacement(&id, &rounded);
2766 total_displacement += sum_disp;
2767 }
2768 coherence.store(id, rounded);
2769 }
2770
2771 assert!(
2772 total_displacement <= 80 * 3,
2773 "Total displacement {} exceeds bound for 80-step sweep",
2774 total_displacement
2775 );
2776 }
2777 }
2778
2779 mod snapshot_layout_tests {
2784 use super::super::*;
2785 use crate::grid::{Grid, GridArea};
2786
2787 fn snapshot_flex(
2788 constraints: &[Constraint],
2789 dir: Direction,
2790 width: u16,
2791 height: u16,
2792 ) -> String {
2793 let flex = Flex::default()
2794 .direction(dir)
2795 .constraints(constraints.iter().copied());
2796 let rects = flex.split(Rect::new(0, 0, width, height));
2797 let mut out = format!(
2798 "Flex {:?} {}x{} ({} constraints)\n",
2799 dir,
2800 width,
2801 height,
2802 constraints.len()
2803 );
2804 for (i, r) in rects.iter().enumerate() {
2805 out.push_str(&format!(
2806 " [{}] x={} y={} w={} h={}\n",
2807 i, r.x, r.y, r.width, r.height
2808 ));
2809 }
2810 let total: u16 = rects
2811 .iter()
2812 .map(|r| match dir {
2813 Direction::Horizontal => r.width,
2814 Direction::Vertical => r.height,
2815 })
2816 .sum();
2817 out.push_str(&format!(" total={}\n", total));
2818 out
2819 }
2820
2821 fn snapshot_grid(
2822 rows: &[Constraint],
2823 cols: &[Constraint],
2824 areas: &[(&str, GridArea)],
2825 width: u16,
2826 height: u16,
2827 ) -> String {
2828 let mut grid = Grid::new()
2829 .rows(rows.iter().copied())
2830 .columns(cols.iter().copied());
2831 for &(name, area) in areas {
2832 grid = grid.area(name, area);
2833 }
2834 let layout = grid.split(Rect::new(0, 0, width, height));
2835
2836 let mut out = format!(
2837 "Grid {}x{} ({}r x {}c)\n",
2838 width,
2839 height,
2840 rows.len(),
2841 cols.len()
2842 );
2843 for r in 0..rows.len() {
2844 for c in 0..cols.len() {
2845 let rect = layout.cell(r, c);
2846 out.push_str(&format!(
2847 " [{},{}] x={} y={} w={} h={}\n",
2848 r, c, rect.x, rect.y, rect.width, rect.height
2849 ));
2850 }
2851 }
2852 for &(name, _) in areas {
2853 if let Some(rect) = layout.area(name) {
2854 out.push_str(&format!(
2855 " area({}) x={} y={} w={} h={}\n",
2856 name, rect.x, rect.y, rect.width, rect.height
2857 ));
2858 }
2859 }
2860 out
2861 }
2862
2863 #[test]
2866 fn snapshot_flex_thirds_80x24() {
2867 let snap = snapshot_flex(
2868 &[
2869 Constraint::Ratio(1, 3),
2870 Constraint::Ratio(1, 3),
2871 Constraint::Ratio(1, 3),
2872 ],
2873 Direction::Horizontal,
2874 80,
2875 24,
2876 );
2877 assert_eq!(
2878 snap,
2879 "\
2880Flex Horizontal 80x24 (3 constraints)
2881 [0] x=0 y=0 w=26 h=24
2882 [1] x=26 y=0 w=26 h=24
2883 [2] x=52 y=0 w=26 h=24
2884 total=78
2885"
2886 );
2887 }
2888
2889 #[test]
2890 fn snapshot_flex_sidebar_content_80x24() {
2891 let snap = snapshot_flex(
2892 &[Constraint::Fixed(20), Constraint::Fill],
2893 Direction::Horizontal,
2894 80,
2895 24,
2896 );
2897 assert_eq!(
2898 snap,
2899 "\
2900Flex Horizontal 80x24 (2 constraints)
2901 [0] x=0 y=0 w=20 h=24
2902 [1] x=20 y=0 w=60 h=24
2903 total=80
2904"
2905 );
2906 }
2907
2908 #[test]
2909 fn snapshot_flex_header_body_footer_80x24() {
2910 let snap = snapshot_flex(
2911 &[Constraint::Fixed(3), Constraint::Fill, Constraint::Fixed(1)],
2912 Direction::Vertical,
2913 80,
2914 24,
2915 );
2916 assert_eq!(
2917 snap,
2918 "\
2919Flex Vertical 80x24 (3 constraints)
2920 [0] x=0 y=0 w=80 h=3
2921 [1] x=0 y=3 w=80 h=20
2922 [2] x=0 y=23 w=80 h=1
2923 total=24
2924"
2925 );
2926 }
2927
2928 #[test]
2931 fn snapshot_flex_thirds_120x40() {
2932 let snap = snapshot_flex(
2933 &[
2934 Constraint::Ratio(1, 3),
2935 Constraint::Ratio(1, 3),
2936 Constraint::Ratio(1, 3),
2937 ],
2938 Direction::Horizontal,
2939 120,
2940 40,
2941 );
2942 assert_eq!(
2943 snap,
2944 "\
2945Flex Horizontal 120x40 (3 constraints)
2946 [0] x=0 y=0 w=40 h=40
2947 [1] x=40 y=0 w=40 h=40
2948 [2] x=80 y=0 w=40 h=40
2949 total=120
2950"
2951 );
2952 }
2953
2954 #[test]
2955 fn snapshot_flex_sidebar_content_120x40() {
2956 let snap = snapshot_flex(
2957 &[Constraint::Fixed(20), Constraint::Fill],
2958 Direction::Horizontal,
2959 120,
2960 40,
2961 );
2962 assert_eq!(
2963 snap,
2964 "\
2965Flex Horizontal 120x40 (2 constraints)
2966 [0] x=0 y=0 w=20 h=40
2967 [1] x=20 y=0 w=100 h=40
2968 total=120
2969"
2970 );
2971 }
2972
2973 #[test]
2974 fn snapshot_flex_percentage_mix_120x40() {
2975 let snap = snapshot_flex(
2976 &[
2977 Constraint::Percentage(25.0),
2978 Constraint::Percentage(50.0),
2979 Constraint::Fill,
2980 ],
2981 Direction::Horizontal,
2982 120,
2983 40,
2984 );
2985 assert_eq!(
2986 snap,
2987 "\
2988Flex Horizontal 120x40 (3 constraints)
2989 [0] x=0 y=0 w=30 h=40
2990 [1] x=30 y=0 w=60 h=40
2991 [2] x=90 y=0 w=30 h=40
2992 total=120
2993"
2994 );
2995 }
2996
2997 #[test]
3000 fn snapshot_grid_2x2_80x24() {
3001 let snap = snapshot_grid(
3002 &[Constraint::Fixed(3), Constraint::Fill],
3003 &[Constraint::Fixed(20), Constraint::Fill],
3004 &[
3005 ("header", GridArea::span(0, 0, 1, 2)),
3006 ("sidebar", GridArea::span(1, 0, 1, 1)),
3007 ("content", GridArea::cell(1, 1)),
3008 ],
3009 80,
3010 24,
3011 );
3012 assert_eq!(
3013 snap,
3014 "\
3015Grid 80x24 (2r x 2c)
3016 [0,0] x=0 y=0 w=20 h=3
3017 [0,1] x=20 y=0 w=60 h=3
3018 [1,0] x=0 y=3 w=20 h=21
3019 [1,1] x=20 y=3 w=60 h=21
3020 area(header) x=0 y=0 w=80 h=3
3021 area(sidebar) x=0 y=3 w=20 h=21
3022 area(content) x=20 y=3 w=60 h=21
3023"
3024 );
3025 }
3026
3027 #[test]
3028 fn snapshot_grid_3x3_80x24() {
3029 let snap = snapshot_grid(
3030 &[Constraint::Fixed(1), Constraint::Fill, Constraint::Fixed(1)],
3031 &[
3032 Constraint::Fixed(10),
3033 Constraint::Fill,
3034 Constraint::Fixed(10),
3035 ],
3036 &[],
3037 80,
3038 24,
3039 );
3040 assert_eq!(
3041 snap,
3042 "\
3043Grid 80x24 (3r x 3c)
3044 [0,0] x=0 y=0 w=10 h=1
3045 [0,1] x=10 y=0 w=60 h=1
3046 [0,2] x=70 y=0 w=10 h=1
3047 [1,0] x=0 y=1 w=10 h=22
3048 [1,1] x=10 y=1 w=60 h=22
3049 [1,2] x=70 y=1 w=10 h=22
3050 [2,0] x=0 y=23 w=10 h=1
3051 [2,1] x=10 y=23 w=60 h=1
3052 [2,2] x=70 y=23 w=10 h=1
3053"
3054 );
3055 }
3056
3057 #[test]
3060 fn snapshot_grid_2x2_120x40() {
3061 let snap = snapshot_grid(
3062 &[Constraint::Fixed(3), Constraint::Fill],
3063 &[Constraint::Fixed(20), Constraint::Fill],
3064 &[
3065 ("header", GridArea::span(0, 0, 1, 2)),
3066 ("sidebar", GridArea::span(1, 0, 1, 1)),
3067 ("content", GridArea::cell(1, 1)),
3068 ],
3069 120,
3070 40,
3071 );
3072 assert_eq!(
3073 snap,
3074 "\
3075Grid 120x40 (2r x 2c)
3076 [0,0] x=0 y=0 w=20 h=3
3077 [0,1] x=20 y=0 w=100 h=3
3078 [1,0] x=0 y=3 w=20 h=37
3079 [1,1] x=20 y=3 w=100 h=37
3080 area(header) x=0 y=0 w=120 h=3
3081 area(sidebar) x=0 y=3 w=20 h=37
3082 area(content) x=20 y=3 w=100 h=37
3083"
3084 );
3085 }
3086
3087 #[test]
3088 fn snapshot_grid_dashboard_120x40() {
3089 let snap = snapshot_grid(
3090 &[
3091 Constraint::Fixed(3),
3092 Constraint::Percentage(60.0),
3093 Constraint::Fill,
3094 ],
3095 &[Constraint::Percentage(30.0), Constraint::Fill],
3096 &[
3097 ("nav", GridArea::span(0, 0, 1, 2)),
3098 ("chart", GridArea::cell(1, 0)),
3099 ("detail", GridArea::cell(1, 1)),
3100 ("log", GridArea::span(2, 0, 1, 2)),
3101 ],
3102 120,
3103 40,
3104 );
3105 assert_eq!(
3106 snap,
3107 "\
3108Grid 120x40 (3r x 2c)
3109 [0,0] x=0 y=0 w=36 h=3
3110 [0,1] x=36 y=0 w=84 h=3
3111 [1,0] x=0 y=3 w=36 h=24
3112 [1,1] x=36 y=3 w=84 h=24
3113 [2,0] x=0 y=27 w=36 h=13
3114 [2,1] x=36 y=27 w=84 h=13
3115 area(nav) x=0 y=0 w=120 h=3
3116 area(chart) x=0 y=3 w=36 h=24
3117 area(detail) x=36 y=3 w=84 h=24
3118 area(log) x=0 y=27 w=120 h=13
3119"
3120 );
3121 }
3122 }
3123}