Skip to main content

native_theme/model/
font.rs

1// Font specification and text scale types
2
3use std::collections::HashSet;
4use std::sync::{Arc, Mutex};
5
6use crate::Rgba;
7use native_theme_derive::ThemeFields;
8use serde::{Deserialize, Serialize};
9
10/// Global font family intern cache.
11///
12/// Stores `Arc<str>` values so that repeated calls with the same family name
13/// return clones of the same `Arc`, avoiding redundant allocations.
14static FONT_FAMILY_CACHE: std::sync::LazyLock<Mutex<HashSet<Arc<str>>>> =
15    std::sync::LazyLock::new(|| Mutex::new(HashSet::new()));
16
17/// Intern a font family name, returning a deduplicated `Arc<str>`.
18///
19/// If the same family name has been interned before, returns a clone of the
20/// existing `Arc<str>` (same allocation, bumped reference count). Otherwise,
21/// creates a new `Arc<str>` and caches it for future lookups.
22///
23/// This is useful for connectors that resolve fonts repeatedly -- calling
24/// `intern_font_family("Inter")` 100 times allocates only once.
25///
26/// # Examples
27///
28/// ```
29/// use std::sync::Arc;
30/// use native_theme::theme::intern_font_family;
31///
32/// let a = intern_font_family("Inter");
33/// let b = intern_font_family("Inter");
34/// assert!(Arc::ptr_eq(&a, &b)); // Same allocation
35/// ```
36///
37/// # Panics
38///
39/// This function does not panic. If the internal mutex is poisoned (which
40/// can only happen if a thread panicked while holding it), a fresh `Arc<str>`
41/// is returned without caching.
42pub fn intern_font_family(family: &str) -> Arc<str> {
43    if let Ok(mut cache) = FONT_FAMILY_CACHE.lock() {
44        if let Some(existing) = cache.get(family) {
45            return Arc::clone(existing);
46        }
47        let arc: Arc<str> = Arc::from(family);
48        cache.insert(Arc::clone(&arc));
49        arc
50    } else {
51        // Mutex poisoned -- degrade gracefully without caching
52        Arc::from(family)
53    }
54}
55
56/// Font style: upright, italic, or oblique.
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
58#[serde(rename_all = "lowercase")]
59pub enum FontStyle {
60    /// Normal upright text.
61    #[default]
62    Normal,
63    /// Italic text (true italic glyph).
64    Italic,
65    /// Oblique text (slanted upright glyph).
66    Oblique,
67}
68
69/// A font size with an explicit unit.
70///
71/// In TOML presets, this appears as either `size_pt` (typographic points)
72/// or `size_px` (logical pixels). That mapping is done by the parent structs
73/// (`FontSpec`, `TextScaleEntry`); `FontSize` derives `Serialize` and
74/// `Deserialize` of its own for [`ResolvedFontSpec::defined_size`].
75///
76/// During validation, all `FontSize` values are converted to logical pixels
77/// via `FontSize::to_logical_px(dpi)`, producing a plain `f32` for the resolved model.
78#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
79pub enum FontSize {
80    /// Typographic points (1/72 inch). Stated by the OS readers (KDE, GNOME,
81    /// macOS, Windows) and by the platform presets other than Material
82    /// (Adwaita, KDE Breeze, macOS, Windows 11, iOS).
83    /// Converted to px during validation: `px = pt * dpi / 72`.
84    Pt(f32),
85    /// Logical pixels. Stated by the Material platform preset and the
86    /// community colour-scheme presets (Catppuccin, Dracula, Gruvbox, Nord,
87    /// One Dark, Solarized, Tokyo Night).
88    Px(f32),
89}
90
91impl FontSize {
92    /// Convert to logical pixels.
93    ///
94    /// - `Pt(v)` -> `v * dpi / 72.0` (DPI matters)
95    /// - `Px(v)` -> `v` (already logical pixels, DPI ignored)
96    ///
97    /// The name `to_logical_px` makes the asymmetry explicit: `Px` values
98    /// are already in logical pixels, so the DPI parameter has no effect.
99    ///
100    /// # Examples
101    ///
102    /// ```
103    /// use native_theme::theme::FontSize;
104    ///
105    /// // Pt branch: DPI affects the result
106    /// let pt_size = FontSize::Pt(10.0);
107    /// assert_eq!(pt_size.to_logical_px(96.0), 10.0 * 96.0 / 72.0);
108    /// assert_eq!(pt_size.to_logical_px(72.0), 10.0); // identity at 72 DPI
109    ///
110    /// // Px branch: DPI is ignored, value returned unchanged
111    /// let px_size = FontSize::Px(14.0);
112    /// assert_eq!(px_size.to_logical_px(96.0), 14.0);
113    /// assert_eq!(px_size.to_logical_px(144.0), 14.0); // same regardless of DPI
114    /// ```
115    pub fn to_logical_px(self, dpi: f32) -> f32 {
116        match self {
117            Self::Pt(v) => v * dpi / 72.0,
118            Self::Px(v) => v,
119        }
120    }
121
122    /// Return the raw numeric value regardless of unit.
123    /// Used during inheritance to compute derived values (e.g. line_height)
124    /// before unit conversion.
125    pub fn raw(self) -> f32 {
126        match self {
127            Self::Pt(v) | Self::Px(v) => v,
128        }
129    }
130
131    /// True when the value is in typographic points.
132    pub fn is_pt(self) -> bool {
133        matches!(self, Self::Pt(_))
134    }
135}
136
137/// Font specification: family name, size, weight, style, and color.
138///
139/// All fields are optional to support partial overlays -- a FontSpec with
140/// only `size` set will only override the size when merged.
141///
142/// **Default behavior asymmetry:** During validation, `family`, `size`,
143/// `weight`, and `color` are required (missing values produce a validation
144/// error). `style` silently defaults to [`FontStyle::Normal`] because
145/// Normal is the universally-safe default -- no theme ever intends to
146/// leave style undefined in a way that would produce incorrect rendering.
147#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
148#[serde(try_from = "FontSpecRaw", into = "FontSpecRaw")]
149// Phase 93-05 G5: serde serializes via FontSpecRaw which maps `size: FontSize`
150// to two mutually-exclusive keys (`size_pt` / `size_px`). The ThemeFields
151// derive's introspection path cannot see the proxy, so declare the wire-format
152// field names explicitly here. Keep in sync with FontSpecRaw below.
153#[theme_layer(fields = "family, size_pt, size_px, weight, style, color")]
154pub struct FontSpec {
155    /// Font family name (e.g., "Inter", "Noto Sans").
156    pub family: Option<Arc<str>>,
157    /// Font size with explicit unit (points or pixels).
158    ///
159    /// In TOML, set as `size_pt` (typographic points) or `size_px` (logical
160    /// pixels). Converted to `f32` logical pixels during validation via
161    /// `FontSize::to_logical_px(dpi)`.
162    pub size: Option<FontSize>,
163    /// CSS font weight (100–900).
164    pub weight: Option<u16>,
165    /// Font style (normal, italic, oblique).
166    pub style: Option<FontStyle>,
167    /// Font color.
168    pub color: Option<Rgba>,
169}
170
171/// Serde proxy for FontSpec. Maps `FontSize` to two mutually-exclusive keys.
172#[serde_with::skip_serializing_none]
173#[derive(Default, Serialize, Deserialize)]
174#[serde(default)]
175struct FontSpecRaw {
176    family: Option<Arc<str>>,
177    size_pt: Option<f32>,
178    size_px: Option<f32>,
179    weight: Option<u16>,
180    style: Option<FontStyle>,
181    color: Option<Rgba>,
182}
183
184/// Joins a proxy's two mutually-exclusive keys into one size; `both_set` is
185/// the error when both are given.
186fn size_from_keys(
187    pt: Option<f32>,
188    px: Option<f32>,
189    both_set: &str,
190) -> Result<Option<FontSize>, String> {
191    match (pt, px) {
192        (Some(v), None) => Ok(Some(FontSize::Pt(v))),
193        (None, Some(v)) => Ok(Some(FontSize::Px(v))),
194        (None, None) => Ok(None),
195        (Some(_), Some(_)) => Err(both_set.into()),
196    }
197}
198
199/// Splits a size into a proxy's `(pt, px)` keys.
200fn size_to_keys(size: Option<FontSize>) -> (Option<f32>, Option<f32>) {
201    match size {
202        Some(FontSize::Pt(v)) => (Some(v), None),
203        Some(FontSize::Px(v)) => (None, Some(v)),
204        None => (None, None),
205    }
206}
207
208impl TryFrom<FontSpecRaw> for FontSpec {
209    type Error = String;
210    fn try_from(raw: FontSpecRaw) -> Result<Self, Self::Error> {
211        let size = size_from_keys(
212            raw.size_pt,
213            raw.size_px,
214            "font: set `size_pt` or `size_px`, not both",
215        )?;
216        Ok(FontSpec {
217            family: raw.family,
218            size,
219            weight: raw.weight,
220            style: raw.style,
221            color: raw.color,
222        })
223    }
224}
225
226impl From<FontSpec> for FontSpecRaw {
227    fn from(fs: FontSpec) -> Self {
228        let (size_pt, size_px) = size_to_keys(fs.size);
229        FontSpecRaw {
230            family: fs.family,
231            size_pt,
232            size_px,
233            weight: fs.weight,
234            style: fs.style,
235            color: fs.color,
236        }
237    }
238}
239
240impl_merge!(FontSpec {
241    option { family, size, weight, style, color }
242});
243
244/// A resolved (non-optional) font specification produced after theme resolution.
245///
246/// Unlike [`FontSpec`], every field but [`defined_size`](Self::defined_size)
247/// is required (non-optional) because resolution has already filled in all
248/// defaults.
249///
250/// No `Default` derive: `ResolvedFontSpec` is always
251/// constructed from a fully populated unresolved source; any "zero"
252/// instance is a placeholder sentinel built manually (see
253/// `resolve::validate_helpers::resolved_font_spec_sentinel`).
254#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
255pub struct ResolvedFontSpec {
256    /// Font family name.
257    pub family: Arc<str>,
258    /// Font size in logical pixels. A size stated in points is converted at
259    /// the resolution context's
260    /// [`font_dpi`](crate::resolve::ResolutionContext::font_dpi).
261    pub size: f32,
262    /// The size as its source stated it, before conversion.
263    ///
264    /// [`size`](Self::size) is always logical pixels, which is what a toolkit
265    /// lays out with. This is the unit and number the preset or the platform
266    /// reader actually gave: the OS readers and the platform presets other
267    /// than Material state points, and Material and the community
268    /// colour-scheme presets state pixels.
269    ///
270    /// Anything that shows a size to a person should show **this**. The two
271    /// cannot be told apart after conversion -- a 14px preset and a 10.5pt
272    /// one at 96 DPI both resolve to 14.0 -- so a display that divides
273    /// `size` by the DPI would label the first as points, which no source
274    /// ever said.
275    ///
276    /// `None` only where the source stated no size at all and validation
277    /// recorded the omission.
278    #[serde(default)]
279    pub defined_size: Option<FontSize>,
280    /// CSS font weight (100–900).
281    pub weight: u16,
282    /// Font style (normal, italic, oblique).
283    pub style: FontStyle,
284    /// Font color.
285    pub color: Rgba,
286}
287
288/// A single entry in a text scale: size, weight, and line height.
289///
290/// Used to define typographic roles (caption, heading, etc.) with
291/// consistent sizing and spacing.
292#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
293#[serde(try_from = "TextScaleEntryRaw", into = "TextScaleEntryRaw")]
294// Phase 93-05 G5: serde proxy through TextScaleEntryRaw maps `size` and
295// `line_height` each to two mutually-exclusive keys. Wire format declared
296// explicitly. Keep in sync with TextScaleEntryRaw below.
297#[theme_layer(fields = "size_pt, size_px, weight, line_height_pt, line_height_px")]
298pub struct TextScaleEntry {
299    /// Font size with explicit unit (points or pixels).
300    ///
301    /// Same semantics as `FontSpec.size` -- in TOML, set as `size_pt` or
302    /// `size_px`. Converted to `f32` logical pixels during validation.
303    pub size: Option<FontSize>,
304    /// CSS font weight (100–900).
305    pub weight: Option<u16>,
306    /// Line height with explicit unit. When `None`, `resolve()` computes it
307    /// as `defaults.line_height * size.raw()`, preserving the unit of `size`.
308    ///
309    /// Its unit need not match `size`'s: validation converts each value to
310    /// logical pixels on its own.
311    pub line_height: Option<FontSize>,
312}
313
314/// Serde proxy for TextScaleEntry. Maps `FontSize` to two mutually-exclusive keys.
315#[serde_with::skip_serializing_none]
316#[derive(Default, Serialize, Deserialize)]
317#[serde(default)]
318struct TextScaleEntryRaw {
319    size_pt: Option<f32>,
320    size_px: Option<f32>,
321    weight: Option<u16>,
322    line_height_pt: Option<f32>,
323    line_height_px: Option<f32>,
324}
325
326impl TryFrom<TextScaleEntryRaw> for TextScaleEntry {
327    type Error = String;
328    fn try_from(raw: TextScaleEntryRaw) -> Result<Self, Self::Error> {
329        let size = size_from_keys(
330            raw.size_pt,
331            raw.size_px,
332            "text_scale: set `size_pt` or `size_px`, not both",
333        )?;
334        let line_height = size_from_keys(
335            raw.line_height_pt,
336            raw.line_height_px,
337            "text_scale: set `line_height_pt` or `line_height_px`, not both",
338        )?;
339        Ok(TextScaleEntry {
340            size,
341            weight: raw.weight,
342            line_height,
343        })
344    }
345}
346
347impl From<TextScaleEntry> for TextScaleEntryRaw {
348    fn from(e: TextScaleEntry) -> Self {
349        let (size_pt, size_px) = size_to_keys(e.size);
350        let (line_height_pt, line_height_px) = size_to_keys(e.line_height);
351        TextScaleEntryRaw {
352            size_pt,
353            size_px,
354            weight: e.weight,
355            line_height_pt,
356            line_height_px,
357        }
358    }
359}
360
361impl_merge!(TextScaleEntry {
362    option { size, weight, line_height }
363});
364
365/// A named text scale with four typographic roles.
366///
367/// Each field is an optional `TextScaleEntry` so that a partial overlay
368/// can override only specific roles.
369#[serde_with::skip_serializing_none]
370#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
371#[serde(default)]
372pub struct TextScale {
373    /// Caption / small label text.
374    pub caption: Option<TextScaleEntry>,
375    /// Section heading text.
376    pub section_heading: Option<TextScaleEntry>,
377    /// Dialog title text.
378    pub dialog_title: Option<TextScaleEntry>,
379    /// Large display / hero text.
380    pub display: Option<TextScaleEntry>,
381}
382
383impl_merge!(TextScale {
384    optional_nested { caption, section_heading, dialog_title, display }
385});
386
387#[cfg(test)]
388#[allow(clippy::unwrap_used, clippy::expect_used)]
389mod tests {
390    use super::FontSize;
391    use super::*;
392
393    // === FontSpec tests ===
394
395    #[test]
396    fn font_spec_default_is_empty() {
397        assert!(FontSpec::default().is_empty());
398    }
399
400    #[test]
401    fn font_spec_not_empty_when_family_set() {
402        let fs = FontSpec {
403            family: Some("Inter".into()),
404            ..Default::default()
405        };
406        assert!(!fs.is_empty());
407    }
408
409    #[test]
410    fn font_spec_not_empty_when_size_set() {
411        let fs = FontSpec {
412            size: Some(FontSize::Px(14.0)),
413            ..Default::default()
414        };
415        assert!(!fs.is_empty());
416    }
417
418    #[test]
419    fn font_spec_not_empty_when_weight_set() {
420        let fs = FontSpec {
421            weight: Some(700),
422            ..Default::default()
423        };
424        assert!(!fs.is_empty());
425    }
426
427    #[test]
428    fn font_spec_toml_round_trip() {
429        let fs = FontSpec {
430            family: Some("Inter".into()),
431            size: Some(FontSize::Px(14.0)),
432            weight: Some(400),
433            ..Default::default()
434        };
435        let toml_str = toml::to_string(&fs).unwrap();
436        let deserialized: FontSpec = toml::from_str(&toml_str).unwrap();
437        assert_eq!(deserialized, fs);
438    }
439
440    #[test]
441    fn font_spec_toml_round_trip_partial() {
442        let fs = FontSpec {
443            family: Some("Inter".into()),
444            size: None,
445            weight: None,
446            ..Default::default()
447        };
448        let toml_str = toml::to_string(&fs).unwrap();
449        let deserialized: FontSpec = toml::from_str(&toml_str).unwrap();
450        assert_eq!(deserialized, fs);
451        assert!(deserialized.size.is_none());
452        assert!(deserialized.weight.is_none());
453    }
454
455    #[test]
456    fn font_spec_merge_overlay_family_replaces_base() {
457        let mut base = FontSpec {
458            family: Some("Noto Sans".into()),
459            size: Some(FontSize::Px(12.0)),
460            weight: None,
461            ..Default::default()
462        };
463        let overlay = FontSpec {
464            family: Some("Inter".into()),
465            size: None,
466            weight: None,
467            ..Default::default()
468        };
469        base.merge(&overlay);
470        assert_eq!(base.family.as_deref(), Some("Inter"));
471        // base size preserved since overlay size is None
472        assert_eq!(base.size, Some(FontSize::Px(12.0)));
473    }
474
475    #[test]
476    fn font_spec_merge_none_preserves_base() {
477        let mut base = FontSpec {
478            family: Some("Noto Sans".into()),
479            size: Some(FontSize::Px(12.0)),
480            weight: Some(400),
481            ..Default::default()
482        };
483        let overlay = FontSpec::default();
484        base.merge(&overlay);
485        assert_eq!(base.family.as_deref(), Some("Noto Sans"));
486        assert_eq!(base.size, Some(FontSize::Px(12.0)));
487        assert_eq!(base.weight, Some(400));
488    }
489
490    // === TextScaleEntry tests ===
491
492    #[test]
493    fn text_scale_entry_default_is_empty() {
494        assert!(TextScaleEntry::default().is_empty());
495    }
496
497    #[test]
498    fn text_scale_entry_toml_round_trip() {
499        let entry = TextScaleEntry {
500            size: Some(FontSize::Px(12.0)),
501            weight: Some(400),
502            line_height: Some(FontSize::Px(1.4)),
503        };
504        let toml_str = toml::to_string(&entry).unwrap();
505        let deserialized: TextScaleEntry = toml::from_str(&toml_str).unwrap();
506        assert_eq!(deserialized, entry);
507    }
508
509    #[test]
510    fn text_scale_entry_merge_overlay_wins() {
511        let mut base = TextScaleEntry {
512            size: Some(FontSize::Px(12.0)),
513            weight: Some(400),
514            line_height: None,
515        };
516        let overlay = TextScaleEntry {
517            size: None,
518            weight: Some(700),
519            line_height: Some(FontSize::Px(1.5)),
520        };
521        base.merge(&overlay);
522        assert_eq!(base.size, Some(FontSize::Px(12.0))); // preserved
523        assert_eq!(base.weight, Some(700)); // overlay wins
524        assert_eq!(base.line_height, Some(FontSize::Px(1.5))); // overlay sets
525    }
526
527    // === TextScale tests ===
528
529    #[test]
530    fn text_scale_default_is_empty() {
531        assert!(TextScale::default().is_empty());
532    }
533
534    #[test]
535    fn text_scale_not_empty_when_entry_set() {
536        let ts = TextScale {
537            caption: Some(TextScaleEntry {
538                size: Some(FontSize::Px(11.0)),
539                ..Default::default()
540            }),
541            ..Default::default()
542        };
543        assert!(!ts.is_empty());
544    }
545
546    #[test]
547    fn text_scale_toml_round_trip() {
548        let ts = TextScale {
549            caption: Some(TextScaleEntry {
550                size: Some(FontSize::Px(11.0)),
551                weight: Some(400),
552                line_height: Some(FontSize::Px(1.3)),
553            }),
554            section_heading: Some(TextScaleEntry {
555                size: Some(FontSize::Px(14.0)),
556                weight: Some(600),
557                line_height: Some(FontSize::Px(1.4)),
558            }),
559            dialog_title: Some(TextScaleEntry {
560                size: Some(FontSize::Px(16.0)),
561                weight: Some(700),
562                line_height: Some(FontSize::Px(1.2)),
563            }),
564            display: Some(TextScaleEntry {
565                size: Some(FontSize::Px(24.0)),
566                weight: Some(300),
567                line_height: Some(FontSize::Px(1.1)),
568            }),
569        };
570        let toml_str = toml::to_string(&ts).unwrap();
571        let deserialized: TextScale = toml::from_str(&toml_str).unwrap();
572        assert_eq!(deserialized, ts);
573    }
574
575    #[test]
576    fn text_scale_merge_some_plus_some_merges_inner() {
577        let mut base = TextScale {
578            caption: Some(TextScaleEntry {
579                size: Some(FontSize::Px(11.0)),
580                weight: Some(400),
581                line_height: None,
582            }),
583            ..Default::default()
584        };
585        let overlay = TextScale {
586            caption: Some(TextScaleEntry {
587                size: None,
588                weight: Some(600),
589                line_height: Some(FontSize::Px(1.3)),
590            }),
591            ..Default::default()
592        };
593        base.merge(&overlay);
594        let cap = base.caption.as_ref().unwrap();
595        assert_eq!(cap.size, Some(FontSize::Px(11.0))); // base preserved
596        assert_eq!(cap.weight, Some(600)); // overlay wins
597        assert_eq!(cap.line_height, Some(FontSize::Px(1.3))); // overlay sets
598    }
599
600    #[test]
601    fn text_scale_merge_none_plus_some_clones_overlay() {
602        let mut base = TextScale::default();
603        let overlay = TextScale {
604            section_heading: Some(TextScaleEntry {
605                size: Some(FontSize::Px(14.0)),
606                ..Default::default()
607            }),
608            ..Default::default()
609        };
610        base.merge(&overlay);
611        assert!(base.section_heading.is_some());
612        assert_eq!(base.section_heading.unwrap().size, Some(FontSize::Px(14.0)));
613    }
614
615    #[test]
616    fn text_scale_merge_none_preserves_base_entry() {
617        let mut base = TextScale {
618            display: Some(TextScaleEntry {
619                size: Some(FontSize::Px(24.0)),
620                ..Default::default()
621            }),
622            ..Default::default()
623        };
624        let overlay = TextScale::default();
625        base.merge(&overlay);
626        assert!(base.display.is_some());
627        assert_eq!(base.display.unwrap().size, Some(FontSize::Px(24.0)));
628    }
629
630    // === Arc<str> sharing test ===
631
632    #[test]
633    fn resolved_font_clone_shares_family_arc() {
634        let font = ResolvedFontSpec {
635            family: Arc::from("Inter"),
636            size: 14.0,
637            defined_size: Some(FontSize::Px(14.0)),
638            weight: 400,
639            style: FontStyle::Normal,
640            color: crate::Rgba::rgb(0, 0, 0),
641        };
642        let cloned = font.clone();
643        // str data pointers are identical -- same Arc allocation, not a deep copy
644        assert!(std::ptr::eq(
645            font.family.as_ref() as *const str,
646            cloned.family.as_ref() as *const str,
647        ));
648    }
649
650    // === FontStyle tests ===
651
652    #[test]
653    fn font_style_default_is_normal() {
654        assert_eq!(FontStyle::default(), FontStyle::Normal);
655    }
656
657    #[test]
658    fn font_style_serde_round_trip() {
659        // TOML cannot serialize a bare enum as a top-level value; use a wrapper struct.
660        #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
661        struct Wrapper {
662            style: FontStyle,
663        }
664
665        for (variant, expected_str) in [
666            (FontStyle::Normal, "normal"),
667            (FontStyle::Italic, "italic"),
668            (FontStyle::Oblique, "oblique"),
669        ] {
670            let original = Wrapper { style: variant };
671            let serialized = toml::to_string(&original).unwrap();
672            assert!(serialized.contains(expected_str), "got: {serialized}");
673            let deserialized: Wrapper = toml::from_str(&serialized).unwrap();
674            assert_eq!(deserialized, original);
675        }
676    }
677
678    #[test]
679    fn font_spec_with_style_and_color_round_trip() {
680        let fs = FontSpec {
681            family: Some("Inter".into()),
682            size: Some(FontSize::Px(14.0)),
683            weight: Some(400),
684            style: Some(FontStyle::Italic),
685            color: Some(crate::Rgba::rgb(255, 0, 0)),
686        };
687        let toml_str = toml::to_string(&fs).unwrap();
688        let deserialized: FontSpec = toml::from_str(&toml_str).unwrap();
689        assert_eq!(deserialized, fs);
690    }
691
692    #[test]
693    fn font_spec_style_none_preserved() {
694        let fs = FontSpec {
695            family: Some("Inter".into()),
696            style: None,
697            ..Default::default()
698        };
699        let toml_str = toml::to_string(&fs).unwrap();
700        let deserialized: FontSpec = toml::from_str(&toml_str).unwrap();
701        assert!(deserialized.style.is_none());
702    }
703
704    #[test]
705    fn font_spec_merge_includes_style_and_color() {
706        let mut base = FontSpec {
707            family: Some("Noto Sans".into()),
708            style: Some(FontStyle::Normal),
709            color: Some(crate::Rgba::rgb(0, 0, 0)),
710            ..Default::default()
711        };
712        let overlay = FontSpec {
713            style: Some(FontStyle::Italic),
714            ..Default::default()
715        };
716        base.merge(&overlay);
717        assert_eq!(base.style, Some(FontStyle::Italic)); // overlay wins
718        assert_eq!(base.color, Some(crate::Rgba::rgb(0, 0, 0))); // base preserved
719        assert_eq!(base.family.as_deref(), Some("Noto Sans")); // base preserved
720    }
721
722    // === FontSize tests ===
723
724    #[test]
725    fn pt_to_logical_px_at_96_dpi() {
726        assert_eq!(FontSize::Pt(10.0).to_logical_px(96.0), 10.0 * 96.0 / 72.0);
727    }
728
729    #[test]
730    fn px_ignores_dpi() {
731        assert_eq!(FontSize::Px(14.0).to_logical_px(96.0), 14.0);
732        assert_eq!(FontSize::Px(14.0).to_logical_px(144.0), 14.0);
733    }
734
735    #[test]
736    fn pt_to_logical_px_at_72_dpi_is_identity() {
737        assert_eq!(FontSize::Pt(10.0).to_logical_px(72.0), 10.0);
738    }
739
740    #[test]
741    fn raw_extracts_value() {
742        assert_eq!(FontSize::Pt(10.0).raw(), 10.0);
743        assert_eq!(FontSize::Px(14.0).raw(), 14.0);
744    }
745
746    // === Serde round-trip tests ===
747
748    #[test]
749    fn fontspec_toml_round_trip_size_pt() {
750        let fs = FontSpec {
751            family: Some("Inter".into()),
752            size: Some(FontSize::Pt(10.0)),
753            weight: Some(400),
754            ..Default::default()
755        };
756        let toml_str = toml::to_string(&fs).expect("serialize");
757        assert!(
758            toml_str.contains("size_pt"),
759            "should contain size_pt: {toml_str}"
760        );
761        assert!(
762            !toml_str.contains("size_px"),
763            "should not contain size_px: {toml_str}"
764        );
765        let deserialized: FontSpec = toml::from_str(&toml_str).expect("deserialize");
766        assert_eq!(deserialized, fs);
767    }
768
769    #[test]
770    fn fontspec_toml_round_trip_size_px() {
771        let fs = FontSpec {
772            size: Some(FontSize::Px(14.0)),
773            ..Default::default()
774        };
775        let toml_str = toml::to_string(&fs).expect("serialize");
776        assert!(
777            toml_str.contains("size_px"),
778            "should contain size_px: {toml_str}"
779        );
780        assert!(
781            !toml_str.contains("size_pt"),
782            "should not contain size_pt: {toml_str}"
783        );
784        let deserialized: FontSpec = toml::from_str(&toml_str).expect("deserialize");
785        assert_eq!(deserialized, fs);
786    }
787
788    #[test]
789    fn fontspec_toml_rejects_both_pt_and_px() {
790        let toml_str = "size_pt = 10.0\nsize_px = 14.0\n";
791        assert!(toml::from_str::<FontSpec>(toml_str).is_err());
792    }
793
794    #[test]
795    fn fontspec_toml_rejects_bare_size() {
796        let toml_str = "size = 10.0\n";
797        // With #[serde(default)], the bare `size` key is NOT a recognized field
798        // in FontSpecRaw. It deserializes to FontSpec with size=None.
799        // The TOML linter (lint_toml) catches `size` as unknown separately.
800        let result: FontSpec = toml::from_str(toml_str).expect("deserialize");
801        assert!(
802            result.size.is_none(),
803            "bare 'size' should not set FontSpec.size"
804        );
805    }
806
807    #[test]
808    fn fontspec_toml_no_size_is_valid() {
809        let fs: FontSpec = toml::from_str(r#"family = "Inter""#).expect("deserialize");
810        assert!(fs.size.is_none());
811    }
812
813    #[test]
814    fn text_scale_entry_toml_round_trip_size_pt() {
815        let entry = TextScaleEntry {
816            size: Some(FontSize::Pt(9.0)),
817            weight: Some(400),
818            line_height: Some(FontSize::Pt(12.6)),
819        };
820        let toml_str = toml::to_string(&entry).expect("serialize");
821        assert!(toml_str.contains("size_pt"));
822        let deserialized: TextScaleEntry = toml::from_str(&toml_str).expect("deserialize");
823        assert_eq!(deserialized, entry);
824    }
825
826    #[test]
827    fn text_scale_entry_toml_round_trip_size_px() {
828        let entry = TextScaleEntry {
829            size: Some(FontSize::Px(14.0)),
830            weight: Some(400),
831            line_height: Some(FontSize::Px(18.0)),
832        };
833        let toml_str = toml::to_string(&entry).expect("serialize");
834        assert!(toml_str.contains("size_px"));
835        let deserialized: TextScaleEntry = toml::from_str(&toml_str).expect("deserialize");
836        assert_eq!(deserialized, entry);
837    }
838}