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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
//! Native GUI owned layout types, geometry, and style specification.
//!
//! Provides backend-agnostic layout structures for the repository-owned layout engine.
//!
//! # Architecture
//!
//! - [`Style`]: Full 24-field layout style configuration (flexbox, grid, sizing, insets).
//! - [`Size`], [`Rect`], [`Point`], [`LayoutRect`]: Coordinate and geometry abstractions.
//! - [`Dimension`], [`LengthPercentage`], [`LengthPercentageAuto`]: Layout sizing units.
//! - [`Display`], [`Position`], [`FlexDirection`], [`FlexWrap`], [`AlignItems`],
//!   [`AlignSelf`], [`AlignContent`], [`JustifyContent`]: Layout flow enums.
//! - [`AvailableSpace`]: Space constraints for intrinsic measurement.

use crate::error::{GuiError, GuiResult};

pub mod box_sizing;
pub mod flex;
pub mod grid;
pub mod tree;

pub use box_sizing::{
    apply_relative_offset, compute_box_sizing, resolve_absolute_position, resolve_box_constraints,
    resolve_dimension, resolve_inset, resolve_margin, resolve_padding, BoxConstraints,
    BoxDimensions, Measurer, TextMeasurementCache, MAX_LAYOUT_DEPTH, STRICT_TOLERANCE_PX,
};
pub use flex::{compute_flex, compute_multi_line_flex, compute_single_line_flex, FlexItem};
pub use grid::compute_grid;
pub use tree::{
    AvailableSpaceKey, CachedLayout, LayoutCacheKey, LayoutMetrics, LayoutNode, LayoutNodeId,
    LayoutTree,
};

/// Available space passed to intrinsic measurement passes.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AvailableSpace {
    /// Definite available space in logical pixels.
    Definite(f32),
    /// Min-content sizing constraint.
    MinContent,
    /// Max-content sizing constraint.
    MaxContent,
}

impl AvailableSpace {
    /// Returns true if this available space is a definite dimension.
    pub fn is_definite(&self) -> bool {
        matches!(self, Self::Definite(_))
    }

    /// Converts to an optional definite length.
    pub fn into_option(self) -> Option<f32> {
        match self {
            Self::Definite(val) => Some(val),
            _ => None,
        }
    }
}

/// A 2D size with width and height components.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Size<T> {
    pub width: T,
    pub height: T,
}

impl<T> Size<T> {
    /// Creates a new `Size` with given width and height.
    pub const fn new(width: T, height: T) -> Self {
        Self { width, height }
    }
}

impl<T: Copy> Size<T> {
    /// Creates a new `Size` with both dimensions set to the same value.
    pub fn all(value: T) -> Self {
        Self {
            width: value,
            height: value,
        }
    }
}

impl Size<Dimension> {
    /// Creates a size where both width and height are `Auto`.
    pub fn auto() -> Self {
        Self {
            width: Dimension::Auto,
            height: Dimension::Auto,
        }
    }

    /// Creates a size with explicit length in logical pixels.
    pub fn from_lengths(width: f32, height: f32) -> Self {
        Self {
            width: Dimension::Length(width),
            height: Dimension::Length(height),
        }
    }
}

impl Size<LengthPercentage> {
    /// Creates a zero size `(0.0, 0.0)`.
    pub fn zero() -> Self {
        Self {
            width: LengthPercentage::Length(0.0),
            height: LengthPercentage::Length(0.0),
        }
    }
}

impl Size<f32> {
    /// Creates a zero size.
    pub const ZERO: Self = Self {
        width: 0.0,
        height: 0.0,
    };
}

/// A 2D point with x and y coordinates.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Point<T> {
    pub x: T,
    pub y: T,
}

impl<T> Point<T> {
    /// Creates a new `Point`.
    pub const fn new(x: T, y: T) -> Self {
        Self { x, y }
    }
}

impl Point<f32> {
    /// Creates a point at `(0.0, 0.0)`.
    pub const ZERO: Self = Self { x: 0.0, y: 0.0 };
}

