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 workspace;
65
66#[cfg(feature = "experimental")]
67pub use cache::S3FifoLayoutCache;
68pub use cache::{CoherenceCache, CoherenceId, LayoutCache, LayoutCacheKey, LayoutCacheStats};
69pub use direction::{FlowDirection, LogicalAlignment, LogicalSides, mirror_rects_horizontal};
70pub use ftui_core::geometry::{Rect, Sides, Size};
71pub use grid::{Grid, GridArea, GridLayout};
72pub use pane::{
73 PANE_AFFORDANCE_EMPHASIS_FULL_BPS, PANE_DEFAULT_MARGIN_CELLS, PANE_DEFAULT_PADDING_CELLS,
74 PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS, PANE_DRAG_RESIZE_DEFAULT_THRESHOLD,
75 PANE_EDGE_GRIP_INSET_CELLS, PANE_MAGNETIC_FIELD_CELLS,
76 PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION, PANE_SEMANTIC_INPUT_TRACE_SCHEMA_VERSION,
77 PANE_SNAP_DEFAULT_HYSTERESIS_BPS, PANE_SNAP_DEFAULT_STEP_BPS, PANE_TREE_SCHEMA_VERSION,
78 PaneAffordanceMotion, PaneCancelReason, PaneConstraints, PaneCoordinateNormalizationError,
79 PaneCoordinateNormalizer, PaneCoordinateRoundingPolicy, PaneDockPreview, PaneDockZone,
80 PaneDragBehaviorTuning, PaneDragResizeEffect, PaneDragResizeMachine,
81 PaneDragResizeMachineError, PaneDragResizeNoopReason, PaneDragResizeState,
82 PaneDragResizeTransition, PaneEdgeResizePlan, PaneEdgeResizePlanError, PaneGroupTransformPlan,
83 PaneId, PaneIdAllocator, PaneInertialThrow, PaneInputCoordinate, PaneInteractionPolicyError,
84 PaneInteractionTimeline, PaneInteractionTimelineCheckpointDecision,
85 PaneInteractionTimelineEntry, PaneInteractionTimelineError,
86 PaneInteractionTimelineReplayDiagnostics, PaneInteractionTimelineRetentionDiagnostics,
87 PaneInvariantCode, PaneInvariantIssue, PaneInvariantReport, PaneInvariantSeverity, PaneLayout,
88 PaneLayoutIntelligenceMode, PaneLeaf, PaneModelError, PaneModifierSnapshot, PaneMotionVector,
89 PaneNodeKind, PaneNodeRecord, PaneNormalizedCoordinate, PaneOperation, PaneOperationError,
90 PaneOperationFailure, PaneOperationFamily, PaneOperationJournalEntry,
91 PaneOperationJournalResult, PaneOperationKind, PaneOperationOutcome, PanePlacement,
92 PanePointerButton, PanePointerPosition, PanePrecisionMode, PanePrecisionPolicy,
93 PanePressureSnapProfile, PaneReflowMovePlan, PaneReflowPlanError, PaneRepairAction,
94 PaneRepairError, PaneRepairFailure, PaneRepairOutcome, PaneResizeDirection, PaneResizeGrip,
95 PaneResizeTarget, PaneScaleFactor, PaneSelectionState, PaneSemanticInputEvent,
96 PaneSemanticInputEventError, PaneSemanticInputEventKind, PaneSemanticInputTrace,
97 PaneSemanticInputTraceError, PaneSemanticInputTraceMetadata,
98 PaneSemanticReplayConformanceArtifact, PaneSemanticReplayDiffArtifact,
99 PaneSemanticReplayDiffKind, PaneSemanticReplayError, PaneSemanticReplayFixture,
100 PaneSemanticReplayOutcome, PaneSnapDecision, PaneSnapReason, PaneSnapTuning, PaneSplit,
101 PaneSplitRatio, PaneTransaction, PaneTransactionOutcome, PaneTree, PaneTreeSnapshot, SplitAxis,
102};
103pub use pane_command::{
104 PaneAccessibilityPreferences, PaneAnnouncement, PaneAnnouncementCategory, PaneAnnouncer,
105 PaneCardinalDirection, PaneCommand, PaneCommandAcceleration, PaneCommandEffect,
106 PaneCommandNoopReason, PaneCommandResolution, PaneFocusContext, PaneFocusOrdinal,
107 PaneKeymapOwner, PaneKeymapPrecedence, announce_command, focus_cyclic, focus_directional,
108 focus_edge, focus_order, resolve as resolve_pane_command,
109};
110pub use pane_execution::{
111 PaneExecutionDecision, PaneExecutionEngine, PaneExecutionError, PaneExecutionPolicy,
112 PaneExecutionSample, PaneExecutionStatus, PaneHistory, PaneStrategyReason, PaneWorkloadProfile,
113};
114pub use pane_memory::{
115 PANE_MEMORY_TELEMETRY_SCHEMA_VERSION, PaneMemoryComparison, PaneMemoryDriver,
116 PaneMemoryStrategy, PaneMemoryStrategyFootprint, pane_memory_comparison,
117};
118pub use pane_monitors::{
119 PaneAssumption, PaneMonitorReport, PaneMonitorStatus, PaneMonitorThresholds,
120 PaneMonitorVerdict, monitor_fallback_frequency, monitor_latency_envelope, monitor_replay_depth,
121 monitor_retention_pressure, monitor_selector_churn,
122};
123pub use pane_persistent::{
124 PaneVersionRetention, PaneVersionStore, PaneVersioningReport, PersistentApplyError,
125 PersistentApplyStrategy, PersistentNode, VersionedPaneTree,
126};
127pub use pane_retention::{
128 PaneRetentionBudget, PaneRetentionDecision, PaneRetentionOutcome, PaneRetentionPolicy,
129 apply_to_timeline as apply_retention_to_timeline,
130 apply_to_version_store as apply_retention_to_version_store,
131};
132pub use responsive::Responsive;
133pub use responsive_layout::{ResponsiveLayout, ResponsiveSplit};
134pub use smallvec;
135use smallvec::SmallVec;
136use std::cmp::min;
137pub use visibility::Visibility;
138pub use workspace::{
139 MigrationResult, WORKSPACE_SCHEMA_VERSION, WorkspaceMetadata, WorkspaceMigrationError,
140 WorkspaceSnapshot, WorkspaceSnapshotJsonError, WorkspaceValidationError,
141 canonicalize_workspace_snapshot, decode_workspace_snapshot_json, migrate_workspace,
142 needs_migration, to_canonical_workspace_snapshot_json,
143};
144
145const LAYOUT_INLINE_CAP: usize = 8;
150
151pub type Rects = SmallVec<[Rect; LAYOUT_INLINE_CAP]>;
153
154type Sizes = SmallVec<[u16; LAYOUT_INLINE_CAP]>;
156
157type Constraints = SmallVec<[Constraint; LAYOUT_INLINE_CAP]>;
159
160#[derive(Debug, Clone, Copy, PartialEq)]
162pub enum Constraint {
163 Fixed(u16),
165 Percentage(f32),
167 Min(u16),
169 Max(u16),
171 Ratio(u32, u32),
173 Fill,
175 FitContent,
180 FitContentBounded {
185 min: u16,
187 max: u16,
189 },
190 FitMin,
194}
195
196#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
219pub struct LayoutSizeHint {
220 pub min: u16,
222 pub preferred: u16,
224 pub max: Option<u16>,
226}
227
228impl LayoutSizeHint {
229 pub const ZERO: Self = Self {
231 min: 0,
232 preferred: 0,
233 max: None,
234 };
235
236 #[inline]
238 pub const fn exact(size: u16) -> Self {
239 Self {
240 min: size,
241 preferred: size,
242 max: Some(size),
243 }
244 }
245
246 #[inline]
248 pub const fn at_least(min: u16, preferred: u16) -> Self {
249 Self {
250 min,
251 preferred,
252 max: None,
253 }
254 }
255
256 #[inline]
258 pub fn clamp(&self, value: u16) -> u16 {
259 let max = self.max.unwrap_or(u16::MAX);
260 value.min(max).max(self.min)
261 }
262}
263
264#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
266pub enum Direction {
267 #[default]
269 Vertical,
270 Horizontal,
272}
273
274#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
276pub enum Alignment {
277 #[default]
279 Start,
280 Center,
282 End,
284 SpaceAround,
286 SpaceBetween,
288}
289
290#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
303pub enum OverflowBehavior {
304 #[default]
308 Clip,
309 Visible,
312 Scroll {
316 max_content: Option<u16>,
319 },
320 Wrap,
323}
324
325#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
338pub enum Breakpoint {
339 Xs,
341 Sm,
343 Md,
345 Lg,
347 Xl,
349}
350
351impl Breakpoint {
352 pub const ALL: [Breakpoint; 5] = [
354 Breakpoint::Xs,
355 Breakpoint::Sm,
356 Breakpoint::Md,
357 Breakpoint::Lg,
358 Breakpoint::Xl,
359 ];
360
361 #[inline]
363 const fn index(self) -> u8 {
364 match self {
365 Breakpoint::Xs => 0,
366 Breakpoint::Sm => 1,
367 Breakpoint::Md => 2,
368 Breakpoint::Lg => 3,
369 Breakpoint::Xl => 4,
370 }
371 }
372
373 #[must_use]
375 pub const fn label(self) -> &'static str {
376 match self {
377 Breakpoint::Xs => "xs",
378 Breakpoint::Sm => "sm",
379 Breakpoint::Md => "md",
380 Breakpoint::Lg => "lg",
381 Breakpoint::Xl => "xl",
382 }
383 }
384}
385
386impl std::fmt::Display for Breakpoint {
387 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
388 f.write_str(self.label())
389 }
390}
391
392#[derive(Debug, Clone, Copy, PartialEq, Eq)]
397pub struct Breakpoints {
398 pub sm: u16,
400 pub md: u16,
402 pub lg: u16,
404 pub xl: u16,
406}
407
408impl Breakpoints {
409 pub const DEFAULT: Self = Self {
411 sm: 60,
412 md: 90,
413 lg: 120,
414 xl: 160,
415 };
416
417 pub const fn new(sm: u16, md: u16, lg: u16) -> Self {
421 let md = if md < sm { sm } else { md };
422 let lg = if lg < md { md } else { lg };
423 let xl = match lg.checked_add(40) {
425 Some(v) => v,
426 None => u16::MAX,
427 };
428 Self { sm, md, lg, xl }
429 }
430
431 pub const fn new_with_xl(sm: u16, md: u16, lg: u16, xl: u16) -> Self {
435 let md = if md < sm { sm } else { md };
436 let lg = if lg < md { md } else { lg };
437 let xl = if xl < lg { lg } else { xl };
438 Self { sm, md, lg, xl }
439 }
440
441 #[inline]
443 pub const fn classify_width(self, width: u16) -> Breakpoint {
444 if width >= self.xl {
445 Breakpoint::Xl
446 } else if width >= self.lg {
447 Breakpoint::Lg
448 } else if width >= self.md {
449 Breakpoint::Md
450 } else if width >= self.sm {
451 Breakpoint::Sm
452 } else {
453 Breakpoint::Xs
454 }
455 }
456
457 #[inline]
459 pub const fn classify_size(self, size: Size) -> Breakpoint {
460 self.classify_width(size.width)
461 }
462
463 #[inline]
465 pub const fn at_least(self, width: u16, min: Breakpoint) -> bool {
466 self.classify_width(width).index() >= min.index()
467 }
468
469 #[inline]
471 pub const fn between(self, width: u16, min: Breakpoint, max: Breakpoint) -> bool {
472 let idx = self.classify_width(width).index();
473 idx >= min.index() && idx <= max.index()
474 }
475
476 #[must_use]
478 pub const fn threshold(self, bp: Breakpoint) -> u16 {
479 match bp {
480 Breakpoint::Xs => 0,
481 Breakpoint::Sm => self.sm,
482 Breakpoint::Md => self.md,
483 Breakpoint::Lg => self.lg,
484 Breakpoint::Xl => self.xl,
485 }
486 }
487
488 #[must_use]
490 pub const fn thresholds(self) -> [(Breakpoint, u16); 5] {
491 [
492 (Breakpoint::Xs, 0),
493 (Breakpoint::Sm, self.sm),
494 (Breakpoint::Md, self.md),
495 (Breakpoint::Lg, self.lg),
496 (Breakpoint::Xl, self.xl),
497 ]
498 }
499}
500
501#[derive(Debug, Clone, Copy, Default)]
503pub struct Measurement {
504 pub min_width: u16,
506 pub min_height: u16,
508 pub max_width: Option<u16>,
510 pub max_height: Option<u16>,
512}
513
514impl Measurement {
515 #[must_use]
517 pub fn fixed(width: u16, height: u16) -> Self {
518 Self {
519 min_width: width,
520 min_height: height,
521 max_width: Some(width),
522 max_height: Some(height),
523 }
524 }
525
526 #[must_use]
528 pub fn flexible(min_width: u16, min_height: u16) -> Self {
529 Self {
530 min_width,
531 min_height,
532 max_width: None,
533 max_height: None,
534 }
535 }
536}
537
538#[derive(Debug, Clone, Default)]
540pub struct Flex {
541 direction: Direction,
542 constraints: Constraints,
543 margin: Sides,
544 gap: u16,
545 alignment: Alignment,
546 flow_direction: direction::FlowDirection,
547 overflow: OverflowBehavior,
548}
549
550impl Flex {
551 #[must_use]
553 pub fn vertical() -> Self {
554 Self {
555 direction: Direction::Vertical,
556 ..Default::default()
557 }
558 }
559
560 #[must_use]
562 pub fn horizontal() -> Self {
563 Self {
564 direction: Direction::Horizontal,
565 ..Default::default()
566 }
567 }
568
569 #[must_use]
571 pub fn direction(mut self, direction: Direction) -> Self {
572 self.direction = direction;
573 self
574 }
575
576 #[must_use]
578 pub fn constraints(mut self, constraints: impl IntoIterator<Item = Constraint>) -> Self {
579 self.constraints = constraints.into_iter().collect();
580 self
581 }
582
583 #[must_use]
585 pub fn margin(mut self, margin: Sides) -> Self {
586 self.margin = margin;
587 self
588 }
589
590 #[must_use]
592 pub fn gap(mut self, gap: u16) -> Self {
593 self.gap = gap;
594 self
595 }
596
597 #[must_use]
599 pub fn alignment(mut self, alignment: Alignment) -> Self {
600 self.alignment = alignment;
601 self
602 }
603
604 #[must_use]
610 pub fn flow_direction(mut self, flow: direction::FlowDirection) -> Self {
611 self.flow_direction = flow;
612 self
613 }
614
615 #[must_use]
617 pub fn overflow(mut self, overflow: OverflowBehavior) -> Self {
618 self.overflow = overflow;
619 self
620 }
621
622 #[must_use]
624 pub fn overflow_behavior(&self) -> OverflowBehavior {
625 self.overflow
626 }
627
628 #[must_use]
630 pub fn constraint_count(&self) -> usize {
631 self.constraints.len()
632 }
633
634 pub fn split(&self, area: Rect) -> Rects {
636 let inner = area.inner(self.margin);
638 if inner.is_empty() {
639 return self.constraints.iter().map(|_| Rect::default()).collect();
640 }
641
642 let total_size = match self.direction {
643 Direction::Horizontal => inner.width,
644 Direction::Vertical => inner.height,
645 };
646
647 let count = self.constraints.len();
648 if count == 0 {
649 return Rects::new();
650 }
651
652 let gap_count = count - 1;
654 let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
655 let available_size = total_size.saturating_sub(total_gap);
656
657 let sizes = solve_constraints(&self.constraints, available_size);
659
660 let mut rects = self.sizes_to_rects(inner, &sizes);
662
663 if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
665 direction::mirror_rects_horizontal(&mut rects, inner);
666 }
667
668 rects
669 }
670
671 fn sizes_to_rects(&self, area: Rect, sizes: &[u16]) -> Rects {
672 let mut rects = SmallVec::with_capacity(sizes.len());
673 if sizes.is_empty() {
674 return rects;
675 }
676
677 let total_items_size: u16 = sizes.iter().fold(0u16, |acc, &s| acc.saturating_add(s));
678 let total_available = match self.direction {
679 Direction::Horizontal => area.width,
680 Direction::Vertical => area.height,
681 };
682
683 let (start_shift, use_formula) = match self.alignment {
685 Alignment::Start => (0, None),
686 Alignment::End => {
687 let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
688 .min(u16::MAX as u64) as u16;
689 let used = total_items_size.saturating_add(gap_space);
690 (total_available.saturating_sub(used), None)
691 }
692 Alignment::Center => {
693 let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
694 .min(u16::MAX as u64) as u16;
695 let used = total_items_size.saturating_add(gap_space);
696 (total_available.saturating_sub(used) / 2, None)
697 }
698 Alignment::SpaceBetween => {
699 let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
700 .min(u16::MAX as u64) as u16;
701 let used = total_items_size.saturating_add(gap_space);
702 let leftover = total_available.saturating_sub(used);
703 let slots = sizes.len().saturating_sub(1);
704 if slots > 0 {
705 (0, Some((leftover, slots, 0))) } else {
707 (0, None)
708 }
709 }
710 Alignment::SpaceAround => {
711 let gap_space = (sizes.len().saturating_sub(1) as u64 * self.gap as u64)
712 .min(u16::MAX as u64) as u16;
713 let used = total_items_size.saturating_add(gap_space);
714 let leftover = total_available.saturating_sub(used);
715 let slots = sizes.len() * 2;
716 if slots > 0 {
717 (0, Some((leftover, slots, 1))) } else {
719 (0, None)
720 }
721 }
722 };
723
724 let mut accumulated_size = 0;
725
726 for (i, &size) in sizes.iter().enumerate() {
727 let explicit_gap_so_far = if i > 0 {
728 (i as u64 * self.gap as u64).min(u16::MAX as u64) as u16
729 } else {
730 0
731 };
732
733 let gap_offset = if let Some((leftover, slots, mode)) = use_formula {
734 if mode == 0 {
735 if i == 0 {
737 0
738 } else {
739 explicit_gap_so_far
740 .saturating_add((leftover as u64 * i as u64 / slots as u64) as u16)
741 }
742 } else {
743 let numerator = leftover as u64 * (2 * i as u64 + 1);
745 let denominator = slots as u64;
746 let raw = (numerator + (denominator / 2)) / denominator;
747 explicit_gap_so_far.saturating_add(raw.min(u64::from(u16::MAX)) as u16)
748 }
749 } else {
750 explicit_gap_so_far
752 };
753
754 let pos = match self.direction {
755 Direction::Horizontal => area
756 .x
757 .saturating_add(start_shift)
758 .saturating_add(accumulated_size)
759 .saturating_add(gap_offset),
760 Direction::Vertical => area
761 .y
762 .saturating_add(start_shift)
763 .saturating_add(accumulated_size)
764 .saturating_add(gap_offset),
765 };
766
767 let rect = match self.direction {
768 Direction::Horizontal => Rect {
769 x: pos,
770 y: area.y,
771 width: size.min(area.right().saturating_sub(pos)),
772 height: area.height,
773 },
774 Direction::Vertical => Rect {
775 x: area.x,
776 y: pos,
777 width: area.width,
778 height: size.min(area.bottom().saturating_sub(pos)),
779 },
780 };
781 rects.push(rect);
782 accumulated_size = accumulated_size.saturating_add(size);
783 }
784
785 rects
786 }
787
788 pub fn split_with_measurer<F>(&self, area: Rect, measurer: F) -> Rects
812 where
813 F: Fn(usize, u16) -> LayoutSizeHint,
814 {
815 let inner = area.inner(self.margin);
817 if inner.is_empty() {
818 return self.constraints.iter().map(|_| Rect::default()).collect();
819 }
820
821 let total_size = match self.direction {
822 Direction::Horizontal => inner.width,
823 Direction::Vertical => inner.height,
824 };
825
826 let count = self.constraints.len();
827 if count == 0 {
828 return Rects::new();
829 }
830
831 let gap_count = count - 1;
833 let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
834 let available_size = total_size.saturating_sub(total_gap);
835
836 let sizes =
838 solve_constraints_with_hints(&self.constraints, available_size, &measurer, None);
839
840 let mut rects = self.sizes_to_rects(inner, &sizes);
842
843 if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
845 direction::mirror_rects_horizontal(&mut rects, inner);
846 }
847
848 rects
849 }
850 pub fn split_with_measurer_stably<F>(
855 &self,
856 area: Rect,
857 measurer: F,
858 cache: &mut CoherenceCache,
859 ) -> Rects
860 where
861 F: Fn(usize, u16) -> LayoutSizeHint,
862 {
863 let inner = area.inner(self.margin);
865 if inner.is_empty() {
866 return self.constraints.iter().map(|_| Rect::default()).collect();
867 }
868
869 let total_size = match self.direction {
870 Direction::Horizontal => inner.width,
871 Direction::Vertical => inner.height,
872 };
873
874 let count = self.constraints.len();
875 if count == 0 {
876 return Rects::new();
877 }
878
879 let gap_count = count - 1;
881 let total_gap = (gap_count as u64 * self.gap as u64).min(u16::MAX as u64) as u16;
882 let available_size = total_size.saturating_sub(total_gap);
883
884 let id = CoherenceId::new(&self.constraints, self.direction);
886 let sizes = solve_constraints_with_hints(
887 &self.constraints,
888 available_size,
889 &measurer,
890 Some((cache, id)),
891 );
892
893 let mut rects = self.sizes_to_rects(inner, &sizes);
895
896 if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
898 direction::mirror_rects_horizontal(&mut rects, inner);
899 }
900
901 rects
902 }
903}
904
905pub(crate) fn solve_constraints(constraints: &[Constraint], available_size: u16) -> Sizes {
910 solve_constraints_with_hints(
912 constraints,
913 available_size,
914 &|_, _| LayoutSizeHint::ZERO,
915 None,
916 )
917}
918
919pub(crate) fn solve_constraints_with_hints<F>(
924 constraints: &[Constraint],
925 available_size: u16,
926 measurer: &F,
927 mut coherence: Option<(&mut CoherenceCache, CoherenceId)>,
928) -> Sizes
929where
930 F: Fn(usize, u16) -> LayoutSizeHint,
931{
932 const WEIGHT_SCALE: u64 = 10_000;
933
934 let mut sizes: Sizes = smallvec::smallvec![0u16; constraints.len()];
935 let mut remaining = available_size;
936 let mut grow_indices: SmallVec<[usize; LAYOUT_INLINE_CAP]> = SmallVec::new();
937
938 let grow_weight = |constraint: Constraint| -> u64 {
939 match constraint {
940 Constraint::Min(_) | Constraint::Max(_) | Constraint::Fill => WEIGHT_SCALE,
941 _ => 0,
942 }
943 };
944
945 for (i, &constraint) in constraints.iter().enumerate() {
948 match constraint {
949 Constraint::Fixed(size) => {
950 let size = min(size, remaining);
951 sizes[i] = size;
952 remaining = remaining.saturating_sub(size);
953 }
954 Constraint::Min(min_size) => {
955 let size = min(min_size, remaining);
956 sizes[i] = size;
957 remaining = remaining.saturating_sub(size);
958 }
960 Constraint::FitMin => {
961 let hint = measurer(i, remaining);
962 let size = min(hint.min, remaining);
963 sizes[i] = size;
964 remaining = remaining.saturating_sub(size);
965 }
966 Constraint::FitContent => {
967 let hint = measurer(i, remaining);
968 let size = min(hint.min, remaining);
969 sizes[i] = size;
970 remaining = remaining.saturating_sub(size);
971 }
972 Constraint::FitContentBounded { min: min_bound, .. } => {
973 let size = min(min_bound, remaining);
975 sizes[i] = size;
976 remaining = remaining.saturating_sub(size);
977 }
978 _ => {} }
980 }
981
982 for (i, &constraint) in constraints.iter().enumerate() {
985 match constraint {
986 Constraint::Percentage(p) => {
987 let target = (available_size as f32 * p / 100.0)
988 .round()
989 .min(u16::MAX as f32) as u16;
990 let needed = target.saturating_sub(sizes[i]);
991 let alloc = min(needed, remaining);
992 sizes[i] = sizes[i].saturating_add(alloc);
993 remaining = remaining.saturating_sub(alloc);
994 }
995 Constraint::Ratio(n, d) => {
996 let target = if d == 0 {
997 0
998 } else {
999 (u64::from(available_size) * u64::from(n) / u64::from(d)).min(u16::MAX as u64)
1000 as u16
1001 };
1002 let needed = target.saturating_sub(sizes[i]);
1003 let alloc = min(needed, remaining);
1004 sizes[i] = sizes[i].saturating_add(alloc);
1005 remaining = remaining.saturating_sub(alloc);
1006 }
1007 Constraint::FitContent => {
1008 let hint = measurer(i, remaining);
1009 let preferred = hint
1010 .preferred
1011 .max(sizes[i])
1012 .min(hint.max.unwrap_or(u16::MAX));
1013 let needed = preferred.saturating_sub(sizes[i]);
1014 let alloc = min(needed, remaining);
1015 sizes[i] = sizes[i].saturating_add(alloc);
1016 remaining = remaining.saturating_sub(alloc);
1017 }
1018 Constraint::FitContentBounded { max: max_bound, .. } => {
1019 let hint = measurer(i, remaining);
1020 let preferred = hint.preferred.max(sizes[i]).min(max_bound);
1021 let needed = preferred.saturating_sub(sizes[i]);
1022 let alloc = min(needed, remaining);
1023 sizes[i] = sizes[i].saturating_add(alloc);
1024 remaining = remaining.saturating_sub(alloc);
1025 }
1026 Constraint::Min(_) => {
1027 grow_indices.push(i);
1028 }
1029 Constraint::Max(_) => {
1030 grow_indices.push(i);
1031 }
1032 Constraint::Fill => {
1033 grow_indices.push(i);
1034 }
1035 _ => {} }
1037 }
1038
1039 loop {
1041 if remaining == 0 || grow_indices.is_empty() {
1042 break;
1043 }
1044
1045 let mut total_weight = 0u128;
1046 for &i in &grow_indices {
1047 let weight = grow_weight(constraints[i]);
1048 if weight > 0 {
1049 total_weight = total_weight.saturating_add(u128::from(weight));
1050 }
1051 }
1052
1053 if total_weight == 0 {
1054 break;
1055 }
1056
1057 let space_to_distribute = remaining;
1058 let mut shares: SmallVec<[u16; LAYOUT_INLINE_CAP]> =
1059 smallvec::smallvec![0u16; constraints.len()];
1060
1061 let targets: Vec<f64> = grow_indices
1063 .iter()
1064 .map(|&i| {
1065 let weight = grow_weight(constraints[i]);
1066 (space_to_distribute as f64 * weight as f64) / total_weight as f64
1067 })
1068 .collect();
1069
1070 let prev_alloc = coherence
1072 .as_ref()
1073 .and_then(|(cache, id)| cache.get(id))
1074 .map(|full_prev| {
1075 grow_indices
1077 .iter()
1078 .map(|&i| full_prev.get(i).copied().unwrap_or(0))
1079 .collect()
1080 });
1081
1082 let distributed = round_layout_stable(&targets, space_to_distribute, prev_alloc);
1084
1085 for (k, &i) in grow_indices.iter().enumerate() {
1086 shares[i] = distributed[k];
1087 }
1088
1089 let mut violations = Vec::new();
1091 for &i in &grow_indices {
1092 if let Constraint::Max(max_val) = constraints[i]
1093 && sizes[i].saturating_add(shares[i]) > max_val
1094 {
1095 violations.push(i);
1096 }
1097 }
1098
1099 if violations.is_empty() {
1100 for &i in &grow_indices {
1102 sizes[i] = sizes[i].saturating_add(shares[i]);
1103 }
1104 if let Some((cache, id)) = coherence.as_mut() {
1105 if distributed.len() == targets.len() {
1108 let mut full_shares: Sizes = smallvec::smallvec![0u16; constraints.len()];
1109 for (k, &i) in grow_indices.iter().enumerate() {
1110 full_shares[i] = distributed[k];
1111 }
1112 cache.store(*id, full_shares);
1113 }
1114 }
1115 break;
1116 }
1117
1118 for i in violations {
1120 if let Constraint::Max(max_val) = constraints[i] {
1121 let consumed = max_val.saturating_sub(sizes[i]);
1124 sizes[i] = max_val;
1125 remaining = remaining.saturating_sub(consumed);
1126
1127 if let Some(pos) = grow_indices.iter().position(|&x| x == i) {
1129 grow_indices.remove(pos);
1130 }
1131 }
1132 }
1133 }
1134
1135 sizes
1136}
1137
1138pub type PreviousAllocation = Option<Sizes>;
1148
1149pub fn round_layout_stable(targets: &[f64], total: u16, prev: PreviousAllocation) -> Sizes {
1211 let n = targets.len();
1212 if n == 0 {
1213 return Sizes::new();
1214 }
1215
1216 let floors: Sizes = targets
1218 .iter()
1219 .map(|&r| (r.max(0.0).floor() as u64).min(u16::MAX as u64) as u16)
1220 .collect();
1221
1222 let floor_sum: u64 = floors.iter().map(|&x| u64::from(x)).sum();
1223 let total_u64 = u64::from(total);
1224
1225 if floor_sum > total_u64 {
1227 return redistribute_overflow(&floors, total);
1228 }
1229
1230 let deficit = (total_u64 - floor_sum) as u16;
1231
1232 if deficit == 0 {
1233 return floors;
1235 }
1236
1237 let mut priority: SmallVec<[(usize, f64, bool); LAYOUT_INLINE_CAP]> = targets
1239 .iter()
1240 .enumerate()
1241 .map(|(i, &r)| {
1242 let raw_remainder = r - (floors[i] as f64);
1245 let remainder = if raw_remainder.is_finite() {
1246 raw_remainder
1247 } else {
1248 0.0
1249 };
1250 let ceil_val = floors[i].saturating_add(1);
1251 let prev_used_ceil = prev
1253 .as_ref()
1254 .is_some_and(|p| p.get(i).copied() == Some(ceil_val));
1255 (i, remainder, prev_used_ceil)
1256 })
1257 .collect();
1258
1259 priority.sort_by(|a, b| {
1265 b.1.total_cmp(&a.1)
1266 .then_with(|| {
1267 b.2.cmp(&a.2)
1269 })
1270 .then_with(|| {
1271 a.0.cmp(&b.0)
1273 })
1274 });
1275
1276 let mut result = floors;
1278 let mut remaining_deficit = deficit;
1279
1280 if remaining_deficit as usize >= n {
1286 let per_item = remaining_deficit / (n as u16);
1287 for val in result.iter_mut() {
1288 *val = val.saturating_add(per_item);
1289 }
1290 remaining_deficit %= n as u16;
1291 }
1292
1293 if remaining_deficit > 0 {
1294 for &(i, _, _) in priority.iter().take(remaining_deficit as usize) {
1295 result[i] = result[i].saturating_add(1);
1296 }
1297 }
1298
1299 result
1300}
1301
1302fn redistribute_overflow(floors: &[u16], total: u16) -> Sizes {
1307 let mut result: Sizes = floors.iter().copied().collect();
1308 let current_sum: u64 = result.iter().map(|&x| u64::from(x)).sum();
1309 let total_u64 = u64::from(total);
1310 let n = result.len();
1311
1312 if current_sum <= total_u64 || n == 0 {
1313 return result;
1314 }
1315
1316 let mut overflow = current_sum - total_u64;
1317
1318 while overflow > 0 {
1319 let &max_val = result.iter().max().unwrap_or(&0);
1320 if max_val == 0 {
1321 for val in result.iter_mut() {
1325 *val = 0;
1326 }
1327 break;
1328 }
1329
1330 let count_max = result.iter().filter(|&&v| v == max_val).count() as u64;
1331 let &next_max = result.iter().filter(|&&v| v < max_val).max().unwrap_or(&0);
1332
1333 let delta = (max_val - next_max) as u64;
1334 let required_per_item = overflow.div_ceil(count_max);
1335 let reduce_per_item = delta.min(required_per_item).max(1) as u16;
1336
1337 let mut reduced_any = false;
1338 for val in result.iter_mut() {
1339 if *val == max_val {
1340 let amount = u64::from(*val)
1341 .min(u64::from(reduce_per_item))
1342 .min(overflow) as u16;
1343 if amount > 0 {
1344 *val -= amount;
1345 overflow -= u64::from(amount);
1346 reduced_any = true;
1347 }
1348 if overflow == 0 {
1349 break;
1350 }
1351 }
1352 }
1353
1354 if !reduced_any {
1355 for val in result.iter_mut() {
1357 if overflow == 0 {
1358 break;
1359 }
1360 if *val > 0 {
1361 *val -= 1;
1362 overflow -= 1;
1363 }
1364 }
1365 break;
1366 }
1367 }
1368
1369 result
1370}
1371
1372#[cfg(test)]
1373mod tests {
1374 use super::*;
1375
1376 #[test]
1377 fn round_layout_stable_nan_targets_do_not_panic_the_sort() {
1378 let mut targets: Vec<f64> = (0..64).map(|i| (i as f64) * 0.37 + 0.1).collect();
1383 targets[7] = f64::NAN;
1384 targets[23] = f64::INFINITY;
1385 targets[41] = f64::NEG_INFINITY;
1386
1387 let sizes = round_layout_stable(&targets, 120, None);
1390 assert_eq!(sizes.len(), 64);
1391
1392 let nan_targets = [f64::NAN; 8];
1395 let sizes = round_layout_stable(&nan_targets, 40, None);
1396 let sum: u64 = sizes.iter().map(|&x| u64::from(x)).sum();
1397 assert_eq!(sum, 40);
1398 }
1399
1400 #[test]
1401 fn fixed_split() {
1402 let flex = Flex::horizontal().constraints([Constraint::Fixed(10), Constraint::Fixed(20)]);
1403 let rects = flex.split(Rect::new(0, 0, 100, 10));
1404 assert_eq!(rects.len(), 2);
1405 assert_eq!(rects[0], Rect::new(0, 0, 10, 10));
1406 assert_eq!(rects[1], Rect::new(10, 0, 20, 10)); }
1408
1409 #[test]
1410 fn percentage_split() {
1411 let flex = Flex::horizontal()
1412 .constraints([Constraint::Percentage(50.0), Constraint::Percentage(50.0)]);
1413 let rects = flex.split(Rect::new(0, 0, 100, 10));
1414 assert_eq!(rects[0].width, 50);
1415 assert_eq!(rects[1].width, 50);
1416 }
1417
1418 #[test]
1419 fn gap_handling() {
1420 let flex = Flex::horizontal()
1421 .gap(5)
1422 .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1423 let rects = flex.split(Rect::new(0, 0, 100, 10));
1424 assert_eq!(rects[0], Rect::new(0, 0, 10, 10));
1428 assert_eq!(rects[1], Rect::new(15, 0, 10, 10));
1429 }
1430
1431 #[test]
1432 fn mixed_constraints() {
1433 let flex = Flex::horizontal().constraints([
1434 Constraint::Fixed(10),
1435 Constraint::Min(10), Constraint::Percentage(10.0), ]);
1438
1439 let rects = flex.split(Rect::new(0, 0, 100, 1));
1447 assert_eq!(rects[0].width, 10); assert_eq!(rects[2].width, 10); assert_eq!(rects[1].width, 80); }
1451
1452 #[test]
1453 fn measurement_fixed_constraints() {
1454 let fixed = Measurement::fixed(5, 7);
1455 assert_eq!(fixed.min_width, 5);
1456 assert_eq!(fixed.min_height, 7);
1457 assert_eq!(fixed.max_width, Some(5));
1458 assert_eq!(fixed.max_height, Some(7));
1459 }
1460
1461 #[test]
1462 fn measurement_flexible_constraints() {
1463 let flexible = Measurement::flexible(2, 3);
1464 assert_eq!(flexible.min_width, 2);
1465 assert_eq!(flexible.min_height, 3);
1466 assert_eq!(flexible.max_width, None);
1467 assert_eq!(flexible.max_height, None);
1468 }
1469
1470 #[test]
1471 fn breakpoints_classify_defaults() {
1472 let bp = Breakpoints::DEFAULT;
1473 assert_eq!(bp.classify_width(20), Breakpoint::Xs);
1474 assert_eq!(bp.classify_width(60), Breakpoint::Sm);
1475 assert_eq!(bp.classify_width(90), Breakpoint::Md);
1476 assert_eq!(bp.classify_width(120), Breakpoint::Lg);
1477 }
1478
1479 #[test]
1480 fn breakpoints_at_least_and_between() {
1481 let bp = Breakpoints::new(50, 80, 110);
1482 assert!(bp.at_least(85, Breakpoint::Sm));
1483 assert!(bp.between(85, Breakpoint::Sm, Breakpoint::Md));
1484 assert!(!bp.between(85, Breakpoint::Lg, Breakpoint::Lg));
1485 }
1486
1487 #[test]
1488 fn alignment_end() {
1489 let flex = Flex::horizontal()
1490 .alignment(Alignment::End)
1491 .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1492 let rects = flex.split(Rect::new(0, 0, 100, 10));
1493 assert_eq!(rects[0], Rect::new(80, 0, 10, 10));
1495 assert_eq!(rects[1], Rect::new(90, 0, 10, 10));
1496 }
1497
1498 #[test]
1499 fn alignment_center() {
1500 let flex = Flex::horizontal()
1501 .alignment(Alignment::Center)
1502 .constraints([Constraint::Fixed(20), Constraint::Fixed(20)]);
1503 let rects = flex.split(Rect::new(0, 0, 100, 10));
1504 assert_eq!(rects[0], Rect::new(30, 0, 20, 10));
1506 assert_eq!(rects[1], Rect::new(50, 0, 20, 10));
1507 }
1508
1509 #[test]
1510 fn alignment_space_between() {
1511 let flex = Flex::horizontal()
1512 .alignment(Alignment::SpaceBetween)
1513 .constraints([
1514 Constraint::Fixed(10),
1515 Constraint::Fixed(10),
1516 Constraint::Fixed(10),
1517 ]);
1518 let rects = flex.split(Rect::new(0, 0, 100, 10));
1519 assert_eq!(rects[0].x, 0);
1521 assert_eq!(rects[1].x, 45); assert_eq!(rects[2].x, 90); }
1524
1525 #[test]
1526 fn vertical_alignment() {
1527 let flex = Flex::vertical()
1528 .alignment(Alignment::End)
1529 .constraints([Constraint::Fixed(5), Constraint::Fixed(5)]);
1530 let rects = flex.split(Rect::new(0, 0, 10, 100));
1531 assert_eq!(rects[0], Rect::new(0, 90, 10, 5));
1533 assert_eq!(rects[1], Rect::new(0, 95, 10, 5));
1534 }
1535
1536 #[test]
1537 fn nested_flex_support() {
1538 let outer = Flex::horizontal()
1540 .constraints([Constraint::Percentage(50.0), Constraint::Percentage(50.0)]);
1541 let outer_rects = outer.split(Rect::new(0, 0, 100, 100));
1542
1543 let inner = Flex::vertical().constraints([Constraint::Fixed(30), Constraint::Min(10)]);
1545 let inner_rects = inner.split(outer_rects[0]);
1546
1547 assert_eq!(inner_rects[0], Rect::new(0, 0, 50, 30));
1548 assert_eq!(inner_rects[1], Rect::new(0, 30, 50, 70));
1549 }
1550
1551 #[test]
1553 fn invariant_total_size_does_not_exceed_available() {
1554 for total in [10u16, 50, 100, 255] {
1556 let flex = Flex::horizontal().constraints([
1557 Constraint::Fixed(30),
1558 Constraint::Percentage(50.0),
1559 Constraint::Min(20),
1560 ]);
1561 let rects = flex.split(Rect::new(0, 0, total, 10));
1562 let total_width: u16 = rects.iter().map(|r| r.width).sum();
1563 assert!(
1564 total_width <= total,
1565 "Total width {} exceeded available {} for constraints",
1566 total_width,
1567 total
1568 );
1569 }
1570 }
1571
1572 #[test]
1573 fn invariant_empty_area_produces_empty_rects() {
1574 let flex = Flex::horizontal().constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1575 let rects = flex.split(Rect::new(0, 0, 0, 0));
1576 assert!(rects.iter().all(|r| r.is_empty()));
1577 }
1578
1579 #[test]
1580 fn invariant_no_constraints_produces_empty_vec() {
1581 let flex = Flex::horizontal().constraints([]);
1582 let rects = flex.split(Rect::new(0, 0, 100, 100));
1583 assert!(rects.is_empty());
1584 }
1585
1586 #[test]
1587 fn flex_constraints_stay_inline_for_common_layouts() {
1588 let flex = Flex::horizontal().constraints([Constraint::Fixed(1); LAYOUT_INLINE_CAP]);
1589 assert_eq!(flex.constraint_count(), LAYOUT_INLINE_CAP);
1590 assert!(!flex.constraints.spilled());
1591
1592 let rects = flex.split(Rect::new(0, 0, LAYOUT_INLINE_CAP as u16, 1));
1593 assert_eq!(rects.len(), LAYOUT_INLINE_CAP);
1594 assert!(rects.iter().all(|rect| rect.width == 1));
1595 }
1596
1597 #[test]
1600 fn ratio_constraint_splits_proportionally() {
1601 let flex =
1602 Flex::horizontal().constraints([Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)]);
1603 let rects = flex.split(Rect::new(0, 0, 90, 10));
1604 assert_eq!(rects[0].width, 30);
1605 assert_eq!(rects[1].width, 60);
1606 }
1607
1608 #[test]
1609 fn ratio_constraint_with_zero_denominator() {
1610 let flex = Flex::horizontal().constraints([Constraint::Ratio(1, 0)]);
1612 let rects = flex.split(Rect::new(0, 0, 100, 10));
1613 assert_eq!(rects.len(), 1);
1614 }
1615
1616 #[test]
1617 fn ratio_is_absolute_fraction() {
1618 let area = Rect::new(0, 0, 100, 1);
1619
1620 let rects = Flex::horizontal()
1622 .constraints([Constraint::Percentage(25.0)])
1623 .split(area);
1624 assert_eq!(rects[0].width, 25);
1625
1626 let rects = Flex::horizontal()
1629 .constraints([Constraint::Ratio(1, 4)])
1630 .split(area);
1631 assert_eq!(rects[0].width, 25);
1632 }
1633
1634 #[test]
1635 fn ratio_is_independent_of_grow_items() {
1636 let area = Rect::new(0, 0, 100, 1);
1637
1638 let rects = Flex::horizontal()
1640 .constraints([Constraint::Ratio(1, 4), Constraint::Fill])
1641 .split(area);
1642 assert_eq!(rects[0].width, 25);
1643 assert_eq!(rects[1].width, 75);
1644 }
1645
1646 #[test]
1647 fn ratio_zero_numerator_should_be_zero() {
1648 let flex = Flex::horizontal().constraints([Constraint::Fill, Constraint::Ratio(0, 1)]);
1651 let rects = flex.split(Rect::new(0, 0, 100, 1));
1652
1653 assert_eq!(rects[0].width, 100, "Fill should take all space");
1655 assert_eq!(rects[1].width, 0, "Ratio(0, 1) should be width 0");
1656 }
1657
1658 #[test]
1661 fn max_constraint_clamps_size() {
1662 let flex = Flex::horizontal().constraints([Constraint::Max(20), Constraint::Fixed(30)]);
1663 let rects = flex.split(Rect::new(0, 0, 100, 10));
1664 assert!(rects[0].width <= 20);
1665 assert_eq!(rects[1].width, 30);
1666 }
1667
1668 #[test]
1669 fn percentage_rounding_never_exceeds_available() {
1670 let constraints = [
1671 Constraint::Percentage(33.4),
1672 Constraint::Percentage(33.3),
1673 Constraint::Percentage(33.3),
1674 ];
1675 let sizes = solve_constraints(&constraints, 7);
1676 let total: u16 = sizes.iter().sum();
1677 assert!(total <= 7, "percent rounding overflowed: {sizes:?}");
1678 assert!(sizes.iter().all(|size| *size <= 7));
1679 }
1680
1681 #[test]
1682 fn tiny_area_saturates_fixed_and_min() {
1683 let constraints = [Constraint::Fixed(5), Constraint::Min(3), Constraint::Max(2)];
1684 let sizes = solve_constraints(&constraints, 2);
1685 assert_eq!(sizes[0], 2);
1686 assert_eq!(sizes[1], 0);
1687 assert_eq!(sizes[2], 0);
1688 assert_eq!(sizes.iter().sum::<u16>(), 2);
1689 }
1690
1691 #[test]
1692 fn ratio_distribution_sums_to_available() {
1693 let constraints = [Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)];
1695 let sizes = solve_constraints(&constraints, 5);
1696 assert_eq!(sizes.iter().sum::<u16>(), 4);
1697 assert_eq!(sizes[0], 1);
1698 assert_eq!(sizes[1], 3);
1699 }
1700
1701 #[test]
1702 fn flex_gap_exceeds_area_yields_zero_widths() {
1703 let flex = Flex::horizontal()
1704 .gap(5)
1705 .constraints([Constraint::Fixed(1), Constraint::Fixed(1)]);
1706 let rects = flex.split(Rect::new(0, 0, 3, 1));
1707 assert_eq!(rects.len(), 2);
1708 assert_eq!(rects[0].width, 0);
1709 assert_eq!(rects[1].width, 0);
1710 }
1711
1712 #[test]
1715 fn alignment_space_around() {
1716 let flex = Flex::horizontal()
1717 .alignment(Alignment::SpaceAround)
1718 .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1719 let rects = flex.split(Rect::new(0, 0, 100, 10));
1720
1721 assert_eq!(rects[0].x, 20);
1724 assert_eq!(rects[1].x, 70);
1725 }
1726
1727 #[test]
1730 fn vertical_gap() {
1731 let flex = Flex::vertical()
1732 .gap(5)
1733 .constraints([Constraint::Fixed(10), Constraint::Fixed(10)]);
1734 let rects = flex.split(Rect::new(0, 0, 50, 100));
1735 assert_eq!(rects[0], Rect::new(0, 0, 50, 10));
1736 assert_eq!(rects[1], Rect::new(0, 15, 50, 10));
1737 }
1738
1739 #[test]
1742 fn vertical_center() {
1743 let flex = Flex::vertical()
1744 .alignment(Alignment::Center)
1745 .constraints([Constraint::Fixed(10)]);
1746 let rects = flex.split(Rect::new(0, 0, 50, 100));
1747 assert_eq!(rects[0].y, 45);
1749 assert_eq!(rects[0].height, 10);
1750 }
1751
1752 #[test]
1755 fn single_min_takes_all() {
1756 let flex = Flex::horizontal().constraints([Constraint::Min(5)]);
1757 let rects = flex.split(Rect::new(0, 0, 80, 24));
1758 assert_eq!(rects[0].width, 80);
1759 }
1760
1761 #[test]
1764 fn fixed_exceeds_available_clamped() {
1765 let flex = Flex::horizontal().constraints([Constraint::Fixed(60), Constraint::Fixed(60)]);
1766 let rects = flex.split(Rect::new(0, 0, 100, 10));
1767 assert_eq!(rects[0].width, 60);
1769 assert_eq!(rects[1].width, 40);
1770 }
1771
1772 #[test]
1775 fn percentage_overflow_clamped() {
1776 let flex = Flex::horizontal()
1777 .constraints([Constraint::Percentage(80.0), Constraint::Percentage(80.0)]);
1778 let rects = flex.split(Rect::new(0, 0, 100, 10));
1779 assert_eq!(rects[0].width, 80);
1780 assert_eq!(rects[1].width, 20); }
1782
1783 #[test]
1786 fn margin_reduces_split_area() {
1787 let flex = Flex::horizontal()
1788 .margin(Sides::all(10))
1789 .constraints([Constraint::Fixed(20), Constraint::Min(0)]);
1790 let rects = flex.split(Rect::new(0, 0, 100, 100));
1791 assert_eq!(rects[0].x, 10);
1793 assert_eq!(rects[0].y, 10);
1794 assert_eq!(rects[0].width, 20);
1795 assert_eq!(rects[0].height, 80);
1796 }
1797
1798 #[test]
1801 fn builder_methods_chain() {
1802 let flex = Flex::vertical()
1803 .direction(Direction::Horizontal)
1804 .gap(3)
1805 .margin(Sides::all(1))
1806 .alignment(Alignment::End)
1807 .constraints([Constraint::Fixed(10)]);
1808 let rects = flex.split(Rect::new(0, 0, 50, 50));
1809 assert_eq!(rects.len(), 1);
1810 }
1811
1812 #[test]
1815 fn space_between_single_item() {
1816 let flex = Flex::horizontal()
1817 .alignment(Alignment::SpaceBetween)
1818 .constraints([Constraint::Fixed(10)]);
1819 let rects = flex.split(Rect::new(0, 0, 100, 10));
1820 assert_eq!(rects[0].x, 0);
1822 assert_eq!(rects[0].width, 10);
1823 }
1824
1825 #[test]
1826 fn invariant_rects_within_bounds() {
1827 let area = Rect::new(10, 20, 80, 60);
1828 let flex = Flex::horizontal()
1829 .margin(Sides::all(5))
1830 .gap(2)
1831 .constraints([
1832 Constraint::Fixed(15),
1833 Constraint::Percentage(30.0),
1834 Constraint::Min(10),
1835 ]);
1836 let rects = flex.split(area);
1837
1838 let inner = area.inner(Sides::all(5));
1840 for rect in &rects {
1841 assert!(
1842 rect.x >= inner.x && rect.right() <= inner.right(),
1843 "Rect {:?} exceeds horizontal bounds of {:?}",
1844 rect,
1845 inner
1846 );
1847 assert!(
1848 rect.y >= inner.y && rect.bottom() <= inner.bottom(),
1849 "Rect {:?} exceeds vertical bounds of {:?}",
1850 rect,
1851 inner
1852 );
1853 }
1854 }
1855
1856 #[test]
1859 fn fill_takes_remaining_space() {
1860 let flex = Flex::horizontal().constraints([Constraint::Fixed(20), Constraint::Fill]);
1861 let rects = flex.split(Rect::new(0, 0, 100, 10));
1862 assert_eq!(rects[0].width, 20);
1863 assert_eq!(rects[1].width, 80); }
1865
1866 #[test]
1867 fn multiple_fills_share_space() {
1868 let flex = Flex::horizontal().constraints([Constraint::Fill, Constraint::Fill]);
1869 let rects = flex.split(Rect::new(0, 0, 100, 10));
1870 assert_eq!(rects[0].width, 50);
1871 assert_eq!(rects[1].width, 50);
1872 }
1873
1874 #[test]
1877 fn fit_content_uses_preferred_size() {
1878 let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
1879 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |idx, _| {
1880 if idx == 0 {
1881 LayoutSizeHint {
1882 min: 5,
1883 preferred: 30,
1884 max: None,
1885 }
1886 } else {
1887 LayoutSizeHint::ZERO
1888 }
1889 });
1890 assert_eq!(rects[0].width, 30); assert_eq!(rects[1].width, 70); }
1893
1894 #[test]
1895 fn fit_content_clamps_to_available() {
1896 let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::FitContent]);
1897 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
1898 min: 5,
1899 preferred: 80,
1900 max: None,
1901 });
1902 assert_eq!(rects[0].width, 80);
1904 assert_eq!(rects[1].width, 20);
1905 }
1906
1907 #[test]
1908 fn fit_content_without_measurer_gets_zero() {
1909 let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
1911 let rects = flex.split(Rect::new(0, 0, 100, 10));
1912 assert_eq!(rects[0].width, 0); assert_eq!(rects[1].width, 100); }
1915
1916 #[test]
1917 fn fit_content_zero_area_returns_empty_rects() {
1918 let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
1919 let rects = flex.split_with_measurer(Rect::new(0, 0, 0, 0), |_, _| LayoutSizeHint {
1920 min: 5,
1921 preferred: 10,
1922 max: None,
1923 });
1924 assert_eq!(rects.len(), 2);
1925 assert_eq!(rects[0].width, 0);
1926 assert_eq!(rects[0].height, 0);
1927 assert_eq!(rects[1].width, 0);
1928 assert_eq!(rects[1].height, 0);
1929 }
1930
1931 #[test]
1932 fn fit_content_tiny_available_clamps_to_remaining() {
1933 let flex = Flex::horizontal().constraints([Constraint::FitContent, Constraint::Fill]);
1934 let rects = flex.split_with_measurer(Rect::new(0, 0, 1, 1), |_, _| LayoutSizeHint {
1935 min: 5,
1936 preferred: 10,
1937 max: None,
1938 });
1939 assert_eq!(rects[0].width, 1);
1940 assert_eq!(rects[1].width, 0);
1941 }
1942
1943 #[test]
1946 fn fit_content_bounded_clamps_to_min() {
1947 let flex = Flex::horizontal().constraints([
1948 Constraint::FitContentBounded { min: 20, max: 50 },
1949 Constraint::Fill,
1950 ]);
1951 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
1952 min: 5,
1953 preferred: 10, max: None,
1955 });
1956 assert_eq!(rects[0].width, 20); assert_eq!(rects[1].width, 80);
1958 }
1959
1960 #[test]
1961 fn fit_content_bounded_respects_small_available() {
1962 let flex = Flex::horizontal().constraints([
1963 Constraint::FitContentBounded { min: 20, max: 50 },
1964 Constraint::Fill,
1965 ]);
1966 let rects = flex.split_with_measurer(Rect::new(0, 0, 5, 2), |_, _| LayoutSizeHint {
1967 min: 5,
1968 preferred: 10,
1969 max: None,
1970 });
1971 assert_eq!(rects[0].width, 5);
1973 assert_eq!(rects[1].width, 0);
1974 }
1975
1976 #[test]
1977 fn fit_content_bounded_clamps_to_max() {
1978 let flex = Flex::horizontal().constraints([
1979 Constraint::FitContentBounded { min: 10, max: 30 },
1980 Constraint::Fill,
1981 ]);
1982 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
1983 min: 5,
1984 preferred: 50, max: None,
1986 });
1987 assert_eq!(rects[0].width, 30); assert_eq!(rects[1].width, 70);
1989 }
1990
1991 #[test]
1992 fn fit_content_bounded_uses_preferred_when_in_range() {
1993 let flex = Flex::horizontal().constraints([
1994 Constraint::FitContentBounded { min: 10, max: 50 },
1995 Constraint::Fill,
1996 ]);
1997 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |_, _| LayoutSizeHint {
1998 min: 5,
1999 preferred: 35, max: None,
2001 });
2002 assert_eq!(rects[0].width, 35);
2003 assert_eq!(rects[1].width, 65);
2004 }
2005
2006 #[test]
2009 fn fit_min_uses_minimum_size() {
2010 let flex = Flex::horizontal().constraints([Constraint::FitMin, Constraint::Fill]);
2011 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |idx, _| {
2012 if idx == 0 {
2013 LayoutSizeHint {
2014 min: 15,
2015 preferred: 40,
2016 max: None,
2017 }
2018 } else {
2019 LayoutSizeHint::ZERO
2020 }
2021 });
2022 assert_eq!(rects[0].width, 15, "FitMin should strict size to min");
2025 assert_eq!(rects[1].width, 85, "Fill should take remaining space");
2026 }
2027
2028 #[test]
2029 fn fit_min_without_measurer_gets_zero() {
2030 let flex = Flex::horizontal().constraints([Constraint::FitMin, Constraint::Fill]);
2031 let rects = flex.split(Rect::new(0, 0, 100, 10));
2032 assert_eq!(rects[0].width, 0);
2035 assert_eq!(rects[1].width, 100);
2036 }
2037
2038 #[test]
2041 fn layout_size_hint_zero_is_default() {
2042 assert_eq!(LayoutSizeHint::default(), LayoutSizeHint::ZERO);
2043 }
2044
2045 #[test]
2046 fn layout_size_hint_exact() {
2047 let h = LayoutSizeHint::exact(25);
2048 assert_eq!(h.min, 25);
2049 assert_eq!(h.preferred, 25);
2050 assert_eq!(h.max, Some(25));
2051 }
2052
2053 #[test]
2054 fn layout_size_hint_at_least() {
2055 let h = LayoutSizeHint::at_least(10, 30);
2056 assert_eq!(h.min, 10);
2057 assert_eq!(h.preferred, 30);
2058 assert_eq!(h.max, None);
2059 }
2060
2061 #[test]
2062 fn layout_size_hint_clamp() {
2063 let h = LayoutSizeHint {
2064 min: 10,
2065 preferred: 20,
2066 max: Some(30),
2067 };
2068 assert_eq!(h.clamp(5), 10); assert_eq!(h.clamp(15), 15); assert_eq!(h.clamp(50), 30); }
2072
2073 #[test]
2074 fn layout_size_hint_clamp_unbounded() {
2075 let h = LayoutSizeHint::at_least(5, 10);
2076 assert_eq!(h.clamp(3), 5); assert_eq!(h.clamp(1000), 1000); }
2079
2080 #[test]
2081 fn layout_size_hint_clamp_min_greater_than_max() {
2082 let h = LayoutSizeHint {
2084 min: 20,
2085 preferred: 20,
2086 max: Some(10),
2087 };
2088 assert_eq!(h.clamp(5), 20); assert_eq!(h.clamp(15), 20); assert_eq!(h.clamp(25), 20); }
2092
2093 #[test]
2096 fn fit_content_with_fixed_and_fill() {
2097 let flex = Flex::horizontal().constraints([
2098 Constraint::Fixed(20),
2099 Constraint::FitContent,
2100 Constraint::Fill,
2101 ]);
2102 let rects = flex.split_with_measurer(Rect::new(0, 0, 100, 10), |idx, _| {
2103 if idx == 1 {
2104 LayoutSizeHint {
2105 min: 5,
2106 preferred: 25,
2107 max: None,
2108 }
2109 } else {
2110 LayoutSizeHint::ZERO
2111 }
2112 });
2113 assert_eq!(rects[0].width, 20); assert_eq!(rects[1].width, 25); assert_eq!(rects[2].width, 55); }
2117
2118 #[test]
2119 fn total_allocation_never_exceeds_available_with_fit_content() {
2120 for available in [10u16, 50, 100, 255] {
2121 let flex = Flex::horizontal().constraints([
2122 Constraint::FitContent,
2123 Constraint::FitContent,
2124 Constraint::Fill,
2125 ]);
2126 let rects =
2127 flex.split_with_measurer(Rect::new(0, 0, available, 10), |_, _| LayoutSizeHint {
2128 min: 10,
2129 preferred: 40,
2130 max: None,
2131 });
2132 let total: u16 = rects.iter().map(|r| r.width).sum();
2133 assert!(
2134 total <= available,
2135 "Total {} exceeded available {} with FitContent",
2136 total,
2137 available
2138 );
2139 }
2140 }
2141
2142 mod rounding_tests {
2147 use super::super::*;
2148
2149 #[test]
2152 fn rounding_conserves_sum_exact() {
2153 let result = round_layout_stable(&[10.0, 20.0, 10.0], 40, None);
2154 assert_eq!(result.iter().copied().sum::<u16>(), 40);
2155 assert_eq!(result.as_slice(), &[10u16, 20u16, 10u16]);
2156 }
2157
2158 #[test]
2159 fn rounding_conserves_sum_fractional() {
2160 let result = round_layout_stable(&[10.4, 20.6, 9.0], 40, None);
2161 assert_eq!(
2162 result.iter().copied().sum::<u16>(),
2163 40,
2164 "Sum must equal total: {:?}",
2165 result
2166 );
2167 }
2168
2169 #[test]
2170 fn rounding_conserves_sum_many_fractions() {
2171 let targets = vec![20.2, 20.2, 20.2, 20.2, 19.2];
2172 let result = round_layout_stable(&targets, 100, None);
2173 assert_eq!(
2174 result.iter().copied().sum::<u16>(),
2175 100,
2176 "Sum must be exactly 100: {:?}",
2177 result
2178 );
2179 }
2180
2181 #[test]
2182 fn rounding_conserves_sum_all_half() {
2183 let targets = vec![10.5, 10.5, 10.5, 10.5];
2184 let result = round_layout_stable(&targets, 42, None);
2185 assert_eq!(
2186 result.iter().copied().sum::<u16>(),
2187 42,
2188 "Sum must be exactly 42: {:?}",
2189 result
2190 );
2191 }
2192
2193 #[test]
2196 fn rounding_displacement_bounded() {
2197 let targets = vec![33.33, 33.33, 33.34];
2198 let result = round_layout_stable(&targets, 100, None);
2199 assert_eq!(result.iter().copied().sum::<u16>(), 100);
2200
2201 for (i, (&x, &r)) in result.iter().zip(targets.iter()).enumerate() {
2202 let floor = r.floor() as u16;
2203 let ceil = floor + 1;
2204 assert!(
2205 x == floor || x == ceil,
2206 "Element {} = {} not in {{floor={}, ceil={}}} of target {}",
2207 i,
2208 x,
2209 floor,
2210 ceil,
2211 r
2212 );
2213 }
2214 }
2215
2216 #[test]
2219 fn temporal_tiebreak_stable_when_unchanged() {
2220 let targets = vec![10.5, 10.5, 10.5, 10.5];
2221 let first = round_layout_stable(&targets, 42, None);
2222 let second = round_layout_stable(&targets, 42, Some(first.clone()));
2223 assert_eq!(
2224 first, second,
2225 "Identical targets should produce identical results"
2226 );
2227 }
2228
2229 #[test]
2230 fn temporal_tiebreak_prefers_previous_direction() {
2231 let targets = vec![10.5, 10.5];
2232 let total = 21;
2233 let first = round_layout_stable(&targets, total, None);
2234 assert_eq!(first.iter().copied().sum::<u16>(), total);
2235 let second = round_layout_stable(&targets, total, Some(first.clone()));
2236 assert_eq!(first, second, "Should maintain rounding direction");
2237 }
2238
2239 #[test]
2240 fn temporal_tiebreak_adapts_to_changed_targets() {
2241 let targets_a = vec![10.5, 10.5];
2242 let result_a = round_layout_stable(&targets_a, 21, None);
2243 let targets_b = vec![15.7, 5.3];
2244 let result_b = round_layout_stable(&targets_b, 21, Some(result_a));
2245 assert_eq!(result_b.iter().copied().sum::<u16>(), 21);
2246 assert!(result_b[0] > result_b[1], "Should follow larger target");
2247 }
2248
2249 #[test]
2252 fn property_min_displacement_brute_force_small() {
2253 let targets = vec![3.3, 3.3, 3.4];
2254 let total: u16 = 10;
2255 let result = round_layout_stable(&targets, total, None);
2256 let our_displacement: f64 = result
2257 .iter()
2258 .zip(targets.iter())
2259 .map(|(&x, &r)| (x as f64 - r).abs())
2260 .sum();
2261
2262 let mut min_displacement = f64::MAX;
2263 let floors: Vec<u16> = targets.iter().map(|&r| r.floor() as u16).collect();
2264 let ceils: Vec<u16> = targets.iter().map(|&r| r.floor() as u16 + 1).collect();
2265
2266 for a in floors[0]..=ceils[0] {
2267 for b in floors[1]..=ceils[1] {
2268 for c in floors[2]..=ceils[2] {
2269 if a + b + c == total {
2270 let disp = (a as f64 - targets[0]).abs()
2271 + (b as f64 - targets[1]).abs()
2272 + (c as f64 - targets[2]).abs();
2273 if disp < min_displacement {
2274 min_displacement = disp;
2275 }
2276 }
2277 }
2278 }
2279 }
2280
2281 assert!(
2282 (our_displacement - min_displacement).abs() < 1e-10,
2283 "Our displacement {} should match optimal {}: {:?}",
2284 our_displacement,
2285 min_displacement,
2286 result
2287 );
2288 }
2289
2290 #[test]
2293 fn rounding_deterministic() {
2294 let targets = vec![7.7, 8.3, 14.0];
2295 let a = round_layout_stable(&targets, 30, None);
2296 let b = round_layout_stable(&targets, 30, None);
2297 assert_eq!(a, b, "Same inputs must produce identical outputs");
2298 }
2299
2300 #[test]
2303 fn rounding_empty_targets() {
2304 let result = round_layout_stable(&[], 0, None);
2305 assert!(result.is_empty());
2306 }
2307
2308 #[test]
2309 fn rounding_single_element() {
2310 let result = round_layout_stable(&[10.7], 11, None);
2311 assert_eq!(result.as_slice(), &[11u16]);
2312 }
2313
2314 #[test]
2315 fn rounding_zero_total() {
2316 let result = round_layout_stable(&[5.0, 5.0], 0, None);
2317 assert_eq!(result.iter().copied().sum::<u16>(), 0);
2318 }
2319
2320 #[test]
2321 fn rounding_zero_total_with_large_overflow_reaches_zero() {
2322 let result = round_layout_stable(&[65535.0, 65535.0], 0, None);
2323 assert_eq!(result.as_slice(), &[0u16, 0u16]);
2324 assert_eq!(result.iter().copied().sum::<u16>(), 0);
2325 }
2326
2327 #[test]
2328 fn rounding_all_zeros() {
2329 let result = round_layout_stable(&[0.0, 0.0, 0.0], 0, None);
2330 assert_eq!(result.as_slice(), &[0u16, 0u16, 0u16]);
2331 }
2332
2333 #[test]
2334 fn rounding_integer_targets() {
2335 let result = round_layout_stable(&[10.0, 20.0, 30.0], 60, None);
2336 assert_eq!(result.as_slice(), &[10u16, 20u16, 30u16]);
2337 }
2338
2339 #[test]
2340 fn rounding_large_deficit() {
2341 let result = round_layout_stable(&[0.9, 0.9, 0.9], 3, None);
2342 assert_eq!(result.iter().copied().sum::<u16>(), 3);
2343 assert_eq!(result.as_slice(), &[1u16, 1u16, 1u16]);
2344 }
2345
2346 #[test]
2347 fn rounding_with_prev_different_length() {
2348 let result = round_layout_stable(
2349 &[10.5, 10.5],
2350 21,
2351 Some(smallvec::smallvec![11u16, 10u16, 5u16]),
2352 );
2353 assert_eq!(result.iter().copied().sum::<u16>(), 21);
2354 }
2355
2356 #[test]
2357 fn rounding_very_small_fractions() {
2358 let targets = vec![10.001, 20.001, 9.998];
2359 let result = round_layout_stable(&targets, 40, None);
2360 assert_eq!(result.iter().copied().sum::<u16>(), 40);
2361 }
2362
2363 #[test]
2364 fn rounding_conserves_sum_stress() {
2365 let n = 50;
2366 let targets: Vec<f64> = (0..n).map(|i| 2.0 + (i as f64 * 0.037)).collect();
2367 let total = 120u16;
2368 let result = round_layout_stable(&targets, total, None);
2369 assert_eq!(
2370 result.iter().copied().sum::<u16>(),
2371 total,
2372 "Sum must be exactly {} for {} items: {:?}",
2373 total,
2374 n,
2375 result
2376 );
2377 }
2378 }
2379
2380 mod property_constraint_tests {
2385 use super::super::*;
2386
2387 struct Lcg(u64);
2389
2390 impl Lcg {
2391 fn new(seed: u64) -> Self {
2392 Self(seed)
2393 }
2394 fn next_u32(&mut self) -> u32 {
2395 self.0 = self
2396 .0
2397 .wrapping_mul(6_364_136_223_846_793_005)
2398 .wrapping_add(1);
2399 (self.0 >> 33) as u32
2400 }
2401 fn next_u16_range(&mut self, lo: u16, hi: u16) -> u16 {
2402 if lo >= hi {
2403 return lo;
2404 }
2405 lo + (self.next_u32() % (hi - lo) as u32) as u16
2406 }
2407 fn next_f32(&mut self) -> f32 {
2408 (self.next_u32() & 0x00FF_FFFF) as f32 / 16_777_216.0
2409 }
2410 }
2411
2412 fn random_constraint(rng: &mut Lcg) -> Constraint {
2414 match rng.next_u32() % 7 {
2415 0 => Constraint::Fixed(rng.next_u16_range(1, 80)),
2416 1 => Constraint::Percentage(rng.next_f32() * 100.0),
2417 2 => Constraint::Min(rng.next_u16_range(0, 40)),
2418 3 => Constraint::Max(rng.next_u16_range(5, 120)),
2419 4 => {
2420 let n = rng.next_u32() % 5 + 1;
2421 let d = rng.next_u32() % 5 + 1;
2422 Constraint::Ratio(n, d)
2423 }
2424 5 => Constraint::Fill,
2425 _ => Constraint::FitContent,
2426 }
2427 }
2428
2429 #[test]
2430 fn property_constraints_respected_fixed() {
2431 let mut rng = Lcg::new(0xDEAD_BEEF);
2432 for _ in 0..200 {
2433 let fixed_val = rng.next_u16_range(1, 60);
2434 let avail = rng.next_u16_range(10, 200);
2435 let flex = Flex::horizontal().constraints([Constraint::Fixed(fixed_val)]);
2436 let rects = flex.split(Rect::new(0, 0, avail, 10));
2437 assert!(
2438 rects[0].width <= fixed_val.min(avail),
2439 "Fixed({}) in avail {} -> width {}",
2440 fixed_val,
2441 avail,
2442 rects[0].width
2443 );
2444 }
2445 }
2446
2447 #[test]
2448 fn property_constraints_respected_max() {
2449 let mut rng = Lcg::new(0xCAFE_BABE);
2450 for _ in 0..200 {
2451 let max_val = rng.next_u16_range(5, 80);
2452 let avail = rng.next_u16_range(10, 200);
2453 let flex =
2454 Flex::horizontal().constraints([Constraint::Max(max_val), Constraint::Fill]);
2455 let rects = flex.split(Rect::new(0, 0, avail, 10));
2456 assert!(
2457 rects[0].width <= max_val,
2458 "Max({}) in avail {} -> width {}",
2459 max_val,
2460 avail,
2461 rects[0].width
2462 );
2463 }
2464 }
2465
2466 #[test]
2467 fn property_constraints_respected_min() {
2468 let mut rng = Lcg::new(0xBAAD_F00D);
2469 for _ in 0..200 {
2470 let min_val = rng.next_u16_range(0, 40);
2471 let avail = rng.next_u16_range(min_val.max(1), 200);
2472 let flex = Flex::horizontal().constraints([Constraint::Min(min_val)]);
2473 let rects = flex.split(Rect::new(0, 0, avail, 10));
2474 assert!(
2475 rects[0].width >= min_val,
2476 "Min({}) in avail {} -> width {}",
2477 min_val,
2478 avail,
2479 rects[0].width
2480 );
2481 }
2482 }
2483
2484 #[test]
2485 fn property_constraints_respected_ratio_proportional() {
2486 let mut rng = Lcg::new(0x1234_5678);
2487 for _ in 0..200 {
2488 let n1 = rng.next_u32() % 5 + 1;
2489 let n2 = rng.next_u32() % 5 + 1;
2490 let d = n1 + n2;
2491 let avail = rng.next_u16_range(20, 200);
2492 let flex = Flex::horizontal()
2493 .constraints([Constraint::Ratio(n1, d), Constraint::Ratio(n2, d)]);
2494 let rects = flex.split(Rect::new(0, 0, avail, 10));
2495 let w1 = rects[0].width as f64;
2496 let w2 = rects[1].width as f64;
2497 let total = w1 + w2;
2498 if total > 0.0 {
2499 let expected_ratio = n1 as f64 / d as f64;
2500 let actual_ratio = w1 / total;
2501 assert!(
2502 (actual_ratio - expected_ratio).abs() < 0.15 || total < 4.0,
2503 "Ratio({},{})/({}+{}) avail={}: ~{:.2} got {:.2} (w1={}, w2={})",
2504 n1,
2505 d,
2506 n1,
2507 n2,
2508 avail,
2509 expected_ratio,
2510 actual_ratio,
2511 w1,
2512 w2
2513 );
2514 }
2515 }
2516 }
2517
2518 #[test]
2519 fn property_total_allocation_never_exceeds_available() {
2520 let mut rng = Lcg::new(0xFACE_FEED);
2521 for _ in 0..500 {
2522 let n = (rng.next_u32() % 6 + 1) as usize;
2523 let constraints: Vec<Constraint> =
2524 (0..n).map(|_| random_constraint(&mut rng)).collect();
2525 let avail = rng.next_u16_range(5, 200);
2526 let dir = if rng.next_u32().is_multiple_of(2) {
2527 Direction::Horizontal
2528 } else {
2529 Direction::Vertical
2530 };
2531 let flex = Flex::default().direction(dir).constraints(constraints);
2532 let area = Rect::new(0, 0, avail, avail);
2533 let rects = flex.split(area);
2534 let total: u16 = rects
2535 .iter()
2536 .map(|r| match dir {
2537 Direction::Horizontal => r.width,
2538 Direction::Vertical => r.height,
2539 })
2540 .sum();
2541 assert!(
2542 total <= avail,
2543 "Total {} exceeded available {} with {} constraints",
2544 total,
2545 avail,
2546 n
2547 );
2548 }
2549 }
2550
2551 #[test]
2552 fn property_no_overlap_horizontal() {
2553 let mut rng = Lcg::new(0xABCD_1234);
2554 for _ in 0..300 {
2555 let n = (rng.next_u32() % 5 + 2) as usize;
2556 let constraints: Vec<Constraint> =
2557 (0..n).map(|_| random_constraint(&mut rng)).collect();
2558 let avail = rng.next_u16_range(20, 200);
2559 let flex = Flex::horizontal().constraints(constraints);
2560 let rects = flex.split(Rect::new(0, 0, avail, 10));
2561
2562 for i in 1..rects.len() {
2563 let prev_end = rects[i - 1].x + rects[i - 1].width;
2564 assert!(
2565 rects[i].x >= prev_end,
2566 "Overlap at {}: prev ends {}, next starts {}",
2567 i,
2568 prev_end,
2569 rects[i].x
2570 );
2571 }
2572 }
2573 }
2574
2575 #[test]
2576 fn property_deterministic_across_runs() {
2577 let mut rng = Lcg::new(0x9999_8888);
2578 for _ in 0..100 {
2579 let n = (rng.next_u32() % 5 + 1) as usize;
2580 let constraints: Vec<Constraint> =
2581 (0..n).map(|_| random_constraint(&mut rng)).collect();
2582 let avail = rng.next_u16_range(10, 200);
2583 let r1 = Flex::horizontal()
2584 .constraints(constraints.clone())
2585 .split(Rect::new(0, 0, avail, 10));
2586 let r2 = Flex::horizontal()
2587 .constraints(constraints)
2588 .split(Rect::new(0, 0, avail, 10));
2589 assert_eq!(r1, r2, "Determinism violation at avail={}", avail);
2590 }
2591 }
2592 }
2593
2594 mod property_temporal_tests {
2599 use super::super::*;
2600 use crate::cache::{CoherenceCache, CoherenceId};
2601
2602 struct Lcg(u64);
2604
2605 impl Lcg {
2606 fn new(seed: u64) -> Self {
2607 Self(seed)
2608 }
2609 fn next_u32(&mut self) -> u32 {
2610 self.0 = self
2611 .0
2612 .wrapping_mul(6_364_136_223_846_793_005)
2613 .wrapping_add(1);
2614 (self.0 >> 33) as u32
2615 }
2616 }
2617
2618 #[test]
2619 fn property_temporal_stability_small_resize() {
2620 let constraints = [
2621 Constraint::Percentage(33.3),
2622 Constraint::Percentage(33.3),
2623 Constraint::Fill,
2624 ];
2625 let mut coherence = CoherenceCache::new(64);
2626 let id = CoherenceId::new(&constraints, Direction::Horizontal);
2627
2628 for total in [80u16, 100, 120] {
2629 let flex = Flex::horizontal().constraints(constraints);
2630 let rects = flex.split(Rect::new(0, 0, total, 10));
2631 let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2632
2633 let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2634 let prev = coherence.get(&id);
2635 let rounded = round_layout_stable(&targets, total, prev);
2636
2637 if let Some(old) = coherence.get(&id) {
2638 let (sum_disp, max_disp) = coherence.displacement(&id, &rounded);
2639 assert!(
2640 max_disp <= total.abs_diff(old.iter().copied().sum()) as u32 + 1,
2641 "max_disp={} too large for size change {} -> {}",
2642 max_disp,
2643 old.iter().copied().sum::<u16>(),
2644 total
2645 );
2646 let _ = sum_disp;
2647 }
2648 coherence.store(id, rounded);
2649 }
2650 }
2651
2652 #[test]
2653 fn property_temporal_stability_random_walk() {
2654 let constraints = [
2655 Constraint::Ratio(1, 3),
2656 Constraint::Ratio(1, 3),
2657 Constraint::Ratio(1, 3),
2658 ];
2659 let id = CoherenceId::new(&constraints, Direction::Horizontal);
2660 let mut coherence = CoherenceCache::new(64);
2661 let mut rng = Lcg::new(0x5555_AAAA);
2662 let mut total: u16 = 90;
2663
2664 for step in 0..200 {
2665 let prev_total = total;
2666 let delta = (rng.next_u32() % 7) as i32 - 3;
2667 total = (total as i32 + delta).clamp(10, 250) as u16;
2668
2669 let flex = Flex::horizontal().constraints(constraints);
2670 let rects = flex.split(Rect::new(0, 0, total, 10));
2671 let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2672
2673 let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2674 let prev = coherence.get(&id);
2675 let rounded = round_layout_stable(&targets, total, prev);
2676
2677 if coherence.get(&id).is_some() {
2678 let (_, max_disp) = coherence.displacement(&id, &rounded);
2679 let size_change = total.abs_diff(prev_total);
2680 assert!(
2681 max_disp <= size_change as u32 + 2,
2682 "step {}: max_disp={} exceeds size_change={} + 2",
2683 step,
2684 max_disp,
2685 size_change
2686 );
2687 }
2688 coherence.store(id, rounded);
2689 }
2690 }
2691
2692 #[test]
2693 fn property_temporal_stability_identical_frames() {
2694 let constraints = [
2695 Constraint::Fixed(20),
2696 Constraint::Fill,
2697 Constraint::Fixed(15),
2698 ];
2699 let id = CoherenceId::new(&constraints, Direction::Horizontal);
2700 let mut coherence = CoherenceCache::new(64);
2701
2702 let flex = Flex::horizontal().constraints(constraints);
2703 let rects = flex.split(Rect::new(0, 0, 100, 10));
2704 let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2705 coherence.store(id, widths.iter().copied().collect());
2706
2707 for _ in 0..10 {
2708 let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2709 let prev = coherence.get(&id);
2710 let rounded = round_layout_stable(&targets, 100, prev);
2711 let (sum_disp, _) = coherence.displacement(&id, &rounded);
2712 assert_eq!(sum_disp, 0, "Identical frames: zero displacement");
2713 coherence.store(id, rounded);
2714 }
2715 }
2716
2717 #[test]
2718 fn property_temporal_coherence_sweep() {
2719 let constraints = [
2720 Constraint::Percentage(25.0),
2721 Constraint::Percentage(50.0),
2722 Constraint::Fill,
2723 ];
2724 let id = CoherenceId::new(&constraints, Direction::Horizontal);
2725 let mut coherence = CoherenceCache::new(64);
2726 let mut total_displacement: u64 = 0;
2727
2728 for total in 60u16..=140 {
2729 let flex = Flex::horizontal().constraints(constraints);
2730 let rects = flex.split(Rect::new(0, 0, total, 10));
2731 let widths: Vec<u16> = rects.iter().map(|r| r.width).collect();
2732
2733 let targets: Vec<f64> = widths.iter().map(|&w| w as f64).collect();
2734 let prev = coherence.get(&id);
2735 let rounded = round_layout_stable(&targets, total, prev);
2736
2737 if coherence.get(&id).is_some() {
2738 let (sum_disp, _) = coherence.displacement(&id, &rounded);
2739 total_displacement += sum_disp;
2740 }
2741 coherence.store(id, rounded);
2742 }
2743
2744 assert!(
2745 total_displacement <= 80 * 3,
2746 "Total displacement {} exceeds bound for 80-step sweep",
2747 total_displacement
2748 );
2749 }
2750 }
2751
2752 mod snapshot_layout_tests {
2757 use super::super::*;
2758 use crate::grid::{Grid, GridArea};
2759
2760 fn snapshot_flex(
2761 constraints: &[Constraint],
2762 dir: Direction,
2763 width: u16,
2764 height: u16,
2765 ) -> String {
2766 let flex = Flex::default()
2767 .direction(dir)
2768 .constraints(constraints.iter().copied());
2769 let rects = flex.split(Rect::new(0, 0, width, height));
2770 let mut out = format!(
2771 "Flex {:?} {}x{} ({} constraints)\n",
2772 dir,
2773 width,
2774 height,
2775 constraints.len()
2776 );
2777 for (i, r) in rects.iter().enumerate() {
2778 out.push_str(&format!(
2779 " [{}] x={} y={} w={} h={}\n",
2780 i, r.x, r.y, r.width, r.height
2781 ));
2782 }
2783 let total: u16 = rects
2784 .iter()
2785 .map(|r| match dir {
2786 Direction::Horizontal => r.width,
2787 Direction::Vertical => r.height,
2788 })
2789 .sum();
2790 out.push_str(&format!(" total={}\n", total));
2791 out
2792 }
2793
2794 fn snapshot_grid(
2795 rows: &[Constraint],
2796 cols: &[Constraint],
2797 areas: &[(&str, GridArea)],
2798 width: u16,
2799 height: u16,
2800 ) -> String {
2801 let mut grid = Grid::new()
2802 .rows(rows.iter().copied())
2803 .columns(cols.iter().copied());
2804 for &(name, area) in areas {
2805 grid = grid.area(name, area);
2806 }
2807 let layout = grid.split(Rect::new(0, 0, width, height));
2808
2809 let mut out = format!(
2810 "Grid {}x{} ({}r x {}c)\n",
2811 width,
2812 height,
2813 rows.len(),
2814 cols.len()
2815 );
2816 for r in 0..rows.len() {
2817 for c in 0..cols.len() {
2818 let rect = layout.cell(r, c);
2819 out.push_str(&format!(
2820 " [{},{}] x={} y={} w={} h={}\n",
2821 r, c, rect.x, rect.y, rect.width, rect.height
2822 ));
2823 }
2824 }
2825 for &(name, _) in areas {
2826 if let Some(rect) = layout.area(name) {
2827 out.push_str(&format!(
2828 " area({}) x={} y={} w={} h={}\n",
2829 name, rect.x, rect.y, rect.width, rect.height
2830 ));
2831 }
2832 }
2833 out
2834 }
2835
2836 #[test]
2839 fn snapshot_flex_thirds_80x24() {
2840 let snap = snapshot_flex(
2841 &[
2842 Constraint::Ratio(1, 3),
2843 Constraint::Ratio(1, 3),
2844 Constraint::Ratio(1, 3),
2845 ],
2846 Direction::Horizontal,
2847 80,
2848 24,
2849 );
2850 assert_eq!(
2851 snap,
2852 "\
2853Flex Horizontal 80x24 (3 constraints)
2854 [0] x=0 y=0 w=26 h=24
2855 [1] x=26 y=0 w=26 h=24
2856 [2] x=52 y=0 w=26 h=24
2857 total=78
2858"
2859 );
2860 }
2861
2862 #[test]
2863 fn snapshot_flex_sidebar_content_80x24() {
2864 let snap = snapshot_flex(
2865 &[Constraint::Fixed(20), Constraint::Fill],
2866 Direction::Horizontal,
2867 80,
2868 24,
2869 );
2870 assert_eq!(
2871 snap,
2872 "\
2873Flex Horizontal 80x24 (2 constraints)
2874 [0] x=0 y=0 w=20 h=24
2875 [1] x=20 y=0 w=60 h=24
2876 total=80
2877"
2878 );
2879 }
2880
2881 #[test]
2882 fn snapshot_flex_header_body_footer_80x24() {
2883 let snap = snapshot_flex(
2884 &[Constraint::Fixed(3), Constraint::Fill, Constraint::Fixed(1)],
2885 Direction::Vertical,
2886 80,
2887 24,
2888 );
2889 assert_eq!(
2890 snap,
2891 "\
2892Flex Vertical 80x24 (3 constraints)
2893 [0] x=0 y=0 w=80 h=3
2894 [1] x=0 y=3 w=80 h=20
2895 [2] x=0 y=23 w=80 h=1
2896 total=24
2897"
2898 );
2899 }
2900
2901 #[test]
2904 fn snapshot_flex_thirds_120x40() {
2905 let snap = snapshot_flex(
2906 &[
2907 Constraint::Ratio(1, 3),
2908 Constraint::Ratio(1, 3),
2909 Constraint::Ratio(1, 3),
2910 ],
2911 Direction::Horizontal,
2912 120,
2913 40,
2914 );
2915 assert_eq!(
2916 snap,
2917 "\
2918Flex Horizontal 120x40 (3 constraints)
2919 [0] x=0 y=0 w=40 h=40
2920 [1] x=40 y=0 w=40 h=40
2921 [2] x=80 y=0 w=40 h=40
2922 total=120
2923"
2924 );
2925 }
2926
2927 #[test]
2928 fn snapshot_flex_sidebar_content_120x40() {
2929 let snap = snapshot_flex(
2930 &[Constraint::Fixed(20), Constraint::Fill],
2931 Direction::Horizontal,
2932 120,
2933 40,
2934 );
2935 assert_eq!(
2936 snap,
2937 "\
2938Flex Horizontal 120x40 (2 constraints)
2939 [0] x=0 y=0 w=20 h=40
2940 [1] x=20 y=0 w=100 h=40
2941 total=120
2942"
2943 );
2944 }
2945
2946 #[test]
2947 fn snapshot_flex_percentage_mix_120x40() {
2948 let snap = snapshot_flex(
2949 &[
2950 Constraint::Percentage(25.0),
2951 Constraint::Percentage(50.0),
2952 Constraint::Fill,
2953 ],
2954 Direction::Horizontal,
2955 120,
2956 40,
2957 );
2958 assert_eq!(
2959 snap,
2960 "\
2961Flex Horizontal 120x40 (3 constraints)
2962 [0] x=0 y=0 w=30 h=40
2963 [1] x=30 y=0 w=60 h=40
2964 [2] x=90 y=0 w=30 h=40
2965 total=120
2966"
2967 );
2968 }
2969
2970 #[test]
2973 fn snapshot_grid_2x2_80x24() {
2974 let snap = snapshot_grid(
2975 &[Constraint::Fixed(3), Constraint::Fill],
2976 &[Constraint::Fixed(20), Constraint::Fill],
2977 &[
2978 ("header", GridArea::span(0, 0, 1, 2)),
2979 ("sidebar", GridArea::span(1, 0, 1, 1)),
2980 ("content", GridArea::cell(1, 1)),
2981 ],
2982 80,
2983 24,
2984 );
2985 assert_eq!(
2986 snap,
2987 "\
2988Grid 80x24 (2r x 2c)
2989 [0,0] x=0 y=0 w=20 h=3
2990 [0,1] x=20 y=0 w=60 h=3
2991 [1,0] x=0 y=3 w=20 h=21
2992 [1,1] x=20 y=3 w=60 h=21
2993 area(header) x=0 y=0 w=80 h=3
2994 area(sidebar) x=0 y=3 w=20 h=21
2995 area(content) x=20 y=3 w=60 h=21
2996"
2997 );
2998 }
2999
3000 #[test]
3001 fn snapshot_grid_3x3_80x24() {
3002 let snap = snapshot_grid(
3003 &[Constraint::Fixed(1), Constraint::Fill, Constraint::Fixed(1)],
3004 &[
3005 Constraint::Fixed(10),
3006 Constraint::Fill,
3007 Constraint::Fixed(10),
3008 ],
3009 &[],
3010 80,
3011 24,
3012 );
3013 assert_eq!(
3014 snap,
3015 "\
3016Grid 80x24 (3r x 3c)
3017 [0,0] x=0 y=0 w=10 h=1
3018 [0,1] x=10 y=0 w=60 h=1
3019 [0,2] x=70 y=0 w=10 h=1
3020 [1,0] x=0 y=1 w=10 h=22
3021 [1,1] x=10 y=1 w=60 h=22
3022 [1,2] x=70 y=1 w=10 h=22
3023 [2,0] x=0 y=23 w=10 h=1
3024 [2,1] x=10 y=23 w=60 h=1
3025 [2,2] x=70 y=23 w=10 h=1
3026"
3027 );
3028 }
3029
3030 #[test]
3033 fn snapshot_grid_2x2_120x40() {
3034 let snap = snapshot_grid(
3035 &[Constraint::Fixed(3), Constraint::Fill],
3036 &[Constraint::Fixed(20), Constraint::Fill],
3037 &[
3038 ("header", GridArea::span(0, 0, 1, 2)),
3039 ("sidebar", GridArea::span(1, 0, 1, 1)),
3040 ("content", GridArea::cell(1, 1)),
3041 ],
3042 120,
3043 40,
3044 );
3045 assert_eq!(
3046 snap,
3047 "\
3048Grid 120x40 (2r x 2c)
3049 [0,0] x=0 y=0 w=20 h=3
3050 [0,1] x=20 y=0 w=100 h=3
3051 [1,0] x=0 y=3 w=20 h=37
3052 [1,1] x=20 y=3 w=100 h=37
3053 area(header) x=0 y=0 w=120 h=3
3054 area(sidebar) x=0 y=3 w=20 h=37
3055 area(content) x=20 y=3 w=100 h=37
3056"
3057 );
3058 }
3059
3060 #[test]
3061 fn snapshot_grid_dashboard_120x40() {
3062 let snap = snapshot_grid(
3063 &[
3064 Constraint::Fixed(3),
3065 Constraint::Percentage(60.0),
3066 Constraint::Fill,
3067 ],
3068 &[Constraint::Percentage(30.0), Constraint::Fill],
3069 &[
3070 ("nav", GridArea::span(0, 0, 1, 2)),
3071 ("chart", GridArea::cell(1, 0)),
3072 ("detail", GridArea::cell(1, 1)),
3073 ("log", GridArea::span(2, 0, 1, 2)),
3074 ],
3075 120,
3076 40,
3077 );
3078 assert_eq!(
3079 snap,
3080 "\
3081Grid 120x40 (3r x 2c)
3082 [0,0] x=0 y=0 w=36 h=3
3083 [0,1] x=36 y=0 w=84 h=3
3084 [1,0] x=0 y=3 w=36 h=24
3085 [1,1] x=36 y=3 w=84 h=24
3086 [2,0] x=0 y=27 w=36 h=13
3087 [2,1] x=36 y=27 w=84 h=13
3088 area(nav) x=0 y=0 w=120 h=3
3089 area(chart) x=0 y=3 w=36 h=24
3090 area(detail) x=36 y=3 w=84 h=24
3091 area(log) x=0 y=27 w=120 h=13
3092"
3093 );
3094 }
3095 }
3096}