diff --git a/crates/text/src/fontdb/composite.rs b/crates/text/src/fontdb/composite.rs index 7b17fb74de..bdcb84ae8c 100644 --- a/crates/text/src/fontdb/composite.rs +++ b/crates/text/src/fontdb/composite.rs @@ -91,6 +91,8 @@ impl FontDb { /// guard's thread uses the fonts it lends and not this one. pub fn set_composite_font(&self, font: &CompositeFont) -> bool { let key = font.name.to_lowercase(); + #[cfg(any(test, feature = "test-fonts"))] + let _change = crate::test_fonts::font_change(); { let mut map = self.composites.write().unwrap_or_else(|e| e.into_inner()); if map.get(&key).is_some_and(|f| **f == *font) { @@ -104,6 +106,8 @@ impl FontDb { /// Forget the composite font named `name` (any case). Whether there was one. pub fn remove_composite_font(&self, name: &str) -> bool { + #[cfg(any(test, feature = "test-fonts"))] + let _change = crate::test_fonts::font_change(); let removed = self.composites.write().unwrap_or_else(|e| e.into_inner()).remove(&name.to_lowercase()).is_some(); if removed { self.changed(); diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 3be2c871de..046db94dfd 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -305,6 +305,8 @@ impl FontDb { } } } + #[cfg(any(test, feature = "test-fonts"))] + let _change = (!made.is_empty()).then(crate::test_fonts::font_change); let mut faces = self.faces.write().unwrap_or_else(std::sync::PoisonError::into_inner); let before = faces.len(); for f in made { @@ -325,7 +327,7 @@ impl FontDb { /// Catalog the installed fonts unless that has been done: the first caller scans the font /// folders, any other waits for that scan to finish. A no-op on wasm. - pub(super) fn ensure_catalog(&self) { + pub(crate) fn ensure_catalog(&self) { #[cfg(not(target_arch = "wasm32"))] self.cataloged.get_or_init(|| { self.scan_font_dirs(); @@ -448,6 +450,9 @@ impl FontDb { } log::debug!("cataloged {n} system font faces"); let installed: std::collections::HashSet = catalog.values().flat_map(|c| c.faces.iter().map(|cf| cf.path.clone())).collect(); + // The first scan waits for nothing: a guard is made only for a database already cataloged. + #[cfg(any(test, feature = "test-fonts"))] + let _change = self.cataloged.get().is_some().then(crate::test_fonts::font_change); *self.stamp.lock().unwrap_or_else(|e| e.into_inner()) = Some(ScanStamp { paths, modified: modified_at }); *self.catalog.write().unwrap_or_else(|e| e.into_inner()) = catalog; *self.aliases.write().unwrap_or_else(|e| e.into_inner()) = aliases; diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 7a2a23f089..1ba4fe3f99 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -45,6 +45,136 @@ pub fn drop_kept_layouts() { crate::kept::drop_kept_layouts(); } +/// Who holds [`SteadyFonts`] and who changes fonts ([`font_change`]), guarded by [`steadiness`] and +/// signaled through [`STEADINESS_CHANGED`]. +struct Steadiness { + /// Threads that hold a [`SteadyFonts`]. + holders: usize, + /// Font changes waiting to start. + waiting: usize, + /// Of `waiting`, those made on a thread that holds a [`SteadyFonts`]. + holders_waiting: usize, + /// Whether a font change is under way. + changing: bool, +} + +static STEADINESS: std::sync::Mutex = std::sync::Mutex::new(Steadiness { holders: 0, waiting: 0, holders_waiting: 0, changing: false }); +static STEADINESS_CHANGED: std::sync::Condvar = std::sync::Condvar::new(); + +fn steadiness() -> std::sync::MutexGuard<'static, Steadiness> { + STEADINESS.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Wait for [`STEADINESS_CHANGED`]. +fn await_steadiness(s: std::sync::MutexGuard<'static, Steadiness>) -> std::sync::MutexGuard<'static, Steadiness> { + STEADINESS_CHANGED.wait(s).unwrap_or_else(std::sync::PoisonError::into_inner) +} + +std::thread_local! { + /// How many [`SteadyFonts`] this thread holds. + static STEADY: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Whether this thread holds the [`FontChange`] under way. + static CHANGING: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// While held, a cataloged font database's fonts and its +/// [`FontDb::generation`](crate::FontDb::generation) change only on this thread: a change on another +/// thread (a system font loaded for a character no loaded font covers, fonts added, a rescan, a +/// composite font set or removed) waits until it is dropped, before it publishes anything. A change +/// on this thread waits until no other thread holds one, unless every other thread that holds one is +/// itself waiting to change fonts. Tests hold it to count the layouts that a cache keyed on the +/// generation keeps. The guards one thread holds count as one, until the last of them is dropped, in +/// whatever order they are. +pub struct SteadyFonts { + /// Dropped on the thread that made it. + _thread: std::marker::PhantomData<*const ()>, +} + +impl Drop for SteadyFonts { + fn drop(&mut self) { + let last = STEADY.with(|n| { + n.set(n.get() - 1); + n.get() == 0 + }); + if last { + steadiness().holders -= 1; + STEADINESS_CHANGED.notify_all(); + } + } +} + +/// [`SteadyFonts`] for `db`. Catalogs `db`'s installed fonts first: a first scan does not wait for +/// any guard, so this thread can wait for one running on another thread while it holds a guard. A +/// thread's first guard waits for the font changes under way or waiting. +pub fn steady_fonts(db: &crate::FontDb) -> SteadyFonts { + db.ensure_catalog(); + if STEADY.with(std::cell::Cell::get) == 0 { + let mut s = steadiness(); + while !CHANGING.with(std::cell::Cell::get) && (s.changing || s.waiting > 0) { + s = await_steadiness(s); + } + s.holders += 1; + } + STEADY.with(|n| n.set(n.get() + 1)); + SteadyFonts { _thread: std::marker::PhantomData } +} + +/// Held while a font database's fonts change, from before the change is published until its +/// generation has changed ([`font_change`]). +pub(crate) struct FontChange { + /// Made while this thread already held one (a change made inside another, as a test hook run + /// when faces are published can). + nested: bool, +} + +impl Drop for FontChange { + fn drop(&mut self) { + if !self.nested { + CHANGING.with(|c| c.set(false)); + steadiness().changing = false; + STEADINESS_CHANGED.notify_all(); + } + } +} + +/// [`FontChange`]: waits until no other change is under way and no other thread holds a +/// [`SteadyFonts`] (on a thread that holds one: none that is not itself waiting to change fonts). +/// Inside a change this thread is making, it does not wait. +pub(crate) fn font_change() -> FontChange { + if CHANGING.with(std::cell::Cell::get) { + return FontChange { nested: true }; + } + let holder = STEADY.with(std::cell::Cell::get) > 0; + let mut s = steadiness(); + #[cfg(test)] + font_changers().push(std::thread::current().id()); + s.waiting += 1; + s.holders_waiting += usize::from(holder); + while s.changing || if holder { s.holders > s.holders_waiting } else { s.holders > 0 } { + s = await_steadiness(s); + } + s.waiting -= 1; + s.holders_waiting -= usize::from(holder); + s.changing = true; + CHANGING.with(|c| c.set(true)); + FontChange { nested: false } +} + +/// Whether a font change on another thread would wait now (a [`SteadyFonts`] is held, or another +/// change is under way). +#[cfg(test)] +pub(crate) fn font_changes_held_back() -> bool { + let s = steadiness(); + s.holders > 0 || s.changing +} + +/// The threads that have asked to change a font database's generation ([`font_change`]). +#[cfg(test)] +pub(crate) fn font_changers() -> std::sync::MutexGuard<'static, Vec> { + static CHANGERS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + CHANGERS.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + /// The family of [`variable_font`]. pub const VARIABLE_FAMILY: &str = "Varitest Sans"; diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index ada5c45dd1..06c4db899c 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -50,6 +50,121 @@ fn concurrent_fallback_lookups_all_find_the_installed_face() { std::fs::remove_dir(dir).unwrap(); } +/// Two [`test_fonts::steady_fonts`] guards on one thread hold font changes back until the last of +/// them is dropped, whichever was made first. +#[test] +fn steady_fonts_hold_back_font_changes_until_the_last_guard_is_dropped() { + let db = FontDb::with_font_dirs(vec![]); + let outer = crate::test_fonts::steady_fonts(&db); + let inner = crate::test_fonts::steady_fonts(&db); + drop(outer); + assert!(crate::test_fonts::font_changes_held_back(), "the inner guard is still held"); + drop(inner); + let first = crate::test_fonts::steady_fonts(&db); + let second = crate::test_fonts::steady_fonts(&db); + drop(second); + assert!(crate::test_fonts::font_changes_held_back(), "the first guard is still held"); + drop(first); +} + +/// While a thread holds [`test_fonts::steady_fonts`], a font added on another thread, which may +/// hold one too, changes the database's generation only once the guard is dropped. A thread that +/// holds the only guard adds a font itself while another thread's change waits, which then still +/// waits for the guard. +#[test] +fn steady_fonts_hold_back_other_threads_font_changes() { + for guarded in [false, true] { + let db = FontDb::with_font_dirs(vec![]); + let font = crate::test_fonts::variable_font().unwrap(); + let steady = crate::test_fonts::steady_fonts(&db); + let before = db.generation(); + std::thread::scope(|scope| { + let adding = scope.spawn(|| { + let _steady = guarded.then(|| crate::test_fonts::steady_fonts(&db)); + db.add_font(font) + }); + let id = adding.thread().id(); + while !adding.is_finished() && !crate::test_fonts::font_changers().contains(&id) { + std::thread::yield_now(); + } + assert_eq!(db.generation(), before, "guarded {guarded}: the other thread's change waits for the guard"); + let listed = db.families().iter().any(|f| f == crate::test_fonts::VARIABLE_FAMILY); + assert!(!listed, "guarded {guarded}: the other thread publishes the font only once the guard is dropped"); + drop(steady); + assert!(adding.join().unwrap() > 0, "guarded {guarded}: the font is new to this database"); + }); + assert_ne!(db.generation(), before, "guarded {guarded}: the change is made once the guard is dropped"); + } + let db = FontDb::with_font_dirs(vec![]); + let steady = crate::test_fonts::steady_fonts(&db); + std::thread::scope(|scope| { + let adding = scope.spawn(|| db.add_font(crate::test_fonts::two_axis_font().unwrap())); + let id = adding.thread().id(); + while !adding.is_finished() && !crate::test_fonts::font_changers().contains(&id) { + std::thread::yield_now(); + } + let before = db.generation(); + assert!(db.add_font(crate::test_fonts::variable_font().unwrap()) > 0); + let after = db.generation(); + assert_ne!(after, before, "the guard's own thread changes the fonts"); + assert!(!adding.is_finished(), "the waiting change still waits for the guard"); + assert_eq!(db.generation(), after, "the waiting change still waits for the guard"); + drop(steady); + assert!(adding.join().unwrap() > 0); + }); +} + +/// The first scan of a database's installed fonts does not wait for [`test_fonts::steady_fonts`] +/// held for another database, so a thread holding one can catalog a database that another thread +/// is scanning. +#[test] +fn a_first_scan_does_not_wait_for_steady_fonts() { + let (held, scanned) = (FontDb::with_font_dirs(vec![]), FontDb::with_font_dirs(vec![])); + let steady = crate::test_fonts::steady_fonts(&held); + std::thread::scope(|scope| { + let scanning = scope.spawn(|| scanned.load_system_fonts()); + let id = scanning.thread().id(); + while !scanning.is_finished() && !crate::test_fonts::font_changers().contains(&id) { + std::thread::yield_now(); + } + let finished = scanning.is_finished(); + drop(steady); + assert!(finished, "the first scan waited for the guard"); + scanning.join().unwrap(); + }); +} + +/// A font that a hook adds while another add publishes its faces, on the same thread, is added +/// without that thread waiting for its own change. +#[test] +fn a_font_added_while_faces_are_published_is_added() { + let db = Arc::new(FontDb::with_font_dirs(vec![])); + let adder = db.clone(); + // Not scoped: a thread that waits for its own change never finishes, and the test still reports. + let adding = std::thread::spawn(move || { + let (hook_db, mut extra) = (adder.clone(), crate::test_fonts::two_axis_font()); + crate::fontdb::on_faces_published(Some(Box::new(move || { + if let Some(font) = extra.take() { + hook_db.add_font(font); + } + }))); + let added = adder.add_font(crate::test_fonts::variable_font().unwrap()); + crate::fontdb::on_faces_published(None); + added + }); + let id = adding.thread().id(); + let changes = || crate::test_fonts::font_changers().iter().filter(|t| **t == id).count(); + while !adding.is_finished() && changes() < 2 { + std::thread::yield_now(); + } + assert!(adding.is_finished(), "the hook's add waited for the change around it"); + assert!(adding.join().unwrap() > 0); + let families = db.families(); + for family in [crate::test_fonts::VARIABLE_FAMILY, crate::test_fonts::TWO_AXIS_FAMILY] { + assert!(families.iter().any(|f| f == family), "{family} is added"); + } +} + /// A bundled Source Sans 3 file renamed [`FAMILY`] (as long as the original name). fn renamed(file: &str) -> Vec { renamed_to(file, FAMILY) diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 688f295478..98d0b999cb 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -705,8 +705,12 @@ pub(crate) mod testutil { /// and a count must not include a refresh another test caused. static LAYOUT_INPUTS: std::sync::RwLock<()> = std::sync::RwLock::new(()); - pub fn steady_layout_inputs() -> std::sync::RwLockReadGuard<'static, ()> { - LAYOUT_INPUTS.read().unwrap_or_else(|e| e.into_inner()) + /// Catalogs the installed fonts, then also holds back the font changes other tests make without + /// [`changing_layout_inputs`] (a system font loaded for a character no loaded font covers, a + /// rescan) until it is dropped. + pub fn steady_layout_inputs() -> (std::sync::RwLockReadGuard<'static, ()>, vectorcraft_text::test_fonts::SteadyFonts) { + let inputs = LAYOUT_INPUTS.read().unwrap_or_else(|e| e.into_inner()); + (inputs, vectorcraft_text::test_fonts::steady_fonts(vectorcraft_text::FontDb::global())) } pub fn changing_layout_inputs() -> std::sync::RwLockWriteGuard<'static, ()> {