Skip to main content

native_gui_core/layout/
box_sizing.rs

1//! Box sizing, box model constraints, intrinsic measurement, and numerical rules.
2//!
3//! Provides:
4//! - Complete box model geometry (`BoxDimensions`: content, padding, border, margin boxes).
5//! - Min/max constraint resolution with strict floor precedence (`min_size > max_size` min wins).
6//! - Aspect ratio proportional resolution (width-to-height and height-to-width).
7//! - Inset and positioning calculations for `Position::Relative` and `Position::Absolute`.
8//! - Sizing units resolution (`Dimension`, `LengthPercentage`, `LengthPercentageAuto`).
9//! - Definite vs indefinite available space handling (indefinite percentages collapse to Auto/0.0).
10//! - Negative margin offsets.
11//! - Intrinsic measurement and text measurement caching with zero redundant calls.
12//! - Strict numerical invariants (finite f32, non-negative dimensions).
13
14use std::collections::HashMap;
15
16use crate::error::{GuiError, GuiResult};
17use crate::layout::{
18    AvailableSpace, Dimension, LayoutNodeId, LengthPercentage, LengthPercentageAuto, Point, Rect,
19    Size, Style,
20};
21
22/// Maximum recursion depth allowed during layout to prevent infinite loops.
23pub const MAX_LAYOUT_DEPTH: usize = 128;
24
25/// Numerical comparison tolerance for logical pixel layout.
26pub const STRICT_TOLERANCE_PX: f32 = 0.01;
27
28/// The four geometric regions of a box in the layout model:
29/// content box, padding box, border box, and margin box.
30#[derive(Debug, Clone, Copy, PartialEq, Default)]
31#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
32pub struct BoxDimensions {
33    /// Inner content dimensions in logical pixels.
34    pub content: Size<f32>,
35    /// Padding insets in logical pixels (>= 0.0).
36    pub padding: Rect<f32>,
37    /// Border insets in logical pixels (>= 0.0).
38    pub border: Rect<f32>,
39    /// Margin insets in logical pixels (can be negative).
40    pub margin: Rect<f32>,
41}
42
43impl BoxDimensions {
44    /// Creates a zero-sized `BoxDimensions`.
45    pub const ZERO: Self = Self {
46        content: Size::ZERO,
47        padding: Rect {
48            left: 0.0,
49            right: 0.0,
50            top: 0.0,
51            bottom: 0.0,
52        },
53        border: Rect {
54            left: 0.0,
55            right: 0.0,
56            top: 0.0,
57            bottom: 0.0,
58        },
59        margin: Rect {
60            left: 0.0,
61            right: 0.0,
62            top: 0.0,
63            bottom: 0.0,
64        },
65    };
66
67    /// Returns the inner content size.
68    pub fn content_box(&self) -> Size<f32> {
69        self.content
70    }
71
72    /// Returns the size including content and padding.
73    pub fn padding_box(&self) -> Size<f32> {
74        Size::new(
75            (self.content.width + self.padding.left + self.padding.right).max(0.0),
76            (self.content.height + self.padding.top + self.padding.bottom).max(0.0),
77        )
78    }
79
80    /// Returns the outer size including content, padding, and border.
81    /// In Native GUI native layout, border-box represents the widget's allocated rectangle.
82    pub fn border_box(&self) -> Size<f32> {
83        let p_box = self.padding_box();
84        Size::new(
85            (p_box.width + self.border.left + self.border.right).max(0.0),
86            (p_box.height + self.border.top + self.border.bottom).max(0.0),
87        )
88    }
89
90    /// Returns the outer margin-box size including content, padding, border, and margin.
91    /// Note that margins can be negative, which contracts the margin box.
92    pub fn margin_box(&self) -> Size<f32> {
93        let b_box = self.border_box();
94        Size::new(
95            (b_box.width + self.margin.left + self.margin.right).max(0.0),
96            (b_box.height + self.margin.top + self.margin.bottom).max(0.0),
97        )
98    }
99
100    /// Validates all dimensions and insets are finite and non-negative where required.
101    pub fn validate(&self) -> GuiResult<()> {
102        if !self.content.width.is_finite()
103            || !self.content.height.is_finite()
104            || self.content.width < 0.0
105            || self.content.height < 0.0
106        {
107            return Err(GuiError::InvalidLayoutGeometry);
108        }
109        if !self.padding.left.is_finite()
110            || !self.padding.right.is_finite()
111            || !self.padding.top.is_finite()
112            || !self.padding.bottom.is_finite()
113            || self.padding.left < 0.0
114            || self.padding.right < 0.0
115            || self.padding.top < 0.0
116            || self.padding.bottom < 0.0
117        {
118            return Err(GuiError::InvalidLayoutGeometry);
119        }
120        if !self.border.left.is_finite()
121            || !self.border.right.is_finite()
122            || !self.border.top.is_finite()
123            || !self.border.bottom.is_finite()
124            || self.border.left < 0.0
125            || self.border.right < 0.0
126            || self.border.top < 0.0
127            || self.border.bottom < 0.0
128        {
129            return Err(GuiError::InvalidLayoutGeometry);
130        }
131        if !self.margin.left.is_finite()
132            || !self.margin.right.is_finite()
133            || !self.margin.top.is_finite()
134            || !self.margin.bottom.is_finite()
135        {
136            return Err(GuiError::InvalidNumericInput);
137        }
138        Ok(())
139    }
140}
141
142/// Min, max, and aspect ratio constraints resolved against available space.
143#[derive(Debug, Clone, Copy, PartialEq, Default)]
144pub struct BoxConstraints {
145    pub min_size: Size<Option<f32>>,
146    pub max_size: Size<Option<f32>>,
147    pub aspect_ratio: Option<f32>,
148}
149
150impl BoxConstraints {
151    /// Clamps a single dimension value following the strict CSS/Native GUI rule:
152    /// `max(min, min(max, value))`.
153    ///
154    /// When `min > max`, `min` wins as the floor clamp (FIX-SIZ-006).
155    pub fn clamp_dimension(val: f32, min: Option<f32>, max: Option<f32>) -> f32 {
156        let mut result = val;
157        if let Some(max_val) = max {
158            result = result.min(max_val);
159        }
160        if let Some(min_val) = min {
161            result = result.max(min_val);
162        }
163        result.max(0.0)
164    }
165
166    /// Clamps a 2D size against min and max constraints.
167    pub fn clamp_size(&self, size: Size<f32>) -> Size<f32> {
168        Size::new(
169            Self::clamp_dimension(size.width, self.min_size.width, self.max_size.width),
170            Self::clamp_dimension(size.height, self.min_size.height, self.max_size.height),
171        )
172    }
173
174    /// Resolves aspect ratio on a candidate size.
175    ///
176    /// - If width is known and height is auto (`None`), height = width / ratio.
177    /// - If height is known and width is auto (`None`), width = height * ratio.
178    pub fn apply_aspect_ratio(&self, size: Size<Option<f32>>) -> Size<Option<f32>> {
179        let Some(ratio) = self.aspect_ratio else {
180            return size;
181        };
182        if ratio <= 0.0 || !ratio.is_finite() {
183            return size;
184        }
185
186        match (size.width, size.height) {
187            (Some(w), None) => Size::new(Some(w), Some((w / ratio).max(0.0))),
188            (None, Some(h)) => Size::new(Some((h * ratio).max(0.0)), Some(h)),
189            _ => size,
190        }
191    }
192}
193
194/// Resolves a `Dimension` against available space on that axis.
195///
196/// - `Length(px)`: returns `Some(px.max(0.0))`.
197/// - `Percent(pct)`:
198///   - If available space is `Definite(parent_size)`, returns `Some((parent_size * pct).max(0.0))`.
199///   - If available space is indefinite (`MinContent` or `MaxContent`), returns `None`
200///     (resolves to Auto / 0.0 per CSS and FIX-SIZ-008).
201/// - `Auto`: returns `None`.
202pub fn resolve_dimension(dim: Dimension, space: AvailableSpace) -> Option<f32> {
203    match dim {
204        Dimension::Length(px) => Some(px.max(0.0)),
205        Dimension::Percent(pct) => match space {
206            AvailableSpace::Definite(parent_size) => Some((parent_size * pct).max(0.0)),
207            _ => None,
208        },
209        Dimension::Auto => None,
210    }
211}
212
213/// Resolves padding against available space. Indefinite space produces 0.0 for percentages.
214pub fn resolve_padding(
215    padding: &Rect<LengthPercentage>,
216    available_space: Size<AvailableSpace>,
217) -> Rect<f32> {
218    let left = match padding.left {
219        LengthPercentage::Length(px) => px.max(0.0),
220        LengthPercentage::Percent(p) => match available_space.width {
221            AvailableSpace::Definite(w) => (w * p).max(0.0),
222            _ => 0.0,
223        },
224    };
225    let right = match padding.right {
226        LengthPercentage::Length(px) => px.max(0.0),
227        LengthPercentage::Percent(p) => match available_space.width {
228            AvailableSpace::Definite(w) => (w * p).max(0.0),
229            _ => 0.0,
230        },
231    };
232    let top = match padding.top {
233        LengthPercentage::Length(px) => px.max(0.0),
234        LengthPercentage::Percent(p) => match available_space.height {
235            AvailableSpace::Definite(h) => (h * p).max(0.0),
236            _ => 0.0,
237        },
238    };
239    let bottom = match padding.bottom {
240        LengthPercentage::Length(px) => px.max(0.0),
241        LengthPercentage::Percent(p) => match available_space.height {
242            AvailableSpace::Definite(h) => (h * p).max(0.0),
243            _ => 0.0,
244        },
245    };
246    Rect::new(left, right, top, bottom)
247}
248
249/// Resolves margins against available space. Negative margins are preserved (FIX-SIZ-009).
250/// Percentages against indefinite space resolve to 0.0. Auto resolves to 0.0.
251pub fn resolve_margin(
252    margin: &Rect<LengthPercentageAuto>,
253    available_space: Size<AvailableSpace>,
254) -> Rect<f32> {
255    let left = match margin.left {
256        LengthPercentageAuto::Length(px) => px,
257        LengthPercentageAuto::Percent(p) => match available_space.width {
258            AvailableSpace::Definite(w) => w * p,
259            _ => 0.0,
260        },
261        LengthPercentageAuto::Auto => 0.0,
262    };
263    let right = match margin.right {
264        LengthPercentageAuto::Length(px) => px,
265        LengthPercentageAuto::Percent(p) => match available_space.width {
266            AvailableSpace::Definite(w) => w * p,
267            _ => 0.0,
268        },
269        LengthPercentageAuto::Auto => 0.0,
270    };
271    let top = match margin.top {
272        LengthPercentageAuto::Length(px) => px,
273        LengthPercentageAuto::Percent(p) => match available_space.height {
274            AvailableSpace::Definite(h) => h * p,
275            _ => 0.0,
276        },
277        LengthPercentageAuto::Auto => 0.0,
278    };
279    let bottom = match margin.bottom {
280        LengthPercentageAuto::Length(px) => px,
281        LengthPercentageAuto::Percent(p) => match available_space.height {
282            AvailableSpace::Definite(h) => h * p,
283            _ => 0.0,
284        },
285        LengthPercentageAuto::Auto => 0.0,
286    };
287    Rect::new(left, right, top, bottom)
288}
289
290/// Resolves insets (left, right, top, bottom) for positioned nodes.
291pub fn resolve_inset(
292    inset: &Rect<LengthPercentageAuto>,
293    available_space: Size<AvailableSpace>,
294) -> Rect<Option<f32>> {
295    let resolve_axis = |val: LengthPercentageAuto, space: AvailableSpace| match val {
296        LengthPercentageAuto::Length(px) => Some(px),
297        LengthPercentageAuto::Percent(p) => match space {
298            AvailableSpace::Definite(s) => Some(s * p),
299            _ => None,
300        },
301        LengthPercentageAuto::Auto => None,
302    };
303    Rect::new(
304        resolve_axis(inset.left, available_space.width),
305        resolve_axis(inset.right, available_space.width),
306        resolve_axis(inset.top, available_space.height),
307        resolve_axis(inset.bottom, available_space.height),
308    )
309}
310
311/// Extracts and resolves min/max constraints and aspect ratio from a node's style.
312pub fn resolve_box_constraints(
313    style: &Style,
314    available_space: Size<AvailableSpace>,
315) -> BoxConstraints {
316    BoxConstraints {
317        min_size: Size::new(
318            resolve_dimension(style.min_size.width, available_space.width),
319            resolve_dimension(style.min_size.height, available_space.height),
320        ),
321        max_size: Size::new(
322            resolve_dimension(style.max_size.width, available_space.width),
323            resolve_dimension(style.max_size.height, available_space.height),
324        ),
325        aspect_ratio: style.aspect_ratio,
326    }
327}
328
329/// Computes the complete box dimensions for a node given its style, available space,
330/// and optional intrinsic content size.
331pub fn compute_box_sizing(
332    style: &Style,
333    available_space: Size<AvailableSpace>,
334    intrinsic_size: Option<Size<f32>>,
335) -> GuiResult<BoxDimensions> {
336    style.validate()?;
337
338    let padding = resolve_padding(&style.padding, available_space);
339    let border = Rect::<f32>::new(0.0, 0.0, 0.0, 0.0);
340    let margin = resolve_margin(&style.margin, available_space);
341    let constraints = resolve_box_constraints(style, available_space);
342
343    let mut raw_width = resolve_dimension(style.size.width, available_space.width);
344    let mut raw_height = resolve_dimension(style.size.height, available_space.height);
345
346    // If dimension is auto, incorporate intrinsic measurement if provided
347    if raw_width.is_none() {
348        if let Some(intr) = intrinsic_size {
349            raw_width = Some(intr.width);
350        }
351    }
352    if raw_height.is_none() {
353        if let Some(intr) = intrinsic_size {
354            raw_height = Some(intr.height);
355        }
356    }
357
358    // Apply aspect ratio when one dimension is known and the other is auto
359    let sized = constraints.apply_aspect_ratio(Size::new(raw_width, raw_height));
360    let mut resolved_w = sized.width.unwrap_or(0.0);
361    let mut resolved_h = sized.height.unwrap_or(0.0);
362
363    // Clamp dimensions (min_size wins over max_size on conflict)
364    resolved_w = BoxConstraints::clamp_dimension(
365        resolved_w,
366        constraints.min_size.width,
367        constraints.max_size.width,
368    );
369    resolved_h = BoxConstraints::clamp_dimension(
370        resolved_h,
371        constraints.min_size.height,
372        constraints.max_size.height,
373    );
374
375    // If height was auto and aspect ratio is active, recompute height from clamped width
376    if raw_height.is_none() && style.aspect_ratio.is_some() {
377        if let Some(ratio) = style.aspect_ratio {
378            if ratio > 0.0 && ratio.is_finite() {
379                resolved_h = (resolved_w / ratio).max(0.0);
380                resolved_h = BoxConstraints::clamp_dimension(
381                    resolved_h,
382                    constraints.min_size.height,
383                    constraints.max_size.height,
384                );
385            }
386        }
387    } else if raw_width.is_none() && style.aspect_ratio.is_some() {
388        if let Some(ratio) = style.aspect_ratio {
389            if ratio > 0.0 && ratio.is_finite() {
390                resolved_w = (resolved_h * ratio).max(0.0);
391                resolved_w = BoxConstraints::clamp_dimension(
392                    resolved_w,
393                    constraints.min_size.width,
394                    constraints.max_size.width,
395                );
396            }
397        }
398    }
399
400    let b_box = Size::new(resolved_w, resolved_h);
401    let content_w =
402        (b_box.width - padding.left - padding.right - border.left - border.right).max(0.0);
403    let content_h =
404        (b_box.height - padding.top - padding.bottom - border.top - border.bottom).max(0.0);
405
406    let dims = BoxDimensions {
407        content: Size::new(content_w, content_h),
408        padding,
409        border,
410        margin,
411    };
412    dims.validate()?;
413    Ok(dims)
414}
415
416/// Applies relative positioning offset to an in-flow item based on its `inset`.
417pub fn apply_relative_offset(flow_position: Point<f32>, inset: &Rect<Option<f32>>) -> Point<f32> {
418    let mut x = flow_position.x;
419    let mut y = flow_position.y;
420
421    if let Some(left) = inset.left {
422        x += left;
423    } else if let Some(right) = inset.right {
424        x -= right;
425    }
426
427    if let Some(top) = inset.top {
428        y += top;
429    } else if let Some(bottom) = inset.bottom {
430        y -= bottom;
431    }
432
433    Point::new(x, y)
434}
435
436/// Computes the layout position for an out-of-flow `Position::Absolute` child
437/// relative to the parent's padding box.
438pub fn resolve_absolute_position(
439    parent_padding_origin: Point<f32>,
440    parent_padding_size: Size<f32>,
441    child_size: Size<f32>,
442    inset: &Rect<Option<f32>>,
443    margin: &Rect<f32>,
444) -> Point<f32> {
445    let x = if let Some(left) = inset.left {
446        parent_padding_origin.x + left + margin.left
447    } else if let Some(right) = inset.right {
448        parent_padding_origin.x + parent_padding_size.width
449            - child_size.width
450            - right
451            - margin.right
452    } else {
453        parent_padding_origin.x + margin.left
454    };
455
456    let y = if let Some(top) = inset.top {
457        parent_padding_origin.y + top + margin.top
458    } else if let Some(bottom) = inset.bottom {
459        parent_padding_origin.y + parent_padding_size.height
460            - child_size.height
461            - bottom
462            - margin.bottom
463    } else {
464        parent_padding_origin.y + margin.top
465    };
466
467    Point::new(x, y)
468}
469
470/// Trait for intrinsic measurement providers.
471pub trait Measurer {
472    fn measure(
473        &mut self,
474        node: LayoutNodeId,
475        known_dimensions: Size<Option<f32>>,
476        available_space: Size<AvailableSpace>,
477    ) -> Option<Size<f32>>;
478}
479
480impl<F> Measurer for F
481where
482    F: FnMut(LayoutNodeId, Size<Option<f32>>, Size<AvailableSpace>) -> Option<Size<f32>>,
483{
484    fn measure(
485        &mut self,
486        node: LayoutNodeId,
487        known_dimensions: Size<Option<f32>>,
488        available_space: Size<AvailableSpace>,
489    ) -> Option<Size<f32>> {
490        self(node, known_dimensions, available_space)
491    }
492}
493
494/// Quantized hash key for [`TextMeasurementCache`] avoiding heap allocation and float formatting.
495#[derive(Debug, Clone, PartialEq, Eq, Hash)]
496struct TextMeasureKey {
497    text: String,
498    known_hundredths: Option<i64>,
499    avail_tag: u8,
500    avail_hundredths: i64,
501    font_tenths: i64,
502}
503
504impl TextMeasureKey {
505    fn from_inputs(
506        text: &str,
507        font_size: f32,
508        known_dimensions: Size<Option<f32>>,
509        available_space: Size<AvailableSpace>,
510    ) -> Self {
511        let (avail_tag, avail_hundredths) = match available_space.width {
512            AvailableSpace::Definite(w) => (0, (w * 100.0).round() as i64),
513            AvailableSpace::MinContent => (1, 0),
514            AvailableSpace::MaxContent => (2, 0),
515        };
516        Self {
517            text: text.to_owned(),
518            known_hundredths: known_dimensions.width.map(|w| (w * 100.0).round() as i64),
519            avail_tag,
520            avail_hundredths,
521            font_tenths: (font_size * 10.0).round() as i64,
522        }
523    }
524}
525
526/// Cache and evaluator for intrinsic text measurements with call counting and constraint caching.
527#[derive(Debug, Clone, Default)]
528pub struct TextMeasurementCache {
529    measure_calls: usize,
530    cache_hits: usize,
531    cache: HashMap<TextMeasureKey, Size<f32>>,
532}
533
534impl TextMeasurementCache {
535    /// Creates a new, empty text measurement cache.
536    pub fn new() -> Self {
537        Self::default()
538    }
539
540    /// Returns the number of measurement calculations performed.
541    pub fn call_count(&self) -> usize {
542        self.measure_calls
543    }
544
545    /// Returns the number of cache hits.
546    pub fn cache_hits(&self) -> usize {
547        self.cache_hits
548    }
549
550    /// Resets call and hit counters.
551    pub fn reset_counts(&mut self) {
552        self.measure_calls = 0;
553        self.cache_hits = 0;
554    }
555
556    /// Clears all cached measurements.
557    pub fn clear(&mut self) {
558        self.cache.clear();
559        self.reset_counts();
560    }
561
562    /// Measures text with line wrapping under available space constraints.
563    ///
564    /// - Unconstrained (`MaxContent` or width >= natural width): returns natural single-line dimensions.
565    /// - Constrained (known width or `Definite` width < natural width): wraps text, expanding height.
566    /// - Empty text (`""`): collapses width to 0.0 while preserving font line height.
567    pub fn measure_text(
568        &mut self,
569        text: &str,
570        font_size: f32,
571        line_height: f32,
572        known_dimensions: Size<Option<f32>>,
573        available_space: Size<AvailableSpace>,
574    ) -> Size<f32> {
575        let key = TextMeasureKey::from_inputs(text, font_size, known_dimensions, available_space);
576
577        if let Some(&cached) = self.cache.get(&key) {
578            self.cache_hits += 1;
579            return cached;
580        }
581
582        self.measure_calls += 1;
583
584        if text.is_empty() {
585            let res = Size::new(0.0, line_height);
586            self.cache.insert(key, res);
587            return res;
588        }
589
590        let char_width = font_size * 0.6;
591        let natural_width = text.len() as f32 * char_width;
592
593        let max_w = known_dimensions
594            .width
595            .or_else(|| available_space.width.into_option());
596
597        let res = match max_w {
598            Some(w) if w < natural_width && w > 0.0 => {
599                let chars_per_line = ((w / char_width).floor() as usize).max(1);
600                let lines = text.len().div_ceil(chars_per_line);
601                Size::new(w, lines as f32 * line_height)
602            }
603            _ => Size::new(natural_width, line_height),
604        };
605
606        self.cache.insert(key, res);
607        res
608    }
609}