Skip to main content

fontique/collection/
mod.rs

1// Copyright 2024 the Parley Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Support for working with font collections.
5
6mod query;
7
8pub use query::{Query, QueryFamily, QueryFont, QueryStatus};
9
10use crate::font::FontInfoOverride;
11
12use super::SourceCache;
13
14use super::{
15    Blob, FontStyle, FontWeight, FontWidth, GenericFamily, Language, Script,
16    backend::SystemFonts,
17    fallback::{FallbackKey, FallbackMap},
18    family::{FamilyId, FamilyInfo},
19    family_name::{FamilyName, FamilyNameMap},
20    font::FontInfo,
21    generic::GenericFamilyMap,
22    source::{SourceId, SourceInfo, SourceKind},
23};
24use crate::{AtomicCounter, CounterInt};
25use alloc::{string::String, sync::Arc, vec::Vec};
26use hashbrown::HashMap;
27use read_fonts::types::NameId;
28#[cfg(feature = "std")]
29use std::path::Path;
30#[cfg(feature = "std")]
31use std::sync::{Mutex, atomic::Ordering};
32
33type FamilyMap = HashMap<FamilyId, Option<FamilyInfo>>;
34
35/// Options for a [font collection](Collection).
36#[derive(Copy, Clone, Debug)]
37pub struct CollectionOptions {
38    /// If true, the font collection will use a secondary shared store
39    /// guaranteeing that any changes to the collection will be
40    /// visible to all clones.
41    ///
42    /// If the font collection will be used by a single thread, this is
43    /// pure overhead and should be disabled.
44    ///
45    /// The default value is `false`.
46    pub shared: bool,
47
48    /// If true, the font collection will provide access to system fonts
49    /// using platform specific APIs.
50    ///
51    /// The default value is `true`.
52    pub system_fonts: bool,
53}
54
55impl Default for CollectionOptions {
56    fn default() -> Self {
57        Self {
58            shared: false,
59            system_fonts: true,
60        }
61    }
62}
63
64/// Collection of fonts.
65#[derive(Clone)]
66pub struct Collection {
67    inner: Inner,
68    query_state: query::QueryState,
69}
70
71impl Collection {
72    /// Creates a new collection with the given options.
73    ///
74    /// If `fontique` was compiled with the `"system"` feature and
75    /// [`CollectionOptions::system_fonts`] was set to `true` when
76    /// creating this collection, then it will register the fonts
77    /// available on the system.
78    ///
79    /// Additional fonts can be registered via [`Collection::register_fonts`]
80    /// and providing it with the data for those fonts.
81    pub fn new(options: CollectionOptions) -> Self {
82        Self {
83            inner: Inner::new(options),
84            query_state: query::QueryState::default(),
85        }
86    }
87
88    /// Converts an unshared collection into a shared collection
89    #[cfg(feature = "std")]
90    pub fn make_shared(&mut self) {
91        self.inner.make_shared();
92    }
93
94    /// Load system fonts. If system fonts are already loaded then this does nothing.
95    pub fn load_system_fonts(&mut self) {
96        if self.inner.system.is_none() {
97            self.inner.load_system_fonts();
98        }
99    }
100
101    /// Loads all fonts contained within the specified directory(s)
102    #[cfg(feature = "std")]
103    pub fn load_fonts_from_paths(&mut self, paths: impl IntoIterator<Item = impl AsRef<Path>>) {
104        self.inner.load_fonts_from_paths(paths);
105    }
106
107    /// Returns an iterator over all available family names in the collection.
108    ///
109    /// If `fontique` was compiled with the `"system"` feature, then it will
110    /// include system fonts after the registered fonts.
111    pub fn family_names(&mut self) -> impl Iterator<Item = &str> + '_ + Clone {
112        self.inner.family_names()
113    }
114
115    /// Returns an iterator over all available family identifiers in the collection.
116    ///
117    /// If `fontique` was compiled with the `"system"` feature, then it will
118    /// include system fonts after the registered fonts.
119    pub fn family_ids(&mut self) -> impl Iterator<Item = FamilyId> + '_ + Clone {
120        self.inner.family_ids()
121    }
122
123    /// Returns the family identifier for the given family name.
124    pub fn family_id(&mut self, name: &str) -> Option<FamilyId> {
125        self.inner.family_id(name)
126    }
127
128    /// Returns the family name for the given family identifier.
129    pub fn family_name(&mut self, id: FamilyId) -> Option<&str> {
130        self.inner.family_name(id)
131    }
132
133    /// Returns the family object for the given family identifier.
134    pub fn family(&mut self, id: FamilyId) -> Option<FamilyInfo> {
135        self.inner.family(id)
136    }
137
138    /// Returns the family object for the given name.
139    pub fn family_by_name(&mut self, name: &str) -> Option<FamilyInfo> {
140        self.inner.family_by_name(name)
141    }
142
143    /// Returns an iterator over the family identifiers for the given
144    /// generic family.
145    pub fn generic_families(
146        &mut self,
147        family: GenericFamily,
148    ) -> impl Iterator<Item = FamilyId> + '_ + Clone {
149        self.inner.generic_families(family)
150    }
151
152    /// Replaces the set of family identifiers associated with the given generic
153    /// family.
154    pub fn set_generic_families(
155        &mut self,
156        generic: GenericFamily,
157        families: impl Iterator<Item = FamilyId>,
158    ) {
159        self.inner.set_generic_families(generic, families);
160    }
161
162    /// Appends the set of family identifiers to the given generic family.
163    pub fn append_generic_families(
164        &mut self,
165        generic: GenericFamily,
166        families: impl Iterator<Item = FamilyId>,
167    ) {
168        self.inner.append_generic_families(generic, families);
169    }
170
171    /// Returns an iterator over the fallback families for the given
172    /// key.
173    pub fn fallback_families(
174        &mut self,
175        key: impl Into<FallbackKey>,
176    ) -> impl Iterator<Item = FamilyId> + '_ + Clone {
177        self.inner.fallback_families(key)
178    }
179
180    /// Replaces the set of family identifiers associated with the fallback
181    /// key.
182    pub fn set_fallbacks(
183        &mut self,
184        key: impl Into<FallbackKey>,
185        families: impl Iterator<Item = FamilyId>,
186    ) -> bool {
187        self.inner.set_fallbacks(key, families)
188    }
189
190    /// Appends the set of family identifiers to the given fallback key.
191    pub fn append_fallbacks(
192        &mut self,
193        key: impl Into<FallbackKey>,
194        families: impl Iterator<Item = FamilyId>,
195    ) -> bool {
196        self.inner.append_fallbacks(key, families)
197    }
198
199    /// Returns an object for selecting fonts from this collection.
200    pub fn query<'a>(&'a mut self, source_cache: &'a mut SourceCache) -> Query<'a> {
201        Query::new(self, source_cache)
202    }
203
204    /// Registers all fonts that exist in the given data.
205    ///
206    /// Returns a list of pairs each containing the family identifier and fonts
207    /// added to that family.
208    ///
209    /// Optionally, you can override various aspects of the font's metadata.
210    ///
211    /// When newly registered fonts join an existing family, they are placed before
212    /// previously-registered fonts. This ordering can be useful, for example, for implementing CSS
213    /// `@font-face` behavior, where faces defined later are checked first. See
214    /// [CSS Fonts 4 ยง 4.5.1][css-composite-fonts].
215    ///
216    /// [css-composite-fonts]: https://www.w3.org/TR/css-fonts-4/#composite-fonlater
217    pub fn register_fonts(
218        &mut self,
219        data: Blob<u8>,
220        info_override: Option<FontInfoOverride<'_>>,
221    ) -> Vec<(FamilyId, Vec<FontInfo>)> {
222        self.inner.register_fonts(data, info_override)
223    }
224
225    /// Unregisters the font with the given attributes from the given family.
226    ///
227    /// Returns true if a font was removed from the family, false otherwise.
228    pub fn unregister_font(
229        &mut self,
230        family: FamilyId,
231        width: FontWidth,
232        style: FontStyle,
233        weight: FontWeight,
234    ) -> bool {
235        self.inner.unregister_font(family, width, style, weight)
236    }
237
238    /// Clears this collection. Un-registers all fonts previously registered via
239    /// [`Self::register_fonts`], and unsets all previously-set generic families
240    /// and fallbacks. This will not remove any system fonts.
241    pub fn clear(&mut self) {
242        self.inner.clear();
243    }
244}
245
246impl Default for Collection {
247    fn default() -> Self {
248        Self::new(CollectionOptions::default())
249    }
250}
251
252/// Collection of fonts.
253#[derive(Clone)]
254struct Inner {
255    system: Option<System>,
256    data: CommonData,
257    #[allow(unused)]
258    shared: Option<Arc<Shared>>,
259    #[allow(unused)]
260    shared_version: CounterInt,
261    fallback_cache: FallbackCache,
262}
263
264impl Inner {
265    /// Creates a new collection with the given options.
266    fn new(options: CollectionOptions) -> Self {
267        let system = options.system_fonts.then(System::new);
268        let shared = options.shared.then(|| Arc::new(Shared::default()));
269        Self {
270            system,
271            data: CommonData::default(),
272            shared,
273            shared_version: 0,
274            fallback_cache: FallbackCache::default(),
275        }
276    }
277
278    #[cfg(feature = "std")]
279    fn make_shared(&mut self) {
280        if self.shared.is_none() {
281            self.shared = Some(Arc::new(Shared {
282                data: Mutex::new(self.data.clone()),
283                version: AtomicCounter::new(self.shared_version),
284            }));
285        }
286    }
287
288    /// Load system fonts. If system fonts are already loaded then they will be reloaded.
289    fn load_system_fonts(&mut self) {
290        self.system = Some(System::new());
291    }
292
293    /// Returns an iterator over all available family names in the collection.
294    ///
295    /// This includes both system and registered fonts.
296    fn family_names(&mut self) -> impl Iterator<Item = &str> + '_ + Clone {
297        self.sync_shared();
298        FamilyNames {
299            ours: self.data.family_names.iter(),
300            system: self.system.as_ref().map(|sys| sys.family_names.iter()),
301        }
302        .map(|name| name.name())
303    }
304
305    /// Returns an iterator over all available family identifiers in the collection.
306    ///
307    /// This includes both system and registered fonts.
308    fn family_ids(&mut self) -> impl Iterator<Item = FamilyId> + '_ + Clone {
309        self.sync_shared();
310        self.data.family_names.ids().chain(
311            self.system
312                .as_ref()
313                .map(|sys| sys.family_names.ids())
314                .into_iter()
315                .flatten(),
316        )
317    }
318
319    /// Returns the family identifier for the given family name.
320    fn family_id(&mut self, name: &str) -> Option<FamilyId> {
321        self.sync_shared();
322        self.data
323            .family_names
324            .get(name)
325            .or_else(|| {
326                self.system
327                    .as_ref()
328                    .and_then(|sys| sys.family_names.get(name))
329            })
330            .map(|n| n.id())
331    }
332
333    /// Returns the family name for the given family identifier.
334    fn family_name(&mut self, id: FamilyId) -> Option<&str> {
335        self.sync_shared();
336        self.data
337            .family_names
338            .get_by_id(id)
339            .or_else(|| {
340                self.system
341                    .as_ref()
342                    .and_then(|sys| sys.family_names.get_by_id(id))
343            })
344            .map(|name| name.name())
345    }
346
347    /// Returns the family object for the given family identifier.
348    fn family(&mut self, id: FamilyId) -> Option<FamilyInfo> {
349        self.sync_shared();
350        if let Some(family) = self.data.families.get(&id) {
351            family.as_ref().cloned()
352        } else {
353            #[cfg(feature = "system")]
354            if let Some(system) = &self.system {
355                let family = system.fonts.lock().unwrap().family(id);
356                self.data.families.insert(id, family.clone());
357                family
358            } else {
359                None
360            }
361            #[cfg(not(feature = "system"))]
362            {
363                None
364            }
365        }
366    }
367
368    /// Returns the family object for the given name.
369    fn family_by_name(&mut self, name: &str) -> Option<FamilyInfo> {
370        if let Some(id) = self.family_id(name) {
371            self.family(id)
372        } else {
373            None
374        }
375    }
376
377    /// Returns an iterator over the family identifiers for the given
378    /// generic family.
379    fn generic_families(
380        &mut self,
381        family: GenericFamily,
382    ) -> impl Iterator<Item = FamilyId> + '_ + Clone {
383        self.sync_shared();
384        GenericFamilies {
385            ours: self.data.generic_families.get(family).iter().copied(),
386            system: self
387                .system
388                .as_ref()
389                .map(|sys| sys.generic_families.get(family).iter().copied()),
390        }
391    }
392
393    /// Replaces the set of family identifiers associated with the given generic
394    /// family.
395    fn set_generic_families(
396        &mut self,
397        generic: GenericFamily,
398        families: impl Iterator<Item = FamilyId>,
399    ) {
400        self.sync_shared();
401        #[cfg(feature = "std")]
402        if let Some(shared) = &self.shared {
403            shared
404                .data
405                .lock()
406                .unwrap()
407                .generic_families
408                .set(generic, families);
409            shared.bump_version();
410        } else {
411            self.data.generic_families.set(generic, families);
412        }
413        #[cfg(not(feature = "std"))]
414        self.data.generic_families.set(generic, families);
415    }
416
417    /// Appends the set of family identifiers to the given generic family.
418    fn append_generic_families(
419        &mut self,
420        generic: GenericFamily,
421        families: impl Iterator<Item = FamilyId>,
422    ) {
423        self.sync_shared();
424        #[cfg(feature = "std")]
425        if let Some(shared) = &self.shared {
426            shared
427                .data
428                .lock()
429                .unwrap()
430                .generic_families
431                .append(generic, families);
432            shared.bump_version();
433        } else {
434            self.data.generic_families.append(generic, families);
435        }
436        #[cfg(not(feature = "std"))]
437        self.data.generic_families.append(generic, families);
438    }
439
440    /// Returns an iterator over the fallback families for the given
441    /// key.
442    fn fallback_families(
443        &mut self,
444        key: impl Into<FallbackKey>,
445    ) -> impl Iterator<Item = FamilyId> + '_ + Clone {
446        let selector = key.into();
447        let script = selector.script();
448        let lang_key = selector.locale();
449        // Sync the collection and resets the fallback cache if another handle changed the shared
450        // data.
451        self.sync_shared();
452        if self.fallback_cache.script != Some(script) || self.fallback_cache.language != lang_key {
453            self.fallback_cache.reset();
454            #[cfg(feature = "system")]
455            if let Some(families) = self.data.fallbacks.get(selector) {
456                self.fallback_cache.set(script, lang_key, families);
457            } else if let Some(system) = self.system.as_ref() {
458                let family = system.fonts.lock().unwrap().fallback(selector);
459                self.data.fallbacks.set(selector, family.into_iter());
460                self.fallback_cache.set(script, lang_key, family.as_slice());
461            }
462            #[cfg(not(feature = "system"))]
463            if let Some(families) = self.data.fallbacks.get(selector) {
464                self.fallback_cache.set(script, lang_key, families);
465            }
466        }
467        self.fallback_cache.families.iter().copied()
468    }
469
470    /// Replaces the set of family identifiers associated with the fallback
471    /// key.
472    fn set_fallbacks(
473        &mut self,
474        key: impl Into<FallbackKey>,
475        families: impl Iterator<Item = FamilyId>,
476    ) -> bool {
477        self.sync_shared();
478        self.fallback_cache.reset();
479        #[cfg(feature = "std")]
480        if let Some(shared) = &self.shared {
481            let result = shared.data.lock().unwrap().fallbacks.set(key, families);
482            shared.bump_version();
483            result
484        } else {
485            self.data.fallbacks.set(key, families)
486        }
487        #[cfg(not(feature = "std"))]
488        self.data.fallbacks.set(key, families)
489    }
490
491    /// Appends the set of family identifiers to the given fallback key.
492    fn append_fallbacks(
493        &mut self,
494        key: impl Into<FallbackKey>,
495        families: impl Iterator<Item = FamilyId>,
496    ) -> bool {
497        self.sync_shared();
498        self.fallback_cache.reset();
499        #[cfg(feature = "std")]
500        if let Some(shared) = &self.shared {
501            let result = shared.data.lock().unwrap().fallbacks.append(key, families);
502            shared.bump_version();
503            result
504        } else {
505            self.data.fallbacks.append(key, families)
506        }
507        #[cfg(not(feature = "std"))]
508        self.data.fallbacks.append(key, families)
509    }
510
511    /// Loads all fonts that exist in the specified directory(s)
512    #[cfg(feature = "std")]
513    fn load_fonts_from_paths(&mut self, paths: impl IntoIterator<Item = impl AsRef<Path>>) {
514        #[cfg(feature = "std")]
515        if let Some(shared) = &self.shared {
516            shared.data.lock().unwrap().load_fonts_from_paths(paths);
517            shared.bump_version();
518        } else {
519            self.data.load_fonts_from_paths(paths);
520        }
521        #[cfg(not(feature = "std"))]
522        self.data.register_fonts(paths)
523    }
524
525    /// Registers all fonts that exist in the given data.
526    ///
527    /// Returns a list of pairs each containing the family identifier and fonts
528    /// added to that family.
529    fn register_fonts(
530        &mut self,
531        data: Blob<u8>,
532        info_override: Option<FontInfoOverride<'_>>,
533    ) -> Vec<(FamilyId, Vec<FontInfo>)> {
534        #[cfg(feature = "std")]
535        if let Some(shared) = &self.shared {
536            let result = shared
537                .data
538                .lock()
539                .unwrap()
540                .register_fonts(data, info_override);
541            shared.bump_version();
542            result
543        } else {
544            self.data.register_fonts(data, info_override)
545        }
546        #[cfg(not(feature = "std"))]
547        self.data.register_fonts(data, info_override)
548    }
549
550    /// Unregisters the font with the given attributes from the given family.
551    ///
552    /// Returns true if a font was removed from the family, false otherwise.
553    fn unregister_font(
554        &mut self,
555        family: FamilyId,
556        width: FontWidth,
557        style: FontStyle,
558        weight: FontWeight,
559    ) -> bool {
560        #[cfg(feature = "std")]
561        if let Some(shared) = &self.shared {
562            let result = shared
563                .data
564                .lock()
565                .unwrap()
566                .unregister_font(family, width, style, weight);
567            shared.bump_version();
568            result.is_some()
569        } else {
570            self.data
571                .unregister_font(family, width, style, weight)
572                .is_some()
573        }
574        #[cfg(not(feature = "std"))]
575        self.data
576            .unregister_font(family, width, style, weight)
577            .is_some()
578    }
579
580    /// Clears this collection. Un-registers all fonts previously registered via
581    /// [`Self::register_fonts`], and unsets all previously-set generic families
582    /// and fallbacks. This will not remove any system fonts.
583    fn clear(&mut self) {
584        #[cfg(feature = "std")]
585        if let Some(shared) = &self.shared {
586            shared.data.lock().unwrap().clear();
587            shared.bump_version();
588        }
589        self.data.clear();
590        self.fallback_cache.reset();
591    }
592
593    fn sync_shared(&mut self) {
594        #[cfg(feature = "std")]
595        if let Some(shared) = &self.shared {
596            let version = shared.version.load(Ordering::Acquire);
597            if self.shared_version != version {
598                // This is an ugly deep copy, but the assumption is that
599                // modifications to font collections are fairly rare.
600                // If this becomes a problem, do more fine grained tracking
601                // of changes.
602                self.data = shared.data.lock().unwrap().clone();
603                self.shared_version = version;
604                self.fallback_cache.reset();
605            }
606        }
607    }
608}
609
610#[derive(Clone)]
611struct FamilyNames<I> {
612    ours: I,
613    system: Option<I>,
614}
615
616impl<'a, I> Iterator for FamilyNames<I>
617where
618    I: Iterator<Item = &'a FamilyName> + 'a,
619{
620    type Item = &'a FamilyName;
621
622    fn next(&mut self) -> Option<Self::Item> {
623        if let Some(ours) = self.ours.next() {
624            return Some(ours);
625        }
626        self.system.as_mut()?.next()
627    }
628}
629
630#[derive(Clone)]
631struct GenericFamilies<I> {
632    ours: I,
633    system: Option<I>,
634}
635
636impl<I> Iterator for GenericFamilies<I>
637where
638    I: Iterator<Item = FamilyId>,
639{
640    type Item = FamilyId;
641
642    fn next(&mut self) -> Option<Self::Item> {
643        if let Some(ours) = self.ours.next() {
644            return Some(ours);
645        }
646        self.system.as_mut()?.next()
647    }
648}
649
650#[derive(Clone, Default)]
651struct FallbackCache {
652    script: Option<Script>,
653    language: Option<Language>,
654    families: Vec<FamilyId>,
655}
656
657impl FallbackCache {
658    fn reset(&mut self) {
659        self.script = None;
660        self.language = None;
661        self.families.clear();
662    }
663
664    fn set(&mut self, script: Script, language: Option<Language>, families: &[FamilyId]) {
665        self.script = Some(script);
666        self.language = language;
667        self.families.clear();
668        self.families.extend_from_slice(families);
669    }
670}
671
672/// Data taken from the system font collection.
673#[derive(Clone)]
674struct System {
675    #[cfg(feature = "system")]
676    fonts: Arc<Mutex<SystemFonts>>,
677    family_names: Arc<FamilyNameMap>,
678    generic_families: Arc<GenericFamilyMap>,
679}
680
681impl System {
682    fn new() -> Self {
683        let fonts = SystemFonts::new();
684        let family_names = fonts.name_map.clone();
685        let generic_families = fonts.generic_families.clone();
686        #[cfg(feature = "system")]
687        let fonts = Arc::new(Mutex::new(fonts));
688        Self {
689            #[cfg(feature = "system")]
690            fonts,
691            family_names,
692            generic_families,
693        }
694    }
695}
696
697/// Common data for base and shared collections.
698#[derive(Clone, Default)]
699struct CommonData {
700    family_names: FamilyNameMap,
701    families: FamilyMap,
702    generic_families: GenericFamilyMap,
703    fallbacks: FallbackMap,
704}
705
706impl CommonData {
707    #[cfg(feature = "std")]
708    fn load_fonts_from_paths(&mut self, paths: impl IntoIterator<Item = impl AsRef<Path>>) {
709        let mut families: HashMap<FamilyId, (FamilyName, Vec<FontInfo>)> = HashMap::default();
710        let mut scratch_family_name = String::default();
711        crate::scan::scan_paths(paths, 16, |scanned_font| {
712            let source = SourceInfo {
713                id: SourceId::new(),
714                kind: SourceKind::Path(Arc::from(scanned_font.path.unwrap())),
715            };
716
717            // `scan_paths` invokes this callback once per face (each face of a
718            // collection is reported separately), so register exactly this font.
719            // Re-scanning the file here would register duplicate faces.
720            families.clear();
721            self.register_scanned_font(
722                scanned_font,
723                &source,
724                None,
725                &mut scratch_family_name,
726                &mut families,
727            );
728            self.merge_families(&families);
729        });
730    }
731
732    fn register_fonts(
733        &mut self,
734        data: Blob<u8>,
735        info_override: Option<FontInfoOverride<'_>>,
736    ) -> Vec<(FamilyId, Vec<FontInfo>)> {
737        let mut families: HashMap<FamilyId, (FamilyName, Vec<FontInfo>)> = HashMap::default();
738        let mut scratch_family_name = String::default();
739
740        let source = SourceInfo {
741            id: SourceId::new(),
742            kind: SourceKind::Memory(data.clone()),
743        };
744
745        super::scan::scan_memory(data.as_ref(), |scanned_font| {
746            self.register_scanned_font(
747                scanned_font,
748                &source,
749                info_override,
750                &mut scratch_family_name,
751                &mut families,
752            );
753        });
754
755        self.merge_families(&families);
756
757        families
758            .into_iter()
759            .map(|(id, (_, fonts))| (id, fonts))
760            .collect()
761    }
762
763    fn register_scanned_font(
764        &mut self,
765        scanned_font: &crate::scan::ScannedFont<'_>,
766        source: &SourceInfo,
767        info_override: Option<FontInfoOverride<'_>>,
768        scratch_family_name: &mut String,
769        families: &mut HashMap<FamilyId, (FamilyName, Vec<FontInfo>)>,
770    ) {
771        scratch_family_name.clear();
772
773        let family_name =
774            if let Some(override_family_name) = info_override.and_then(|o| o.family_name) {
775                override_family_name
776            } else {
777                let family_chars = scanned_font
778                    .english_or_first_name(NameId::TYPOGRAPHIC_FAMILY_NAME)
779                    .or_else(|| scanned_font.english_or_first_name(NameId::FAMILY_NAME))
780                    .map(|name| name.chars());
781                let Some(family_chars) = family_chars else {
782                    return;
783                };
784                scratch_family_name.extend(family_chars);
785
786                #[allow(clippy::needless_borrow)] // false positive
787                &scratch_family_name
788            };
789
790        if family_name.is_empty() {
791            return;
792        }
793
794        let Some(mut font) =
795            FontInfo::from_font_ref(&scanned_font.font, source.clone(), scanned_font.index)
796        else {
797            return;
798        };
799
800        if let Some(info_override) = info_override.as_ref() {
801            font.apply_override(info_override);
802        }
803
804        let name = self.family_names.get_or_insert(family_name);
805        families
806            .entry(name.id())
807            .or_insert_with(|| (name, Vec::default()))
808            .1
809            .push(font);
810    }
811
812    fn merge_families(&mut self, families: &HashMap<FamilyId, (FamilyName, Vec<FontInfo>)>) {
813        for (id, (name, fonts)) in families.iter() {
814            if let Some(Some(family)) = self.families.get_mut(id) {
815                let new_fonts = fonts.iter().chain(family.fonts()).cloned();
816                *family = FamilyInfo::new(name.clone(), new_fonts);
817            } else {
818                let family = FamilyInfo::new(name.clone(), fonts.iter().cloned());
819                self.families.insert(*id, Some(family));
820            }
821        }
822    }
823
824    fn unregister_font(
825        &mut self,
826        family: FamilyId,
827        width: FontWidth,
828        style: FontStyle,
829        weight: FontWeight,
830    ) -> Option<()> {
831        let family_name = self.family_names.get_by_id(family)?;
832        let family = self.families.get_mut(&family)?.as_mut()?;
833
834        let new_fonts = family
835            .fonts()
836            .iter()
837            .filter(|f| f.width() != width || f.style() != style || f.weight() != weight)
838            .cloned();
839        *family = FamilyInfo::new(family_name.clone(), new_fonts);
840
841        Some(())
842    }
843
844    fn clear(&mut self) {
845        *self = Self::default();
846    }
847}
848
849/// Synchronized shared collection data.
850#[derive(Default)]
851struct Shared {
852    #[allow(unused)]
853    version: AtomicCounter,
854    #[cfg(feature = "std")]
855    #[allow(unused)]
856    data: Mutex<CommonData>,
857}
858
859impl Shared {
860    #[cfg(feature = "std")]
861    fn bump_version(&self) {
862        self.version.fetch_add(1, Ordering::Release);
863    }
864}
865
866#[test]
867#[cfg(all(
868    feature = "std",
869    any(
870        target_os = "linux",
871        target_os = "freebsd",
872        target_os = "netbsd",
873        target_os = "openbsd",
874        target_os = "dragonfly",
875        target_os = "macos",
876        target_os = "windows"
877    )
878))]
879fn make_shared_matches_local() {
880    use crate::{Collection, CollectionOptions};
881
882    let mut collection = Collection::new(CollectionOptions {
883        shared: false,
884        system_fonts: false,
885    });
886
887    let font_dirs: Vec<std::path::PathBuf> = [
888        #[cfg(target_os = "macos")]
889        "/Library/Fonts",
890        #[cfg(target_os = "linux")]
891        "/usr/share/fonts",
892        #[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "dragonfly"))]
893        "/usr/local/share/fonts",
894        #[cfg(target_os = "netbsd")]
895        "/usr/pkg/share/fonts",
896        #[cfg(target_os = "windows")]
897        "C:\\Windows\\Fonts",
898    ]
899    .iter()
900    .map(std::path::PathBuf::from)
901    .filter(|p| p.is_dir())
902    .collect();
903
904    if font_dirs.is_empty() {
905        return;
906    }
907
908    collection.load_fonts_from_paths(&font_dirs);
909
910    let names_before: Vec<String> = collection.family_names().map(String::from).collect();
911
912    collection.make_shared();
913
914    let names_after: Vec<String> = collection.family_names().map(String::from).collect();
915
916    assert_eq!(names_before.len(), names_after.len());
917}
918
919// Regression test for https://github.com/linebender/parley/issues/683: loading
920// fonts from a directory used to register the same face several times because a
921// shared accumulator was never cleared and every callback re-scanned the whole
922// file. Each face should appear exactly once, identified by its source and index.
923#[test]
924#[cfg(all(
925    feature = "std",
926    any(
927        target_os = "linux",
928        target_os = "freebsd",
929        target_os = "netbsd",
930        target_os = "openbsd",
931        target_os = "dragonfly",
932        target_os = "macos",
933        target_os = "windows"
934    )
935))]
936fn load_fonts_from_paths_registers_each_face_once() {
937    use crate::{Collection, CollectionOptions};
938    use std::collections::HashSet;
939
940    let mut collection = Collection::new(CollectionOptions {
941        shared: false,
942        system_fonts: false,
943    });
944
945    let font_dirs: Vec<std::path::PathBuf> = [
946        #[cfg(target_os = "macos")]
947        "/Library/Fonts",
948        #[cfg(target_os = "linux")]
949        "/usr/share/fonts",
950        #[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "dragonfly"))]
951        "/usr/local/share/fonts",
952        #[cfg(target_os = "netbsd")]
953        "/usr/pkg/share/fonts",
954        #[cfg(target_os = "windows")]
955        "C:\\Windows\\Fonts",
956    ]
957    .iter()
958    .map(std::path::PathBuf::from)
959    .filter(|p| p.is_dir())
960    .collect();
961
962    if font_dirs.is_empty() {
963        return;
964    }
965
966    collection.load_fonts_from_paths(&font_dirs);
967
968    let family_ids: Vec<_> = collection.family_ids().collect();
969    for id in family_ids {
970        let Some(family) = collection.family(id) else {
971            continue;
972        };
973        let mut seen = HashSet::new();
974        for font in family.fonts() {
975            let face = (font.source().id(), font.index());
976            assert!(
977                seen.insert(face),
978                "family {:?} contains a duplicate face {face:?}",
979                collection.family_name(id),
980            );
981        }
982    }
983}
984
985#[test]
986fn clear_empties_fallbacks() {
987    let mut collection = Collection::new(CollectionOptions {
988        shared: false,
989        system_fonts: false,
990    });
991    let latin = Script::from_bytes(*b"Latn");
992    collection.set_fallbacks(latin, core::iter::once(FamilyId::new()));
993    // This read fills the cache.
994    assert_eq!(collection.fallback_families(latin).count(), 1);
995
996    collection.clear();
997    assert_eq!(collection.fallback_families(latin).count(), 0);
998}