native-theme 0.6.1

Cross-platform native theme detection and loading for Rust GUI applications
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
// Helper functions, range-check utilities, and ValidateNested trait for validate().
//
// Extracted from validate.rs to keep the orchestration module focused on
// defaults extraction, per-widget dispatch, and construction.
//
// Phase 93-01 (G1): `require<T: Clone>` takes an explicit `fallback: T`
// instead of requiring `T: Default`, breaking the bound chain that forced
// `impl Default for Rgba`. See `fn require` below for details.

use crate::Rgba;
use crate::model::border::{ResolvedPadding, ResolvedWidgetBorder, WidgetBorderSpec};
use crate::model::font::FontStyle;
use crate::model::{FontSpec, ResolvedFontSpec};
use std::sync::Arc;

/// Standard screen DPI (96 dots per inch). Used as the font_dpi fallback
/// when no DPI was set on the unresolved variant (e.g. community presets
/// loaded standalone without OS reader). This matches the CSS/Web reference
/// pixel and the Windows default. Validation uses this to convert
/// `FontSize::Pt` values to logical pixels via `FontSize::to_logical_px(dpi)`.
pub(crate) const DEFAULT_FONT_DPI: f32 = 96.0;

/// Empty `Arc<str>` placeholder used as the sentinel for missing font-family
/// fields. Never observed by user code: `validate()` returns `Err` whenever
/// any field was recorded as missing.
fn empty_arc_str() -> Arc<str> {
    Arc::<str>::from("")
}

/// Construct the zero-value sentinel for `ResolvedFontSpec`. Fields mirror
/// the pre-G1 `ResolvedFontSpec::default()` output (empty family, 0.0 size,
/// 0 weight, `FontStyle::Normal`, `Rgba::TRANSPARENT`).
fn resolved_font_spec_sentinel() -> ResolvedFontSpec {
    ResolvedFontSpec {
        family: empty_arc_str(),
        size: 0.0,
        defined_size: None,
        weight: 0,
        style: FontStyle::Normal,
        color: Rgba::TRANSPARENT,
    }
}

/// Construct the placeholder sentinel for `ResolvedWidgetBorder`
/// (TRANSPARENT color, 0.0 geometry, false shadow, every padding side
/// unstated). Never observed by user code: `validate()` returns `Err`
/// whenever a required border was recorded as missing.
fn resolved_widget_border_sentinel() -> ResolvedWidgetBorder {
    ResolvedWidgetBorder {
        color: Rgba::TRANSPARENT,
        corner_radius: 0.0,
        line_width: 0.0,
        shadow_enabled: false,
        padding: ResolvedPadding::default(),
    }
}

/// A widget border's padding sides, each as the theme states it: `None`
/// where it states nothing.
fn padding_of(b: &WidgetBorderSpec) -> ResolvedPadding {
    ResolvedPadding {
        top: b.padding_top,
        right: b.padding_right,
        bottom: b.padding_bottom,
        left: b.padding_left,
    }
}

// --- validate() helpers ---

/// Extract a required field, recording the path if missing.
///
/// Returns the value if present, or the caller-supplied `fallback` as a
/// placeholder if missing. The placeholder is never observed: `validate()`
/// returns `Err` before constructing `ResolvedTheme` whenever any field was
/// recorded as missing.
///
/// Callers supply `fallback` as an explicit sentinel (e.g.
/// [`crate::color::Rgba::TRANSPARENT`], `0.0_f32`, `false`). This lets the
/// function stay bound-free (`T: Clone` only) -- in particular, no `Default`
/// bound is required on `T`, so types like [`crate::color::Rgba`] do not
/// need `impl Default`.
pub(crate) fn require<T: Clone>(
    field: &Option<T>,
    path: &str,
    missing: &mut Vec<String>,
    fallback: T,
) -> T {
    match field {
        Some(val) => val.clone(),
        None => {
            missing.push(path.to_string());
            fallback
        }
    }
}