/// A four-sided rect used for insets (padding, margin, inset).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Rect<T> {
    pub left: T,
    pub right: T,
    pub top: T,
    pub bottom: T,
}

impl<T> Rect<T> {
    /// Creates a new `Rect` with four explicit edges.
    pub const fn new(left: T, right: T, top: T, bottom: T) -> Self {
        Self {
            left,
            right,
            top,
            bottom,
        }
    }
}

impl<T: Copy> Rect<T> {
    /// Sets all four edges to the same value.
    pub fn all(value: T) -> Self {
        Self {
            left: value,
            right: value,
            top: value,
            bottom: value,
        }
    }

    /// Sets symmetric vertical and horizontal insets.
    pub fn symmetric(vertical: T, horizontal: T) -> Self {
        Self {
            left: horizontal,
            right: horizontal,
            top: vertical,
            bottom: vertical,
        }
    }
}

impl Rect<LengthPercentage> {
    /// Creates a zero rect with all edges at `Length(0.0)`.
    pub fn zero() -> Self {
        Self::all(LengthPercentage::Length(0.0))
    }
}

impl Rect<LengthPercentageAuto> {
    /// Creates a zero rect with all edges at `Length(0.0)`.
    pub fn zero() -> Self {
        Self::all(LengthPercentageAuto::Length(0.0))
    }

    /// Creates an auto rect with all edges at `Auto`.
    pub fn auto() -> Self {
        Self::all(LengthPercentageAuto::Auto)
    }
}

/// Computed layout rectangle in logical coordinates.
///
/// [`Ui::layout_rect`](crate::Ui::layout_rect) exposes widget rectangles in
/// parent-local coordinates; raw [`LayoutTree`] results are layout-root-relative.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LayoutRect {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

impl LayoutRect {
    /// Creates a new layout rectangle.
    pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    /// Creates a zero-sized layout rectangle at `(0.0, 0.0)`.
    pub const ZERO: Self = Self {
        x: 0.0,
        y: 0.0,
        width: 0.0,
        height: 0.0,
    };

    /// Returns the top-left position.
    pub fn location(&self) -> Point<f32> {
        Point::new(self.x, self.y)
    }

    /// Returns the size.
    pub fn size(&self) -> Size<f32> {
        Size::new(self.width, self.height)
    }
}

/// Sizing dimension supporting auto, explicit length, or percentage.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Dimension {
    #[default]
    Auto,
    Length(f32),
    Percent(f32),
}

impl Dimension {
    /// Returns `Dimension::Auto`.
    pub const fn auto() -> Self {
        Self::Auto
    }

    /// Returns `Dimension::Length(px)`.
    pub const fn length(px: f32) -> Self {
        Self::Length(px)
    }

    /// Returns `Dimension::Percent(pct)` where `pct = 1.0` is 100%.
    pub const fn percent(pct: f32) -> Self {
        Self::Percent(pct)
    }

    /// Returns true if this dimension is `Auto`.
    pub fn is_auto(&self) -> bool {
        matches!(self, Self::Auto)
    }

    /// Returns true if this dimension is an explicit `Length`.
    pub fn is_length(&self) -> bool {
        matches!(self, Self::Length(_))
    }

    /// Returns true if this dimension is a `Percent`.
    pub fn is_percent(&self) -> bool {
        matches!(self, Self::Percent(_))
    }

    /// Validates numeric values are finite.
    pub fn validate(&self) -> GuiResult<()> {
        match self {
            Self::Auto => Ok(()),
            Self::Length(v) | Self::Percent(v) => {
                if !v.is_finite() {
                    Err(GuiError::InvalidNumericInput)
                } else if *self == Self::Length(*v) && *v < 0.0 {
                    Err(GuiError::InvalidLayoutGeometry)
                } else {
                    Ok(())
                }
            }
        }
    }
}

/// Inset dimension supporting explicit length or percentage.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LengthPercentage {
    Length(f32),
    Percent(f32),
}

