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)]
80pub enum FontSize {
81 Pt(f32),
86 Px(f32),
90}
91
92impl FontSize {
93 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 pub fn raw(self) -> f32 {
127 match self {
128 Self::Pt(v) | Self::Px(v) => v,
129 }
130 }
131
132 pub fn is_pt(self) -> bool {
134 matches!(self, Self::Pt(_))
135 }
136}
137
138#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
149#[serde(try_from = "FontSpecRaw", into = "FontSpecRaw")]
150#[theme_layer(fields = "family, size_pt, size_px, weight, style, color")]
155pub struct FontSpec {
156 pub family: Option<Arc<str>>,
158 pub size: Option<FontSize>,
164 pub weight: Option<u16>,
166 pub style: Option<FontStyle>,
168 pub color: Option<Rgba>,
170}
171
172#[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
185fn 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
200fn 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#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
256pub struct ResolvedFontSpec {
257 pub family: Arc<str>,
259 pub size: f32,
263 #[serde(default)]
280 pub defined_size: Option<FontSize>,
281 pub weight: u16,
283 pub style: FontStyle,
285 pub color: Rgba,
287}
288
289#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
294#[serde(try_from = "TextScaleEntryRaw", into = "TextScaleEntryRaw")]
295#[theme_layer(fields = "size_pt, size_px, weight, line_height_pt, line_height_px")]
299pub struct TextScaleEntry {
300 pub size: Option<FontSize>,
305 pub weight: Option<u16>,
307 pub line_height: Option<FontSize>,
313}
314
315#[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#[serde_with::skip_serializing_none]
371#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
372#[serde(default)]
373pub struct TextScale {
374 pub caption: Option<TextScaleEntry>,
376 pub section_heading: Option<TextScaleEntry>,
378 pub dialog_title: Option<TextScaleEntry>,
380 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 #[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 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 #[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))); assert_eq!(base.weight, Some(700)); assert_eq!(base.line_height, Some(FontSize::Px(1.5))); }
527
528 #[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))); assert_eq!(cap.weight, Some(600)); assert_eq!(cap.line_height, Some(FontSize::Px(1.3))); }
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 #[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 assert!(std::ptr::eq(
646 font.family.as_ref() as *const str,
647 cloned.family.as_ref() as *const str,
648 ));
649 }
650
651 #[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 #[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)); assert_eq!(base.color, Some(crate::Rgba::rgb(0, 0, 0))); assert_eq!(base.family.as_deref(), Some("Noto Sans")); }
722
723 #[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 #[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 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}