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, serde::Serialize, serde::Deserialize)]
79pub enum FontSize {
80 Pt(f32),
85 Px(f32),
89}
90
91impl FontSize {
92 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 pub fn raw(self) -> f32 {
126 match self {
127 Self::Pt(v) | Self::Px(v) => v,
128 }
129 }
130
131 pub fn is_pt(self) -> bool {
133 matches!(self, Self::Pt(_))
134 }
135}
136
137#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
148#[serde(try_from = "FontSpecRaw", into = "FontSpecRaw")]
149#[theme_layer(fields = "family, size_pt, size_px, weight, style, color")]
154pub struct FontSpec {
155 pub family: Option<Arc<str>>,
157 pub size: Option<FontSize>,
163 pub weight: Option<u16>,
165 pub style: Option<FontStyle>,
167 pub color: Option<Rgba>,
169}
170
171#[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
184fn 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
199fn 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#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
255pub struct ResolvedFontSpec {
256 pub family: Arc<str>,
258 pub size: f32,
262 #[serde(default)]
279 pub defined_size: Option<FontSize>,
280 pub weight: u16,
282 pub style: FontStyle,
284 pub color: Rgba,
286}
287
288#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
293#[serde(try_from = "TextScaleEntryRaw", into = "TextScaleEntryRaw")]
294#[theme_layer(fields = "size_pt, size_px, weight, line_height_pt, line_height_px")]
298pub struct TextScaleEntry {
299 pub size: Option<FontSize>,
304 pub weight: Option<u16>,
306 pub line_height: Option<FontSize>,
312}
313
314#[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#[serde_with::skip_serializing_none]
370#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
371#[serde(default)]
372pub struct TextScale {
373 pub caption: Option<TextScaleEntry>,
375 pub section_heading: Option<TextScaleEntry>,
377 pub dialog_title: Option<TextScaleEntry>,
379 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 #[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 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 #[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))); assert_eq!(base.weight, Some(700)); assert_eq!(base.line_height, Some(FontSize::Px(1.5))); }
526
527 #[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))); assert_eq!(cap.weight, Some(600)); assert_eq!(cap.line_height, Some(FontSize::Px(1.3))); }
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 #[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 assert!(std::ptr::eq(
645 font.family.as_ref() as *const str,
646 cloned.family.as_ref() as *const str,
647 ));
648 }
649
650 #[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 #[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)); assert_eq!(base.color, Some(crate::Rgba::rgb(0, 0, 0))); assert_eq!(base.family.as_deref(), Some("Noto Sans")); }
721
722 #[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 #[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 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}