impl LengthPercentage {
    /// Returns `LengthPercentage::Length(px)`.
    pub const fn length(px: f32) -> Self {
        Self::Length(px)
    }

    /// Returns `LengthPercentage::Percent(pct)`.
    pub const fn percent(pct: f32) -> Self {
        Self::Percent(pct)
    }

    /// Returns true if this inset is an explicit `Length`.
    pub fn is_length(&self) -> bool {
        matches!(self, Self::Length(_))
    }

    /// Returns true if this inset is a `Percent`.
    pub fn is_percent(&self) -> bool {
        matches!(self, Self::Percent(_))
    }

    /// Returns the length in rounded integer pixels if this is an explicit `Length`, or 0 otherwise.
    pub fn to_i32_pixels(&self) -> i32 {
        match self {
            Self::Length(px) => px.max(0.0).round() as i32,
            _ => 0,
        }
    }

    /// Validates numeric values are finite and non-negative.
    pub fn validate(&self) -> GuiResult<()> {
        match self {
            Self::Length(v) | Self::Percent(v) => {
                if !v.is_finite() {
                    Err(GuiError::InvalidNumericInput)
                } else if *v < 0.0 {
                    Err(GuiError::InvalidLayoutGeometry)
                } else {
                    Ok(())
                }
            }
        }
    }
}

impl Default for LengthPercentage {
    fn default() -> Self {
        Self::Length(0.0)
    }
}

/// Inset dimension supporting auto, length, or percentage.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LengthPercentageAuto {
    #[default]
    Auto,
    Length(f32),
    Percent(f32),
}

impl LengthPercentageAuto {
    /// Returns `LengthPercentageAuto::Auto`.
    pub const fn auto() -> Self {
        Self::Auto
    }

    /// Returns `LengthPercentageAuto::Length(px)`.
    pub const fn length(px: f32) -> Self {
        Self::Length(px)
    }

    /// Returns `LengthPercentageAuto::Percent(pct)`.
    pub const fn percent(pct: f32) -> Self {
        Self::Percent(pct)
    }

    /// Returns true if this inset is `Auto`.
    pub fn is_auto(&self) -> bool {
        matches!(self, Self::Auto)
    }

    /// Returns true if this inset is an explicit `Length`.
    pub fn is_length(&self) -> bool {
        matches!(self, Self::Length(_))
    }

    /// Returns true if this inset is a `Percent`.
    pub fn is_percent(&self) -> bool {
        matches!(self, Self::Percent(_))
    }

    /// Returns the length in rounded integer pixels if this is an explicit `Length`, or 0 otherwise.
    pub fn to_i32_pixels(&self) -> i32 {
        match self {
            Self::Length(px) => px.max(0.0).round() as i32,
            _ => 0,
        }
    }

    /// Validates numeric values are finite. (Margins may be negative where intentional).
    pub fn validate(&self) -> GuiResult<()> {
        match self {
            Self::Auto => Ok(()),
            Self::Length(v) | Self::Percent(v) => {
                if !v.is_finite() {
                    Err(GuiError::InvalidNumericInput)
                } else {
                    Ok(())
                }
            }
        }
    }
}

/// Container display mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Display {
    #[default]
    Flex,
    Grid,
    None,
}

/// Item positioning mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Position {
    #[default]
    Relative,
    Absolute,
}

/// Direction of primary layout axis for flex containers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum FlexDirection {
    #[default]
    Row,
    Column,
    RowReverse,
    ColumnReverse,
}

impl FlexDirection {
    pub const ROW: Self = Self::Row;
    pub const COLUMN: Self = Self::Column;
    pub const ROW_REVERSE: Self = Self::RowReverse;
    pub const COLUMN_REVERSE: Self = Self::ColumnReverse;
}

/// Wrapping behavior along the flex axis.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum FlexWrap {
    #[default]
    NoWrap,
    Wrap,
    WrapReverse,
}

impl FlexWrap {
    pub const NO_WRAP: Self = Self::NoWrap;
    pub const WRAP: Self = Self::Wrap;
    pub const WRAP_REVERSE: Self = Self::WrapReverse;
}

