native-theme 0.7.0

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
// Font specification and text scale types

use std::collections::HashSet;
use std::sync::{Arc, Mutex};

use crate::Rgba;
use native_theme_derive::ThemeFields;
use serde::{Deserialize, Serialize};

/// Global font family intern cache.
///
/// Stores `Arc<str>` values so that repeated calls with the same family name
/// return clones of the same `Arc`, avoiding redundant allocations.
static FONT_FAMILY_CACHE: std::sync::LazyLock<Mutex<HashSet<Arc<str>>>> =
    std::sync::LazyLock::new(|| Mutex::new(HashSet::new()));

/// Intern a font family name, returning a deduplicated `Arc<str>`.
///
/// If the same family name has been interned before, returns a clone of the
/// existing `Arc<str>` (same allocation, bumped reference count). Otherwise,
/// creates a new `Arc<str>` and caches it for future lookups.
///
/// This is useful for connectors that resolve fonts repeatedly -- calling
/// `intern_font_family("Inter")` 100 times allocates only once.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// use native_theme::theme::intern_font_family;
///
/// let a = intern_font_family("Inter");
/// let b = intern_font_family("Inter");
/// assert!(Arc::ptr_eq(&a, &b)); // Same allocation
/// ```
///
/// # Panics
///
/// This function does not panic. If the internal mutex is poisoned (which
/// can only happen if a thread panicked while holding it), a fresh `Arc<str>`
/// is returned without caching.
pub fn intern_font_family(family: &str) -> Arc<str> {
    if let Ok(mut cache) = FONT_FAMILY_CACHE.lock() {
        if let Some(existing) = cache.get(family) {
            return Arc::clone(existing);
        }
        let arc: Arc<str> = Arc::from(family);
        cache.insert(Arc::clone(&arc));
        arc
    } else {
        // Mutex poisoned -- degrade gracefully without caching
        Arc::from(family)
    }
}

/// Font style: upright, italic, or oblique.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FontStyle {
    /// Normal upright text.
    #[default]
    Normal,
    /// Italic text (true italic glyph).
    Italic,
    /// Oblique text (slanted upright glyph).
    Oblique,
}

/// A font size with an explicit unit.
///
/// In TOML presets, this appears as either `size_pt` (typographic points)
/// or `size_px` (logical pixels). That mapping is done by the parent structs
/// (`FontSpec`, `TextScaleEntry`); `FontSize` derives `Serialize` and
/// `Deserialize` of its own for [`ResolvedFontSpec::defined_size`].
///
/// During validation, all `FontSize` values are converted to logical pixels
/// via `FontSize::to_logical_px(dpi)`, producing a plain `f32` for the resolved model.
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum FontSize {
    /// Typographic points (1/72 inch). Stated by the OS readers (KDE, GNOME,
    /// macOS, Windows) and by the platform presets other than Material
    /// (Adwaita, KDE Breeze, macOS, Windows 11, iOS).
    /// Converted to px during validation: `px = pt * dpi / 72`.
    Pt(f32),
    /// Logical pixels. Stated by the Material platform preset and the
    /// community colour-scheme presets (Catppuccin, Dracula, Gruvbox, Nord,
    /// One Dark, Solarized, Tokyo Night).
    Px(f32),
}

impl FontSize {
    /// Convert to logical pixels.
    ///
    /// - `Pt(v)` -> `v * dpi / 72.0` (DPI matters)
    /// - `Px(v)` -> `v` (already logical pixels, DPI ignored)
    ///
    /// The name `to_logical_px` makes the asymmetry explicit: `Px` values
    /// are already in logical pixels, so the DPI parameter has no effect.
    ///
    /// # Examples
    ///
    /// ```
    /// use native_theme::theme::FontSize;
    ///
    /// // Pt branch: DPI affects the result
    /// let pt_size = FontSize::Pt(10.0);
    /// assert_eq!(pt_size.to_logical_px(96.0), 10.0 * 96.0 / 72.0);
    /// assert_eq!(pt_size.to_logical_px(72.0), 10.0); // identity at 72 DPI
    ///
    /// // Px branch: DPI is ignored, value returned unchanged
    /// let px_size = FontSize::Px(14.0);
    /// assert_eq!(px_size.to_logical_px(96.0), 14.0);
    /// assert_eq!(px_size.to_logical_px(144.0), 14.0); // same regardless of DPI
    /// ```
    pub fn to_logical_px(self, dpi: f32) -> f32 {
        match self {
            Self::Pt(v) => v * dpi / 72.0,
            Self::Px(v) => v,
        }
    }

