1use std::collections::HashSet;
4use std::sync::{Arc, Mutex};
5
6use crate::Rgba;
7use native_theme_derive::ThemeFields;
8use serde::{Deserialize, Serialize};
9
10static FONT_FAMILY_CACHE: std::sync::LazyLock<Mutex<HashSet<Arc<str>>>> =
15 std::sync::LazyLock::new(|| Mutex::new(HashSet::new()));
16
17pub 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 Arc::from(family)
53 }
54}
55
56#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
58#[serde(rename_all = "lowercase")]
59pub enum FontStyle {
60 #[default]
62 Normal,
63 Italic,
65 Oblique,
67}
68
69#[derive(Clone, Copy, Debug, PartialEq)]
79pub enum FontSize {
80 Pt(f32),
84 Px(f32),
87}
88
89impl FontSize {
90 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 pub fn raw(self) -> f32 {
124 match self {
125 Self::Pt(v) | Self::Px(v) => v,
126 }
127 }
128
129 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#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
152#[serde(try_from = "FontSpecRaw", into = "FontSpecRaw")]
153#[theme_layer(fields = "family, size_pt, size_px, weight, style, color")]
158pub struct FontSpec {
159 pub family: Option<Arc<str>>,
161 pub size: Option<FontSize>,
167 pub weight: Option<u16>,
169 pub style: Option<FontStyle>,
171 pub color: Option<Rgba>,
173}
174
175#[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#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
239pub struct ResolvedFontSpec {
240 pub family: Arc<str>,
242 pub size: f32,
245 pub weight: u16,
247 pub style: FontStyle,
249 pub color: Rgba,
251}
252
253#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
258#[serde(try_from = "TextScaleEntryRaw", into = "TextScaleEntryRaw")]
259#[theme_layer(fields = "size_pt, size_px, weight, line_height_pt, line_height_px")]
263pub struct TextScaleEntry {
264 pub size: Option<FontSize>,
269 pub weight: Option<u16>,
271 pub line_height: Option<FontSize>,
274}
275
276#[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#[serde_with::skip_serializing_none]
356#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
357#[serde(default)]
358pub struct TextScale {
359 pub caption: Option<TextScaleEntry>,
361 pub section_heading: Option<TextScaleEntry>,
363 pub dialog_title: Option<TextScaleEntry>,
365 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 #[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 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 #[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))); assert_eq!(base.weight, Some(700)); assert_eq!(base.line_height, Some(FontSize::Px(1.5))); }
512
513 #[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))); assert_eq!(cap.weight, Some(600)); assert_eq!(cap.line_height, Some(FontSize::Px(1.3))); }
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 #[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 assert!(std::ptr::eq(
630 font.family.as_ref() as *const str,
631 cloned.family.as_ref() as *const str,
632 ));
633 }
634
635 #[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 #[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)); assert_eq!(base.color, Some(crate::Rgba::rgb(0, 0, 0))); assert_eq!(base.family.as_deref(), Some("Noto Sans")); }
706
707 #[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 #[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 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}