/// Cross-axis alignment for items in flex or grid lines.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AlignItems {
    Start,
    End,
    Center,
    Baseline,
    Stretch,
}

impl AlignItems {
    pub const START: Self = Self::Start;
    pub const END: Self = Self::End;
    pub const CENTER: Self = Self::Center;
    pub const BASELINE: Self = Self::Baseline;
    pub const STRETCH: Self = Self::Stretch;
}

/// Cross-axis alignment override for individual items.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AlignSelf {
    Start,
    End,
    Center,
    Baseline,
    Stretch,
}

impl AlignSelf {
    pub const START: Self = Self::Start;
    pub const END: Self = Self::End;
    pub const CENTER: Self = Self::Center;
    pub const BASELINE: Self = Self::Baseline;
    pub const STRETCH: Self = Self::Stretch;
}

/// Cross-axis distribution of wrapped flex lines.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AlignContent {
    Start,
    End,
    Center,
    Stretch,
    SpaceBetween,
    SpaceAround,
    SpaceEvenly,
}

impl AlignContent {
    pub const START: Self = Self::Start;
    pub const END: Self = Self::End;
    pub const CENTER: Self = Self::Center;
    pub const STRETCH: Self = Self::Stretch;
    pub const SPACE_BETWEEN: Self = Self::SpaceBetween;
    pub const SPACE_AROUND: Self = Self::SpaceAround;
    pub const SPACE_EVENLY: Self = Self::SpaceEvenly;
}

/// Main-axis distribution of items.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum JustifyContent {
    Start,
    End,
    Center,
    Stretch,
    SpaceBetween,
    SpaceAround,
    SpaceEvenly,
}

impl JustifyContent {
    pub const START: Self = Self::Start;
    pub const END: Self = Self::End;
    pub const CENTER: Self = Self::Center;
    pub const STRETCH: Self = Self::Stretch;
    pub const SPACE_BETWEEN: Self = Self::SpaceBetween;
    pub const SPACE_AROUND: Self = Self::SpaceAround;
    pub const SPACE_EVENLY: Self = Self::SpaceEvenly;
}

/// Grid auto flow direction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum GridAutoFlow {
    #[default]
    Row,
    Column,
}

/// Grid track sizing function.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TrackSizingFunction {
    Fixed(f32),
    Percent(f32),
    Flex(f32),
    Auto,
    MinMax(Box<TrackSizingFunction>, Box<TrackSizingFunction>),
}

/// Grid item coordinate placement.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GridPlacement {
    pub start: i16,
    pub span: u16,
}

impl GridPlacement {
    /// Creates a placement with 1-based start line and span count.
    pub const fn new(start: i16, span: u16) -> Self {
        Self { start, span }
    }
}

/// Complete layout style specification.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Style {
    pub display: Display,
    pub position: Position,
    pub size: Size<Dimension>,
    pub min_size: Size<Dimension>,
    pub max_size: Size<Dimension>,
    pub aspect_ratio: Option<f32>,
    pub padding: Rect<LengthPercentage>,
    pub margin: Rect<LengthPercentageAuto>,
    pub inset: Rect<LengthPercentageAuto>,
    pub flex_direction: FlexDirection,
    pub flex_wrap: FlexWrap,
    pub flex_grow: f32,
    pub flex_shrink: f32,
    pub flex_basis: Dimension,
    pub gap: Size<LengthPercentage>,
    pub align_items: Option<AlignItems>,
    pub align_self: Option<AlignSelf>,
    pub justify_items: Option<AlignItems>,
    pub justify_self: Option<AlignSelf>,
    pub align_content: Option<AlignContent>,
    pub justify_content: Option<JustifyContent>,
    pub grid_template_rows: Vec<TrackSizingFunction>,
    pub grid_template_columns: Vec<TrackSizingFunction>,
    pub grid_auto_rows: Vec<TrackSizingFunction>,
    pub grid_auto_columns: Vec<TrackSizingFunction>,
    pub grid_auto_flow: GridAutoFlow,
    pub grid_row: GridPlacement,
    pub grid_column: GridPlacement,
}

