native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//! Box sizing, box model constraints, intrinsic measurement, and numerical rules.
//!
//! Provides:
//! - Complete box model geometry (`BoxDimensions`: content, padding, border, margin boxes).
//! - Min/max constraint resolution with strict floor precedence (`min_size > max_size` min wins).
//! - Aspect ratio proportional resolution (width-to-height and height-to-width).
//! - Inset and positioning calculations for `Position::Relative` and `Position::Absolute`.
//! - Sizing units resolution (`Dimension`, `LengthPercentage`, `LengthPercentageAuto`).
//! - Definite vs indefinite available space handling (indefinite percentages collapse to Auto/0.0).
//! - Negative margin offsets.
//! - Intrinsic measurement and text measurement caching with zero redundant calls.
//! - Strict numerical invariants (finite f32, non-negative dimensions).

use std::collections::HashMap;

use crate::error::{GuiError, GuiResult};
use crate::layout::{
    AvailableSpace, Dimension, LayoutNodeId, LengthPercentage, LengthPercentageAuto, Point, Rect,
    Size, Style,
};

/// Maximum recursion depth allowed during layout to prevent infinite loops.
pub const MAX_LAYOUT_DEPTH: usize = 128;

/// Numerical comparison tolerance for logical pixel layout.
pub const STRICT_TOLERANCE_PX: f32 = 0.01;

/// The four geometric regions of a box in the layout model:
/// content box, padding box, border box, and margin box.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BoxDimensions {
    /// Inner content dimensions in logical pixels.
    pub content: Size<f32>,
    /// Padding insets in logical pixels (>= 0.0).
    pub padding: Rect<f32>,
    /// Border insets in logical pixels (>= 0.0).
    pub border: Rect<f32>,
    /// Margin insets in logical pixels (can be negative).
    pub margin: Rect<f32>,
}

impl BoxDimensions {
    /// Creates a zero-sized `BoxDimensions`.
    pub const ZERO: Self = Self {
        content: Size::ZERO,
        padding: Rect {
            left: 0.0,
            right: 0.0,
            top: 0.0,
            bottom: 0.0,
        },
        border: Rect {
            left: 0.0,
            right: 0.0,
            top: 0.0,
            bottom: 0.0,
        },
        margin: Rect {
            left: 0.0,
            right: 0.0,
            top: 0.0,
            bottom: 0.0,
        },
    };

    /// Returns the inner content size.
    pub fn content_box(&self) -> Size<f32> {
        self.content
    }

    /// Returns the size including content and padding.
    pub fn padding_box(&self) -> Size<f32> {
        Size::new(
            (self.content.width + self.padding.left + self.padding.right).max(0.0),
            (self.content.height + self.padding.top + self.padding.bottom).max(0.0),
        )
    }

    /// Returns the outer size including content, padding, and border.
    /// In Native GUI native layout, border-box represents the widget's allocated rectangle.
    pub fn border_box(&self) -> Size<f32> {
        let p_box = self.padding_box();
        Size::new(
            (p_box.width + self.border.left + self.border.right).max(0.0),
            (p_box.height + self.border.top + self.border.bottom).max(0.0),
        )
    }

    /// Returns the outer margin-box size including content, padding, border, and margin.
    /// Note that margins can be negative, which contracts the margin box.
    pub fn margin_box(&self) -> Size<f32> {
        let b_box = self.border_box();
        Size::new(
            (b_box.width + self.margin.left + self.margin.right).max(0.0),
            (b_box.height + self.margin.top + self.margin.bottom).max(0.0),
        )
    }