    /// Return the raw numeric value regardless of unit.
    /// Used during inheritance to compute derived values (e.g. line_height)
    /// before unit conversion.
    pub fn raw(self) -> f32 {
        match self {
            Self::Pt(v) | Self::Px(v) => v,
        }
    }

    /// True when the value is in typographic points.
    pub fn is_pt(self) -> bool {
        matches!(self, Self::Pt(_))
    }
}

/// Font specification: family name, size, weight, style, and color.
///
/// All fields are optional to support partial overlays -- a FontSpec with
/// only `size` set will only override the size when merged.
///
/// **Default behavior asymmetry:** During validation, `family`, `size`,
/// `weight`, and `color` are required (missing values produce a validation
/// error). `style` silently defaults to [`FontStyle::Normal`] because
/// Normal is the universally-safe default -- no theme ever intends to
/// leave style undefined in a way that would produce incorrect rendering.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
#[serde(try_from = "FontSpecRaw", into = "FontSpecRaw")]
// Phase 93-05 G5: serde serializes via FontSpecRaw which maps `size: FontSize`
// to two mutually-exclusive keys (`size_pt` / `size_px`). The ThemeFields
// derive's introspection path cannot see the proxy, so declare the wire-format
// field names explicitly here. Keep in sync with FontSpecRaw below.
#[theme_layer(fields = "family, size_pt, size_px, weight, style, color")]
pub struct FontSpec {
    /// Font family name (e.g., "Inter", "Noto Sans").
    pub family: Option<Arc<str>>,
    /// Font size with explicit unit (points or pixels).
    ///
    /// In TOML, set as `size_pt` (typographic points) or `size_px` (logical
    /// pixels). Converted to `f32` logical pixels during validation via
    /// `FontSize::to_logical_px(dpi)`.
    pub size: Option<FontSize>,
    /// CSS font weight (100–900).
    pub weight: Option<u16>,
    /// Font style (normal, italic, oblique).
    pub style: Option<FontStyle>,
    /// Font color.
    pub color: Option<Rgba>,
}

/// Serde proxy for FontSpec. Maps `FontSize` to two mutually-exclusive keys.
#[serde_with::skip_serializing_none]
#[derive(Default, Serialize, Deserialize)]
#[serde(default)]
struct FontSpecRaw {
    family: Option<Arc<str>>,
    size_pt: Option<f32>,
    size_px: Option<f32>,
    weight: Option<u16>,
    style: Option<FontStyle>,
    color: Option<Rgba>,
}

/// Joins a proxy's two mutually-exclusive keys into one size; `both_set` is
/// the error when both are given.
fn size_from_keys(
    pt: Option<f32>,
    px: Option<f32>,
    both_set: &str,
) -> Result<Option<FontSize>, String> {
    match (pt, px) {
        (Some(v), None) => Ok(Some(FontSize::Pt(v))),
        (None, Some(v)) => Ok(Some(FontSize::Px(v))),
        (None, None) => Ok(None),
        (Some(_), Some(_)) => Err(both_set.into()),
    }
}

/// Splits a size into a proxy's `(pt, px)` keys.
fn size_to_keys(size: Option<FontSize>) -> (Option<f32>, Option<f32>) {
    match size {
        Some(FontSize::Pt(v)) => (Some(v), None),
        Some(FontSize::Px(v)) => (None, Some(v)),
        None => (None, None),
    }
}

impl TryFrom<FontSpecRaw> for FontSpec {
    type Error = String;
    fn try_from(raw: FontSpecRaw) -> Result<Self, Self::Error> {
        let size = size_from_keys(
            raw.size_pt,
            raw.size_px,
            "font: set `size_pt` or `size_px`, not both",
        )?;
        Ok(FontSpec {
            family: raw.family,
            size,
            weight: raw.weight,
            style: raw.style,
            color: raw.color,
        })
    }
}