impl Default for Style {
    fn default() -> Self {
        Self {
            display: Display::Flex,
            position: Position::Relative,
            size: Size::auto(),
            min_size: Size::auto(),
            max_size: Size::auto(),
            aspect_ratio: None,
            padding: Rect::<LengthPercentage>::zero(),
            margin: Rect::<LengthPercentageAuto>::zero(),
            inset: Rect::auto(),
            flex_direction: FlexDirection::Row,
            flex_wrap: FlexWrap::NoWrap,
            flex_grow: 0.0,
            flex_shrink: 1.0,
            flex_basis: Dimension::Auto,
            gap: Size::zero(),
            align_items: None,
            align_self: None,
            justify_items: None,
            justify_self: None,
            align_content: None,
            justify_content: None,
            grid_template_rows: Vec::new(),
            grid_template_columns: Vec::new(),
            grid_auto_rows: Vec::new(),
            grid_auto_columns: Vec::new(),
            grid_auto_flow: GridAutoFlow::Row,
            grid_row: GridPlacement::default(),
            grid_column: GridPlacement::default(),
        }
    }
}

impl Style {
    /// Validates all numeric constraints and properties.
    pub fn validate(&self) -> GuiResult<()> {
        if let Some(ratio) = self.aspect_ratio {
            if !ratio.is_finite() || ratio <= 0.0 {
                return Err(GuiError::InvalidNumericInput);
            }
        }
        if !self.flex_grow.is_finite() || self.flex_grow < 0.0 {
            return Err(GuiError::InvalidNumericInput);
        }
        if !self.flex_shrink.is_finite() || self.flex_shrink < 0.0 {
            return Err(GuiError::InvalidNumericInput);
        }

        self.size.width.validate()?;
        self.size.height.validate()?;
        self.min_size.width.validate()?;
        self.min_size.height.validate()?;
        self.max_size.width.validate()?;
        self.max_size.height.validate()?;

        self.padding.left.validate()?;
        self.padding.right.validate()?;
        self.padding.top.validate()?;
        self.padding.bottom.validate()?;

        self.gap.width.validate()?;
        self.gap.height.validate()?;

        self.margin.left.validate()?;
        self.margin.right.validate()?;
        self.margin.top.validate()?;
        self.margin.bottom.validate()?;

        self.inset.left.validate()?;
        self.inset.right.validate()?;
        self.inset.top.validate()?;
        self.inset.bottom.validate()?;

        self.flex_basis.validate()?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_style_defaults_and_validation() {
        let style = Style::default();
        assert_eq!(style.display, Display::Flex);
        assert_eq!(style.flex_grow, 0.0);
        assert_eq!(style.flex_shrink, 1.0);
        assert!(style.validate().is_ok());
    }

    #[test]
    fn test_style_validation_rejects_nan_and_negative_dimensions() {
        let mut style = Style {
            flex_grow: -1.0,
            ..Style::default()
        };
        assert_eq!(style.validate(), Err(GuiError::InvalidNumericInput));

        style.flex_grow = f32::NAN;
        assert_eq!(style.validate(), Err(GuiError::InvalidNumericInput));

        style = Style {
            size: Size {
                width: Dimension::Length(-10.0),
                ..Size::auto()
            },
            ..Style::default()
        };
        assert_eq!(style.validate(), Err(GuiError::InvalidLayoutGeometry));

        style = Style {
            aspect_ratio: Some(-2.0),
            ..Style::default()
        };
        assert_eq!(style.validate(), Err(GuiError::InvalidNumericInput));
    }

    #[test]
    fn test_layout_rect_helpers() {
        let rect = LayoutRect::new(10.0, 20.0, 300.0, 200.0);
        assert_eq!(rect.location(), Point::new(10.0, 20.0));
        assert_eq!(rect.size(), Size::new(300.0, 200.0));
    }
}