    /// Validates all dimensions and insets are finite and non-negative where required.
    pub fn validate(&self) -> GuiResult<()> {
        if !self.content.width.is_finite()
            || !self.content.height.is_finite()
            || self.content.width < 0.0
            || self.content.height < 0.0
        {
            return Err(GuiError::InvalidLayoutGeometry);
        }
        if !self.padding.left.is_finite()
            || !self.padding.right.is_finite()
            || !self.padding.top.is_finite()
            || !self.padding.bottom.is_finite()
            || self.padding.left < 0.0
            || self.padding.right < 0.0
            || self.padding.top < 0.0
            || self.padding.bottom < 0.0
        {
            return Err(GuiError::InvalidLayoutGeometry);
        }
        if !self.border.left.is_finite()
            || !self.border.right.is_finite()
            || !self.border.top.is_finite()
            || !self.border.bottom.is_finite()
            || self.border.left < 0.0
            || self.border.right < 0.0
            || self.border.top < 0.0
            || self.border.bottom < 0.0
        {
            return Err(GuiError::InvalidLayoutGeometry);
        }
        if !self.margin.left.is_finite()
            || !self.margin.right.is_finite()
            || !self.margin.top.is_finite()
            || !self.margin.bottom.is_finite()
        {
            return Err(GuiError::InvalidNumericInput);
        }
        Ok(())
    }
}

/// Min, max, and aspect ratio constraints resolved against available space.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct BoxConstraints {
    pub min_size: Size<Option<f32>>,
    pub max_size: Size<Option<f32>>,
    pub aspect_ratio: Option<f32>,
}

impl BoxConstraints {
    /// Clamps a single dimension value following the strict CSS/Native GUI rule:
    /// `max(min, min(max, value))`.
    ///
    /// When `min > max`, `min` wins as the floor clamp (FIX-SIZ-006).
    pub fn clamp_dimension(val: f32, min: Option<f32>, max: Option<f32>) -> f32 {
        let mut result = val;
        if let Some(max_val) = max {
            result = result.min(max_val);
        }
        if let Some(min_val) = min {
            result = result.max(min_val);
        }
        result.max(0.0)
    }

    /// Clamps a 2D size against min and max constraints.
    pub fn clamp_size(&self, size: Size<f32>) -> Size<f32> {
        Size::new(
            Self::clamp_dimension(size.width, self.min_size.width, self.max_size.width),
            Self::clamp_dimension(size.height, self.min_size.height, self.max_size.height),
        )
    }

    /// Resolves aspect ratio on a candidate size.
    ///
    /// - If width is known and height is auto (`None`), height = width / ratio.
    /// - If height is known and width is auto (`None`), width = height * ratio.
    pub fn apply_aspect_ratio(&self, size: Size<Option<f32>>) -> Size<Option<f32>> {
        let Some(ratio) = self.aspect_ratio else {
            return size;
        };
        if ratio <= 0.0 || !ratio.is_finite() {
            return size;
        }

        match (size.width, size.height) {
            (Some(w), None) => Size::new(Some(w), Some((w / ratio).max(0.0))),
            (None, Some(h)) => Size::new(Some((h * ratio).max(0.0)), Some(h)),
            _ => size,
        }
    }
}

/// Resolves a `Dimension` against available space on that axis.
///
/// - `Length(px)`: returns `Some(px.max(0.0))`.
/// - `Percent(pct)`:
///   - If available space is `Definite(parent_size)`, returns `Some((parent_size * pct).max(0.0))`.
///   - If available space is indefinite (`MinContent` or `MaxContent`), returns `None`
///     (resolves to Auto / 0.0 per CSS and FIX-SIZ-008).
/// - `Auto`: returns `None`.
pub fn resolve_dimension(dim: Dimension, space: AvailableSpace) -> Option<f32> {
    match dim {
        Dimension::Length(px) => Some(px.max(0.0)),
        Dimension::Percent(pct) => match space {
            AvailableSpace::Definite(parent_size) => Some((parent_size * pct).max(0.0)),
            _ => None,
        },
        Dimension::Auto => None,
    }
}

/// Resolves padding against available space. Indefinite space produces 0.0 for percentages.
pub fn resolve_padding(
    padding: &Rect<LengthPercentage>,
    available_space: Size<AvailableSpace>,
) -> Rect<f32> {
    let left = match padding.left {
        LengthPercentage::Length(px) => px.max(0.0),
        LengthPercentage::Percent(p) => match available_space.width {
            AvailableSpace::Definite(w) => (w * p).max(0.0),
            _ => 0.0,
        },
    };
    let right = match padding.right {
        LengthPercentage::Length(px) => px.max(0.0),
        LengthPercentage::Percent(p) => match available_space.width {
            AvailableSpace::Definite(w) => (w * p).max(0.0),
            _ => 0.0,
        },
    };
    let top = match padding.top {
        LengthPercentage::Length(px) => px.max(0.0),
        LengthPercentage::Percent(p) => match available_space.height {
            AvailableSpace::Definite(h) => (h * p).max(0.0),
            _ => 0.0,
        },
    };
    let bottom = match padding.bottom {
        LengthPercentage::Length(px) => px.max(0.0),
        LengthPercentage::Percent(p) => match available_space.height {
            AvailableSpace::Definite(h) => (h * p).max(0.0),
            _ => 0.0,
        },
    };
    Rect::new(left, right, top, bottom)
}