/// Validate a FontSpec that is stored directly (not wrapped in Option).
/// Checks each sub-field individually. Converts `FontSize` to `f32` px via `to_logical_px(dpi)`.
pub(crate) fn require_font(
    font: &FontSpec,
    prefix: &str,
    dpi: f32,
    missing: &mut Vec<String>,
) -> ResolvedFontSpec {
    let family = require(
        &font.family,
        &format!("{prefix}.family"),
        missing,
        empty_arc_str(),
    );
    let size = font
        .size
        .map(|fs| fs.to_logical_px(dpi))
        .unwrap_or_else(|| {
            missing.push(format!("{prefix}.size"));
            0.0
        });
    let weight_fallback: u16 = 0;
    let weight = require(
        &font.weight,
        &format!("{prefix}.weight"),
        missing,
        weight_fallback,
    );
    let color = require(
        &font.color,
        &format!("{prefix}.color"),
        missing,
        Rgba::TRANSPARENT,
    );
    ResolvedFontSpec {
        family,
        size,
        defined_size: font.size,
        weight,
        // `style` is inherently optional: `FontStyle::Normal` is the universally-safe
        // default when a theme omits italic/oblique. Unlike `family`, `size`, `weight`,
        // and `color` -- which have no safe universal default -- `style` can always
        // fall back to Normal without producing an incorrect rendering. This asymmetry
        // is intentional (doc 2 D1).
        style: font.style.unwrap_or(FontStyle::Normal),
        color,
    }
}

/// Validate an `Option<FontSpec>` (widget font fields).
/// If None, records the path as missing. Converts `FontSize` to `f32` px via `to_logical_px(dpi)`.
pub(crate) fn require_font_opt(
    font: &Option<FontSpec>,
    prefix: &str,
    dpi: f32,
    missing: &mut Vec<String>,
) -> ResolvedFontSpec {
    match font {
        None => {
            missing.push(prefix.to_string());
            resolved_font_spec_sentinel()
        }
        Some(f) => {
            let family = require(
                &f.family,
                &format!("{prefix}.family"),
                missing,
                empty_arc_str(),
            );
            let size = f.size.map(|fs| fs.to_logical_px(dpi)).unwrap_or_else(|| {
                missing.push(format!("{prefix}.size"));
                0.0
            });
            let weight_fallback: u16 = 0;
            let weight = require(
                &f.weight,
                &format!("{prefix}.weight"),
                missing,
                weight_fallback,
            );
            let color = require(
                &f.color,
                &format!("{prefix}.color"),
                missing,
                Rgba::TRANSPARENT,
            );
            ResolvedFontSpec {
                family,
                size,
                defined_size: f.size,
                weight,
                // `style` is inherently optional: `FontStyle::Normal` is the universally-safe
                // default when a theme omits italic/oblique (see require_font for full rationale).
                style: f.style.unwrap_or(FontStyle::Normal),
                color,
            }
        }
    }
}

/// Validate an `Option<TextScaleEntry>`.
/// Converts `FontSize` to `f32` px via `to_logical_px(dpi)`. Also converts `line_height`
/// when the sibling `size` is in points (same unit, same DPI factor).
pub(crate) fn require_text_scale_entry(
    entry: &Option<crate::model::TextScaleEntry>,
    prefix: &str,
    dpi: f32,
    missing: &mut Vec<String>,
) -> crate::model::resolved::ResolvedTextScaleEntry {
    match entry {
        None => {
            missing.push(prefix.to_string());
            crate::model::resolved::ResolvedTextScaleEntry {
                size: 0.0,
                weight: 0,
                line_height: 0.0,
            }
        }
        Some(e) => {
            let size = e.size.map(|fs| fs.to_logical_px(dpi)).unwrap_or_else(|| {
                missing.push(format!("{prefix}.size"));
                0.0
            });
            let line_height = e
                .line_height
                .map(|fs| fs.to_logical_px(dpi))
                .unwrap_or_else(|| {
                    missing.push(format!("{prefix}.line_height"));
                    0.0
                });
            let weight_fallback: u16 = 0;
            let weight = require(
                &e.weight,
                &format!("{prefix}.weight"),
                missing,
                weight_fallback,
            );
            crate::model::resolved::ResolvedTextScaleEntry {
                size,
                weight,
                line_height,
            }
        }
    }
}