impl From<FontSpec> for FontSpecRaw {
    fn from(fs: FontSpec) -> Self {
        let (size_pt, size_px) = size_to_keys(fs.size);
        FontSpecRaw {
            family: fs.family,
            size_pt,
            size_px,
            weight: fs.weight,
            style: fs.style,
            color: fs.color,
        }
    }
}

impl_merge!(FontSpec {
    option { family, size, weight, style, color }
});

/// A resolved (non-optional) font specification produced after theme resolution.
///
/// Unlike [`FontSpec`], every field but [`defined_size`](Self::defined_size)
/// is required (non-optional) because resolution has already filled in all
/// defaults.
///
/// No `Default` derive: `ResolvedFontSpec` is always
/// constructed from a fully populated unresolved source; any "zero"
/// instance is a placeholder sentinel built manually (see
/// `resolve::validate_helpers::resolved_font_spec_sentinel`).
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ResolvedFontSpec {
    /// Font family name.
    pub family: Arc<str>,
    /// Font size in logical pixels. A size stated in points is converted at
    /// the resolution context's
    /// [`font_dpi`](crate::resolve::ResolutionContext::font_dpi).
    pub size: f32,
    /// The size as its source stated it, before conversion.
    ///
    /// [`size`](Self::size) is always logical pixels, which is what a toolkit
    /// lays out with. This is the unit and number the preset or the platform
    /// reader actually gave: the OS readers and the platform presets other
    /// than Material state points, and Material and the community
    /// colour-scheme presets state pixels.
    ///
    /// Anything that shows a size to a person should show **this**. The two
    /// cannot be told apart after conversion -- a 14px preset and a 10.5pt
    /// one at 96 DPI both resolve to 14.0 -- so a display that divides
    /// `size` by the DPI would label the first as points, which no source
    /// ever said.
    ///
    /// `None` only where the source stated no size at all and validation
    /// recorded the omission.
    #[serde(default)]
    pub defined_size: Option<FontSize>,
    /// CSS font weight (100–900).
    pub weight: u16,
    /// Font style (normal, italic, oblique).
    pub style: FontStyle,
    /// Font color.
    pub color: Rgba,
}

/// A single entry in a text scale: size, weight, and line height.
///
/// Used to define typographic roles (caption, heading, etc.) with
/// consistent sizing and spacing.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
#[serde(try_from = "TextScaleEntryRaw", into = "TextScaleEntryRaw")]
// Phase 93-05 G5: serde proxy through TextScaleEntryRaw maps `size` and
// `line_height` each to two mutually-exclusive keys. Wire format declared
// explicitly. Keep in sync with TextScaleEntryRaw below.
#[theme_layer(fields = "size_pt, size_px, weight, line_height_pt, line_height_px")]
pub struct TextScaleEntry {
    /// Font size with explicit unit (points or pixels).
    ///
    /// Same semantics as `FontSpec.size` -- in TOML, set as `size_pt` or
    /// `size_px`. Converted to `f32` logical pixels during validation.
    pub size: Option<FontSize>,
    /// CSS font weight (100–900).
    pub weight: Option<u16>,
    /// Line height with explicit unit. When `None`, `resolve()` computes it
    /// as `defaults.line_height * size.raw()`, preserving the unit of `size`.
    ///
    /// Its unit need not match `size`'s: validation converts each value to
    /// logical pixels on its own.
    pub line_height: Option<FontSize>,
}

/// Serde proxy for TextScaleEntry. Maps `FontSize` to two mutually-exclusive keys.
#[serde_with::skip_serializing_none]
#[derive(Default, Serialize, Deserialize)]
#[serde(default)]
struct TextScaleEntryRaw {
    size_pt: Option<f32>,
    size_px: Option<f32>,
    weight: Option<u16>,
    line_height_pt: Option<f32>,
    line_height_px: Option<f32>,
}