/// Resolves margins against available space. Negative margins are preserved (FIX-SIZ-009).
/// Percentages against indefinite space resolve to 0.0. Auto resolves to 0.0.
pub fn resolve_margin(
    margin: &Rect<LengthPercentageAuto>,
    available_space: Size<AvailableSpace>,
) -> Rect<f32> {
    let left = match margin.left {
        LengthPercentageAuto::Length(px) => px,
        LengthPercentageAuto::Percent(p) => match available_space.width {
            AvailableSpace::Definite(w) => w * p,
            _ => 0.0,
        },
        LengthPercentageAuto::Auto => 0.0,
    };
    let right = match margin.right {
        LengthPercentageAuto::Length(px) => px,
        LengthPercentageAuto::Percent(p) => match available_space.width {
            AvailableSpace::Definite(w) => w * p,
            _ => 0.0,
        },
        LengthPercentageAuto::Auto => 0.0,
    };
    let top = match margin.top {
        LengthPercentageAuto::Length(px) => px,
        LengthPercentageAuto::Percent(p) => match available_space.height {
            AvailableSpace::Definite(h) => h * p,
            _ => 0.0,
        },
        LengthPercentageAuto::Auto => 0.0,
    };
    let bottom = match margin.bottom {
        LengthPercentageAuto::Length(px) => px,
        LengthPercentageAuto::Percent(p) => match available_space.height {
            AvailableSpace::Definite(h) => h * p,
            _ => 0.0,
        },
        LengthPercentageAuto::Auto => 0.0,
    };
    Rect::new(left, right, top, bottom)
}

/// Resolves insets (left, right, top, bottom) for positioned nodes.
pub fn resolve_inset(
    inset: &Rect<LengthPercentageAuto>,
    available_space: Size<AvailableSpace>,
) -> Rect<Option<f32>> {
    let resolve_axis = |val: LengthPercentageAuto, space: AvailableSpace| match val {
        LengthPercentageAuto::Length(px) => Some(px),
        LengthPercentageAuto::Percent(p) => match space {
            AvailableSpace::Definite(s) => Some(s * p),
            _ => None,
        },
        LengthPercentageAuto::Auto => None,
    };
    Rect::new(
        resolve_axis(inset.left, available_space.width),
        resolve_axis(inset.right, available_space.width),
        resolve_axis(inset.top, available_space.height),
        resolve_axis(inset.bottom, available_space.height),
    )
}

/// Extracts and resolves min/max constraints and aspect ratio from a node's style.
pub fn resolve_box_constraints(
    style: &Style,
    available_space: Size<AvailableSpace>,
) -> BoxConstraints {
    BoxConstraints {
        min_size: Size::new(
            resolve_dimension(style.min_size.width, available_space.width),
            resolve_dimension(style.min_size.height, available_space.height),
        ),
        max_size: Size::new(
            resolve_dimension(style.max_size.width, available_space.width),
            resolve_dimension(style.max_size.height, available_space.height),
        ),
        aspect_ratio: style.aspect_ratio,
    }
}

