1mod blob;
4mod cache;
5mod format;
6mod source;
7mod tables;
8
9#[doc(inline)]
10pub use blob::Blob;
11#[doc(inline)]
12pub use format::Format;
13#[doc(inline)]
14pub use source::Source;
15#[doc(inline)]
16pub use tables::{TableFunction, Tables};
17
18#[doc(hidden)]
20#[rust_analyzer::completions(hidden_from_completion)]
21pub mod interop;
22
23use super::attribute::Attributes;
24use super::charmap::{Charmap, EncodingTables, SfntUnicodeCharmap};
25use super::glyph::{
26 bitmap::BitmapStrikes,
27 color::{ColorGlyphs, Palettes},
28 outline::{varc, OutlineGlyphs, OutlineSource},
29 GlyphSource, GlyphSourceOrder,
30};
31use super::metrics::{empty_glyph_metrics, GlyphMetrics, Metrics, StyleMetrics};
32use super::name::{self, GlyphName, Names};
33use super::once::Once;
34use super::variation::{Axes, NamedInstances, NormalizedCoord, Variation};
35use crate::tables::glyf::outline::OutlineContext;
36use crate::tables::loca::LocaGlyph;
37use crate::tables::{
38 avar::Avar,
39 fvar::Fvar,
40 glyf::{Glyf, PHANTOM_POINT_COUNT},
41 gvar::{GlyphVariationData, SelectedGvar},
42 hmtx::GlyphMetricRecords,
43 hvar::Hvar,
44 layout::SelectedFeatureVariations,
45 loca::Loca,
46 vorg::Vorg,
47 vvar::Vvar,
48};
49use crate::{
50 ps::{
51 cff::{CffFontRef, Subfont},
52 type1::{MultipleMaster, Type1Font, Type1Instance},
53 },
54 tables::{
55 cbdt::Cbdt, cblc::Cblc, cpal::Cpal, ebdt::Ebdt, eblc::Eblc, fvar::VariationAxisRecord,
56 sbix::Sbix,
57 },
58 TableProvider,
59};
60use alloc::{boxed::Box, sync::Arc};
61pub(crate) use cache::ColrTables;
62use cache::{
63 CbdtTables, Cff2Font, CffFont, CpalTable, EbdtTables, GlyfLoca, GvarTable, HvarTable,
64 MetricsTable, SbixTable, TableCache, VorgTable, VvarTable,
65};
66use core::{
67 any::Any,
68 sync::atomic::{self, AtomicBool, AtomicU32},
69};
70use smallvec::SmallVec;
71use types::{F2Dot14, Fixed, GlyphId, Point};
72use yoke::Yoke;
73
74#[derive(Clone)]
78pub struct Font(Repr);
79
80#[derive(Clone)]
81enum Repr {
82 Default(SharedFont),
83 Varied(Arc<VariedInstance>),
84}
85
86impl Font {
87 pub fn new(source: impl Into<Source>, index: u32) -> Option<Self> {
101 Some(Font(Repr::Default(SharedFont::new(source, index)?)))
102 }
103
104 pub fn axes(&self) -> Axes<'_> {
107 Axes::new(self)
108 }
109
110 pub fn named_instances(&self) -> NamedInstances<'_> {
112 NamedInstances::new(self)
113 }
114
115 pub fn instance_builder(&self) -> InstanceBuilder {
120 InstanceBuilder {
121 font: self.shared().clone(),
122 coords: CoordStorage::default(),
123 type1_blend: SmallVec::new(),
124 }
125 }
126
127 #[inline]
129 pub fn default_instance(&self) -> Font {
130 Font(Repr::Default(self.shared().clone()))
131 }
132
133 pub fn normalized_coords(&self) -> &[NormalizedCoord] {
135 match &self.0 {
136 Repr::Default(_) => &[],
137 Repr::Varied(varied) => varied.coords.as_slice(),
138 }
139 }
140
141 pub fn feature_variations(&self) -> SelectedFeatureVariations {
143 match self.sfnt_location() {
144 Some(location) => location
145 .feature_vars
146 .load(self.shared(), self.normalized_coords()),
147 None => SelectedFeatureVariations::default(),
149 }
150 }
151
152 #[inline]
156 pub fn num_glyphs(&self) -> u32 {
157 self.shared().num_glyphs()
158 }
159
160 #[inline]
164 pub fn units_per_em(&self) -> u16 {
165 self.shared().units_per_em()
166 }
167
168 pub fn default_attributes(&self) -> Attributes {
179 Attributes::from_font(self)
180 }
181
182 pub fn is_hint_reliant(&self) -> bool {
190 use core::sync::atomic::Ordering;
191 const UNKNOWN: u8 = 0;
192 const KNOWN: u8 = 1;
193 let Some(sfnt) = self.shared().sfnt() else {
195 return false;
196 };
197 let cell = &sfnt.hint_reliant;
198 match cell.load(Ordering::Relaxed) {
199 UNKNOWN => {
200 let answer = crate::tables::glyf::is_hint_reliant(&self.tables());
201 cell.store(KNOWN + answer as u8, Ordering::Relaxed);
202 answer
203 }
204 state => state > KNOWN,
205 }
206 }
207
208 pub fn names(&self) -> Names<'_> {
210 match self.kind() {
211 Kind::Type1(font) => Names::from_type1(font),
212 Kind::Cff(ref font, _) => Names::from_cff(font),
213 _ => Names::from_sfnt(&self.tables()),
214 }
215 }
216
217 pub fn glyph_name(&self, glyph: GlyphId) -> Option<GlyphName> {
221 name::glyph_name(self, glyph)
222 }
223
224 pub fn glyph_names(&self) -> impl Iterator<Item = (GlyphId, GlyphName)> + '_ {
229 name::glyph_names(self)
230 }
231
232 pub fn glyph_by_name(&self, name: &str) -> Option<GlyphId> {
240 self.shared()
241 .0
242 .glyph_name_index
243 .get_or_init(|| name::GlyphNameIndex::new(self))
244 .get(name)
245 }
246
247 pub fn is_cid_keyed(&self) -> bool {
253 if let Kind::Type1(font) = self.kind() {
254 return font.is_cid_keyed();
255 }
256 self.shared()
257 .standalone_cff()
258 .is_some_and(|cff| cff.is_cid())
259 }
260
261 pub fn max_cid(&self) -> Option<u32> {
268 if let Kind::Type1(font) = self.kind() {
269 return font.max_cid();
270 }
271 Some(self.shared().cid_glyphs()?.len() as u32 - 1)
272 }
273
274 pub fn glyph_by_cid(&self, cid: u32) -> Option<GlyphId> {
282 if let Kind::Type1(font) = self.kind() {
283 return font.glyph_by_cid(cid);
284 }
285 let glyph = *self.shared().cid_glyphs()?.get(cid as usize)?;
286 (cid == 0 || glyph != 0).then(|| GlyphId::new(glyph as u32))
287 }
288
289 pub fn charmap(&self) -> Charmap<'_> {
291 Charmap::new(self)
292 }
293
294 pub fn metrics(&self) -> &Metrics {
297 match &self.0 {
298 Repr::Default(font) => font.metrics(),
300 Repr::Varied(varied) if matches!(varied.kind, VariedKind::Type1(_)) => {
303 varied.font.metrics()
304 }
305 Repr::Varied(varied) => varied.location.metrics.get_or_init(|| {
306 debug_assert!(!varied.coords.as_slice().is_empty());
307 Metrics::from_sfnt(&varied.font.tables(), varied.coords.as_slice())
308 }),
309 }
310 }
311
312 pub fn style_metrics(&self) -> &StyleMetrics {
316 match &self.0 {
317 Repr::Default(font) => font.style_metrics(),
318 Repr::Varied(varied) if matches!(varied.kind, VariedKind::Type1(_)) => {
319 varied.font.style_metrics()
320 }
321 Repr::Varied(varied) => varied
322 .location
323 .style_metrics
324 .get_or_init(|| {
325 Box::new(StyleMetrics::from_sfnt(
326 &varied.font.tables(),
327 varied.coords.as_slice(),
328 ))
329 })
330 .as_ref(),
331 }
332 }
333
334 #[inline]
337 pub fn glyph_metrics(&self) -> GlyphMetrics<'_> {
338 GlyphMetrics::new(self, self.metrics(), self.normalized_coords())
339 }
340
341 pub fn outline_glyphs(&self) -> OutlineGlyphs<'_> {
344 OutlineGlyphs::new(self, GlyphSourceOrder::DEFAULT)
345 }
346
347 pub fn outline_glyphs_with(&self, order: GlyphSourceOrder) -> OutlineGlyphs<'_> {
355 OutlineGlyphs::new(self, order)
356 }
357
358 pub fn bitmap_strikes(&self) -> BitmapStrikes<'_> {
361 BitmapStrikes::new(self, GlyphSourceOrder::BITMAPS)
362 }
363
364 pub fn bitmap_strikes_with(&self, order: GlyphSourceOrder) -> BitmapStrikes<'_> {
369 BitmapStrikes::new(self, order)
370 }
371
372 pub fn color_glyphs(&self) -> ColorGlyphs<'_> {
374 ColorGlyphs::new(self)
375 }
376
377 pub fn palettes(&self) -> Palettes<'_> {
379 Palettes::new(self)
380 }
381
382 #[inline]
384 pub fn source(&self) -> &Source {
385 self.shared().source()
386 }
387
388 #[inline]
390 pub fn kind(&self) -> Kind<'_> {
391 self.shared().kind()
392 }
393
394 #[inline]
398 pub fn tables(&self) -> &Tables {
399 self.shared().tables()
400 }
401}
402
403impl Font {
404 pub(super) fn scaling_data(&self) -> &Once<Box<dyn Any + Send + Sync>> {
410 &self.location_caches().scaling_data
411 }
412
413 fn location_caches(&self) -> &LocationCaches {
418 match &self.0 {
419 Repr::Default(font) => &font.0.default_location,
420 Repr::Varied(varied) => &varied.location,
421 }
422 }
423
424 fn sfnt_location(&self) -> Option<&SfntLocation> {
427 match &self.0 {
428 Repr::Default(font) => font.sfnt().map(|sfnt| &sfnt.default_location),
429 Repr::Varied(varied) => match &varied.kind {
430 VariedKind::Sfnt(sfnt) => Some(&sfnt.location),
431 VariedKind::Type1(_) => None,
432 },
433 }
434 }
435
436 pub(super) fn shared(&self) -> &SharedFont {
438 match &self.0 {
439 Repr::Default(font) => font,
440 Repr::Varied(varied) => &varied.font,
441 }
442 }
443
444 pub(crate) fn type1_axes(&self) -> Option<&[VariationAxisRecord]> {
447 self.shared().multiple_master()?;
448 Some(self.shared().type1_axes())
449 }
450
451 pub(crate) fn type1_instance(&self) -> Option<Type1Instance<'_>> {
453 let Kind::Type1(font) = self.shared().kind() else {
454 return None;
455 };
456 Some(match &self.0 {
457 Repr::Varied(varied) => match &varied.kind {
458 VariedKind::Type1(type1) => font.instance(&type1.weights),
459 VariedKind::Sfnt(_) => font.default_instance(),
460 },
461 Repr::Default(_) => font.default_instance(),
462 })
463 }
464
465 #[inline]
467 pub(crate) fn h_metric_records(&self) -> &GlyphMetricRecords<'_> {
468 self.shared().h_metric_records()
469 }
470
471 #[inline]
473 pub(crate) fn v_metric_records(&self) -> &GlyphMetricRecords<'_> {
474 self.shared().v_metric_records()
475 }
476
477 #[inline]
479 pub(crate) fn selected_glyf_loca(&self) -> Option<&(Glyf<'_>, Loca<'_>)> {
480 self.shared().selected_glyf_loca()
481 }
482
483 #[inline]
485 pub(crate) fn hvar(&self) -> Option<&Hvar<'_>> {
486 self.shared().hvar()
487 }
488
489 #[inline]
491 pub(crate) fn vvar(&self) -> Option<&Vvar<'_>> {
492 self.shared().vvar()
493 }
494
495 #[inline]
497 pub(crate) fn selected_gvar(&self) -> Option<&SelectedGvar<'_>> {
498 self.shared().selected_gvar()
499 }
500
501 pub(crate) fn gvar_scalars(&self) -> &[Fixed] {
504 self.location_scalars(
505 |sfnt| &sfnt.gvar_scalars,
506 |varied| match varied.font.selected_gvar() {
507 Some(gvar) => scalars_with(gvar.shared_tuple_count() as usize, |out| {
508 gvar.compute_scalars(varied.coords.as_slice(), out)
509 }),
510 None => Box::new([]),
511 },
512 )
513 }
514
515 pub(crate) fn hvar_scalars(&self) -> &[Fixed] {
517 self.location_scalars(
518 |sfnt| &sfnt.hvar_scalars,
519 |varied| {
520 let store = varied
521 .font
522 .hvar()
523 .and_then(|hvar| hvar.item_variation_store().ok());
524 store_scalars(store.as_ref(), varied.coords.as_slice())
525 },
526 )
527 }
528
529 pub(crate) fn vvar_scalars(&self) -> &[Fixed] {
531 self.location_scalars(
532 |sfnt| &sfnt.vvar_scalars,
533 |varied| {
534 let store = varied
535 .font
536 .vvar()
537 .and_then(|vvar| vvar.item_variation_store().ok());
538 store_scalars(store.as_ref(), varied.coords.as_slice())
539 },
540 )
541 }
542
543 pub(crate) fn colr_scalars(&self) -> &[Fixed] {
545 self.location_scalars(
546 |sfnt| &sfnt.colr_scalars,
547 |varied| {
548 let store = varied
549 .font
550 .colr_tables()
551 .and_then(|tables| tables.var_store.as_ref());
552 store_scalars(store, varied.coords.as_slice())
553 },
554 )
555 }
556
557 fn location_scalars(
560 &self,
561 cache: fn(&VariedSfnt) -> &Once<Box<[Fixed]>>,
562 compute: impl FnOnce(&VariedInstance) -> Box<[Fixed]>,
563 ) -> &[Fixed] {
564 match &self.0 {
565 Repr::Default(_) => &[],
566 Repr::Varied(varied) => match &varied.kind {
567 VariedKind::Sfnt(sfnt) => cache(sfnt).get_or_init(|| compute(varied)),
568 VariedKind::Type1(_) => &[],
569 },
570 }
571 }
572
573 #[inline]
575 pub(crate) fn cff(&self) -> Option<&CffFontRef<'_>> {
576 self.shared().cff()
577 }
578
579 pub(crate) fn charstrings(&self, source: OutlineSource) -> Option<&CffFontRef<'_>> {
584 let shared = self.shared();
585 match source {
586 OutlineSource::Cff2 => shared.cff2(),
587 OutlineSource::Cff => shared.cff().or_else(|| shared.standalone_cff()),
588 _ => None,
589 }
590 }
591
592 pub(crate) fn cff_subfont(&self, source: OutlineSource, index: u16) -> Option<Subfont> {
602 let cff = self.charstrings(source)?;
603 if let Some(subfonts) = self.shared().standalone_cff_subfonts() {
604 return match subfonts.get(usize::from(index)) {
605 Some(subfont) => *subfont,
606 None => cff.subfont(index, &[]).ok(),
607 };
608 }
609 let location = self.sfnt_location()?;
610 let cache = match source {
611 OutlineSource::Cff2 => &location.cff2_subfonts,
612 _ => &location.cff_subfonts,
613 };
614 let coords = self.normalized_coords();
615 let subfonts = cache.get_or_init(|| {
616 let count = (cff.num_subfonts() as usize).min(CACHED_SUBFONTS);
617 (0..count).map(|_| Once::new()).collect()
618 });
619 match subfonts.get(usize::from(index)) {
620 Some(subfont) => *subfont.get_or_init(|| cff.subfont(index, coords).ok()),
621 None => cff.subfont(index, coords).ok(),
622 }
623 }
624
625 pub(crate) fn has_layered_source(&self, source: GlyphSource) -> bool {
631 use core::sync::atomic::Ordering;
632 let Some(sfnt) = self.shared().sfnt() else {
633 return false;
634 };
635 let shift = 2 * (source as u32 - 1);
636 match (sfnt.glyph_sources.load(Ordering::Relaxed) >> shift) & 3 {
637 SOURCE_ABSENT => return false,
638 SOURCE_PRESENT => return true,
639 _ => {}
640 }
641 let present = match source {
642 GlyphSource::Sbix | GlyphSource::Cbdt | GlyphSource::Ebdt => !self
643 .bitmap_strikes_with(GlyphSourceOrder::new(&[source]))
644 .is_empty(),
645 GlyphSource::Colr => !self.color_glyphs().is_empty(),
646 GlyphSource::Varc => self.varc_outlines().is_some(),
647 _ => return false,
648 };
649 let state = if present {
650 SOURCE_PRESENT
651 } else {
652 SOURCE_ABSENT
653 };
654 sfnt.glyph_sources
655 .fetch_or(state << shift, Ordering::Relaxed);
656 present
657 }
658
659 pub(crate) fn has_layered_source_in(&self, order: GlyphSourceOrder) -> bool {
665 let Some(sfnt) = self.shared().sfnt() else {
666 return false;
667 };
668 let known = sfnt
669 .glyph_sources
670 .load(core::sync::atomic::Ordering::Relaxed);
671 order.iter().any(|source| {
672 if !matches!(
673 source,
674 GlyphSource::Sbix
675 | GlyphSource::Cbdt
676 | GlyphSource::Ebdt
677 | GlyphSource::Colr
678 | GlyphSource::Varc
679 ) {
680 return false;
681 }
682 match (known >> (2 * (source as u32 - 1))) & 3 {
683 SOURCE_ABSENT => false,
684 SOURCE_PRESENT => true,
685 _ => self.has_layered_source(source),
686 }
687 })
688 }
689
690 #[cfg(test)]
692 pub(crate) fn probed_glyph_sources(&self) -> u32 {
693 self.shared().sfnt().map_or(0, |sfnt| {
694 sfnt.glyph_sources
695 .load(core::sync::atomic::Ordering::Relaxed)
696 })
697 }
698
699 #[inline]
701 pub(crate) fn varc_outlines(&self) -> Option<&varc::Outlines<'_>> {
702 self.shared().varc_outlines()
703 }
704
705 #[inline]
707 pub(crate) fn colr_tables(&self) -> Option<&ColrTables<'_>> {
708 self.shared().colr_tables()
709 }
710
711 #[inline]
713 pub(crate) fn cpal(&self) -> Option<&Cpal<'_>> {
714 self.shared().cpal()
715 }
716
717 #[inline]
719 pub(crate) fn sbix(&self) -> Option<&Sbix<'_>> {
720 self.shared().sbix()
721 }
722
723 #[inline]
725 pub(crate) fn cbdt(&self) -> Option<&(Cblc<'_>, Cbdt<'_>)> {
726 self.shared().cbdt()
727 }
728
729 #[inline]
731 pub(crate) fn ebdt(&self) -> Option<&(Eblc<'_>, Ebdt<'_>)> {
732 self.shared().ebdt()
733 }
734
735 #[inline]
737 pub(crate) fn vorg(&self) -> Option<&Vorg<'_>> {
738 self.shared().vorg()
739 }
740}
741
742impl<'a> OutlineContext<'a> for &'a Font {
743 fn glyph(&self, glyph: GlyphId) -> Option<LocaGlyph<'a>> {
744 let (glyf, loca) = self.selected_glyf_loca()?;
745 loca.get(glyph, glyf)
746 }
747
748 fn glyph_variation_data(&self, glyph: GlyphId) -> Option<GlyphVariationData<'a>> {
749 self.selected_gvar()?.glyph_variation_data(glyph).ok()?
750 }
751
752 fn has_gvar(&self) -> bool {
753 self.selected_gvar().is_some()
754 }
755
756 fn phantom_point_deltas(&self, glyph: GlyphId) -> Option<[Point<Fixed>; PHANTOM_POINT_COUNT]> {
757 let (glyf, loca) = self.selected_glyf_loca()?;
758 self.selected_gvar()?.phantom_point_deltas_with_scalars(
759 glyf,
760 loca,
761 self.normalized_coords(),
762 self.gvar_scalars(),
763 glyph,
764 )
765 }
766
767 fn gvar_scalars(&self) -> &[Fixed] {
768 Font::gvar_scalars(self)
769 }
770
771 fn coords(&self) -> &[F2Dot14] {
772 self.normalized_coords()
773 }
774
775 fn units_per_em(&self) -> u16 {
776 Font::units_per_em(self)
777 }
778
779 fn h_metrics(&self, glyph: GlyphId) -> (i32, i32) {
780 let metrics = self.h_metric_records();
781 (
782 metrics
783 .stated_side_bearing(glyph)
784 .unwrap_or_default()
785 .to_i32(),
786 metrics.stated_advance(self.num_glyphs(), glyph).to_i32(),
787 )
788 }
789
790 fn v_metrics(&self, glyph: GlyphId) -> Option<(i32, i32)> {
791 let metrics = self.v_metric_records();
792 if metrics.is_empty() {
793 return None;
794 }
795 Some((
796 metrics
797 .stated_side_bearing(glyph)
798 .unwrap_or_default()
799 .to_i32(),
800 metrics.stated_advance(self.num_glyphs(), glyph).to_i32(),
801 ))
802 }
803
804 fn h_line_metrics(&self) -> (i32, i32) {
805 self.shared().metrics().h_line().map_or((0, 0), |line| {
806 (line.ascender.to_i32(), line.descender.to_i32())
807 })
808 }
809
810 fn has_hvar(&self) -> bool {
811 self.hvar().is_some()
812 }
813}
814
815#[derive(Clone)]
817pub enum Kind<'a> {
818 Sfnt(&'a Tables, u32),
820 Type1(&'a Type1Font),
822 Cff(CffFontRef<'a>, u32),
824}
825
826pub struct InstanceBuilder {
828 font: SharedFont,
829 coords: CoordStorage,
830 type1_blend: SmallVec<[Fixed; 4]>,
833}
834
835impl InstanceBuilder {
836 pub fn variations<V>(mut self, variations: V) -> Self
844 where
845 V: IntoIterator,
846 V::Item: Into<Variation>,
847 {
848 self.set_variations(variations);
849 self
850 }
851
852 pub fn normalized_coords(mut self, coords: impl IntoIterator<Item = NormalizedCoord>) -> Self {
862 self.set_coords(coords);
863 self
864 }
865
866 pub fn named_instance(mut self, index: u32) -> Self {
873 self.set_named_instance(index);
874 self
875 }
876
877 pub fn named_instance_with_overrides<V>(mut self, index: u32, overrides: V) -> Self
885 where
886 V: IntoIterator,
887 V::Item: Into<Variation>,
888 {
889 self.set_named_instance_with_overrides(index, overrides);
890 self
891 }
892
893 pub fn build(self) -> Font {
895 if self.coords.as_slice().is_empty() {
898 return Font(Repr::Default(self.font));
899 }
900 let kind = match &self.font.0.kind {
901 KindRepr::Sfnt(_) => VariedKind::Sfnt(VariedSfnt {
902 location: SfntLocation::new(),
903 gvar_scalars: Once::new(),
904 hvar_scalars: Once::new(),
905 colr_scalars: Once::new(),
906 vvar_scalars: Once::new(),
907 }),
908 KindRepr::Type1(type1) => {
909 let Some(mm) = type1.font.multiple_master() else {
910 return Font(Repr::Default(self.font));
911 };
912 let mut weights = SmallVec::from_elem(Fixed::ZERO, mm.num_masters());
913 mm.blend_to_weights(&self.type1_blend, &mut weights);
914 VariedKind::Type1(VariedType1 { weights })
915 }
916 KindRepr::StandaloneCff(_) => return Font(Repr::Default(self.font)),
919 };
920 Font(Repr::Varied(Arc::new(VariedInstance {
921 font: self.font,
922 coords: self.coords,
923 location: LocationCaches::new(),
924 kind,
925 })))
926 }
927}
928
929impl InstanceBuilder {
930 fn set_variations<V>(&mut self, variations: V)
931 where
932 V: IntoIterator,
933 V::Item: Into<Variation>,
934 {
935 if let Some(mm) = self.font.multiple_master() {
936 let axes = self.font.type1_axes();
938 let mut design: SmallVec<[Fixed; 4]> =
939 axes.iter().map(|axis| axis.default_value()).collect();
940 let mut named: SmallVec<[bool; 4]> = SmallVec::from_elem(false, design.len());
941 for variation in variations {
942 let variation = variation.into();
943 for ((axis, value), named) in axes.iter().zip(design.iter_mut()).zip(&mut named) {
944 if axis.axis_tag() == variation.tag {
945 *value = Fixed::from_f64(variation.value as f64);
946 *named = true;
947 }
948 }
949 }
950 let mut blend = SmallVec::from_elem(Fixed::ZERO, design.len());
951 mm.design_to_blend(&design, &mut blend);
952 let mut default = SmallVec::<[Fixed; 4]>::from_elem(Fixed::ZERO, design.len());
955 mm.default_blend(&mut default);
956 for ((value, default), named) in blend.iter_mut().zip(default).zip(named) {
957 if !named {
958 *value = default;
959 }
960 }
961 self.set_type1_blend(blend);
962 return;
963 }
964 let tables = self.font.tables();
965 if let Ok(fvar) = tables.fvar() {
966 set_variations(&fvar, tables.avar().ok(), &mut self.coords, variations);
967 } else {
968 self.coords.clear();
969 }
970 }
971
972 fn set_coords(&mut self, coords: impl IntoIterator<Item = NormalizedCoord>) {
973 if let Some(mm) = self.font.multiple_master() {
974 let mut blend: SmallVec<[Fixed; 4]> = SmallVec::from_elem(Fixed::ZERO, mm.axes().len());
976 mm.default_blend(&mut blend);
977 for (dst, src) in blend.iter_mut().zip(coords) {
978 *dst = src.to_fixed();
979 }
980 self.set_type1_blend(blend);
981 return;
982 }
983 if let Ok(fvar) = self.font.tables().fvar() {
984 let count = fvar.axis_count() as usize;
985 self.coords.resize(count, NormalizedCoord::ZERO);
986 for (dst, src) in self.coords.as_mut_slice().iter_mut().zip(
987 coords
988 .into_iter()
989 .chain(core::iter::repeat(NormalizedCoord::ZERO)),
990 ) {
991 *dst = src;
992 }
993 clear_if_all_zeroes(&mut self.coords);
994 } else {
995 self.coords.clear();
996 }
997 }
998
999 fn set_type1_blend(&mut self, blend: SmallVec<[Fixed; 4]>) {
1008 let font = self.font.clone();
1009 let Some(mm) = font.multiple_master() else {
1010 return;
1011 };
1012 let mut weights: SmallVec<[Fixed; 16]> = SmallVec::from_elem(Fixed::ZERO, mm.num_masters());
1013 mm.blend_to_weights(&blend, &mut weights);
1014 let mut reported: SmallVec<[Fixed; 4]> = SmallVec::from_elem(Fixed::ZERO, blend.len());
1015 mm.weights_to_blend(&weights, &mut reported);
1016 self.coords = reported.iter().map(|value| value.to_f2dot14()).collect();
1017 self.type1_blend = blend;
1018 }
1019
1020 fn set_named_instance(&mut self, index: u32) {
1021 let tables = self.font.tables();
1022 if let Ok(fvar) = tables.fvar() {
1023 set_variations(
1024 &fvar,
1025 tables.avar().ok(),
1026 &mut self.coords,
1027 named_instance_variations(&fvar, index),
1028 );
1029 } else {
1030 self.coords.clear();
1031 }
1032 }
1033
1034 fn set_named_instance_with_overrides<V>(&mut self, index: u32, overrides: V)
1035 where
1036 V: IntoIterator,
1037 V::Item: Into<Variation>,
1038 {
1039 if self.font.multiple_master().is_some() {
1042 self.set_variations(overrides);
1043 return;
1044 }
1045 let tables = self.font.tables();
1046 if let Ok(fvar) = tables.fvar() {
1047 set_variations(
1048 &fvar,
1049 tables.avar().ok(),
1050 &mut self.coords,
1051 named_instance_variations(&fvar, index)
1052 .chain(overrides.into_iter().map(Into::into)),
1053 );
1054 } else {
1055 self.coords.clear();
1056 }
1057 }
1058}
1059
1060fn named_instance_variations<'a>(
1062 fvar: &'a Fvar,
1063 index: u32,
1064) -> impl Iterator<Item = Variation> + 'a {
1065 fvar.axis_instance_arrays()
1066 .ok()
1067 .and_then(|arrays| {
1068 let axes = arrays.axes();
1069 arrays.instances().get(index as usize).ok().map(|instance| {
1070 axes.iter()
1071 .zip(instance.coordinates)
1072 .map(|(axis, coord)| Variation::new(axis.axis_tag(), coord.get().to_f32()))
1073 })
1074 })
1075 .into_iter()
1076 .flatten()
1077}
1078
1079fn set_variations<V>(fvar: &Fvar, avar: Option<Avar>, coords: &mut CoordStorage, variations: V)
1083where
1084 V: IntoIterator,
1085 V::Item: Into<Variation>,
1086{
1087 coords.resize(fvar.axis_count() as usize, NormalizedCoord::ZERO);
1088 fvar.user_to_normalized(
1089 avar.as_ref(),
1090 variations
1091 .into_iter()
1092 .map(Into::into)
1093 .map(|var| (var.tag, Fixed::from_f64(var.value as _))),
1094 coords.as_mut_slice(),
1095 );
1096 clear_if_all_zeroes(coords);
1097}
1098
1099#[derive(Clone)]
1104pub(super) struct SharedFont(Arc<SharedFontRepr>);
1105
1106impl SharedFont {
1107 fn new(source: impl Into<Source>, index: u32) -> Option<Self> {
1111 let source = source.into();
1112 let kind = if let Some(tables) = Tables::new(source.clone(), index) {
1113 Some(KindRepr::Sfnt(SfntCaches::new(Arc::new(tables), index)))
1114 } else if let Source::Blob(blob) = &source {
1115 match Format::new(blob) {
1116 Some(Format::Type1) => Type1Font::new(blob).ok().map(|font| {
1117 let axes = font
1118 .multiple_master()
1119 .map(super::variation::type1_axis_records)
1120 .unwrap_or_default();
1121 KindRepr::Type1(Type1Data { font, axes })
1122 }),
1123 Some(Format::Cff(count)) if index < count => {
1124 let font = Yoke::<CffFontRef<'static>, Arc<Blob>>::try_attach_to_cart(
1125 Arc::new(blob.clone()),
1126 |blob| CffFontRef::new_cff(blob, index, None),
1127 )
1128 .ok()?;
1129 let count = font.get().num_subfonts().min(CACHED_SUBFONTS as _);
1132 let subfonts = (0..count)
1133 .map(|index| font.get().subfont(index, &[]).ok())
1134 .collect();
1135 Some(KindRepr::StandaloneCff(StandaloneCffData {
1136 font,
1137 subfonts,
1138 index,
1139 unicode_charmap: Once::new(),
1140 cid_glyphs: Once::new(),
1141 }))
1142 }
1143 _ => None,
1144 }
1145 } else {
1146 None
1147 };
1148 let kind = kind?;
1149 let repr = SharedFontRepr {
1150 source,
1151 kind,
1152 shaping_data: Once::new(),
1153 glyph_name_index: Once::new(),
1154 default_location: LocationCaches::new(),
1155 };
1156 Some(Self(Arc::new(repr)))
1157 }
1158
1159 fn source(&self) -> &Source {
1161 &self.0.source
1162 }
1163
1164 pub(super) fn kind(&self) -> Kind<'_> {
1166 match &self.0.kind {
1167 KindRepr::Sfnt(sfnt) => Kind::Sfnt(&sfnt.tables, sfnt.index),
1168 KindRepr::Type1(type1) => Kind::Type1(&type1.font),
1169 KindRepr::StandaloneCff(cff) => Kind::Cff(cff.font.get().clone(), cff.index),
1170 }
1171 }
1172
1173 fn multiple_master(&self) -> Option<&MultipleMaster> {
1175 match &self.0.kind {
1176 KindRepr::Type1(type1) => type1.font.multiple_master(),
1177 _ => None,
1178 }
1179 }
1180
1181 fn type1_axes(&self) -> &[VariationAxisRecord] {
1184 match &self.0.kind {
1185 KindRepr::Type1(type1) => &type1.axes,
1186 _ => &[],
1187 }
1188 }
1189
1190 #[inline]
1193 fn metrics(&self) -> &Metrics {
1194 self.0
1195 .default_location
1196 .metrics
1197 .get_or_init(|| match self.kind() {
1198 Kind::Type1(font) => Metrics::from_type1(font),
1199 Kind::Cff(font, _) => Metrics::from_cff(&font),
1200 _ => Metrics::from_sfnt(&self.tables(), &[]),
1201 })
1202 }
1203
1204 fn style_metrics(&self) -> &StyleMetrics {
1206 self.0
1207 .default_location
1208 .style_metrics
1209 .get_or_init(|| {
1210 Box::new(match self.kind() {
1211 Kind::Type1(font) => StyleMetrics::from_type1(font),
1212 Kind::Cff(font, _) => StyleMetrics::from_cff(&font),
1213 _ => StyleMetrics::from_sfnt(&self.tables(), &[]),
1214 })
1215 })
1216 .as_ref()
1217 }
1218
1219 #[inline]
1223 pub(super) fn num_glyphs(&self) -> u32 {
1224 self.metrics().num_glyphs
1225 }
1226
1227 #[inline]
1231 fn units_per_em(&self) -> u16 {
1232 self.metrics().units_per_em
1233 }
1234
1235 #[inline]
1238 pub(super) fn sfnt(&self) -> Option<&SfntCaches> {
1239 match &self.0.kind {
1240 KindRepr::Sfnt(sfnt) => Some(sfnt),
1241 _ => None,
1242 }
1243 }
1244
1245 fn tables_arc(&self) -> Option<&Arc<Tables>> {
1247 self.sfnt().map(|sfnt| &sfnt.tables)
1248 }
1249
1250 pub(super) fn unicode_charmap(&self) -> Option<&SfntUnicodeCharmap<'_>> {
1252 let sfnt = self.sfnt()?;
1253 Some(
1254 sfnt.charmap
1255 .get_or_init(|| {
1256 TableCache::read(sfnt.tables.clone(), |tables| {
1257 SfntUnicodeCharmap::read(&tables)
1258 })
1259 })
1260 .get(),
1261 )
1262 }
1263
1264 pub(super) fn encodings(&self) -> Option<&EncodingTables<'_>> {
1266 let sfnt = self.sfnt()?;
1267 Some(
1268 sfnt.encodings
1269 .get_or_init(|| {
1270 Box::new(TableCache::read(sfnt.tables.clone(), |tables| {
1271 EncodingTables::read(&tables)
1272 }))
1273 })
1274 .get(),
1275 )
1276 }
1277
1278 pub(super) fn standalone_cff_unicode_charmap(&self) -> Option<&crate::ps::UnicodeCharmap> {
1279 let KindRepr::StandaloneCff(cff) = &self.0.kind else {
1280 return None;
1281 };
1282 Some(cff.unicode_charmap.get_or_init(|| {
1283 #[cfg(feature = "agl")]
1284 {
1285 let cff = cff.font.get();
1286 if cff.is_cid() {
1287 return crate::ps::UnicodeCharmap::default();
1288 }
1289 crate::ps::UnicodeCharmap::from_glyph_names(
1290 cff.charset()
1291 .into_iter()
1292 .flat_map(|charset| charset.iter())
1293 .filter_map(|(glyph, sid)| {
1294 let name = core::str::from_utf8(cff.string(sid)?).ok()?;
1295 Some((glyph, name))
1296 }),
1297 )
1298 }
1299 #[cfg(not(feature = "agl"))]
1300 {
1301 let _ = cff;
1302 crate::ps::UnicodeCharmap::default()
1303 }
1304 }))
1305 }
1306
1307 #[inline]
1309 fn h_metric_records(&self) -> &GlyphMetricRecords<'_> {
1310 let Some(sfnt) = self.sfnt() else {
1311 return empty_glyph_metrics();
1312 };
1313 &sfnt
1314 .h_metrics
1315 .get_or_init(|| {
1316 TableCache::read(sfnt.tables.clone(), |tables| {
1317 MetricsTable(tables.h_glyph_metric_records().unwrap_or_default())
1318 })
1319 })
1320 .get()
1321 .0
1322 }
1323
1324 #[inline]
1329 fn v_metric_records(&self) -> &GlyphMetricRecords<'_> {
1330 let Some(sfnt) = self.sfnt() else {
1331 return empty_glyph_metrics();
1332 };
1333 &sfnt
1334 .v_metrics
1335 .get_or_init(|| {
1336 TableCache::read(sfnt.tables.clone(), |tables| {
1337 MetricsTable(tables.v_glyph_metric_records().unwrap_or_default())
1338 })
1339 })
1340 .get()
1341 .0
1342 }
1343
1344 #[inline]
1349 fn selected_glyf_loca(&self) -> Option<&(Glyf<'_>, Loca<'_>)> {
1350 let sfnt = self.sfnt()?;
1351 sfnt.glyf_loca
1352 .get_or_init(|| TableCache::read(sfnt.tables.clone(), |tables| GlyfLoca::read(&tables)))
1353 .get()
1354 .0
1355 .as_ref()
1356 }
1357
1358 #[inline]
1360 fn hvar(&self) -> Option<&Hvar<'_>> {
1361 let sfnt = self.sfnt()?;
1362 sfnt.hvar
1363 .get_or_init(|| {
1364 TableCache::read(sfnt.tables.clone(), |tables| HvarTable::read(&tables))
1365 })
1366 .get()
1367 .0
1368 .as_ref()
1369 }
1370
1371 #[inline]
1373 fn vvar(&self) -> Option<&Vvar<'_>> {
1374 let sfnt = self.sfnt()?;
1375 sfnt.vvar
1376 .get_or_init(|| {
1377 TableCache::read(sfnt.tables.clone(), |tables| VvarTable::read(&tables))
1378 })
1379 .get()
1380 .0
1381 .as_ref()
1382 }
1383
1384 #[inline]
1389 fn selected_gvar(&self) -> Option<&SelectedGvar<'_>> {
1390 let sfnt = self.sfnt()?;
1391 sfnt.gvar
1392 .get_or_init(|| {
1393 TableCache::read(sfnt.tables.clone(), |tables| GvarTable::read(&tables))
1394 })
1395 .get()
1396 .0
1397 .as_ref()
1398 }
1399
1400 #[inline]
1402 fn vorg(&self) -> Option<&Vorg<'_>> {
1403 let sfnt = self.sfnt()?;
1404 sfnt.vorg
1405 .get_or_init(|| {
1406 TableCache::read(sfnt.tables.clone(), |tables| VorgTable::read(&tables))
1407 })
1408 .get()
1409 .0
1410 .as_ref()
1411 }
1412
1413 #[inline]
1418 fn cff2(&self) -> Option<&CffFontRef<'_>> {
1419 let sfnt = self.sfnt()?;
1420 sfnt.cff2
1421 .get_or_init(|| TableCache::read(sfnt.tables.clone(), |tables| Cff2Font::read(&tables)))
1422 .get()
1423 .0
1424 .as_ref()
1425 }
1426
1427 #[inline]
1429 fn cff(&self) -> Option<&CffFontRef<'_>> {
1430 let sfnt = self.sfnt()?;
1431 sfnt.cff
1432 .get_or_init(|| TableCache::read(sfnt.tables.clone(), |tables| CffFont::read(&tables)))
1433 .get()
1434 .0
1435 .as_ref()
1436 }
1437
1438 fn standalone_cff(&self) -> Option<&CffFontRef<'_>> {
1439 match &self.0.kind {
1440 KindRepr::StandaloneCff(cff) => Some(cff.font.get()),
1441 _ => None,
1442 }
1443 }
1444
1445 fn cid_glyphs(&self) -> Option<&[u16]> {
1451 let KindRepr::StandaloneCff(data) = &self.0.kind else {
1452 return None;
1453 };
1454 let cff = data.font.get();
1455 if !cff.is_cid() {
1456 return None;
1457 }
1458 let glyphs = data.cid_glyphs.get_or_init(|| {
1459 let num_glyphs = cff.num_glyphs();
1460 let Some(charset) = cff.charset() else {
1461 return Box::new([0]);
1462 };
1463 cid_table(|| {
1464 charset
1465 .iter()
1466 .filter(move |(glyph, _)| glyph.to_u32() < num_glyphs)
1467 .map(|(glyph, cid)| (glyph.to_u32() as u16, cid.to_u16() as usize))
1468 })
1469 });
1470 Some(glyphs)
1471 }
1472
1473 fn standalone_cff_subfonts(&self) -> Option<&[Option<Subfont>]> {
1474 match &self.0.kind {
1475 KindRepr::StandaloneCff(cff) => Some(&cff.subfonts),
1476 _ => None,
1477 }
1478 }
1479
1480 fn varc_outlines(&self) -> Option<&varc::Outlines<'_>> {
1482 let sfnt = self.sfnt()?;
1483 sfnt.varc
1484 .get_or_init(|| {
1485 Box::new(TableCache::read(sfnt.tables.clone(), |tables| {
1486 varc::Outlines::read(&tables)
1487 }))
1488 })
1489 .get()
1490 .as_ref()
1491 }
1492
1493 fn colr_tables(&self) -> Option<&ColrTables<'_>> {
1495 let sfnt = self.sfnt()?;
1496 sfnt.colr
1497 .get_or_init(|| {
1498 Box::new(TableCache::read(sfnt.tables.clone(), |tables| {
1499 ColrTables::read(&tables)
1500 }))
1501 })
1502 .get()
1503 .as_ref()
1504 }
1505
1506 fn cpal(&self) -> Option<&Cpal<'_>> {
1508 let sfnt = self.sfnt()?;
1509 sfnt.cpal
1510 .get_or_init(|| {
1511 Box::new(TableCache::read(sfnt.tables.clone(), |tables| {
1512 CpalTable::read(&tables)
1513 }))
1514 })
1515 .get()
1516 .0
1517 .as_ref()
1518 }
1519
1520 fn sbix(&self) -> Option<&Sbix<'_>> {
1522 let sfnt = self.sfnt()?;
1523 sfnt.sbix
1524 .get_or_init(|| {
1525 Box::new(TableCache::read(sfnt.tables.clone(), |tables| {
1526 SbixTable::read(&tables)
1527 }))
1528 })
1529 .get()
1530 .0
1531 .as_ref()
1532 }
1533
1534 fn cbdt(&self) -> Option<&(Cblc<'_>, Cbdt<'_>)> {
1536 let sfnt = self.sfnt()?;
1537 sfnt.cbdt
1538 .get_or_init(|| {
1539 Box::new(TableCache::read(sfnt.tables.clone(), |tables| {
1540 CbdtTables::read(&tables)
1541 }))
1542 })
1543 .get()
1544 .0
1545 .as_ref()
1546 }
1547
1548 fn ebdt(&self) -> Option<&(Eblc<'_>, Ebdt<'_>)> {
1550 let sfnt = self.sfnt()?;
1551 sfnt.ebdt
1552 .get_or_init(|| {
1553 Box::new(TableCache::read(sfnt.tables.clone(), |tables| {
1554 EbdtTables::read(&tables)
1555 }))
1556 })
1557 .get()
1558 .0
1559 .as_ref()
1560 }
1561
1562 fn tables(&self) -> &Tables {
1566 if let KindRepr::Sfnt(sfnt) = &self.0.kind {
1567 &sfnt.tables
1568 } else {
1569 &tables::EMPTY_FONT_TABLES
1570 }
1571 }
1572}
1573
1574fn cid_table<I: Iterator<Item = (u16, usize)>>(cids: impl Fn() -> I) -> Box<[u16]> {
1579 let max_cid = cids().map(|(_, cid)| cid).max().unwrap_or(0);
1580 let mut glyphs = alloc::vec![0u16; max_cid + 1];
1581 for (glyph, cid) in cids() {
1584 if cid != 0 && glyphs[cid] == 0 {
1585 glyphs[cid] = glyph;
1586 }
1587 }
1588 glyphs.into_boxed_slice()
1589}
1590
1591struct SharedFontRepr {
1592 source: Source,
1593 kind: KindRepr,
1594 shaping_data: Once<Box<dyn Any + Send + Sync>>,
1596 glyph_name_index: Once<name::GlyphNameIndex>,
1598 default_location: LocationCaches,
1601}
1602
1603#[allow(
1609 clippy::large_enum_variant,
1610 reason = "boxing the SFNT caches would put a pointer chase on every advance, to save space only in the rare fonts of the other kinds"
1611)]
1612enum KindRepr {
1613 Sfnt(SfntCaches),
1614 Type1(Type1Data),
1615 StandaloneCff(StandaloneCffData),
1616}
1617
1618struct Type1Data {
1620 font: Type1Font,
1621 axes: Box<[VariationAxisRecord]>,
1622}
1623
1624pub(super) struct SfntCaches {
1626 tables: Arc<Tables>,
1627 index: u32,
1628 hint_reliant: core::sync::atomic::AtomicU8,
1631 glyph_sources: core::sync::atomic::AtomicU32,
1635 default_location: SfntLocation,
1638 h_metrics: Once<TableCache<MetricsTable<'static>>>,
1641 v_metrics: Once<TableCache<MetricsTable<'static>>>,
1644 glyf_loca: Once<TableCache<GlyfLoca<'static>>>,
1649 hvar: Once<TableCache<HvarTable<'static>>>,
1650 vvar: Once<TableCache<VvarTable<'static>>>,
1651 gvar: Once<TableCache<GvarTable<'static>>>,
1652 cff2: Once<TableCache<Cff2Font<'static>>>,
1656 cff: Once<TableCache<CffFont<'static>>>,
1657 varc: Once<Box<TableCache<Option<varc::Outlines<'static>>>>>,
1660 colr: Once<Box<TableCache<Option<ColrTables<'static>>>>>,
1661 cpal: Once<Box<TableCache<CpalTable<'static>>>>,
1662 sbix: Once<Box<TableCache<SbixTable<'static>>>>,
1663 cbdt: Once<Box<TableCache<CbdtTables<'static>>>>,
1664 ebdt: Once<Box<TableCache<EbdtTables<'static>>>>,
1665 vorg: Once<TableCache<VorgTable<'static>>>,
1667 charmap: Once<TableCache<SfntUnicodeCharmap<'static>>>,
1669 encodings: Once<Box<TableCache<EncodingTables<'static>>>>,
1671}
1672
1673impl SfntCaches {
1674 fn new(tables: Arc<Tables>, index: u32) -> Self {
1675 Self {
1676 tables,
1677 index,
1678 hint_reliant: core::sync::atomic::AtomicU8::new(0),
1679 glyph_sources: core::sync::atomic::AtomicU32::new(0),
1680 default_location: SfntLocation::new(),
1681 h_metrics: Once::new(),
1682 v_metrics: Once::new(),
1683 glyf_loca: Once::new(),
1684 hvar: Once::new(),
1685 vvar: Once::new(),
1686 gvar: Once::new(),
1687 cff2: Once::new(),
1688 cff: Once::new(),
1689 varc: Once::new(),
1690 colr: Once::new(),
1691 cpal: Once::new(),
1692 sbix: Once::new(),
1693 cbdt: Once::new(),
1694 ebdt: Once::new(),
1695 vorg: Once::new(),
1696 charmap: Once::new(),
1697 encodings: Once::new(),
1698 }
1699 }
1700}
1701
1702struct StandaloneCffData {
1703 font: Yoke<CffFontRef<'static>, Arc<Blob>>,
1704 subfonts: Box<[Option<Subfont>]>,
1707 index: u32,
1708 unicode_charmap: Once<crate::ps::UnicodeCharmap>,
1709 cid_glyphs: Once<Box<[u16]>>,
1711}
1712
1713struct LocationCaches {
1715 scaling_data: Once<Box<dyn Any + Send + Sync>>,
1717 metrics: Once<Metrics>,
1721 style_metrics: Once<Box<StyleMetrics>>,
1722}
1723
1724impl LocationCaches {
1725 const fn new() -> Self {
1726 Self {
1727 scaling_data: Once::new(),
1728 metrics: Once::new(),
1729 style_metrics: Once::new(),
1730 }
1731 }
1732}
1733
1734struct SfntLocation {
1736 feature_vars: FeatureVarsStorage,
1739 cff2_subfonts: SubfontCache,
1742 cff_subfonts: SubfontCache,
1743}
1744
1745impl SfntLocation {
1746 fn new() -> Self {
1747 Self {
1748 feature_vars: FeatureVarsStorage::new(),
1749 cff2_subfonts: Once::new(),
1750 cff_subfonts: Once::new(),
1751 }
1752 }
1753}
1754
1755struct VariedInstance {
1757 font: SharedFont,
1758 coords: CoordStorage,
1760 location: LocationCaches,
1761 kind: VariedKind,
1762}
1763
1764enum VariedKind {
1768 Sfnt(VariedSfnt),
1769 Type1(VariedType1),
1770}
1771
1772struct VariedType1 {
1774 weights: SmallVec<[Fixed; 16]>,
1776}
1777
1778struct VariedSfnt {
1780 location: SfntLocation,
1781 gvar_scalars: Once<Box<[Fixed]>>,
1784 hvar_scalars: Once<Box<[Fixed]>>,
1785 vvar_scalars: Once<Box<[Fixed]>>,
1786 colr_scalars: Once<Box<[Fixed]>>,
1787}
1788
1789const MAX_PRECOMPUTED_SCALARS: usize = 128;
1790
1791const SOURCE_ABSENT: u32 = 1;
1793const SOURCE_PRESENT: u32 = 2;
1795
1796fn scalars_with(count: usize, compute: impl FnOnce(&mut [Fixed]) -> usize) -> Box<[Fixed]> {
1799 let mut scalars = alloc::vec![Fixed::ZERO; count.min(MAX_PRECOMPUTED_SCALARS)];
1800 let written = compute(&mut scalars);
1801 scalars.truncate(written);
1802 scalars.into_boxed_slice()
1803}
1804
1805fn store_scalars(
1808 store: Option<&crate::tables::variations::ItemVariationStore<'_>>,
1809 coords: &[NormalizedCoord],
1810) -> Box<[Fixed]> {
1811 let Some(store) = store else {
1812 return Box::new([]);
1813 };
1814 let count = store
1815 .variation_region_list()
1816 .ok()
1817 .map_or(0, |regions| regions.variation_regions().len());
1818 scalars_with(count, |out| store.compute_scalars(coords, out))
1819}
1820
1821struct FeatureVarsStorage {
1825 gsub: AtomicU32,
1826 gpos: AtomicU32,
1827 has_lookup_variations: AtomicBool,
1829}
1830
1831impl Default for FeatureVarsStorage {
1832 fn default() -> Self {
1833 Self::new()
1834 }
1835}
1836
1837impl FeatureVarsStorage {
1838 const UNCHECKED: u32 = u32::MAX;
1843 const ABSENT: u32 = u32::MAX - 1;
1845
1846 fn new() -> Self {
1847 Self {
1848 gsub: AtomicU32::new(Self::UNCHECKED),
1849 gpos: AtomicU32::new(Self::UNCHECKED),
1850 has_lookup_variations: AtomicBool::new(false),
1851 }
1852 }
1853
1854 fn load(&self, font: &SharedFont, coords: &[NormalizedCoord]) -> SelectedFeatureVariations {
1855 let (gsub, gpos) = (
1856 self.gsub.load(atomic::Ordering::Acquire),
1857 self.gpos.load(atomic::Ordering::Acquire),
1858 );
1859 if gsub != Self::UNCHECKED && gpos != Self::UNCHECKED {
1860 return SelectedFeatureVariations {
1861 gsub: Self::decode(gsub),
1862 gpos: Self::decode(gpos),
1863 has_lookup_variations: self.has_lookup_variations.load(atomic::Ordering::Relaxed),
1864 };
1865 }
1866 let selected = SelectedFeatureVariations::new(&font.tables(), coords);
1869 self.has_lookup_variations
1870 .store(selected.has_lookup_variations, atomic::Ordering::Relaxed);
1871 self.gsub
1872 .store(Self::encode(selected.gsub), atomic::Ordering::Release);
1873 self.gpos
1874 .store(Self::encode(selected.gpos), atomic::Ordering::Release);
1875 selected
1876 }
1877
1878 fn decode(value: u32) -> Option<u32> {
1880 (value < Self::ABSENT).then_some(value)
1881 }
1882
1883 fn encode(index: Option<u32>) -> u32 {
1885 index.unwrap_or(Self::ABSENT)
1886 }
1887}
1888
1889type SubfontCache = Once<Box<[Once<Option<Subfont>>]>>;
1894
1895const CACHED_SUBFONTS: usize = 8;
1898
1899const MAX_INLINE_COORDS: usize = 12;
1904
1905type CoordStorage = SmallVec<[NormalizedCoord; MAX_INLINE_COORDS]>;
1906
1907fn clear_if_all_zeroes(coords: &mut CoordStorage) {
1910 if coords.iter().all(|&c| c == NormalizedCoord::ZERO) {
1911 coords.clear();
1912 }
1913}
1914
1915#[cfg(test)]
1916impl Font {
1917 fn feature_vars(&self) -> &FeatureVarsStorage {
1919 match &self.0 {
1920 Repr::Varied(varied) => &varied.sfnt().location.feature_vars,
1921 Repr::Default(_) => panic!("the default instance keeps no storage of its own"),
1922 }
1923 }
1924}
1925
1926#[cfg(test)]
1927impl VariedInstance {
1928 fn sfnt(&self) -> &VariedSfnt {
1930 match &self.kind {
1931 VariedKind::Sfnt(sfnt) => sfnt,
1932 VariedKind::Type1(_) => panic!("not an SFNT instance"),
1933 }
1934 }
1935}
1936
1937#[cfg(test)]
1938mod tests {
1939 use super::*;
1940 use crate::ps::Sid;
1941 use crate::tables::glyf::outline::{Outline, Unscaled};
1942 use core::sync::atomic::Ordering;
1943 use types::Tag;
1944
1945 #[test]
1946 fn type1_loading_requires_feature() {
1947 let cid = font_test_data::type1::cid_font(false);
1948 for data in [
1949 font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA,
1950 font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFB,
1951 &cid,
1952 ] {
1953 assert_eq!(
1954 Font::new(data.to_vec(), 0).is_some(),
1955 cfg!(feature = "type1")
1956 );
1957 assert_eq!(
1958 crate::ps::type1::Type1Font::new(data).is_ok(),
1959 cfg!(feature = "type1")
1960 );
1961 }
1962 }
1963
1964 #[cfg(feature = "type1")]
1967 fn type1_mm_start(font: &Font) -> f32 {
1968 use crate::model::glyph::outline::{DrawMemory, DrawOptions, PathElement};
1969 let mut path = alloc::vec::Vec::<PathElement>::new();
1970 font.outline_glyphs()
1971 .get(GlyphId::new(1))
1972 .unwrap()
1973 .draw(&DrawOptions::default(), DrawMemory::Scratch, &mut path)
1974 .unwrap();
1975 match path[0] {
1976 PathElement::MoveTo { x, .. } => x,
1977 _ => panic!("expected a move"),
1978 }
1979 }
1980
1981 #[test]
1984 #[cfg(feature = "type1")]
1985 fn type1_multiple_master_instances() {
1986 use crate::ps::type1::multiple_master_tests::{pfa_with_blend, ONE_AXIS};
1987 let font = Font::new(pfa_with_blend(ONE_AXIS), 0).unwrap();
1988 let axes = font.axes();
1989 assert_eq!(axes.len(), 1);
1990 let axis = axes.get(0).unwrap();
1991 assert_eq!(axis.tag(), Tag::new(b"wght"));
1992 assert_eq!(
1995 (axis.min_value(), axis.default_value(), axis.max_value()),
1996 (100.0, 300.0, 900.0)
1997 );
1998 let name = font.names().get(axis.name()).unwrap();
1999 assert_eq!(name.english_or_first().unwrap().name(), "Weight");
2000 assert!(font.named_instances().is_empty());
2001 assert!(font.normalized_coords().is_empty());
2002 assert_eq!(type1_mm_start(&font), 150.0);
2003 for (design, blend, start) in [
2006 (900.0, 1.0, 300.0),
2007 (500.0, 0.5, 200.0),
2008 (100.0, 0.0, 100.0),
2009 ] {
2010 let instance = font
2011 .instance_builder()
2012 .variations([("wght", design)])
2013 .build();
2014 assert_eq!(
2015 instance.normalized_coords(),
2016 [NormalizedCoord::from_f32(blend)],
2017 "{design}"
2018 );
2019 assert_eq!(type1_mm_start(&instance), start, "{design}");
2020 let extents = instance.glyph_metrics().extents(GlyphId::new(1)).unwrap();
2021 assert_eq!(extents.x_bearing, start, "{design}");
2022 let by_blend = font
2023 .instance_builder()
2024 .normalized_coords([NormalizedCoord::from_f32(blend)])
2025 .build();
2026 assert_eq!(type1_mm_start(&by_blend), start, "{design}");
2027 }
2028 }
2029
2030 #[test]
2034 #[cfg(feature = "type1")]
2035 fn type1_multiple_master_ignores_unknown_axes() {
2036 use crate::ps::type1::multiple_master_tests::pfa_with_blend;
2037 let font = Font::new(
2038 pfa_with_blend(
2039 "/BlendAxisTypes [/Weight] def /BlendDesignPositions [[0] [1]] def /BlendDesignMap [[[0 0] [500 0.5] [1000 1]]] def /WeightVector [0.25 0.75] def",
2040 ),
2041 0,
2042 )
2043 .unwrap();
2044 assert_eq!(type1_mm_start(&font), 250.0);
2045 let instance = font.instance_builder().variations([("XXXX", 42.0)]).build();
2046 assert_eq!(type1_mm_start(&instance), 250.0);
2047 }
2048
2049 #[test]
2052 #[cfg(feature = "type1")]
2053 fn type1_multiple_master_widest_axes() {
2054 use crate::ps::type1::multiple_master_tests::pfa_with_blend;
2055 let font = Font::new(
2056 pfa_with_blend(
2057 "/BlendAxisTypes [/Weight] def /BlendDesignPositions [[0] [1]] def /BlendDesignMap [[[-2147483648 0] [2147483647 1]]] def /WeightVector [0.5 0.5] def",
2058 ),
2059 0,
2060 )
2061 .unwrap();
2062 let axis = font.axes().get(0).unwrap();
2063 assert_eq!(
2064 (axis.min_value(), axis.default_value(), axis.max_value()),
2065 (-32768.0, 0.0, 32767.0)
2066 );
2067 }
2068
2069 #[test]
2072 #[cfg(feature = "type1")]
2073 fn type1_multiple_master_instances_keep_metrics() {
2074 use crate::ps::type1::multiple_master_tests::{pfa_with_blend, ONE_AXIS};
2075 let font = Font::new(
2076 pfa_with_blend(&format!(
2077 "{ONE_AXIS} /FontBBox [-10 -200 600 800] def \
2078 /ItalicAngle -12 def /UnderlinePosition -100 def \
2079 /UnderlineThickness 50 def"
2080 )),
2081 0,
2082 )
2083 .unwrap();
2084 let instance = font
2085 .instance_builder()
2086 .variations([("wght", 900.0)])
2087 .build();
2088 assert!(!instance.normalized_coords().is_empty());
2089 assert_eq!(instance.metrics().num_glyphs, 2);
2090 assert_eq!(instance.metrics(), font.metrics());
2091 assert!(instance.style_metrics().underline.is_some());
2092 assert_eq!(instance.style_metrics(), font.style_metrics());
2093 }
2094
2095 #[test]
2097 #[cfg(feature = "type1")]
2098 fn type1_multiple_master_named_instance_overrides() {
2099 use crate::ps::type1::multiple_master_tests::{pfa_with_blend, ONE_AXIS};
2100 let font = Font::new(pfa_with_blend(ONE_AXIS), 0).unwrap();
2101 let instance = font
2102 .instance_builder()
2103 .named_instance_with_overrides(0, [("wght", 900.0)])
2104 .build();
2105 assert_eq!(type1_mm_start(&instance), 300.0);
2106 }
2107
2108 #[test]
2111 fn new_uses_the_index_as_documented() {
2112 assert!(Font::new(font_test_data::TINOS_SUBSET, 0).is_some());
2113 assert!(Font::new(font_test_data::TINOS_SUBSET, 1).is_none());
2114 let count = crate::FileRef::new(font_test_data::ttc::TTC)
2115 .ok()
2116 .and_then(|file| match file {
2117 crate::FileRef::Collection(collection) => Some(collection.len()),
2118 _ => None,
2119 })
2120 .unwrap();
2121 assert!(count > 1);
2122 assert!(Font::new(font_test_data::ttc::TTC, count - 1).is_some());
2123 assert!(Font::new(font_test_data::ttc::TTC, count).is_none());
2124 #[cfg(feature = "type1")]
2125 assert!(Font::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA, 7).is_some());
2126 let sfnt = crate::FontRef::new(font_test_data::NOTO_SANS_JP_CFF).unwrap();
2127 let cff = sfnt.cff().unwrap().offset_data().as_bytes().to_vec();
2128 assert!(Font::new(cff.clone(), 0).is_some());
2129 assert!(Font::new(cff, 1).is_none());
2130 }
2131
2132 #[test]
2135 fn cid_keyed_fonts_map_cids_to_glyphs() {
2136 let sfnt = crate::FontRef::new(font_test_data::NOTO_SANS_JP_CFF).unwrap();
2137 let font = Font::new(sfnt.cff().unwrap().offset_data().as_bytes(), 0).unwrap();
2138 assert!(font.is_cid_keyed());
2139 let charset = font.shared().standalone_cff().unwrap().charset().unwrap();
2140 let max = charset
2141 .iter()
2142 .map(|(_, cid)| cid.to_u16() as u32)
2143 .max()
2144 .unwrap();
2145 assert_eq!(font.max_cid(), Some(max));
2146 for cid in 0..=max + 1 {
2147 let expected = charset
2148 .glyph_id(Sid::new(cid as u16))
2149 .filter(|glyph| glyph.to_u32() < font.num_glyphs());
2150 assert_eq!(font.glyph_by_cid(cid), expected, "cid {cid}");
2151 }
2152 assert_eq!(font.glyph_by_cid(0x10000), None);
2153 }
2154
2155 #[test]
2158 fn the_first_glyph_keeps_its_cid() {
2159 let cids = [(0u16, 0usize), (1, 2), (2, 0), (3, 2), (4, 1)];
2160 assert_eq!(&*cid_table(|| cids.into_iter()), &[0, 4, 1]);
2161 }
2162
2163 #[test]
2164 fn other_fonts_have_no_cids() {
2165 for font in [
2166 Font::new(font_test_data::NOTO_SANS_JP_CFF, 0).unwrap(),
2168 Font::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED, 0).unwrap(),
2169 Font::new(font_test_data::VAZIRMATN_VAR, 0).unwrap(),
2170 #[cfg(feature = "type1")]
2171 Font::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA, 0).unwrap(),
2172 ] {
2173 assert!(!font.is_cid_keyed());
2174 assert_eq!(font.glyph_by_cid(1), None);
2175 assert_eq!(font.max_cid(), None);
2176 }
2177 }
2178
2179 #[test]
2180 fn standalone_cff_with_a_bad_private_dict_still_opens() {
2181 let sfnt = crate::FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
2182 let mut raw = sfnt.cff().unwrap().offset_data().as_bytes().to_vec();
2183 let private = CffFontRef::new_cff(&raw, 0, None)
2184 .unwrap()
2185 .sid_private_dict_range()
2186 .unwrap();
2187 let damage = [29u8, 0xff, 0xff, 0xff, 0xff, 19];
2189 assert!(private.len() >= damage.len());
2190 raw[private.start..private.start + damage.len()].copy_from_slice(&damage);
2191 let font = Font::new(raw, 0).unwrap();
2192 let subfonts = font.shared().standalone_cff_subfonts().unwrap();
2193 assert!(subfonts.len() == 1 && subfonts[0].is_none());
2194 assert!(font.num_glyphs() > 1);
2195 let outlines = font.outline_glyphs();
2198 assert_eq!(outlines.source(), Some(OutlineSource::Cff));
2199 for glyph in 0..font.num_glyphs() {
2200 let glyph = GlyphId::new(glyph);
2201 assert!(outlines.get(glyph).is_none());
2202 assert_eq!(font.glyph_metrics().h_advance(glyph), 0.0);
2203 assert!(font.glyph_metrics().extents(glyph).is_none());
2204 }
2205 }
2206
2207 #[test]
2208 fn standalone_cff_uses_selected_font_data() {
2209 let sfnt = crate::FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
2210 let raw = sfnt.cff().unwrap().offset_data().as_bytes();
2211 let direct = CffFontRef::new_cff(raw, 0, None).unwrap();
2212 let font = Font::new(raw.to_vec(), 0).unwrap();
2213 assert!(matches!(font.kind(), Kind::Cff(_, 0)));
2214 assert!(Font::new(raw.to_vec(), 1).is_none());
2215 assert_eq!(font.num_glyphs(), direct.num_glyphs());
2216 assert_eq!(font.units_per_em(), direct.upem() as u16);
2217 let bbox = direct.metadata().unwrap().bbox();
2218 assert_eq!(font.metrics().bounds.x_min, bbox.x_min.to_f48dot16());
2219 assert_eq!(font.metrics().bounds.y_max, bbox.y_max.to_f48dot16());
2220 assert_eq!(
2221 font.style_metrics().italic_angle,
2222 Some(direct.metadata().unwrap().italic_angle())
2223 );
2224 assert_eq!(
2225 font.shared().standalone_cff_subfonts().unwrap().len(),
2226 direct.num_subfonts() as usize
2227 );
2228 assert!(font.tables().cff().is_err());
2229 assert!(font.cff().is_none());
2230 let metadata = direct.metadata().unwrap();
2231 assert_eq!(metadata.version(), Some("2.9"));
2232 assert_eq!(
2233 metadata.notice(),
2234 Some("Noto is a trademark of Google LLC.")
2235 );
2236 assert!(metadata.copyright().unwrap().starts_with("Copyright 2022"));
2237 for (id, expected) in [
2238 (types::NameId::COPYRIGHT_NOTICE, metadata.copyright()),
2239 (types::NameId::FAMILY_NAME, metadata.family_name()),
2240 (types::NameId::SUBFAMILY_NAME, metadata.weight()),
2241 (types::NameId::FULL_NAME, metadata.full_name()),
2242 (types::NameId::VERSION_STRING, metadata.version()),
2243 (types::NameId::POSTSCRIPT_NAME, metadata.name()),
2244 (types::NameId::TRADEMARK, metadata.notice()),
2245 ] {
2246 let entries: Vec<_> = font
2247 .names()
2248 .get(id)
2249 .map(|name| name.iter().collect())
2250 .unwrap_or_default();
2251 assert_eq!(entries.len(), usize::from(expected.is_some()));
2252 if let Some(expected) = expected {
2253 assert_eq!(entries[0].name(), expected);
2254 assert!(entries[0].language().is_none());
2255 assert!(entries[0].sfnt_record().is_none());
2256 }
2257 }
2258 assert!(font
2259 .glyph_metrics()
2260 .extents_exact(GlyphId::new(1))
2261 .is_some());
2262 assert_eq!(font.glyph_name(GlyphId::new(1)).unwrap().as_str(), "i");
2263 #[cfg(feature = "agl")]
2264 assert_eq!(font.charmap().map_unicode('i'), Some(GlyphId::new(1)));
2265 let native = font
2266 .charmap()
2267 .encodings()
2268 .find(|encoding| encoding.kind() != super::super::charmap::EncodingKind::Unicode)
2269 .unwrap();
2270 for encoding in font.charmap().encodings() {
2272 assert_eq!(encoding.sfnt_index(), None);
2273 assert_eq!(encoding.sfnt_ids(), None);
2274 }
2275 assert_eq!(
2276 font.charmap().map_code(native, b'i' as u32),
2277 direct.encoding().unwrap().map(b'i')
2278 );
2279 assert!(font
2280 .charmap()
2281 .codes(native)
2282 .any(|(code, glyph)| code == b'i' as u32 && glyph == GlyphId::new(1)));
2283
2284 let names: Vec<_> = font.glyph_names().collect();
2285 assert_eq!(names.len(), font.num_glyphs() as usize);
2286 for (glyph, name) in names.iter().take(8) {
2287 assert_eq!(font.glyph_name(*glyph).unwrap().as_str(), name.as_str());
2288 let subfont = direct
2289 .subfont(direct.subfont_index(*glyph).unwrap(), &[])
2290 .unwrap();
2291 let width = direct.evaluate_width(&subfont, *glyph, &[]).unwrap();
2292 assert_eq!(
2293 font.glyph_metrics().h_advance_exact(*glyph),
2294 width.map(|width| width.to_f48dot16()).unwrap_or_default(),
2295 );
2296 }
2297 assert_eq!(
2298 font.glyph_metrics()
2299 .h_advance_exact(GlyphId::new(font.num_glyphs())),
2300 types::F48Dot16::ZERO
2301 );
2302 assert_eq!(
2303 font.default_instance()
2304 .glyph_name(GlyphId::new(1))
2305 .unwrap()
2306 .as_str(),
2307 font.glyph_name(GlyphId::new(1)).unwrap().as_str()
2308 );
2309 }
2310
2311 #[cfg(feature = "std")]
2312 #[test]
2313 fn variation_scalars_are_lazy_bounded_and_shared() {
2314 let font = Font::new(font_test_data::VAZIRMATN_VAR, 0).unwrap();
2315 let instance = font
2316 .instance_builder()
2317 .normalized_coords([NormalizedCoord::from_f32(-0.75)])
2318 .build();
2319 let Repr::Varied(varied) = &instance.0 else {
2320 panic!("expected a varied instance");
2321 };
2322 assert!(varied.sfnt().gvar_scalars.get().is_none());
2323 assert!(varied.sfnt().hvar_scalars.get().is_none());
2324
2325 let gvar_scalars = instance.gvar_scalars();
2326 assert!(!gvar_scalars.is_empty());
2327 let gvar = instance.selected_gvar().unwrap();
2328 assert_eq!(
2329 gvar_scalars.len(),
2330 (gvar.shared_tuple_count() as usize).min(MAX_PRECOMPUTED_SCALARS)
2331 );
2332 assert!(varied.sfnt().hvar_scalars.get().is_none());
2333 let mut expected = alloc::vec![Fixed::ZERO; gvar_scalars.len()];
2334 let count = gvar.compute_scalars(instance.normalized_coords(), &mut expected);
2335 assert_eq!(gvar_scalars, &expected[..count]);
2336
2337 let hvar_scalars = instance.hvar_scalars();
2338 assert!(!hvar_scalars.is_empty());
2339 let hvar = instance.hvar().unwrap();
2340 let regions = hvar
2341 .item_variation_store()
2342 .unwrap()
2343 .variation_region_list()
2344 .unwrap();
2345 assert_eq!(
2346 hvar_scalars.len(),
2347 regions
2348 .variation_regions()
2349 .len()
2350 .min(MAX_PRECOMPUTED_SCALARS)
2351 );
2352 expected.resize(hvar_scalars.len(), Fixed::ZERO);
2353 let count = hvar.compute_scalars(instance.normalized_coords(), &mut expected);
2354 assert_eq!(hvar_scalars, &expected[..count]);
2355 let clone = instance.clone();
2356 assert!(core::ptr::eq(gvar_scalars, clone.gvar_scalars()));
2357 assert!(core::ptr::eq(hvar_scalars, clone.hvar_scalars()));
2358 assert!(font.gvar_scalars().is_empty());
2359 assert!(font.hvar_scalars().is_empty());
2360 }
2361
2362 #[cfg(feature = "std")]
2363 #[test]
2364 fn vvar_scalars_are_lazy_bounded_and_shared() {
2365 let font = Font::new(font_test_data::MPLUS1CODE_VERTICAL_SUBSET, 0).unwrap();
2366 let instance = font
2367 .instance_builder()
2368 .normalized_coords([NormalizedCoord::from_f32(-0.75)])
2369 .build();
2370 let Repr::Varied(varied) = &instance.0 else {
2371 panic!("expected a varied instance");
2372 };
2373 assert!(varied.sfnt().vvar_scalars.get().is_none());
2374
2375 let scalars = instance.vvar_scalars();
2376 assert!(!scalars.is_empty());
2377 let vvar = instance.vvar().unwrap();
2378 let regions = vvar
2379 .item_variation_store()
2380 .unwrap()
2381 .variation_region_list()
2382 .unwrap();
2383 assert_eq!(
2384 scalars.len(),
2385 regions
2386 .variation_regions()
2387 .len()
2388 .min(MAX_PRECOMPUTED_SCALARS)
2389 );
2390 let mut expected = alloc::vec![Fixed::ZERO; scalars.len()];
2391 let count = vvar.compute_scalars(instance.normalized_coords(), &mut expected);
2392 assert_eq!(scalars, &expected[..count]);
2393 assert!(core::ptr::eq(scalars, instance.clone().vvar_scalars()));
2394 assert!(font.vvar_scalars().is_empty());
2395 }
2396
2397 #[test]
2398 fn font_outline_context_uses_stated_vertical_metrics() {
2399 let data = font_test_data::MPLUS1CODE_VERTICAL_SUBSET;
2400 let font = Font::new(data, 0).unwrap();
2401 let direct = crate::FontRef::new(data).unwrap();
2402 let gid = GlyphId::new(1);
2403 let glyph = direct
2404 .loca(None)
2405 .unwrap()
2406 .get_glyf(gid, &direct.glyf().unwrap())
2407 .unwrap()
2408 .unwrap();
2409 let tsb = direct.vmtx().unwrap().side_bearing(gid).unwrap();
2410 let context = &font;
2411 let mut outline = Outline::<Unscaled>::new();
2412 let loaded = outline.load_with(&context, gid, &Unscaled, None).unwrap();
2413 assert_eq!(
2414 loaded.phantom_points()[2].y,
2415 glyph.y_max() as i32 + tsb as i32
2416 );
2417 }
2418
2419 #[test]
2420 fn outline_context_uses_unvaried_h_line_metrics() {
2421 let font = Font::new(MVAR_FONT, 0).unwrap();
2422 let far = font
2423 .instance_builder()
2424 .normalized_coords([NormalizedCoord::from_f32(1.0); 12])
2425 .build();
2426 let line = font.shared().metrics().h_line().unwrap();
2427 assert_ne!(Some(line), font.metrics().typo_line);
2428 let expected = (line.ascender.to_i32(), line.descender.to_i32());
2429 assert_ne!(far.metrics().h_line(), font.metrics().h_line());
2430 assert_eq!((&font).h_line_metrics(), expected);
2431 assert_eq!((&far).h_line_metrics(), expected);
2432 }
2433
2434 #[test]
2435 fn named_instances() {
2436 let font = Font::new(font_test_data::CANTARELL_VF_TRIMMED, 0).unwrap();
2437 let cases = [
2438 (0, 100.0),
2440 (1, 300.0),
2441 (2, 400.0),
2442 (3, 700.0),
2443 (4, 800.0),
2444 ];
2445 for (index, weight) in cases {
2446 let named_instance = font.instance_builder().named_instance(index).build();
2447 let var_instance = font
2448 .instance_builder()
2449 .variations([("wght", weight)])
2450 .build();
2451 assert_eq!(
2452 named_instance.normalized_coords(),
2453 var_instance.normalized_coords(),
2454 "index={index}"
2455 );
2456 }
2457 let invalid_instance = font.instance_builder().named_instance(5).build();
2459 assert!(
2460 invalid_instance.normalized_coords().is_empty(),
2461 "out of bounds index should give default instance"
2462 );
2463 }
2464
2465 #[test]
2466 fn named_instance_with_overrides_override_named_value() {
2467 let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2468 let actual = font
2469 .instance_builder()
2470 .named_instance_with_overrides(3, [("FILL", 1.0)])
2471 .build();
2472 let expected = font
2473 .instance_builder()
2474 .variations([
2475 ("FILL", 1.0),
2476 ("GRAD", 0.0),
2477 ("opsz", 24.0),
2478 ("wght", 400.0),
2479 ])
2480 .build();
2481 assert_eq!(actual.normalized_coords(), expected.normalized_coords());
2482 }
2483
2484 #[test]
2485 fn named_instance_with_overrides_invalid_index_uses_overrides_only() {
2486 let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2487 let actual = font
2488 .instance_builder()
2489 .named_instance_with_overrides(999, [("FILL", 1.0), ("ZZZZ", 123.0)])
2490 .build();
2491 let expected = font
2492 .instance_builder()
2493 .variations([("FILL", 1.0), ("ZZZZ", 123.0)])
2494 .build();
2495 assert_eq!(actual.normalized_coords(), expected.normalized_coords());
2496 assert_eq!(actual.normalized_coords().len(), 4);
2497 }
2498
2499 #[test]
2500 fn named_instance_with_overrides_overwrites_previous_settings() {
2501 let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2502 let actual = font
2503 .instance_builder()
2504 .variations([("FILL", 0.0), ("wght", 100.0)])
2505 .named_instance_with_overrides(5, [("GRAD", -25.0)])
2506 .build();
2507 let expected = font
2508 .instance_builder()
2509 .variations([
2510 ("FILL", 0.0),
2511 ("GRAD", -25.0),
2512 ("opsz", 24.0),
2513 ("wght", 600.0),
2514 ])
2515 .build();
2516 assert_eq!(actual.normalized_coords(), expected.normalized_coords());
2517 }
2518
2519 #[test]
2520 fn feature_variations() {
2521 let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2522 let cases = [
2523 (0.0, [None, None]),
2525 (0.5, [None, None]),
2526 (0.98, [None, None]),
2527 (0.99, [Some(0), None]),
2528 (1.0, [Some(0), None]),
2529 ];
2530 for (fill, [gsub, gpos]) in cases {
2531 let instance = font.instance_builder().variations([("FILL", fill)]).build();
2532 let feature_vars = instance.feature_variations();
2533 let actual = [feature_vars.gsub, feature_vars.gpos];
2534 assert_eq!(actual, [gsub, gpos], "fill={fill}");
2535 }
2536 }
2537
2538 #[test]
2539 fn default_instance_evaluates_and_caches_feature_variations() {
2540 let source = crate::FontRef::new(font_test_data::MATERIAL_SYMBOLS_SUBSET).unwrap();
2541 let tables = super::super::TableFunction::new(Arc::new(move |tag| {
2542 if tag == Tag::new(b"GSUB") {
2543 return Some(super::super::Blob::from(vec![
2546 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 16,
2547 0, 0, 0, 0, 0, 1, 0, 0, 0, 6, 0, 1, 0, 0, 0, 0, 0, 0,
2548 ]));
2549 }
2550 if tag == Tag::new(b"GPOS") {
2551 return None;
2552 }
2553 source
2554 .data_for_tag(tag)
2555 .map(|data| super::super::Blob::from(data.as_bytes().to_vec()))
2556 }));
2557 let font = Font::new(tables, 0).unwrap();
2558 assert_eq!(
2559 font.shared()
2560 .sfnt()
2561 .unwrap()
2562 .default_location
2563 .feature_vars
2564 .gsub
2565 .load(Ordering::Acquire),
2566 FeatureVarsStorage::UNCHECKED
2567 );
2568 let expected = SelectedFeatureVariations {
2569 gsub: Some(0),
2570 gpos: None,
2571 has_lookup_variations: false,
2572 };
2573 assert_eq!(font.feature_variations(), expected);
2574 assert_eq!(
2575 font.shared()
2576 .sfnt()
2577 .unwrap()
2578 .default_location
2579 .feature_vars
2580 .gsub
2581 .load(Ordering::Acquire),
2582 0
2583 );
2584 assert_eq!(font.default_instance().feature_variations(), expected);
2585 let default = font
2586 .instance_builder()
2587 .normalized_coords([NormalizedCoord::ZERO; 4])
2588 .build();
2589 assert!(default.normalized_coords().is_empty());
2590 assert_eq!(default.feature_variations(), expected);
2591 let varied = font
2592 .instance_builder()
2593 .normalized_coords([NormalizedCoord::from_f32(0.5); 4])
2594 .build();
2595 assert_eq!(
2596 varied.feature_variations(),
2597 SelectedFeatureVariations::default()
2598 );
2599 assert_eq!(font.feature_variations(), expected);
2600 }
2601
2602 #[test]
2603 fn feature_variation_cache_marks_both_absent() {
2604 let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2605 let instance = font.instance_builder().variations([("FILL", 0.5)]).build();
2606 let storage = instance.feature_vars();
2607 assert_eq!(
2608 storage.gsub.load(Ordering::Acquire),
2609 FeatureVarsStorage::UNCHECKED
2610 );
2611 assert_eq!(
2612 storage.gpos.load(Ordering::Acquire),
2613 FeatureVarsStorage::UNCHECKED
2614 );
2615 assert_eq!(
2616 instance.feature_variations(),
2617 SelectedFeatureVariations::default()
2618 );
2619 assert_eq!(
2620 storage.gsub.load(Ordering::Acquire),
2621 FeatureVarsStorage::ABSENT
2622 );
2623 assert_eq!(
2624 storage.gpos.load(Ordering::Acquire),
2625 FeatureVarsStorage::ABSENT
2626 );
2627 }
2628
2629 #[test]
2630 fn feature_variation_cache_is_thread_safe_and_stable() {
2631 let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2632 let instance = font.instance_builder().variations([("FILL", 1.0)]).build();
2633 std::thread::scope(|scope| {
2634 for _ in 0..8 {
2635 scope.spawn(|| {
2636 for _ in 0..64 {
2637 let vars = instance.feature_variations();
2638 assert_eq!(
2639 vars,
2640 SelectedFeatureVariations {
2641 gsub: Some(0),
2642 gpos: None,
2643 has_lookup_variations: false,
2644 }
2645 );
2646 }
2647 });
2648 }
2649 });
2650 let storage = instance.feature_vars();
2651 assert_eq!(storage.gsub.load(Ordering::Acquire), 0);
2652 assert_eq!(
2653 storage.gpos.load(Ordering::Acquire),
2654 FeatureVarsStorage::ABSENT
2655 );
2656 }
2657
2658 #[test]
2659 fn variations_last_value_wins_and_unknown_axis_ignored() {
2660 let font = Font::new(font_test_data::CANTARELL_VF_TRIMMED, 0).unwrap();
2661 let expected = font
2662 .instance_builder()
2663 .variations([("wght", 700.0)])
2664 .build();
2665 let repeated_axis = font
2666 .instance_builder()
2667 .variations([("wght", 100.0), ("wght", 700.0)])
2668 .build();
2669 assert_eq!(
2670 repeated_axis.normalized_coords(),
2671 expected.normalized_coords()
2672 );
2673 let unknown_axis = font
2674 .instance_builder()
2675 .variations([("wght", 700.0), ("ZZZZ", 123.0)])
2676 .build();
2677 assert_eq!(
2678 unknown_axis.normalized_coords(),
2679 expected.normalized_coords()
2680 );
2681 }
2682
2683 #[test]
2684 fn later_variation_call_overwrites_previous() {
2685 let font = Font::new(font_test_data::CANTARELL_VF_TRIMMED, 0).unwrap();
2686 let overwritten = font
2687 .instance_builder()
2688 .variations([("wght", 700.0)])
2689 .variations([("wght", 100.0)])
2690 .build();
2691 let expected = font
2692 .instance_builder()
2693 .variations([("wght", 100.0)])
2694 .build();
2695 assert_eq!(
2696 overwritten.normalized_coords(),
2697 expected.normalized_coords()
2698 );
2699 }
2700
2701 #[test]
2702 fn normalized_coords_empty_resets_to_default_instance() {
2703 let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2704 let instance = font.instance_builder().normalized_coords([]).build();
2705 assert!(instance.normalized_coords().is_empty());
2706 }
2707
2708 #[test]
2709 fn normalized_coords_truncates_and_pads() {
2710 let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2711 let axis_count = font.tables().fvar().unwrap().axis_count() as usize;
2712 let values = [0.25, -0.5, 1.0, 0.75, -0.25].map(NormalizedCoord::from_f32);
2713 let instance = font.instance_builder().normalized_coords(values).build();
2714 let coords = instance.normalized_coords();
2715 assert_eq!(coords.len(), axis_count);
2716 let copied = values.len().min(axis_count);
2717 assert_eq!(&coords[..copied], &values[..copied]);
2718 assert!(coords[copied..]
2719 .iter()
2720 .all(|&coord| coord == NormalizedCoord::ZERO));
2721 }
2722
2723 const MVAR_FONT: &[u8] = font_test_data::AMSTELVAR_AVAR2_A;
2725
2726 #[test]
2727 fn ordinary_metrics_do_not_read_post() {
2728 let asked = Arc::new(std::sync::Mutex::new(Vec::new()));
2729 let logged = asked.clone();
2730 let source: Arc<dyn Fn(Tag) -> Option<Blob> + Send + Sync> = Arc::new(move |tag| {
2731 logged.lock().unwrap().push(tag);
2732 let font = crate::FontRef::new(font_test_data::TINOS_SUBSET).ok()?;
2733 font.table_data(tag)
2734 .map(|data| Blob::from(data.as_bytes().to_vec()))
2735 });
2736 let font = Font::new(source, 0).unwrap();
2737 asked.lock().unwrap().clear();
2738 let _ = font.metrics();
2739 assert!(!asked.lock().unwrap().contains(&Tag::new(b"post")));
2740 let _ = font.style_metrics();
2741 assert!(asked.lock().unwrap().contains(&Tag::new(b"post")));
2742 assert!(core::ptr::eq(font.style_metrics(), font.style_metrics()));
2743 }
2744
2745 #[test]
2746 fn an_instance_varies_its_metrics() {
2747 let font = Font::new(MVAR_FONT, 0).unwrap();
2748 let far = font
2749 .instance_builder()
2750 .normalized_coords([NormalizedCoord::from_f32(1.0); 12])
2751 .build();
2752 assert!(!far.normalized_coords().is_empty());
2753 assert_ne!(far.metrics(), font.metrics());
2754 }
2755
2756 #[test]
2757 fn an_instance_varies_and_shares_its_style_metrics() {
2758 let font = Font::new(MVAR_FONT, 0).unwrap();
2759 let far = font
2760 .instance_builder()
2761 .normalized_coords([NormalizedCoord::from_f32(1.0); 12])
2762 .build();
2763 assert_ne!(
2764 far.style_metrics().strike_through,
2765 font.style_metrics().strike_through
2766 );
2767 assert!(core::ptr::eq(
2768 far.style_metrics(),
2769 far.clone().style_metrics()
2770 ));
2771 }
2772
2773 #[test]
2774 fn an_instance_at_the_default_location_shares_the_font_metrics() {
2775 let font = Font::new(MVAR_FONT, 0).unwrap();
2777 let default = font.instance_builder().build();
2778 assert!(core::ptr::eq(default.metrics(), font.metrics()));
2779 }
2780
2781 #[test]
2782 fn clones_of_an_instance_share_one_set_of_metrics() {
2783 let font = Font::new(MVAR_FONT, 0).unwrap();
2784 let far = font
2785 .instance_builder()
2786 .normalized_coords([NormalizedCoord::from_f32(1.0); 12])
2787 .build();
2788 let shared = far.clone();
2789 assert!(core::ptr::eq(far.metrics(), shared.metrics()));
2791 }
2792
2793 #[test]
2794 fn the_fixed_numbers_do_not_resolve_a_location() {
2795 let asked = Arc::new(std::sync::Mutex::new(Vec::new()));
2798 let logged = asked.clone();
2799 let source: Arc<dyn Fn(Tag) -> Option<crate::model::Blob> + Send + Sync> =
2800 Arc::new(move |tag: Tag| {
2801 logged.lock().unwrap().push(tag);
2802 let font = crate::FontRef::new(MVAR_FONT).ok()?;
2803 Some(crate::model::Blob::from(
2804 font.table_data(tag)?.as_bytes().to_vec(),
2805 ))
2806 });
2807 let font = Font::new(source, 0).unwrap();
2808 let far = font
2809 .instance_builder()
2810 .normalized_coords([NormalizedCoord::from_f32(1.0); 12])
2811 .build();
2812 asked.lock().unwrap().clear();
2813
2814 assert_eq!(far.num_glyphs(), font.num_glyphs());
2815 assert_eq!(far.units_per_em(), font.units_per_em());
2816 assert!(
2817 !asked.lock().unwrap().contains(&Tag::new(b"MVAR")),
2818 "reading a fixed number resolved the location"
2819 );
2820
2821 let _ = far.metrics();
2823 assert!(asked.lock().unwrap().contains(&Tag::new(b"MVAR")));
2824 }
2825
2826 #[test]
2827 fn a_default_instance_is_only_its_font() {
2828 let font = Font::new(MVAR_FONT, 0).unwrap();
2831 for instance in [
2832 font.default_instance(),
2833 font.instance_builder().build(),
2834 font.instance_builder()
2837 .normalized_coords([NormalizedCoord::from_f32(0.0); 12])
2838 .build(),
2839 ] {
2840 assert!(matches!(instance.0, Repr::Default(_)));
2841 assert!(instance.normalized_coords().is_empty());
2842 assert!(core::ptr::eq(instance.metrics(), font.metrics()));
2843 }
2844 }
2845
2846 #[test]
2847 fn a_location_away_from_the_default_is_owned() {
2848 let font = Font::new(MVAR_FONT, 0).unwrap();
2849 let far = font
2850 .instance_builder()
2851 .normalized_coords([NormalizedCoord::from_f32(1.0); 12])
2852 .build();
2853 assert!(matches!(far.0, Repr::Varied(_)));
2854 assert_eq!(far.normalized_coords().len(), 12);
2855 }
2856}