impl TryFrom<TextScaleEntryRaw> for TextScaleEntry {
    type Error = String;
    fn try_from(raw: TextScaleEntryRaw) -> Result<Self, Self::Error> {
        let size = size_from_keys(
            raw.size_pt,
            raw.size_px,
            "text_scale: set `size_pt` or `size_px`, not both",
        )?;
        let line_height = size_from_keys(
            raw.line_height_pt,
            raw.line_height_px,
            "text_scale: set `line_height_pt` or `line_height_px`, not both",
        )?;
        Ok(TextScaleEntry {
            size,
            weight: raw.weight,
            line_height,
        })
    }
}

impl From<TextScaleEntry> for TextScaleEntryRaw {
    fn from(e: TextScaleEntry) -> Self {
        let (size_pt, size_px) = size_to_keys(e.size);
        let (line_height_pt, line_height_px) = size_to_keys(e.line_height);
        TextScaleEntryRaw {
            size_pt,
            size_px,
            weight: e.weight,
            line_height_pt,
            line_height_px,
        }
    }
}

impl_merge!(TextScaleEntry {
    option { size, weight, line_height }
});

/// A named text scale with four typographic roles.
///
/// Each field is an optional `TextScaleEntry` so that a partial overlay
/// can override only specific roles.
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
#[serde(default)]
pub struct TextScale {
    /// Caption / small label text.
    pub caption: Option<TextScaleEntry>,
    /// Section heading text.
    pub section_heading: Option<TextScaleEntry>,
    /// Dialog title text.
    pub dialog_title: Option<TextScaleEntry>,
    /// Large display / hero text.
    pub display: Option<TextScaleEntry>,
}

