Skip to main content

ftui_layout/
lib.rs

1#![forbid(unsafe_code)]
2
3//! Layout primitives and solvers.
4//!
5//! This crate provides layout components for terminal UIs:
6//!
7//! - [`Flex`] - 1D constraint-based layout (rows or columns)
8//! - [`Grid`] - 2D constraint-based layout with cell spanning
9//! - [`Constraint`] - Size constraints (Fixed, Percentage, Min, Max, Ratio, FitContent)
10//! - [`debug`] - Layout constraint debugging and introspection
11//! - [`cache`] - Layout result caching for memoization
12//!
13//! # Role in FrankenTUI
14//! `ftui-layout` is the geometry solver for widgets and screens. It converts
15//! constraints into concrete rectangles, with support for intrinsic sizing and
16//! caching to keep layout deterministic and fast.
17//!
18//! # How it fits in the system
19//! The runtime and widgets call into this crate to split a `Rect` into nested
20//! regions. Those regions are then passed to widgets or custom renderers, which
21//! ultimately draw into `ftui-render` frames.
22//!
23//! # Intrinsic Sizing
24//!
25//! The layout system supports content-aware sizing via [`LayoutSizeHint`] and
26//! [`Flex::split_with_measurer`]:
27//!
28//! ```ignore
29//! use ftui_layout::{Flex, Constraint, LayoutSizeHint};
30//!
31//! let flex = Flex::horizontal()
32//!     .constraints([Constraint::FitContent, Constraint::Fill]);
33//!
34//! let rects = flex.split_with_measurer(area, |idx, available| {
35//!     match idx {
36//!         0 => LayoutSizeHint { min: 5, preferred: 20, max: None },
37//!         _ => LayoutSizeHint::ZERO,
38//!     }
39//! });
40//! ```
41
42pub 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
147/// Inline capacity for layout result vectors.
148///
149/// Most layouts use ≤8 constraints, so inlining avoids heap allocation in the
150/// common case. The `SmallVec` spills to the heap transparently when needed.
151const LAYOUT_INLINE_CAP: usize = 8;
152
153/// Stack-inlined vector of rectangles returned by layout split operations.
154pub type Rects = SmallVec<[Rect; LAYOUT_INLINE_CAP]>;
155
156/// Stack-inlined vector of sizes returned by the constraint solver.
157type Sizes = SmallVec<[u16; LAYOUT_INLINE_CAP]>;
158
159/// Stack-inlined vector of flex constraints.
160type Constraints = SmallVec<[Constraint; LAYOUT_INLINE_CAP]>;
161
162/// A constraint on the size of a layout area.
163#[derive(Debug, Clone, Copy, PartialEq)]
164pub enum Constraint {
165    /// An exact size in cells.
166    Fixed(u16),
167    /// A percentage of the total available size (0.0 to 100.0).
168    Percentage(f32),
169    /// A minimum size in cells.
170    Min(u16),
171    /// A maximum size in cells.
172    Max(u16),
173    /// A ratio of the total available space (numerator, denominator).
174    Ratio(u32, u32),
175    /// Fill remaining space (like Min(0) but semantically clearer).
176    Fill,
177    /// Size to fit content using widget's preferred size from [`LayoutSizeHint`].
178    ///
179    /// When used with [`Flex::split_with_measurer`], the measurer callback provides
180    /// the size hints. Defaults to zero size if no measurer is provided.
181    FitContent,
182    /// Fit content but clamp to explicit bounds.
183    ///
184    /// The allocated size will be between `min` and `max`, using the widget's
185    /// preferred size when within range.
186    FitContentBounded {
187        /// Minimum allocation regardless of content size.
188        min: u16,
189        /// Maximum allocation regardless of content size.
190        max: u16,
191    },
192    /// Use widget's minimum size (shrink-to-fit).
193    ///
194    /// Allocates only the minimum space the widget requires.
195    FitMin,
196}
197
198/// Size hint returned by measurer callbacks for intrinsic sizing.
199///
200/// This is a 1D projection of a widget's size constraints along the layout axis.
201/// Use with [`Flex::split_with_measurer`] for content-aware layouts.
202///
203/// # Example
204///
205/// ```
206/// use ftui_layout::LayoutSizeHint;
207///
208/// // A label that needs 5-20 cells, ideally 15
209/// let hint = LayoutSizeHint {
210///     min: 5,
211///     preferred: 15,
212///     max: Some(20),
213/// };
214///
215/// // Clamp allocation to hint bounds
216/// assert_eq!(hint.clamp(10), 10); // Within range
217/// assert_eq!(hint.clamp(3), 5);   // Below min
218/// assert_eq!(hint.clamp(30), 20); // Above max
219/// ```
220#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
221pub struct LayoutSizeHint {
222    /// Minimum size (widget clips below this).
223    pub min: u16,
224    /// Preferred size (ideal for content).
225    pub preferred: u16,
226    /// Maximum useful size (None = unbounded).
227    pub max: Option<u16>,
228}
229
230impl LayoutSizeHint {
231    /// Zero hint (no minimum, no preferred, unbounded).
232    pub const ZERO: Self = Self {
233        min: 0,
234        preferred: 0,
235        max: None,
236    };
237
238    /// Create an exact size hint (min = preferred = max).
239    #[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    /// Create a hint with minimum and preferred size, unbounded max.
249    #[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    /// Clamp a value to this hint's bounds.
259    #[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/// The direction to layout items.
267#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
268pub enum Direction {
269    /// Top to bottom.
270    #[default]
271    Vertical,
272    /// Left to right.
273    Horizontal,
274}
275
276/// Alignment of items within the layout.
277#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
278pub enum Alignment {
279    /// Align items to the start (left/top).
280    #[default]
281    Start,
282    /// Center items within available space.
283    Center,
284    /// Align items to the end (right/bottom).
285    End,
286    /// Distribute space evenly around each item.
287    SpaceAround,
288    /// Distribute space evenly between items (no outer space).
289    SpaceBetween,
290}
291
292/// How a layout container handles content that exceeds available space.
293///
294/// This enum models the CSS `overflow` property for terminal layouts.
295/// The actual clipping or scrolling is performed by the render layer;
296/// this value acts as a declarative hint attached to [`Flex`] or [`Grid`]
297/// so that widgets and the renderer know how to treat overflow regions.
298///
299/// # Migration rationale
300///
301/// Web components routinely set `overflow: hidden`, `overflow: scroll`, etc.
302/// Without an explicit model the migration code emitter cannot faithfully
303/// translate these semantics. This enum bridges that gap.
304#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
305pub enum OverflowBehavior {
306    /// Content that exceeds the container is clipped at the boundary.
307    /// This is the safe default for terminals where drawing outside
308    /// an allocated region corrupts neighbouring widgets.
309    #[default]
310    Clip,
311    /// Content is allowed to overflow visually (useful for popovers,
312    /// tooltips, and hit-test regions that extend beyond their container).
313    Visible,
314    /// Content is clipped but a scrollbar region is reserved.
315    /// The `max_content` field, when set, tells the scrollbar how
316    /// large the virtual content area is.
317    Scroll {
318        /// Size of the virtual content area in the overflow direction.
319        /// `None` means "determine from content measurement".
320        max_content: Option<u16>,
321    },
322    /// Items that don't fit are wrapped to the next row/column.
323    /// Only meaningful for [`Flex`] containers.
324    Wrap,
325}
326
327/// Responsive breakpoint tiers for terminal widths.
328///
329/// Ordered from smallest to largest. Each variant represents a width
330/// range determined by [`Breakpoints`].
331///
332/// | Breakpoint | Default Min Width | Typical Use               |
333/// |-----------|-------------------|---------------------------|
334/// | `Xs`      | < 60 cols         | Minimal / ultra-narrow    |
335/// | `Sm`      | 60–89 cols        | Compact layouts           |
336/// | `Md`      | 90–119 cols       | Standard terminal width   |
337/// | `Lg`      | 120–159 cols      | Wide terminals            |
338/// | `Xl`      | 160+ cols         | Ultra-wide / tiled        |
339#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
340pub enum Breakpoint {
341    /// Extra small: narrowest tier.
342    Xs,
343    /// Small: compact layouts.
344    Sm,
345    /// Medium: standard terminal width.
346    Md,
347    /// Large: wide terminals.
348    Lg,
349    /// Extra large: ultra-wide or tiled layouts.
350    Xl,
351}
352
353impl Breakpoint {
354    /// All breakpoints in ascending order.
355    pub const ALL: [Breakpoint; 5] = [
356        Breakpoint::Xs,
357        Breakpoint::Sm,
358        Breakpoint::Md,
359        Breakpoint::Lg,
360        Breakpoint::Xl,
361    ];
362
363    /// Ordinal index (0–4).
364    #[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    /// Short label for display.
376    #[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/// Breakpoint thresholds for responsive layouts.
395///
396/// Each field is the minimum width (in terminal columns) for that breakpoint.
397/// Xs implicitly starts at width 0.
398#[derive(Debug, Clone, Copy, PartialEq, Eq)]
399pub struct Breakpoints {
400    /// Minimum width for Sm.
401    pub sm: u16,
402    /// Minimum width for Md.
403    pub md: u16,
404    /// Minimum width for Lg.
405    pub lg: u16,
406    /// Minimum width for Xl.
407    pub xl: u16,
408}
409
410impl Breakpoints {
411    /// Default breakpoints: 60 / 90 / 120 / 160 columns.
412    pub const DEFAULT: Self = Self {
413        sm: 60,
414        md: 90,
415        lg: 120,
416        xl: 160,
417    };
418
419    /// Create breakpoints with explicit thresholds.
420    ///
421    /// Values are sanitized to be monotonically non-decreasing.
422    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        // Default xl to lg + 40 if not specified via new_with_xl.
426        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    /// Create breakpoints with all four explicit thresholds.
434    ///
435    /// Values are sanitized to be monotonically non-decreasing.
436    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    /// Classify a width into a breakpoint bucket.
444    #[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    /// Classify a Size (uses width).
460    #[inline]
461    pub const fn classify_size(self, size: Size) -> Breakpoint {
462        self.classify_width(size.width)
463    }
464
465    /// Check if width is at least a given breakpoint.
466    #[inline]
467    pub const fn at_least(self, width: u16, min: Breakpoint) -> bool {
468        self.classify_width(width).index() >= min.index()
469    }
470
471    /// Check if width is between two breakpoints (inclusive).
472    #[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    /// Get the minimum width threshold for a given breakpoint.
479    #[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    /// Get all thresholds as `(Breakpoint, min_width)` pairs.
491    #[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/// Size negotiation hints for layout.
504#[derive(Debug, Clone, Copy, Default)]
505pub struct Measurement {
506    /// Minimum width in columns.
507    pub min_width: u16,
508    /// Minimum height in rows.
509    pub min_height: u16,
510    /// Maximum width (None = unbounded).
511    pub max_width: Option<u16>,
512    /// Maximum height (None = unbounded).
513    pub max_height: Option<u16>,
514}
515
516impl Measurement {
517    /// Create a fixed-size measurement (min == max).
518    #[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    /// Create a flexible measurement with minimum size and no maximum.
529    #[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/// A flexible layout container.
541#[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    /// Create a new vertical flex layout.
554    #[must_use]
555    pub fn vertical() -> Self {
556        Self {
557            direction: Direction::Vertical,
558            ..Default::default()
559        }
560    }
561
562    /// Create a new horizontal flex layout.
563    #[must_use]
564    pub fn horizontal() -> Self {
565        Self {
566            direction: Direction::Horizontal,
567            ..Default::default()
568        }
569    }
570
571    /// Set the layout direction.
572    #[must_use]
573    pub fn direction(mut self, direction: Direction) -> Self {
574        self.direction = direction;
575        self
576    }
577
578    /// Set the constraints.
579    #[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    /// Set the margin.
586    #[must_use]
587    pub fn margin(mut self, margin: Sides) -> Self {
588        self.margin = margin;
589        self
590    }
591
592    /// Set the gap between items.
593    #[must_use]
594    pub fn gap(mut self, gap: u16) -> Self {
595        self.gap = gap;
596        self
597    }
598
599    /// Set the alignment.
600    #[must_use]
601    pub fn alignment(mut self, alignment: Alignment) -> Self {
602        self.alignment = alignment;
603        self
604    }
605
606    /// Set the horizontal flow direction (LTR or RTL).
607    ///
608    /// When set to [`FlowDirection::Rtl`],
609    /// horizontal layouts are mirrored: the first child appears at the right
610    /// edge instead of the left. Vertical layouts are not affected.
611    #[must_use]
612    pub fn flow_direction(mut self, flow: direction::FlowDirection) -> Self {
613        self.flow_direction = flow;
614        self
615    }
616
617    /// Set the overflow behavior for this container.
618    #[must_use]
619    pub fn overflow(mut self, overflow: OverflowBehavior) -> Self {
620        self.overflow = overflow;
621        self
622    }
623
624    /// Get the current overflow behavior.
625    #[must_use]
626    pub fn overflow_behavior(&self) -> OverflowBehavior {
627        self.overflow
628    }
629
630    /// Number of constraints (and thus output rects from [`split`](Self::split)).
631    #[must_use]
632    pub fn constraint_count(&self) -> usize {
633        self.constraints.len()
634    }
635
636    /// Split the given area into smaller rectangles according to the configuration.
637    pub fn split(&self, area: Rect) -> Rects {
638        // Apply margin
639        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        // Calculate gaps safely
655        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        // Solve constraints to get sizes
660        let sizes = solve_constraints(&self.constraints, available_size);
661
662        // Convert sizes to rects
663        let mut rects = self.sizes_to_rects(inner, &sizes);
664
665        // Mirror horizontally for RTL horizontal layouts.
666        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        // Determine offsets strategy
686        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))) // 0 = Between
708                } 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))) // 1 = Around
720                } 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                    // Between: (Leftover * i) / slots + explicit gaps
738                    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                    // Around: nearest-integer rounding + explicit gaps
746                    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                // Fixed gap
753                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    /// Split area using intrinsic sizing from a measurer callback.
791    ///
792    /// This method enables content-aware layout with [`Constraint::FitContent`],
793    /// [`Constraint::FitContentBounded`], and [`Constraint::FitMin`].
794    ///
795    /// # Arguments
796    ///
797    /// - `area`: Available rectangle
798    /// - `measurer`: Callback that returns [`LayoutSizeHint`] for item at index
799    ///
800    /// # Example
801    ///
802    /// ```ignore
803    /// let flex = Flex::horizontal()
804    ///     .constraints([Constraint::FitContent, Constraint::Fill]);
805    ///
806    /// let rects = flex.split_with_measurer(area, |idx, available| {
807    ///     match idx {
808    ///         0 => LayoutSizeHint { min: 5, preferred: 20, max: None },
809    ///         _ => LayoutSizeHint::ZERO,
810    ///     }
811    /// });
812    /// ```
813    pub fn split_with_measurer<F>(&self, area: Rect, measurer: F) -> Rects
814    where
815        F: Fn(usize, u16) -> LayoutSizeHint,
816    {
817        // Apply margin
818        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        // Calculate gaps safely
834        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        // Solve constraints with hints from measurer
839        let sizes =
840            solve_constraints_with_hints(&self.constraints, available_size, &measurer, None);
841
842        // Convert sizes to rects
843        let mut rects = self.sizes_to_rects(inner, &sizes);
844
845        // Mirror horizontally for RTL horizontal layouts.
846        if self.flow_direction.is_rtl() && self.direction == Direction::Horizontal {
847            direction::mirror_rects_horizontal(&mut rects, inner);
848        }
849
850        rects
851    }
852    /// Split area using intrinsic sizing and temporal coherence.
853    ///
854    /// Combines the content-aware sizing of [`split_with_measurer`](Self::split_with_measurer)
855    /// with stability across small geometry perturbations.
856    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        // Apply margin
866        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        // Calculate gaps safely
882        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        // Solve constraints with hints and coherence
887        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        // Convert sizes to rects
896        let mut rects = self.sizes_to_rects(inner, &sizes);
897
898        // Mirror horizontally for RTL horizontal layouts.
899        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
907/// Solve 1D constraints to determine sizes.
908///
909/// This shared logic is used by both Flex and Grid layouts.
910/// For intrinsic sizing support, use [`solve_constraints_with_hints`].
911pub(crate) fn solve_constraints(constraints: &[Constraint], available_size: u16) -> Sizes {
912    // Use the with_hints version with a no-op measurer and no coherence
913    solve_constraints_with_hints(
914        constraints,
915        available_size,
916        &|_, _| LayoutSizeHint::ZERO,
917        None,
918    )
919}
920
921/// Solve 1D constraints with intrinsic sizing support.
922///
923/// The measurer callback provides size hints for FitContent, FitContentBounded, and FitMin
924/// constraints. It receives the constraint index and remaining available space.
925pub(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    // Pass 1: Allocate hard minimums (Fixed, Min, FitMin, FitContentBounded min).
948    // These constraints are non-negotiable and take precedence over relative/soft constraints.
949    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                // Min will also be added to grow_indices in Pass 2
961            }
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                // Reserve the minimum bound immediately
976                let size = min(min_bound, remaining);
977                sizes[i] = size;
978                remaining = remaining.saturating_sub(size);
979            }
980            _ => {} // Soft constraints handled in Pass 2
981        }
982    }
983
984    // Pass 2: Allocate soft/relative constraints (Percentage, Ratio, FitContent preferred).
985    // These fill remaining space after hard minimums.
986    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            _ => {} // Hard constraints handled in Pass 1
1038        }
1039    }
1040
1041    // 3. Iterative distribution to flexible constraints
1042    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        // Calculate float targets for fair distribution (Largest Remainder Method)
1064        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        // Get previous allocation if coherence is enabled
1073        let prev_alloc = coherence
1074            .as_ref()
1075            .and_then(|(cache, id)| cache.get(id))
1076            .map(|full_prev| {
1077                // Extract only the shares for the current grow_indices
1078                grow_indices
1079                    .iter()
1080                    .map(|&i| full_prev.get(i).copied().unwrap_or(0))
1081                    .collect()
1082            });
1083
1084        // Distribute space with stable rounding to minimize jitter and error
1085        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        // Check for Max constraint violations
1092        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            // No violations, commit shares and exit
1103            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                // Store full-sized vector mapping constraint index -> share.
1108                // We must inflate the dense `distributed` vector to the sparse constraint space.
1109                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        // Handle violations: clamp to Max and remove from grow pool
1121        for i in violations {
1122            if let Constraint::Max(max_val) = constraints[i] {
1123                // Calculate how much space this item *actually* consumes from remaining
1124                // which is (max - current_size)
1125                let consumed = max_val.saturating_sub(sizes[i]);
1126                sizes[i] = max_val;
1127                remaining = remaining.saturating_sub(consumed);
1128
1129                // Remove from grow indices
1130                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
1140// ---------------------------------------------------------------------------
1141// Stable Layout Rounding: Min-Displacement with Temporal Coherence
1142// ---------------------------------------------------------------------------
1143
1144/// Previous frame's allocation, used as tie-breaker for temporal stability.
1145///
1146/// Pass `None` for the first frame or when no history is available.
1147/// When provided, the rounding algorithm prefers allocations that
1148/// minimize change from the previous frame, reducing visual jitter.
1149pub type PreviousAllocation = Option<Sizes>;
1150
1151/// Round real-valued layout targets to integer cells with exact sum conservation.
1152///
1153/// # Mathematical Model
1154///
1155/// Given real-valued targets `r_i` (from the constraint solver) and a required
1156/// integer total, find integer allocations `x_i` that:
1157///
1158/// ```text
1159/// minimize   Σ_i |x_i − r_i|  +  μ · Σ_i |x_i − x_i_prev|
1160/// subject to Σ_i x_i = total
1161///            x_i ≥ 0
1162/// ```
1163///
1164/// where `x_i_prev` is the previous frame's allocation and `μ` is the temporal
1165/// stability weight (default 0.1).
1166///
1167/// # Algorithm: Largest Remainder with Temporal Tie-Breaking
1168///
1169/// This uses a variant of the Largest Remainder Method (Hamilton's method),
1170/// which provides optimal bounded displacement (|x_i − r_i| < 1 for all i):
1171///
1172/// 1. **Floor phase**: Set `x_i = floor(r_i)` for each element.
1173/// 2. **Deficit**: Compute `D = total − Σ floor(r_i)` extra cells to distribute.
1174/// 3. **Priority sort**: Rank elements by remainder `r_i − floor(r_i)` (descending).
1175///    Break ties using a composite key:
1176///    a. Prefer elements where `x_i_prev = ceil(r_i)` (temporal stability).
1177///    b. Prefer elements with smaller index (determinism).
1178/// 4. **Distribute**: Award one extra cell to each of the top `D` elements.
1179///
1180/// # Properties
1181///
1182/// 1. **Sum conservation**: `Σ x_i = total` exactly (proven by construction).
1183/// 2. **Bounded displacement**: `|x_i − r_i| < 1` for all `i` (since each x_i
1184///    is either `floor(r_i)` or `ceil(r_i)`).
1185/// 3. **Deterministic**: Same inputs → identical outputs (temporal tie-break +
1186///    index tie-break provide total ordering).
1187/// 4. **Temporal coherence**: When targets change slightly, allocations tend to
1188///    stay the same (preferring the previous frame's rounding direction).
1189/// 5. **Optimal displacement**: Among all integer allocations summing to `total`
1190///    with `floor(r_i) ≤ x_i ≤ ceil(r_i)`, the Largest Remainder Method
1191///    minimizes total absolute displacement.
1192///
1193/// # Failure Modes
1194///
1195/// - **All-zero targets**: Returns all zeros. Harmless (empty layout).
1196/// - **Negative deficit**: Can occur if targets sum to less than `total` after
1197///   flooring. The algorithm handles this via the clamp in step 2.
1198/// - **Very large N**: O(N log N) due to sorting. Acceptable for typical
1199///   layout counts (< 100 items).
1200///
1201/// # Example
1202///
1203/// ```
1204/// use ftui_layout::round_layout_stable;
1205///
1206/// // Targets: [10.4, 20.6, 9.0] must sum to 40
1207/// let result = round_layout_stable(&[10.4, 20.6, 9.0], 40, None);
1208/// assert_eq!(result.iter().sum::<u16>(), 40);
1209/// // 10.4 → 10, 20.6 → 21, 9.0 → 9 = 40 ✓
1210/// assert_eq!(result.as_slice(), &[10, 21, 9]);
1211/// ```
1212pub 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    // Step 1: Floor all targets
1219    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    // Step 2: Compute deficit (extra cells to distribute)
1228    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        // Exact fit — no rounding needed
1236        return floors;
1237    }
1238
1239    // Step 3: Compute remainders and build priority list
1240    let mut priority: SmallVec<[(usize, f64, bool); LAYOUT_INLINE_CAP]> = targets
1241        .iter()
1242        .enumerate()
1243        .map(|(i, &r)| {
1244            // Sanitize non-finite targets (NaN/inf): NaN.max(0.0) already
1245            // floors to 0 above; a NaN remainder here would poison the sort.
1246            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            // Temporal stability: did previous allocation use ceil?
1254            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    // Sort by: remainder descending, then temporal preference, then index ascending.
1262    // total_cmp keeps the comparator a TOTAL order: the previous
1263    // partial_cmp().unwrap_or(Equal) made NaN compare Equal to everything
1264    // while real values still ordered — an intransitive comparator that
1265    // std's sort is documented to panic on.
1266    priority.sort_by(|a, b| {
1267        b.1.total_cmp(&a.1)
1268            .then_with(|| {
1269                // Prefer items where prev used ceil (true > false)
1270                b.2.cmp(&a.2)
1271            })
1272            .then_with(|| {
1273                // Deterministic tie-break: smaller index first
1274                a.0.cmp(&b.0)
1275            })
1276    });
1277
1278    // Step 4: Distribute deficit
1279    let mut result = floors;
1280    let mut remaining_deficit = deficit;
1281
1282    // We award at most one extra cell per item to maintain the invariant
1283    // |x_i - r_i| < 1 (bounded displacement). Hamilton's method only
1284    // handles D < n. If D >= n, it implies sum(floors) + n <= total,
1285    // which means sum(targets) was significantly less than total.
1286    // In this case, we distribute the surplus as evenly as possible.
1287    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
1304/// Handle the edge case where floored values exceed total.
1305///
1306/// This can happen with very small totals and many items. We greedily
1307/// reduce the largest items by 1 until the sum matches.
1308fn 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            // Cannot reduce further, even though overflow persists.
1324            // This happens if total < 0 (impossible for u16) or some other
1325            // degenerate state. Force sum to 0.
1326            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            // Hard fallback: should not happen if max_val > 0.
1358            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        // Min beside Fixed, asked for more than the row has. The solver gives
1381        // the minimum to the first and the remainder to the second: the rects
1382        // stay disjoint and inside the row, and it is the *caller* who has to
1383        // decide whether a column that small is still worth drawing into.
1384        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        // Regression: NaN remainders made the priority comparator
1406        // intransitive (NaN Equal to everything while real values still
1407        // ordered); std's sort is documented to panic on non-total orders.
1408        // Large-ish N to engage the driftsort merge paths.
1409        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        // The invariant under test is "no panic": the sort must stay a
1415        // total order in the presence of non-finite remainders.
1416        let sizes = round_layout_stable(&targets, 120, None);
1417        assert_eq!(sizes.len(), 64);
1418
1419        // And with only-NaN targets, all floors are 0 and the deficit path
1420        // still distributes exactly the requested total.
1421        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)); // Gap is 0 by default
1434    }
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        // Item 1: 0..10
1452        // Gap: 10..15
1453        // Item 2: 15..25
1454        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), // Should take half of remaining (90/2 = 45) + base 10? No, logic is simplified.
1463            Constraint::Percentage(10.0), // 10% of 100 = 10
1464        ]);
1465
1466        // Available: 100
1467        // Fixed(10) -> 10. Rem: 90.
1468        // Percent(10%) -> 10. Rem: 80.
1469        // Min(10) -> 10. Rem: 70.
1470        // Grow candidates: Min(10).
1471        // Distribute 70 to Min(10). Size = 10 + 70 = 80.
1472
1473        let rects = flex.split(Rect::new(0, 0, 100, 1));
1474        assert_eq!(rects[0].width, 10); // Fixed
1475        assert_eq!(rects[2].width, 10); // Percent
1476        assert_eq!(rects[1].width, 80); // Min + Remainder
1477    }
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        // Items should be pushed to the end: leftover = 100 - 20 = 80
1521        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        // Items should be centered: leftover = 100 - 40 = 60, offset = 30
1532        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        // Items: 30 total, leftover = 70, 2 gaps, 35 per gap
1547        assert_eq!(rects[0].x, 0);
1548        assert_eq!(rects[1].x, 45); // 10 + 35
1549        assert_eq!(rects[2].x, 90); // 45 + 10 + 35
1550    }
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        // Vertical: leftover = 100 - 10 = 90
1559        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        // Outer horizontal split
1566        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        // Inner vertical split on the first half
1571        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    // Property-like invariant tests
1579    #[test]
1580    fn invariant_total_size_does_not_exceed_available() {
1581        // Test that constraint solving never allocates more than available
1582        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    // --- Ratio constraint ---
1625
1626    #[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        // Zero denominator should not panic (max(1) guard)
1638        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        // Percentage is absolute against the total available.
1648        let rects = Flex::horizontal()
1649            .constraints([Constraint::Percentage(25.0)])
1650            .split(area);
1651        assert_eq!(rects[0].width, 25);
1652
1653        // Ratio(1, 4) should also be absolute (25% of 100 = 25).
1654        // It does NOT grow to fill remaining space.
1655        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        // Ratio(1, 4) takes 25 fixed. Fill takes remaining 75.
1666        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        // Ratio(0, 1) should logically get 0 space.
1676        // Test with Fill first to expose "last item gets remainder" logic artifact
1677        let flex = Flex::horizontal().constraints([Constraint::Fill, Constraint::Ratio(0, 1)]);
1678        let rects = flex.split(Rect::new(0, 0, 100, 1));
1679
1680        // Fill should get 100, Ratio should get 0
1681        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    // --- Max constraint ---
1686
1687    #[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        // Since Ratio is absolute, 1/3 of 5 is 1, and 2/3 of 5 is 3.
1721        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    // --- SpaceAround alignment ---
1740
1741    #[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        // SpaceAround: leftover = 80, space_unit = 80/(2*2) = 20
1749        // First item starts at 20, second at 20+10+40=70
1750        assert_eq!(rects[0].x, 20);
1751        assert_eq!(rects[1].x, 70);
1752    }
1753
1754    // --- Vertical with gap ---
1755
1756    #[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    // --- Vertical center alignment ---
1767
1768    #[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        // leftover = 90, offset = 45
1775        assert_eq!(rects[0].y, 45);
1776        assert_eq!(rects[0].height, 10);
1777    }
1778
1779    // --- Single constraint gets all space ---
1780
1781    #[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    // --- Fixed exceeds available ---
1789
1790    #[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        // First gets 60, second gets remaining 40 (clamped)
1795        assert_eq!(rects[0].width, 60);
1796        assert_eq!(rects[1].width, 40);
1797    }
1798
1799    // --- Percentage that sums beyond 100% ---
1800
1801    #[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); // clamped to remaining
1808    }
1809
1810    // --- Margin reduces available space ---
1811
1812    #[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        // Inner: 10,10,80,80
1819        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    // --- Builder chain ---
1826
1827    #[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    // --- SpaceBetween with single item ---
1840
1841    #[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        // Single item: starts at 0, no extra spacing
1848        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        // All rects should be within the inner area (after margin)
1866        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    // --- Fill constraint ---
1884
1885    #[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); // Fill gets remaining
1891    }
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    // --- FitContent constraint ---
1902
1903    #[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); // FitContent gets preferred
1918        assert_eq!(rects[1].width, 70); // Fill gets remainder
1919    }
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        // First FitContent takes 80, second gets remaining 20
1930        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        // Without measurer (via split()), FitContent gets zero from default hint
1937        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); // No preferred size
1940        assert_eq!(rects[1].width, 100); // Fill gets all
1941    }
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    // --- FitContentBounded constraint ---
1971
1972    #[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, // Below min bound
1981            max: None,
1982        });
1983        assert_eq!(rects[0].width, 20); // Clamped to min bound
1984        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        // Available is 5 total, so FitContentBounded must clamp to remaining.
1999        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, // Above max bound
2012            max: None,
2013        });
2014        assert_eq!(rects[0].width, 30); // Clamped to max bound
2015        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, // Within bounds
2027            max: None,
2028        });
2029        assert_eq!(rects[0].width, 35);
2030        assert_eq!(rects[1].width, 65);
2031    }
2032
2033    // --- FitMin constraint ---
2034
2035    #[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        // FitMin gets minimum (15) and DOES NOT grow.
2050        // Fill gets the remaining 85.
2051        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        // Without measurer, min is 0. FitMin gets 0 and does not grow.
2060        // Fill takes all 100.
2061        assert_eq!(rects[0].width, 0);
2062        assert_eq!(rects[1].width, 100);
2063    }
2064
2065    // --- LayoutSizeHint tests ---
2066
2067    #[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); // Below min
2096        assert_eq!(h.clamp(15), 15); // In range
2097        assert_eq!(h.clamp(50), 30); // Above max
2098    }
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); // Below min
2104        assert_eq!(h.clamp(1000), 1000); // No max, stays as-is
2105    }
2106
2107    #[test]
2108    fn layout_size_hint_clamp_min_greater_than_max() {
2109        // When min > max, min should win (strict lower bound)
2110        let h = LayoutSizeHint {
2111            min: 20,
2112            preferred: 20,
2113            max: Some(10),
2114        };
2115        assert_eq!(h.clamp(5), 20); // 20 > 5, clamped to min
2116        assert_eq!(h.clamp(15), 20); // 20 > 15, clamped to min
2117        assert_eq!(h.clamp(25), 20); // 20 > 10, clamped to min
2118    }
2119
2120    // --- Integration: FitContent with other constraints ---
2121
2122    #[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); // Fixed
2141        assert_eq!(rects[1].width, 25); // FitContent preferred
2142        assert_eq!(rects[2].width, 55); // Fill gets remainder
2143    }
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    // -----------------------------------------------------------------------
2170    // Stable Layout Rounding Tests (bd-4kq0.4.1)
2171    // -----------------------------------------------------------------------
2172
2173    mod rounding_tests {
2174        use super::super::*;
2175
2176        // --- Sum conservation (REQUIRED) ---
2177
2178        #[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        // --- Bounded displacement ---
2221
2222        #[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        // --- Temporal tie-break (REQUIRED) ---
2244
2245        #[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        // --- Property: min displacement (REQUIRED) ---
2277
2278        #[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        // --- Determinism ---
2318
2319        #[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        // --- Edge cases ---
2328
2329        #[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    // -----------------------------------------------------------------------
2408    // Property Tests: Constraint Satisfaction (bd-4kq0.4.3)
2409    // -----------------------------------------------------------------------
2410
2411    mod property_constraint_tests {
2412        use super::super::*;
2413
2414        /// Deterministic LCG pseudo-random number generator (no external deps).
2415        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        /// Generate a random constraint from the LCG.
2440        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    // -----------------------------------------------------------------------
2622    // Property Tests: Temporal Stability (bd-4kq0.4.3)
2623    // -----------------------------------------------------------------------
2624
2625    mod property_temporal_tests {
2626        use super::super::*;
2627        use crate::cache::{CoherenceCache, CoherenceId};
2628
2629        /// Deterministic LCG.
2630        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    // -----------------------------------------------------------------------
2780    // Snapshot Regression: Canonical Flex/Grid Layouts (bd-4kq0.4.3)
2781    // -----------------------------------------------------------------------
2782
2783    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        // --- Flex snapshots: 80x24 ---
2864
2865        #[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        // --- Flex snapshots: 120x40 ---
2929
2930        #[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        // --- Grid snapshots: 80x24 ---
2998
2999        #[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        // --- Grid snapshots: 120x40 ---
3058
3059        #[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}