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