/// Which border sub-fields are required vs optional for a given widget.
///
/// Drives `validate_border()` dispatch. Each widget declares its border kind
/// via `#[theme_layer(border_kind = "...")]` on the struct; the proc-macro
/// emits the corresponding `BorderKind` variant in generated `validate_widget()`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BorderKind {
    /// All 4 inherited sub-fields required (color, corner_radius, line_width, shadow_enabled).
    /// Used by: window, button, input, checkbox, tooltip, progress_bar, toolbar,
    /// list, popover, dialog, combo_box, segmented_control, expander.
    Full,
    /// Only color + line_width required; corner_radius and shadow_enabled optional.
    /// Used by: sidebar, status_bar.
    Partial,
    /// All sub-fields optional — no validation errors recorded.
    /// Used by: menu, tab, card.
    None,
}

/// Validate an `Option<WidgetBorderSpec>` according to its `BorderKind`.
///
/// - `Full`: requires color, corner_radius, line_width, shadow_enabled.
/// - `Partial`: requires color and line_width only.
/// - `None`: all sub-fields optional, no missing-field errors.
///
/// Padding sides are sizing fields with no inheritance: each side is the
/// value the theme states, or `None` where it states none.
pub(crate) fn validate_border(
    border: &Option<WidgetBorderSpec>,
    prefix: &str,
    kind: BorderKind,
    missing: &mut Vec<String>,
) -> ResolvedWidgetBorder {
    match kind {
        BorderKind::None => match border {
            Option::None => resolved_widget_border_sentinel(),
            Some(b) => ResolvedWidgetBorder {
                // `b.color: Option<Rgba>`. Once `impl Default for Rgba` is
                // removed in Task 2, `Option::unwrap_or_default()` can no
                // longer synthesise an Rgba. Pass TRANSPARENT explicitly
                // (same value as the old `Rgba::default()`).
                color: b.color.unwrap_or(Rgba::TRANSPARENT),
                corner_radius: b.corner_radius.unwrap_or_default(),
                line_width: b.line_width.unwrap_or_default(),
                shadow_enabled: b.shadow_enabled.unwrap_or_default(),
                padding: padding_of(b),
            },
        },
        BorderKind::Full | BorderKind::Partial => match border {
            Option::None => {
                missing.push(prefix.to_string());
                resolved_widget_border_sentinel()
            }
            Some(b) => {
                let color = require(
                    &b.color,
                    &format!("{prefix}.color"),
                    missing,
                    Rgba::TRANSPARENT,
                );
                let zero_width: f32 = 0.0;
                let line_width = require(
                    &b.line_width,
                    &format!("{prefix}.line_width"),
                    missing,
                    zero_width,
                );

                let (corner_radius, shadow_enabled) = if kind == BorderKind::Full {
                    let zero_radius: f32 = 0.0;
                    (
                        require(
                            &b.corner_radius,
                            &format!("{prefix}.corner_radius"),
                            missing,
                            zero_radius,
                        ),
                        require(
                            &b.shadow_enabled,
                            &format!("{prefix}.shadow_enabled"),
                            missing,
                            false,
                        ),
                    )
                } else {
                    (
                        b.corner_radius.unwrap_or_default(),
                        b.shadow_enabled.unwrap_or_default(),
                    )
                };

                ResolvedWidgetBorder {
                    color,
                    corner_radius,
                    line_width,
                    shadow_enabled,
                    padding: padding_of(b),
                }
            }
        },
    }
}

// --- Range-check helpers for validate() ---
//
// These push `RangeViolation` structs to the `errors` vec so that range
// violations are reported as structured data, separate from missing fields.

/// Check that an `f32` value is finite and non-negative (>= 0.0).
///
/// Path string (`"{prefix}.{field}"`) is only formatted in the error branch,
/// so the happy path (value in range) allocates zero strings.
pub(crate) fn check_non_negative(
    value: f32,
    prefix: &str,
    field: &str,
    errors: &mut Vec<crate::error::RangeViolation>,
) {
    if !value.is_finite() || value < 0.0 {
        errors.push(crate::error::RangeViolation {
            path: format!("{prefix}.{field}"),
            value: value as f64,
            min: Some(0.0),
            max: None,
        });
    }
}

/// Check that an `f32` value is finite and strictly positive (> 0.0).
///
/// Path string (`"{prefix}.{field}"`) is only formatted in the error branch,
/// so the happy path (value in range) allocates zero strings.
pub(crate) fn check_positive(
    value: f32,
    prefix: &str,
    field: &str,
    errors: &mut Vec<crate::error::RangeViolation>,
) {
    if !value.is_finite() || value <= 0.0 {
        errors.push(crate::error::RangeViolation {
            path: format!("{prefix}.{field}"),
            value: value as f64,
            min: Some(f64::MIN_POSITIVE),
            max: None,
        });
    }
}