/// Computes the complete box dimensions for a node given its style, available space,
/// and optional intrinsic content size.
pub fn compute_box_sizing(
    style: &Style,
    available_space: Size<AvailableSpace>,
    intrinsic_size: Option<Size<f32>>,
) -> GuiResult<BoxDimensions> {
    style.validate()?;

    let padding = resolve_padding(&style.padding, available_space);
    let border = Rect::<f32>::new(0.0, 0.0, 0.0, 0.0);
    let margin = resolve_margin(&style.margin, available_space);
    let constraints = resolve_box_constraints(style, available_space);

    let mut raw_width = resolve_dimension(style.size.width, available_space.width);
    let mut raw_height = resolve_dimension(style.size.height, available_space.height);

    // If dimension is auto, incorporate intrinsic measurement if provided
    if raw_width.is_none() {
        if let Some(intr) = intrinsic_size {
            raw_width = Some(intr.width);
        }
    }
    if raw_height.is_none() {
        if let Some(intr) = intrinsic_size {
            raw_height = Some(intr.height);
        }
    }

    // Apply aspect ratio when one dimension is known and the other is auto
    let sized = constraints.apply_aspect_ratio(Size::new(raw_width, raw_height));
    let mut resolved_w = sized.width.unwrap_or(0.0);
    let mut resolved_h = sized.height.unwrap_or(0.0);

    // Clamp dimensions (min_size wins over max_size on conflict)
    resolved_w = BoxConstraints::clamp_dimension(
        resolved_w,
        constraints.min_size.width,
        constraints.max_size.width,
    );
    resolved_h = BoxConstraints::clamp_dimension(
        resolved_h,
        constraints.min_size.height,
        constraints.max_size.height,
    );

    // If height was auto and aspect ratio is active, recompute height from clamped width
    if raw_height.is_none() && style.aspect_ratio.is_some() {
        if let Some(ratio) = style.aspect_ratio {
            if ratio > 0.0 && ratio.is_finite() {
                resolved_h = (resolved_w / ratio).max(0.0);
                resolved_h = BoxConstraints::clamp_dimension(
                    resolved_h,
                    constraints.min_size.height,
                    constraints.max_size.height,
                );
            }
        }
    } else if raw_width.is_none() && style.aspect_ratio.is_some() {
        if let Some(ratio) = style.aspect_ratio {
            if ratio > 0.0 && ratio.is_finite() {
                resolved_w = (resolved_h * ratio).max(0.0);
                resolved_w = BoxConstraints::clamp_dimension(
                    resolved_w,
                    constraints.min_size.width,
                    constraints.max_size.width,
                );
            }
        }
    }

    let b_box = Size::new(resolved_w, resolved_h);
    let content_w =
        (b_box.width - padding.left - padding.right - border.left - border.right).max(0.0);
    let content_h =
        (b_box.height - padding.top - padding.bottom - border.top - border.bottom).max(0.0);

    let dims = BoxDimensions {
        content: Size::new(content_w, content_h),
        padding,
        border,
        margin,
    };
    dims.validate()?;
    Ok(dims)
}

/// Applies relative positioning offset to an in-flow item based on its `inset`.
pub fn apply_relative_offset(flow_position: Point<f32>, inset: &Rect<Option<f32>>) -> Point<f32> {
    let mut x = flow_position.x;
    let mut y = flow_position.y;

    if let Some(left) = inset.left {
        x += left;
    } else if let Some(right) = inset.right {
        x -= right;
    }

    if let Some(top) = inset.top {
        y += top;
    } else if let Some(bottom) = inset.bottom {
        y -= bottom;
    }

    Point::new(x, y)
}

/// Computes the layout position for an out-of-flow `Position::Absolute` child
/// relative to the parent's padding box.
pub fn resolve_absolute_position(
    parent_padding_origin: Point<f32>,
    parent_padding_size: Size<f32>,
    child_size: Size<f32>,
    inset: &Rect<Option<f32>>,
    margin: &Rect<f32>,
) -> Point<f32> {
    let x = if let Some(left) = inset.left {
        parent_padding_origin.x + left + margin.left
    } else if let Some(right) = inset.right {
        parent_padding_origin.x + parent_padding_size.width
            - child_size.width
            - right
            - margin.right
    } else {
        parent_padding_origin.x + margin.left
    };

    let y = if let Some(top) = inset.top {
        parent_padding_origin.y + top + margin.top
    } else if let Some(bottom) = inset.bottom {
        parent_padding_origin.y + parent_padding_size.height
            - child_size.height
            - bottom
            - margin.bottom
    } else {
        parent_padding_origin.y + margin.top
    };

    Point::new(x, y)
}

