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