/// Check that an `f32` value is finite and falls within an inclusive range.
///
/// Path string (`"{prefix}.{field}"`) is only formatted in the error branch,
/// so the happy path (value in range) allocates zero strings.
pub(crate) fn check_range_f32(
    value: f32,
    min: f32,
    max: f32,
    prefix: &str,
    field: &str,
    errors: &mut Vec<crate::error::RangeViolation>,
) {
    if !value.is_finite() || value < min || value > max {
        errors.push(crate::error::RangeViolation {
            path: format!("{prefix}.{field}"),
            value: value as f64,
            min: Some(min as f64),
            max: Some(max as f64),
        });
    }
}

/// Check that a `u16` value falls within an inclusive range.
///
/// Path string (`"{prefix}.{field}"`) is only formatted in the error branch,
/// so the happy path (value in range) allocates zero strings.
pub(crate) fn check_range_u16(
    value: u16,
    min: u16,
    max: u16,
    prefix: &str,
    field: &str,
    errors: &mut Vec<crate::error::RangeViolation>,
) {
    if value < min || value > max {
        errors.push(crate::error::RangeViolation {
            path: format!("{prefix}.{field}"),
            value: value as f64,
            min: Some(min as f64),
            max: Some(max as f64),
        });
    }
}

/// Check that a min value does not exceed its corresponding max value.
///
/// Path string (`"{prefix}.{min_field}"`) is only formatted in the error branch,
/// so the happy path (min <= max) allocates zero strings.
pub(crate) fn check_min_max(
    min_val: f32,
    max_val: f32,
    prefix: &str,
    min_field: &str,
    _max_field: &str,
    errors: &mut Vec<crate::error::RangeViolation>,
) {
    if min_val > max_val {
        errors.push(crate::error::RangeViolation {
            path: format!("{prefix}.{min_field}"),
            value: min_val as f64,
            min: None,
            max: Some(max_val as f64),
        });
    }
}

/// Check that every padding side a widget border states is finite and
/// non-negative. An unstated side is not checked. Paths name the model's
/// side fields: `"{prefix}.{field}.padding_left"`.
pub(crate) fn check_padding(
    padding: &ResolvedPadding,
    prefix: &str,
    field: &str,
    errors: &mut Vec<crate::error::RangeViolation>,
) {
    let sides = [
        ("padding_top", padding.top),
        ("padding_right", padding.right),
        ("padding_bottom", padding.bottom),
        ("padding_left", padding.left),
    ];
    for (side, value) in sides {
        if let Some(value) = value
            && (!value.is_finite() || value < 0.0)
        {
            errors.push(crate::error::RangeViolation {
                path: format!("{prefix}.{field}.{side}"),
                value: value as f64,
                min: Some(0.0),
                max: None,
            });
        }
    }
}

/// Trait for nested types that can be validated from an Option wrapper.
/// Used by `define_widget_pair!` generated `validate_widget()` methods
/// to dispatch to the correct extraction function without knowing the
/// concrete type at macro expansion time.
pub(crate) trait ValidateNested {
    /// The resolved (non-Option) output type.
    type Resolved;

    /// Extract from `Option<Self>`, recording missing fields in `missing`.
    fn validate_nested(
        source: &Option<Self>,
        prefix: &str,
        dpi: f32,
        missing: &mut Vec<String>,
    ) -> Self::Resolved
    where
        Self: Sized;
}

impl ValidateNested for FontSpec {
    type Resolved = ResolvedFontSpec;
    fn validate_nested(
        source: &Option<Self>,
        prefix: &str,
        dpi: f32,
        missing: &mut Vec<String>,
    ) -> ResolvedFontSpec {
        require_font_opt(source, prefix, dpi, missing)
    }
}

impl ValidateNested for WidgetBorderSpec {
    type Resolved = ResolvedWidgetBorder;
    fn validate_nested(
        source: &Option<Self>,
        prefix: &str,
        _dpi: f32,
        missing: &mut Vec<String>,
    ) -> ResolvedWidgetBorder {
        validate_border(source, prefix, BorderKind::Full, missing)
    }
}