/// Trait for intrinsic measurement providers.
pub trait Measurer {
    fn measure(
        &mut self,
        node: LayoutNodeId,
        known_dimensions: Size<Option<f32>>,
        available_space: Size<AvailableSpace>,
    ) -> Option<Size<f32>>;
}

impl<F> Measurer for F
where
    F: FnMut(LayoutNodeId, Size<Option<f32>>, Size<AvailableSpace>) -> Option<Size<f32>>,
{
    fn measure(
        &mut self,
        node: LayoutNodeId,
        known_dimensions: Size<Option<f32>>,
        available_space: Size<AvailableSpace>,
    ) -> Option<Size<f32>> {
        self(node, known_dimensions, available_space)
    }
}

/// Quantized hash key for [`TextMeasurementCache`] avoiding heap allocation and float formatting.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct TextMeasureKey {
    text: String,
    known_hundredths: Option<i64>,
    avail_tag: u8,
    avail_hundredths: i64,
    font_tenths: i64,
}

impl TextMeasureKey {
    fn from_inputs(
        text: &str,
        font_size: f32,
        known_dimensions: Size<Option<f32>>,
        available_space: Size<AvailableSpace>,
    ) -> Self {
        let (avail_tag, avail_hundredths) = match available_space.width {
            AvailableSpace::Definite(w) => (0, (w * 100.0).round() as i64),
            AvailableSpace::MinContent => (1, 0),
            AvailableSpace::MaxContent => (2, 0),
        };
        Self {
            text: text.to_owned(),
            known_hundredths: known_dimensions.width.map(|w| (w * 100.0).round() as i64),
            avail_tag,
            avail_hundredths,
            font_tenths: (font_size * 10.0).round() as i64,
        }
    }
}

/// Cache and evaluator for intrinsic text measurements with call counting and constraint caching.
#[derive(Debug, Clone, Default)]
pub struct TextMeasurementCache {
    measure_calls: usize,
    cache_hits: usize,
    cache: HashMap<TextMeasureKey, Size<f32>>,
}

impl TextMeasurementCache {
    /// Creates a new, empty text measurement cache.
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the number of measurement calculations performed.
    pub fn call_count(&self) -> usize {
        self.measure_calls
    }

    /// Returns the number of cache hits.
    pub fn cache_hits(&self) -> usize {
        self.cache_hits
    }

    /// Resets call and hit counters.
    pub fn reset_counts(&mut self) {
        self.measure_calls = 0;
        self.cache_hits = 0;
    }

    /// Clears all cached measurements.
    pub fn clear(&mut self) {
        self.cache.clear();
        self.reset_counts();
    }

    /// Measures text with line wrapping under available space constraints.
    ///
    /// - Unconstrained (`MaxContent` or width >= natural width): returns natural single-line dimensions.
    /// - Constrained (known width or `Definite` width < natural width): wraps text, expanding height.
    /// - Empty text (`""`): collapses width to 0.0 while preserving font line height.
    pub fn measure_text(
        &mut self,
        text: &str,
        font_size: f32,
        line_height: f32,
        known_dimensions: Size<Option<f32>>,
        available_space: Size<AvailableSpace>,
    ) -> Size<f32> {
        let key = TextMeasureKey::from_inputs(text, font_size, known_dimensions, available_space);

        if let Some(&cached) = self.cache.get(&key) {
            self.cache_hits += 1;
            return cached;
        }

        self.measure_calls += 1;

        if text.is_empty() {
            let res = Size::new(0.0, line_height);
            self.cache.insert(key, res);
            return res;
        }

        let char_width = font_size * 0.6;
        let natural_width = text.len() as f32 * char_width;

        let max_w = known_dimensions
            .width
            .or_else(|| available_space.width.into_option());

        let res = match max_w {
            Some(w) if w < natural_width && w > 0.0 => {
                let chars_per_line = ((w / char_width).floor() as usize).max(1);
                let lines = text.len().div_ceil(chars_per_line);
                Size::new(w, lines as f32 * line_height)
            }
            _ => Size::new(natural_width, line_height),
        };

        self.cache.insert(key, res);
        res
    }
}