impl_merge!(TextScale {
    optional_nested { caption, section_heading, dialog_title, display }
});

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::FontSize;
    use super::*;

    // === FontSpec tests ===

    #[test]
    fn font_spec_default_is_empty() {
        assert!(FontSpec::default().is_empty());
    }

    #[test]
    fn font_spec_not_empty_when_family_set() {
        let fs = FontSpec {
            family: Some("Inter".into()),
            ..Default::default()
        };
        assert!(!fs.is_empty());
    }

    #[test]
    fn font_spec_not_empty_when_size_set() {
        let fs = FontSpec {
            size: Some(FontSize::Px(14.0)),
            ..Default::default()
        };
        assert!(!fs.is_empty());
    }

    #[test]
    fn font_spec_not_empty_when_weight_set() {
        let fs = FontSpec {
            weight: Some(700),
            ..Default::default()
        };
        assert!(!fs.is_empty());
    }

    #[test]
    fn font_spec_toml_round_trip() {
        let fs = FontSpec {
            family: Some("Inter".into()),
            size: Some(FontSize::Px(14.0)),
            weight: Some(400),
            ..Default::default()
        };
        let toml_str = toml::to_string(&fs).unwrap();
        let deserialized: FontSpec = toml::from_str(&toml_str).unwrap();
        assert_eq!(deserialized, fs);
    }

    #[test]
    fn font_spec_toml_round_trip_partial() {
        let fs = FontSpec {
            family: Some("Inter".into()),
            size: None,
            weight: None,
            ..Default::default()
        };
        let toml_str = toml::to_string(&fs).unwrap();
        let deserialized: FontSpec = toml::from_str(&toml_str).unwrap();
        assert_eq!(deserialized, fs);
        assert!(deserialized.size.is_none());
        assert!(deserialized.weight.is_none());
    }

    #[test]
    fn font_spec_merge_overlay_family_replaces_base() {
        let mut base = FontSpec {
            family: Some("Noto Sans".into()),
            size: Some(FontSize::Px(12.0)),
            weight: None,
            ..Default::default()
        };
        let overlay = FontSpec {
            family: Some("Inter".into()),
            size: None,
            weight: None,
            ..Default::default()
        };
        base.merge(&overlay);
        assert_eq!(base.family.as_deref(), Some("Inter"));
        // base size preserved since overlay size is None
        assert_eq!(base.size, Some(FontSize::Px(12.0)));
    }

    #[test]
    fn font_spec_merge_none_preserves_base() {
        let mut base = FontSpec {
            family: Some("Noto Sans".into()),
            size: Some(FontSize::Px(12.0)),
            weight: Some(400),
            ..Default::default()
        };
        let overlay = FontSpec::default();
        base.merge(&overlay);
        assert_eq!(base.family.as_deref(), Some("Noto Sans"));
        assert_eq!(base.size, Some(FontSize::Px(12.0)));
        assert_eq!(base.weight, Some(400));
    }

    // === TextScaleEntry tests ===

    #[test]
    fn text_scale_entry_default_is_empty() {
        assert!(TextScaleEntry::default().is_empty());
    }

    #[test]
    fn text_scale_entry_toml_round_trip() {
        let entry = TextScaleEntry {
            size: Some(FontSize::Px(12.0)),
            weight: Some(400),
            line_height: Some(FontSize::Px(1.4)),
        };
        let toml_str = toml::to_string(&entry).unwrap();
        let deserialized: TextScaleEntry = toml::from_str(&toml_str).unwrap();
        assert_eq!(deserialized, entry);
    }

    #[test]
    fn text_scale_entry_merge_overlay_wins() {
        let mut base = TextScaleEntry {
            size: Some(FontSize::Px(12.0)),
            weight: Some(400),
            line_height: None,
        };
        let overlay = TextScaleEntry {
            size: None,
            weight: Some(700),
            line_height: Some(FontSize::Px(1.5)),
        };
        base.merge(&overlay);
        assert_eq!(base.size, Some(FontSize::Px(12.0))); // preserved
        assert_eq!(base.weight, Some(700)); // overlay wins
        assert_eq!(base.line_height, Some(FontSize::Px(1.5))); // overlay sets
    }

    // === TextScale tests ===

    #[test]
    fn text_scale_default_is_empty() {
        assert!(TextScale::default().is_empty());
    }

    #[test]
    fn text_scale_not_empty_when_entry_set() {
        let ts = TextScale {
            caption: Some(TextScaleEntry {
                size: Some(FontSize::Px(11.0)),
                ..Default::default()
            }),
            ..Default::default()
        };
        assert!(!ts.is_empty());
    }

    #[test]
    fn text_scale_toml_round_trip() {
        let ts = TextScale {
            caption: Some(TextScaleEntry {
                size: Some(FontSize::Px(11.0)),
                weight: Some(400),
                line_height: Some(FontSize::Px(1.3)),
            }),
            section_heading: Some(TextScaleEntry {
                size: Some(FontSize::Px(14.0)),
                weight: Some(600),
                line_height: Some(FontSize::Px(1.4)),
            }),
            dialog_title: Some(TextScaleEntry {
                size: Some(FontSize::Px(16.0)),
                weight: Some(700),
                line_height: Some(FontSize::Px(1.2)),
            }),
            display: Some(TextScaleEntry {
                size: Some(FontSize::Px(24.0)),
                weight: Some(300),
                line_height: Some(FontSize::Px(1.1)),
            }),
        };
        let toml_str = toml::to_string(&ts).unwrap();
        let deserialized: TextScale = toml::from_str(&toml_str).unwrap();
        assert_eq!(deserialized, ts);
    }

    #[test]
    fn text_scale_merge_some_plus_some_merges_inner() {
        let mut base = TextScale {
            caption: Some(TextScaleEntry {
                size: Some(FontSize::Px(11.0)),
                weight: Some(400),
                line_height: None,
            }),
            ..Default::default()
        };
        let overlay = TextScale {
            caption: Some(TextScaleEntry {
                size: None,
                weight: Some(600),
                line_height: Some(FontSize::Px(1.3)),
            }),
            ..Default::default()
        };
        base.merge(&overlay);
        let cap = base.caption.as_ref().unwrap();
        assert_eq!(cap.size, Some(FontSize::Px(11.0))); // base preserved
        assert_eq!(cap.weight, Some(600)); // overlay wins
        assert_eq!(cap.line_height, Some(FontSize::Px(1.3))); // overlay sets
    }

    #[test]
    fn text_scale_merge_none_plus_some_clones_overlay() {
        let mut base = TextScale::default();
        let overlay = TextScale {
            section_heading: Some(TextScaleEntry {
                size: Some(FontSize::Px(14.0)),
                ..Default::default()
            }),
            ..Default::default()
        };
        base.merge(&overlay);
        assert!(base.section_heading.is_some());
        assert_eq!(base.section_heading.unwrap().size, Some(FontSize::Px(14.0)));
    }

    #[test]
    fn text_scale_merge_none_preserves_base_entry() {
        let mut base = TextScale {
            display: Some(TextScaleEntry {
                size: Some(FontSize::Px(24.0)),
                ..Default::default()
            }),
            ..Default::default()
        };
        let overlay = TextScale::default();
        base.merge(&overlay);
        assert!(base.display.is_some());
        assert_eq!(base.display.unwrap().size, Some(FontSize::Px(24.0)));
    }

    // === Arc<str> sharing test ===

    #[test]
    fn resolved_font_clone_shares_family_arc() {
        let font = ResolvedFontSpec {
            family: Arc::from("Inter"),
            size: 14.0,
            defined_size: Some(FontSize::Px(14.0)),
            weight: 400,
            style: FontStyle::Normal,
            color: crate::Rgba::rgb(0, 0, 0),
        };
        let cloned = font.clone();
        // str data pointers are identical -- same Arc allocation, not a deep copy
        assert!(std::ptr::eq(
            font.family.as_ref() as *const str,
            cloned.family.as_ref() as *const str,
        ));
    }

    // === FontStyle tests ===

    #[test]
    fn font_style_default_is_normal() {
        assert_eq!(FontStyle::default(), FontStyle::Normal);
    }

    #[test]
    fn font_style_serde_round_trip() {
        // TOML cannot serialize a bare enum as a top-level value; use a wrapper struct.
        #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
        struct Wrapper {
            style: FontStyle,
        }

        for (variant, expected_str) in [
            (FontStyle::Normal, "normal"),
            (FontStyle::Italic, "italic"),
            (FontStyle::Oblique, "oblique"),
        ] {
            let original = Wrapper { style: variant };
            let serialized = toml::to_string(&original).unwrap();
            assert!(serialized.contains(expected_str), "got: {serialized}");
            let deserialized: Wrapper = toml::from_str(&serialized).unwrap();
            assert_eq!(deserialized, original);
        }
    }

    #[test]
    fn font_spec_with_style_and_color_round_trip() {
        let fs = FontSpec {
            family: Some("Inter".into()),
            size: Some(FontSize::Px(14.0)),
            weight: Some(400),
            style: Some(FontStyle::Italic),
            color: Some(crate::Rgba::rgb(255, 0, 0)),
        };
        let toml_str = toml::to_string(&fs).unwrap();
        let deserialized: FontSpec = toml::from_str(&toml_str).unwrap();
        assert_eq!(deserialized, fs);
    }

    #[test]
    fn font_spec_style_none_preserved() {
        let fs = FontSpec {
            family: Some("Inter".into()),
            style: None,
            ..Default::default()
        };
        let toml_str = toml::to_string(&fs).unwrap();
        let deserialized: FontSpec = toml::from_str(&toml_str).unwrap();
        assert!(deserialized.style.is_none());
    }

    #[test]
    fn font_spec_merge_includes_style_and_color() {
        let mut base = FontSpec {
            family: Some("Noto Sans".into()),
            style: Some(FontStyle::Normal),
            color: Some(crate::Rgba::rgb(0, 0, 0)),
            ..Default::default()
        };
        let overlay = FontSpec {
            style: Some(FontStyle::Italic),
            ..Default::default()
        };
        base.merge(&overlay);
        assert_eq!(base.style, Some(FontStyle::Italic)); // overlay wins
        assert_eq!(base.color, Some(crate::Rgba::rgb(0, 0, 0))); // base preserved
        assert_eq!(base.family.as_deref(), Some("Noto Sans")); // base preserved
    }

    // === FontSize tests ===

    #[test]
    fn pt_to_logical_px_at_96_dpi() {
        assert_eq!(FontSize::Pt(10.0).to_logical_px(96.0), 10.0 * 96.0 / 72.0);
    }

    #[test]
    fn px_ignores_dpi() {
        assert_eq!(FontSize::Px(14.0).to_logical_px(96.0), 14.0);
        assert_eq!(FontSize::Px(14.0).to_logical_px(144.0), 14.0);
    }

    #[test]
    fn pt_to_logical_px_at_72_dpi_is_identity() {
        assert_eq!(FontSize::Pt(10.0).to_logical_px(72.0), 10.0);
    }

    #[test]
    fn raw_extracts_value() {
        assert_eq!(FontSize::Pt(10.0).raw(), 10.0);
        assert_eq!(FontSize::Px(14.0).raw(), 14.0);
    }

    // === Serde round-trip tests ===

    #[test]
    fn fontspec_toml_round_trip_size_pt() {
        let fs = FontSpec {
            family: Some("Inter".into()),
            size: Some(FontSize::Pt(10.0)),
            weight: Some(400),
            ..Default::default()
        };
        let toml_str = toml::to_string(&fs).expect("serialize");
        assert!(
            toml_str.contains("size_pt"),
            "should contain size_pt: {toml_str}"
        );
        assert!(
            !toml_str.contains("size_px"),
            "should not contain size_px: {toml_str}"
        );
        let deserialized: FontSpec = toml::from_str(&toml_str).expect("deserialize");
        assert_eq!(deserialized, fs);
    }

    #[test]
    fn fontspec_toml_round_trip_size_px() {
        let fs = FontSpec {
            size: Some(FontSize::Px(14.0)),
            ..Default::default()
        };
        let toml_str = toml::to_string(&fs).expect("serialize");
        assert!(
            toml_str.contains("size_px"),
            "should contain size_px: {toml_str}"
        );
        assert!(
            !toml_str.contains("size_pt"),
            "should not contain size_pt: {toml_str}"
        );
        let deserialized: FontSpec = toml::from_str(&toml_str).expect("deserialize");
        assert_eq!(deserialized, fs);
    }

    #[test]
    fn fontspec_toml_rejects_both_pt_and_px() {
        let toml_str = "size_pt = 10.0\nsize_px = 14.0\n";
        assert!(toml::from_str::<FontSpec>(toml_str).is_err());
    }

    #[test]
    fn fontspec_toml_rejects_bare_size() {
        let toml_str = "size = 10.0\n";
        // With #[serde(default)], the bare `size` key is NOT a recognized field
        // in FontSpecRaw. It deserializes to FontSpec with size=None.
        // The TOML linter (lint_toml) catches `size` as unknown separately.
        let result: FontSpec = toml::from_str(toml_str).expect("deserialize");
        assert!(
            result.size.is_none(),
            "bare 'size' should not set FontSpec.size"
        );
    }

    #[test]
    fn fontspec_toml_no_size_is_valid() {
        let fs: FontSpec = toml::from_str(r#"family = "Inter""#).expect("deserialize");
        assert!(fs.size.is_none());
    }

    #[test]
    fn text_scale_entry_toml_round_trip_size_pt() {
        let entry = TextScaleEntry {
            size: Some(FontSize::Pt(9.0)),
            weight: Some(400),
            line_height: Some(FontSize::Pt(12.6)),
        };
        let toml_str = toml::to_string(&entry).expect("serialize");
        assert!(toml_str.contains("size_pt"));
        let deserialized: TextScaleEntry = toml::from_str(&toml_str).expect("deserialize");
        assert_eq!(deserialized, entry);
    }

    #[test]
    fn text_scale_entry_toml_round_trip_size_px() {
        let entry = TextScaleEntry {
            size: Some(FontSize::Px(14.0)),
            weight: Some(400),
            line_height: Some(FontSize::Px(18.0)),
        };
        let toml_str = toml::to_string(&entry).expect("serialize");
        assert!(toml_str.contains("size_px"));
        let deserialized: TextScaleEntry = toml::from_str(&toml_str).expect("deserialize");
        assert_eq!(deserialized, entry);
    }
}