// --- Declarative macros for defaults/text_scale extraction ---

/// Extract all defaults fields and construct `ResolvedDefaults` in one invocation.
///
/// Handles five extraction patterns:
/// - **font**: non-Option `FontSpec` fields via `require_font()`.
/// - **option_color**: `Option<Rgba>` fields via `require()` with
///   `Rgba::TRANSPARENT` fallback.
/// - **option_f32**: `Option<f32>` fields via `require()` with `0.0_f32`
///   fallback.
/// - **border_required**: `Option<T>` fields nested under `defaults.border`
///   with per-field fallback expressions supplied at the call site
///   (Rgba / f32 / bool).
/// - **icon_sizes**: `Option<f32>` fields nested under `defaults.icon_sizes`
///   via `require()` with `0.0_f32` fallback.
///
/// The split between `option_color` and `option_f32` is intentional: after
/// G1 removes `impl Default for Rgba`, there is no uniform way for the
/// macro to synthesise a per-field fallback without a sealed
/// `Default`-equivalent trait. Encoding the type group at the macro call
/// site keeps the fallback sentinel construction local and explicit.
///
/// `defaults.border` has no padding: padding is a widget-level field
/// (`ResolvedWidgetBorder::padding`).
macro_rules! validate_defaults {
    (
        $src:expr, $dpi:expr, $missing:expr;
        font { $($font_field:ident),* $(,)? }
        option_color { $($color_field:ident),* $(,)? }
        option_f32 { $($f32_field:ident),* $(,)? }
        border_required { $($br_field:ident : $br_fallback:expr),* $(,)? }
        icon_sizes { $($is_field:ident),* $(,)? }
    ) => {{
        use $crate::resolve::validate_helpers::{require, require_font};
        // Pattern B: font fields (non-Option FontSpec -> ResolvedFontSpec)
        $(
            let $font_field = require_font(
                &$src.defaults.$font_field,
                concat!("defaults.", stringify!($font_field)),
                $dpi,
                $missing,
            );
        )*
        // Pattern A1: Option<Rgba> fields
        $(
            let $color_field = require(
                &$src.defaults.$color_field,
                concat!("defaults.", stringify!($color_field)),
                $missing,
                $crate::color::Rgba::TRANSPARENT,
            );
        )*
        // Pattern A2: Option<f32> fields
        $(
            let $f32_field = require(
                &$src.defaults.$f32_field,
                concat!("defaults.", stringify!($f32_field)),
                $missing,
                0.0_f32,
            );
        )*
        // Pattern C: border sub-fields (require'd, with explicit per-field fallback)
        $(
            let $br_field = require(
                &$src.defaults.border.$br_field,
                concat!("defaults.border.", stringify!($br_field)),
                $missing,
                $br_fallback,
            );
        )*
        // Pattern D: icon_sizes sub-fields (Option<f32>)
        $(
            let $is_field = require(
                &$src.defaults.icon_sizes.$is_field,
                concat!("defaults.icon_sizes.", stringify!($is_field)),
                $missing,
                0.0_f32,
            );
        )*

        use $crate::model::border::ResolvedDefaultsBorder;
        use $crate::model::resolved::{ResolvedDefaults, ResolvedIconSizes};
        ResolvedDefaults {
            $($font_field,)*
            $($color_field,)*
            $($f32_field,)*
            border: ResolvedDefaultsBorder {
                $($br_field,)*
            },
            icon_sizes: ResolvedIconSizes {
                $($is_field,)*
            },
        }
    }};
}
pub(crate) use validate_defaults;

/// Extract all text_scale fields and construct `ResolvedTextScale` in one invocation.
///
/// Each field is an `Option<TextScaleEntry>` extracted via `require_text_scale_entry()`.
macro_rules! validate_text_scale {
    ($src:expr, $dpi:expr, $missing:expr; $($field:ident),* $(,)?) => {{
        use $crate::resolve::validate_helpers::require_text_scale_entry;
        $(
            let $field = require_text_scale_entry(
                &$src.text_scale.$field,
                concat!("text_scale.", stringify!($field)),
                $dpi,
                $missing,
            );
        )*
        $crate::model::resolved::ResolvedTextScale { $($field),* }
    }};
}
pub(crate) use validate_text_scale;

/// Validate defaults and text_scale range checks.
///
/// This centralizes all the range-check calls for the global defaults
/// and the text_scale entries that were previously inline in validate().
pub(crate) fn check_defaults_ranges(
    defaults: &crate::model::resolved::ResolvedDefaults,
    text_scale: &crate::model::resolved::ResolvedTextScale,
    errors: &mut Vec<crate::error::RangeViolation>,
) {
    // Fonts: size > 0, weight 100..=900
    check_positive(defaults.font.size, "defaults.font", "size", errors);
    check_range_u16(
        defaults.font.weight,
        100,
        900,
        "defaults.font",
        "weight",
        errors,
    );
    check_positive(
        defaults.mono_font.size,
        "defaults.mono_font",
        "size",
        errors,
    );
    check_range_u16(
        defaults.mono_font.weight,
        100,
        900,
        "defaults.mono_font",
        "weight",
        errors,
    );

    // defaults: line_height > 0
    check_positive(defaults.line_height, "defaults", "line_height", errors);

    // defaults: radius, geometry >= 0
    check_non_negative(
        defaults.border.corner_radius,
        "defaults.border",
        "corner_radius",
        errors,
    );
    check_non_negative(
        defaults.border.corner_radius_lg,
        "defaults.border",
        "corner_radius_lg",
        errors,
    );
    check_non_negative(
        defaults.border.line_width,
        "defaults.border",
        "line_width",
        errors,
    );
    check_non_negative(
        defaults.focus_ring_width,
        "defaults",
        "focus_ring_width",
        errors,
    );
    // Note: focus_ring_offset is intentionally NOT range-checked -- negative values
    // mean an inset focus ring (e.g., adwaita uses -2.0, macOS uses -1.0).

    // defaults: opacity 0..=1
    check_range_f32(
        defaults.disabled_opacity,
        0.0,
        1.0,
        "defaults",
        "disabled_opacity",
        errors,
    );
    check_range_f32(
        defaults.border.opacity,
        0.0,
        1.0,
        "defaults.border",
        "opacity",
        errors,
    );

    // defaults: icon sizes >= 0
    check_non_negative(
        defaults.icon_sizes.toolbar,
        "defaults.icon_sizes",
        "toolbar",
        errors,
    );
    check_non_negative(
        defaults.icon_sizes.small,
        "defaults.icon_sizes",
        "small",
        errors,
    );
    check_non_negative(
        defaults.icon_sizes.large,
        "defaults.icon_sizes",
        "large",
        errors,
    );
    check_non_negative(
        defaults.icon_sizes.dialog,
        "defaults.icon_sizes",
        "dialog",
        errors,
    );
    check_non_negative(
        defaults.icon_sizes.panel,
        "defaults.icon_sizes",
        "panel",
        errors,
    );

    // text_scale: entry sizes > 0, line_height > 0
    check_positive(
        text_scale.caption.size,
        "text_scale.caption",
        "size",
        errors,
    );
    check_positive(
        text_scale.caption.line_height,
        "text_scale.caption",
        "line_height",
        errors,
    );
    check_range_u16(
        text_scale.caption.weight,
        100,
        900,
        "text_scale.caption",
        "weight",
        errors,
    );
    check_positive(
        text_scale.section_heading.size,
        "text_scale.section_heading",
        "size",
        errors,
    );
    check_positive(
        text_scale.section_heading.line_height,
        "text_scale.section_heading",
        "line_height",
        errors,
    );
    check_range_u16(
        text_scale.section_heading.weight,
        100,
        900,
        "text_scale.section_heading",
        "weight",
        errors,
    );
    check_positive(
        text_scale.dialog_title.size,
        "text_scale.dialog_title",
        "size",
        errors,
    );
    check_positive(
        text_scale.dialog_title.line_height,
        "text_scale.dialog_title",
        "line_height",
        errors,
    );
    check_range_u16(
        text_scale.dialog_title.weight,
        100,
        900,
        "text_scale.dialog_title",
        "weight",
        errors,
    );
    check_positive(
        text_scale.display.size,
        "text_scale.display",
        "size",
        errors,
    );
    check_positive(
        text_scale.display.line_height,
        "text_scale.display",
        "line_height",
        errors,
    );
    check_range_u16(
        text_scale.display.weight,
        100,
        900,
        "text_scale.display",
        "weight",
        errors,
    );
}