Merge remote-tracking branch 'origin/next' into sync/next

# Conflicts:
#	crates/font-catalog/src/catalog.rs
This commit is contained in:
bflatastic
2026-11-23 14:37:24 +07:00
8 changed files with 550 additions and 13 deletions
+6 -1
View File
@@ -68,8 +68,13 @@ Each face (`FaceInfo`) has its family and style, legacy family and style, family
- `rescan` scans again, reading only new and changed files.
- `installed_fonts_changed` compares the modification times of every folder the scan read (and the folders of files a font service named) and, on Windows, the registry's font list. It costs a few hundred `stat` calls, not a scan.
- `rescan_if_changed` does both; apps call it when their window is activated.
- `store_changed` compares the modification times of the font store's folders only, cheap enough to poll every second.
- `watch(interval, on_change)` polls on a background thread.
- `generation` counts the catalog's changes.
- `generation` counts the catalog's changes; `changes_since(generation)` names the families added, removed and changed since then (`full` when the history of the last 64 changes no longer reaches back that far).
## In an app
`app::start(AppFonts { .. })` at launch sets the app's folders, starts the first scan on a background thread and polls the font store's folders every second, so a family the launcher installs shows at once. `app::on_activated()` on window activation rescans on a worker thread when any folder changed, with a full rescan at most every five minutes. `AppFonts::on_change` wakes the app after a change; the app then calls `app::changes_since` with the generation it last saw. A CLI calls `app::configure` instead, which neither scans in the background nor polls.
## One enumeration for the UI and documents
+250
View File
@@ -0,0 +1,250 @@
//! What every Craft app does with the catalog: start it at launch, follow the suite's font store,
//! refresh it when a window is activated, and learn which families changed so it lays out only
//! the documents they affect.
//!
//! ```no_run
//! use std::sync::Arc;
//! use craft_font_catalog::app::{self, AppFonts};
//!
//! // At launch, before the first window. `on_change` wakes the app's event loop.
//! let wake: app::OnChange = Arc::new(|_| { /* request a repaint */ });
//! let catalog = app::start(AppFonts { dirs: vec!["/path/to/prefs/Fonts".into()], on_change: Some(wake), ..AppFonts::default() });
//! let mut seen = catalog.generation();
//!
//! // When a window is activated.
//! app::on_activated();
//!
//! // Where the app checks for work (each frame, or after `on_change` woke it).
//! if catalog.generation() != seen {
//! let changes = app::changes_since(seen);
//! seen = changes.generation;
//! // Re-resolve the families each document asked for that were missing or nearest-style
//! // (all of them when `changes.full`), and lay out the documents where one now resolves
//! // differently or uses a removed or changed family.
//! }
//! ```
//!
//! - Desktop: [`start`] adds the app's folders, scans on a background thread and polls the font
//! store's folders ([`Catalog::store_changed`]), so a family the launcher installs shows at
//! once. [`on_activated`] runs [`Catalog::rescan_if_changed`] on a worker thread for every other
//! folder, and a full [`Catalog::rescan`] at most every [`AppFonts::full_rescan_every`], for
//! fonts a font service (Adobe Fonts, FontBase) activates from folders no scan has seen.
//! - CLI: [`configure`] instead of [`start`]: the first lookup scans and waits for it, and nothing
//! polls.
//! - wasm: there are no folders, no font service and no threads. Fonts come in through
//! [`Catalog::add_bytes`]; [`start`] polls nothing and [`on_activated`] does nothing.
use std::path::PathBuf;
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, Weak};
use std::time::{Duration, Instant};
use crate::{Catalog, Changes};
/// How often [`on_activated`] runs a full [`Catalog::rescan`] at most, by default. A full rescan
/// lists the font service's files again: about 60 ms with 150 font files and 0.5 s with 4,000 on
/// Linux, on the worker thread.
pub const FULL_RESCAN_EVERY: Duration = Duration::from_secs(5 * 60);
/// How often [`start`] checks the font store's folders, by default. A check reads the
/// modification time of each folder in the store, one per installed family.
pub const STORE_POLL: Duration = Duration::from_secs(1);
/// Called on a worker thread after a family was added, removed or changed.
pub type OnChange = Arc<dyn Fn(&Catalog) + Send + Sync>;
/// The app's fonts, for [`start`].
#[derive(Clone)]
pub struct AppFonts {
/// The app's own font folders (`<prefs>/Fonts`, folders the user added).
pub dirs: Vec<PathBuf>,
/// How often [`on_activated`] runs a full [`Catalog::rescan`] at most ([`Duration::MAX`]:
/// never).
pub full_rescan_every: Duration,
/// How often [`start`] checks the font store's folders; `None`: only on activation.
pub store_poll: Option<Duration>,
/// Called after a store change or [`on_activated`] added, removed or changed a family, to wake
/// an idle window so it checks [`changes_since`]. Keep it short: activations do nothing while
/// it runs.
pub on_change: Option<OnChange>,
}
impl Default for AppFonts {
fn default() -> Self {
Self { dirs: Vec::new(), full_rescan_every: FULL_RESCAN_EVERY, store_poll: Some(STORE_POLL), on_change: None }
}
}
/// Start the global catalog for a desktop or web app: [`configure`], the first scan on a
/// background thread, and the font store poll. It doesn't wait for the scan. Call it once, before
/// the first window and before anything else uses [`Catalog::global`] or [`on_activated`].
pub fn start(fonts: AppFonts) -> &'static Arc<Catalog> {
let poll = fonts.store_poll;
let catalog = configure(fonts);
catalog.scan_in_background();
if let Some(interval) = poll
&& !cfg!(target_arch = "wasm32")
{
refresh().watch_store(interval);
}
catalog
}
/// [`start`] without the background scan or the store poll, for a CLI: the first lookup scans and
/// waits for it.
pub fn configure(fonts: AppFonts) -> &'static Arc<Catalog> {
let catalog = Catalog::global();
catalog.set_app_dirs(fonts.dirs);
let _ = REFRESH.set(Arc::new(Refresh::new(Arc::clone(catalog), fonts.full_rescan_every, fonts.on_change)));
catalog
}
/// For a window's activation: on a worker thread, [`Catalog::rescan_if_changed`], or a full
/// [`Catalog::rescan`] when the last was [`AppFonts::full_rescan_every`] ago or more. It never
/// blocks: while a worker runs, another activation does nothing. Nothing happens before the
/// first scan has finished, or on wasm. Returns whether a worker started.
pub fn on_activated() -> bool {
if cfg!(target_arch = "wasm32") {
return false;
}
refresh().activated_at(Instant::now())
}
/// A full [`Catalog::rescan`] now, on this thread, for the app's "Reload fonts" command. It counts
/// as [`on_activated`]'s full rescan, so the next activation doesn't run one again at once, and
/// calls [`AppFonts::on_change`] when a family changed. Returns what changed.
pub fn rescan_now() -> Changes {
refresh().rescan_now(if cfg!(target_arch = "wasm32") { None } else { Some(Instant::now()) })
}
/// [`Catalog::changes_since`] of the global catalog.
pub fn changes_since(generation: u64) -> Changes {
Catalog::global().changes_since(generation)
}
static REFRESH: OnceLock<Arc<Refresh>> = OnceLock::new();
fn refresh() -> &'static Arc<Refresh> {
REFRESH.get_or_init(|| Arc::new(Refresh::new(Arc::clone(Catalog::global()), FULL_RESCAN_EVERY, None)))
}
/// The rescans one catalog runs for activations and font store changes, one at a time.
pub(crate) struct Refresh {
catalog: Arc<Catalog>,
full_every: Duration,
on_change: Option<OnChange>,
state: Mutex<RefreshState>,
}
#[derive(Default)]
struct RefreshState {
running: bool,
/// When the last full rescan started; the first activation counts the first scan as one.
/// Not taken at construction: `Instant::now` panics on wasm.
last_full: Option<Instant>,
}
fn lock(m: &Mutex<RefreshState>) -> MutexGuard<'_, RefreshState> {
m.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Clears [`RefreshState::running`] when the rescan ends, panicking included.
struct Running<'a>(&'a Mutex<RefreshState>);
impl Drop for Running<'_> {
fn drop(&mut self) {
lock(self.0).running = false;
}
}
impl Refresh {
pub(crate) fn new(catalog: Arc<Catalog>, full_every: Duration, on_change: Option<OnChange>) -> Self {
Self { catalog, full_every, on_change, state: Mutex::default() }
}
pub(crate) fn activated_at(self: &Arc<Self>, now: Instant) -> bool {
if !self.catalog.is_ready() {
return false;
}
let (full, last_full) = {
let mut state = lock(&self.state);
if state.running {
return false;
}
let last_full = *state.last_full.get_or_insert(now);
let full = now.saturating_duration_since(last_full) >= self.full_every;
if full {
state.last_full = Some(now);
}
state.running = true;
(full, last_full)
};
let me = Arc::clone(self);
let spawned = std::thread::Builder::new().name("font-catalog-refresh".into()).spawn(move || {
let _running = Running(&me.state);
let before = me.catalog.generation();
if full {
me.catalog.rescan();
} else {
me.catalog.rescan_if_changed();
}
me.changed_since(before);
});
if spawned.is_err() {
let mut state = lock(&self.state);
state.running = false;
state.last_full = Some(last_full);
return false;
}
true
}
/// Check the font store's folders every `interval` on a background thread, and rescan when
/// they changed. A check that finds an activation's rescan running skips its turn. Stops when
/// the `Refresh` is dropped.
pub(crate) fn watch_store(self: &Arc<Self>, interval: Duration) {
let me: Weak<Self> = Arc::downgrade(self);
let _ = std::thread::Builder::new().name("font-catalog-store".into()).spawn(move || {
loop {
std::thread::sleep(interval);
let Some(refresh) = me.upgrade() else { return };
if !refresh.catalog.store_changed() {
continue;
}
{
let mut state = lock(&refresh.state);
if state.running {
continue;
}
state.running = true;
// A rescan lists the font service's files again: it counts as the full one.
state.last_full = Some(Instant::now());
}
let _running = Running(&refresh.state);
let before = refresh.catalog.generation();
refresh.catalog.rescan();
refresh.changed_since(before);
}
});
}
/// [`rescan_now`] at `now` (`None` on wasm, which has no clock).
pub(crate) fn rescan_now(&self, now: Option<Instant>) -> Changes {
if let Some(now) = now {
lock(&self.state).last_full = Some(now);
}
let before = self.catalog.generation();
self.catalog.rescan();
self.changed_since(before)
}
/// The changes since `before`, after calling `on_change` when there are any.
fn changed_since(&self, before: u64) -> Changes {
let changes = self.catalog.changes_since(before);
if let Some(on_change) = &self.on_change
&& !changes.is_empty()
{
on_change(&self.catalog);
}
changes
}
}
+192 -8
View File
@@ -1,7 +1,8 @@
//! The catalog: every installed face, found by any of its names, loaded once.
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::{DefaultHasher, Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, RwLock, Weak};
@@ -132,6 +133,8 @@ struct Index {
/// The faces left out of `faces` for having a listed face's family, style, PostScript name
/// and variations (another file's version of it), by the listed face.
versions: HashMap<usize, Vec<FaceInfo>>,
/// A hash of each family's faces by lowercase name, for [`Catalog::changes_since`].
signatures: HashMap<String, u64>,
}
impl Index {
@@ -191,7 +194,33 @@ impl Index {
}
families.sort_by_cached_key(|f| (f.to_lowercase(), f.clone()));
let infos: Arc<[FaceInfo]> = faces.iter().map(|f| f.info.clone()).collect();
Self { faces, infos, families: families.into(), by_family, aliases, postscript, versions }
let mut index = Self { faces, infos, families: families.into(), by_family, aliases, postscript, versions, signatures: HashMap::new() };
index.signatures = index.family_signatures();
index
}
fn family_signatures(&self) -> HashMap<String, u64> {
self.by_family
.iter()
.map(|(key, faces)| {
let mut h = DefaultHasher::new();
for f in faces.iter().filter_map(|i| self.face(*i)) {
let i = &f.info;
(&i.family, &i.style, &i.postscript_name, &i.path, i.index, i.blob, i.source, i.italic).hash(&mut h);
(i.weight.to_bits(), i.width.to_bits()).hash(&mut h);
for (tag, value) in &i.variations {
(tag, value.to_bits()).hash(&mut h);
}
}
(key.clone(), h.finish())
})
.collect()
}
/// The name of the family with lowercase name `key`.
fn family_named(&self, key: &str) -> Option<&str> {
let i = *self.by_family.get(key)?.first()?;
self.face(i).map(|f| f.info.family.as_str())
}
fn face(&self, i: usize) -> Option<&Face> {
@@ -262,6 +291,93 @@ impl Index {
}
}
/// How many changes of the family set the history keeps ([`Catalog::changes_since`]).
const HISTORY_CHANGES: usize = 64;
/// How many family names the history holds in all. A change naming more (the first scan of a
/// large system) clears the history.
const HISTORY_NAMES: usize = 4096;
/// How a family changed between two indexes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Change {
Added,
Removed,
Changed,
}
/// A family's lowercase name, its name and how it changed.
type FamilyChange = (String, String, Change);
/// The families each recent generation added, removed or changed.
#[derive(Default)]
struct History {
/// Each generation that changed a family, oldest first.
changes: VecDeque<(u64, Vec<FamilyChange>)>,
names: usize,
/// The oldest generation [`Catalog::changes_since`] can start from: the history holds every
/// change after it.
floor: u64,
}
impl History {
fn record(&mut self, generation: u64, old: &Index, new: &Index) {
let mut changes = Vec::new();
for (key, sig) in &new.signatures {
let change = match old.signatures.get(key) {
None => Change::Added,
Some(old) if old != sig => Change::Changed,
Some(_) => continue,
};
changes.push((key.clone(), new.family_named(key).unwrap_or(key).to_owned(), change));
}
for key in old.signatures.keys().filter(|k| !new.signatures.contains_key(*k)) {
changes.push((key.clone(), old.family_named(key).unwrap_or(key).to_owned(), Change::Removed));
}
if changes.is_empty() {
return;
}
if changes.len() > HISTORY_NAMES {
self.changes.clear();
self.names = 0;
self.floor = generation;
return;
}
self.names += changes.len();
self.changes.push_back((generation, changes));
while self.changes.len() > HISTORY_CHANGES || self.names > HISTORY_NAMES {
let Some((generation, changes)) = self.changes.pop_front() else { break };
self.names -= changes.len();
self.floor = generation;
}
}
}
/// The families lookups find differently since a generation ([`Catalog::changes_since`]): what
/// an app re-resolves to know which documents to lay out again. Each list is sorted ignoring
/// case.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Changes {
/// The generation these changes lead to: pass it to the next call.
pub generation: u64,
/// The catalog no longer knows what changed since then: re-resolve every family, and the
/// lists are empty.
pub full: bool,
/// Families found now that weren't.
pub added: Vec<String>,
/// Families that were found and aren't any more.
pub removed: Vec<String>,
/// Families found before and now whose faces changed: a style installed or removed, a file
/// replaced, a face added over an installed one.
pub changed: Vec<String>,
}
impl Changes {
/// Nothing changed.
pub fn is_empty(&self) -> bool {
!self.full && self.added.is_empty() && self.removed.is_empty() && self.changed.is_empty()
}
}
/// A style name as compared: normalized, with no style meaning `Regular`.
fn style_key(style: &str) -> String {
let ns = norm(style);
@@ -296,6 +412,8 @@ struct Stamp {
/// Every folder the scan listed, and the folders holding the files listers named, with their
/// modification times (`None`: missing).
dirs: Vec<(PathBuf, Option<SystemTime>)>,
/// The font store's folders among `dirs`.
store_dirs: Vec<(PathBuf, Option<SystemTime>)>,
/// The fonts registered with Windows.
registered: Vec<PathBuf>,
}
@@ -331,6 +449,8 @@ pub struct Catalog {
scanned: Mutex<Arc<[Face]>>,
stamp: Mutex<Stamp>,
generation: AtomicU64,
/// Locked while [`Catalog::publish`] moves the generation on, so it and the history agree.
history: Mutex<History>,
added: Mutex<Added>,
loaded: Mutex<HashMap<String, FamilyLoad>>,
/// The bytes of each file read, while a face of it is loaded. A file's own lock is held while it is read, so faces of
@@ -370,6 +490,7 @@ impl Catalog {
scanned: Mutex::new(Arc::from([])),
stamp: Mutex::new(Stamp::default()),
generation: AtomicU64::new(0),
history: Mutex::new(History::default()),
added: Mutex::new(Added::default()),
loaded: Mutex::new(HashMap::new()),
files: Mutex::new(HashMap::new()),
@@ -510,6 +631,14 @@ impl Catalog {
self.read_config().font_service && self.env.os == Os::Windows && stamp.registered != crate::registry::registered_font_files()
}
/// Whether the font store's folders ([`font_store_dir`]) changed since the last scan: the
/// suite's font store installed or removed a font. It reads only the store's folders, so it
/// costs far less than [`Catalog::installed_fonts_changed`] and can be polled often.
/// `false` before the first scan.
pub fn store_changed(&self) -> bool {
self.is_ready() && lock(&self.stamp).store_dirs.iter().any(|(p, t)| modified(p) != *t)
}
/// Poll for installed and removed fonts every `interval` on a background thread: when
/// [`Catalog::installed_fonts_changed`], rescan and call `on_change`. Stops when the returned
/// [`Watch`] or the catalog is dropped.
@@ -543,15 +672,55 @@ impl Catalog {
self.generation.load(Ordering::Acquire)
}
/// What changed since `generation` (a value of [`Catalog::generation`]): the families added,
/// removed and changed, so an app re-resolves only the names those affect and lays out only
/// the documents that use them. Take the generation before resolving a document's fonts, so a
/// change during that shows in the next call. `full` when the history no longer reaches back
/// that far (it keeps the last 64 changes of the family set, and the first scan of a large
/// system clears it): re-resolve everything then.
pub fn changes_since(&self, generation: u64) -> Changes {
let history = lock(&self.history);
let now = self.generation();
if generation >= now {
return Changes { generation: now, ..Changes::default() };
}
if generation < history.floor {
return Changes { generation: now, full: true, ..Changes::default() };
}
// Each family's state before the first change and after the last, with its latest name.
let mut net: HashMap<&str, (bool, bool, &str)> = HashMap::new();
for (key, name, change) in history.changes.iter().filter(|(g, _)| *g > generation).flat_map(|(_, c)| c) {
let entry = net.entry(key.as_str()).or_insert((*change != Change::Added, false, name.as_str()));
entry.1 = *change != Change::Removed;
entry.2 = name.as_str();
}
let mut changes = Changes { generation: now, ..Changes::default() };
for (before, after, name) in net.into_values() {
match (before, after) {
(false, true) => changes.added.push(name.to_owned()),
(true, false) => changes.removed.push(name.to_owned()),
(true, true) => changes.changed.push(name.to_owned()),
(false, false) => {}
}
}
for list in [&mut changes.added, &mut changes.removed, &mut changes.changed] {
list.sort_by_cached_key(|f| (f.to_lowercase(), f.clone()));
}
changes
}
fn snapshot(&self) -> Arc<Index> {
self.ensure();
Arc::clone(&self.index.read().unwrap_or_else(PoisonError::into_inner))
}
fn publish(&self, index: Index) {
*self.index.write().unwrap_or_else(PoisonError::into_inner) = Arc::new(index);
let mut history = lock(&self.history);
let new = Arc::new(index);
let old = std::mem::replace(&mut *self.index.write().unwrap_or_else(PoisonError::into_inner), Arc::clone(&new));
lock(&self.loaded).clear();
self.generation.fetch_add(1, Ordering::AcqRel);
let generation = self.generation.fetch_add(1, Ordering::AcqRel) + 1;
history.record(generation, &old, &new);
}
/// The family names, sorted ignoring case. Private system families are among them ([`is_private_family`]): a
@@ -776,8 +945,13 @@ impl Catalog {
files: Vec::new(),
};
walk.confined = confined_dirs.iter().map(|dir| walk.key(dir)).collect();
let mut store_dirs = Vec::new();
for (root, source) in &roots {
let first = walk.dirs.len();
walk.dir(root, *source, 0);
if *source == Source::Store {
store_dirs.extend(walk.dirs.iter().skip(first).cloned());
}
}
let mut parents = HashSet::new();
for file in named {
@@ -794,10 +968,12 @@ impl Catalog {
}
let mut files = HashMap::new();
let mut read = false;
for (path, source, by_name) in walk.files {
let Ok(meta) = std::fs::metadata(&path) else { continue };
let (len, mtime) = (meta.len(), meta.modified().ok());
let cached = state.files.remove(&path).filter(|c| c.len == len && c.modified == mtime);
read |= cached.is_none();
let mut faces = match cached {
Some(c) => c.faces,
None if by_name || scan::is_font_file(&path) || crate::suitcase::is_suitcase(&path) => scan::file_faces(&path, MAX_SCAN_READ, source),
@@ -808,13 +984,21 @@ impl Catalog {
}
files.insert(path, Cached { len, modified: mtime, faces });
}
let mut by_path: Vec<(&PathBuf, &Cached)> = files.iter().collect();
by_path.sort_by(|a, b| a.0.cmp(b.0));
*lock(&self.scanned) = by_path.into_iter().flat_map(|(_, c)| c.faces.iter().cloned()).collect();
// A rescan that read no file and lost none keeps the index and its generation, so the caches keyed on the
// generation (the picker's family infos and samples) stay.
let unchanged = !read && state.files.is_empty() && self.generation() > 0;
if !unchanged {
let mut by_path: Vec<(&PathBuf, &Cached)> = files.iter().collect();
by_path.sort_by(|a, b| a.0.cmp(b.0));
*lock(&self.scanned) = by_path.into_iter().flat_map(|(_, c)| c.faces.iter().cloned()).collect();
}
state.files = files;
drop(state);
*lock(&self.stamp) = Stamp { app_dirs, dirs: walk.dirs, registered };
*lock(&self.stamp) = Stamp { app_dirs, dirs: walk.dirs, store_dirs, registered };
if unchanged {
return;
}
let added = lock(&self.added);
let scanned = self.scanned();
self.publish(Index::build(&added.faces, &scanned));
+2 -1
View File
@@ -20,6 +20,7 @@
//! }
//! ```
pub mod app;
mod catalog;
mod embedding;
mod env;
@@ -40,7 +41,7 @@ mod suitcase;
pub mod system;
mod visual_order;
pub use catalog::{Catalog, FontData, FontFileError, Limits, Lister, LoadedFace, Match, Watch, is_private_family};
pub use catalog::{Catalog, Changes, FontData, FontFileError, Limits, Lister, LoadedFace, Match, Watch, is_private_family};
pub use embedding::{SubsetEmbedding, subset_embedding};
pub use env::{FontEnv, Os, font_dirs, font_store_dir, office_font_dirs};
pub use face_data::FaceData;
+69
View File
@@ -282,6 +282,75 @@ fn installed_and_removed_fonts_are_seen_without_a_restart() {
assert_eq!(rx.recv_timeout(Duration::from_secs(10)).unwrap(), (None, Some("Later".into())));
}
#[test]
fn a_rescan_with_no_changes_keeps_the_generation() {
let root = temp("rescan-same");
write(&root.join("home/.local/share/fonts/Same-Regular.ttf"), font(&spec("Same", "Regular", 400)));
let cat = Catalog::new(linux_env(&root)).with_font_service(false);
cat.rescan();
let generation = cat.generation();
assert_eq!(cat.families().as_ref(), ["Same"]);
cat.rescan();
assert_eq!(cat.generation(), generation, "nothing changed, so the catalog keeps its generation");
write(&root.join("home/.local/share/fonts/Other-Regular.ttf"), font(&spec("Other", "Regular", 400)));
cat.rescan();
assert!(cat.generation() > generation, "a new font file publishes a new generation");
}
#[test]
fn a_font_store_install_shows_in_the_change_list() {
let root = temp("store-watch");
let store = root.join("home/.local/share/craft-fonts");
// As the font store installs: a staged `.part` file moved into the family's folder.
let staging = store.join(".staging/1");
let install = |dest: &str, family: &'static str, style: &'static str| {
let part = staging.join("face.part");
write(&part, font(&spec(family, style, 400)));
let dest = store.join(dest);
std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
std::fs::rename(&part, dest).unwrap();
};
install("ofl/storeone/StoreOne-Regular.ttf", "Store One", "Regular");
let cat = Arc::new(Catalog::new(linux_env(&root)).with_font_service(false));
let start = cat.generation();
cat.rescan();
assert_eq!(cat.changes_since(start).added, ["Store One"]);
assert!(!cat.store_changed());
let (tx, rx) = mpsc::channel();
let on_change: app::OnChange = Arc::new(move |_| {
let _ = tx.send(());
});
let refresh = Arc::new(app::Refresh::new(Arc::clone(&cat), Duration::MAX, Some(on_change)));
refresh.watch_store(Duration::from_millis(20));
let wait_for = |since: u64, added: &[&str], removed: &[&str], changed: &[&str]| loop {
rx.recv_timeout(Duration::from_secs(10)).expect("a store change wakes the app");
let c = cat.changes_since(since);
if c.added == added && c.removed == removed && c.changed == changed {
return c.generation;
}
};
let before = cat.generation();
install("ofl/storetwo/StoreTwo-Regular.ttf", "Store Two", "Regular");
let two = wait_for(before, &["Store Two"], &[], &[]);
assert_eq!(cat.styles("Store Two")[0].source, Source::Store);
install("ofl/storeone/StoreOne-Bold.ttf", "Store One", "Bold");
std::fs::remove_dir_all(store.join("ofl/storetwo")).unwrap();
wait_for(two, &[], &["Store Two"], &["Store One"]);
assert!(cat.changes_since(cat.generation()).is_empty());
// The history keeps the last 64 changes of the family set; older generations get `full`.
let bytes = font(&spec("Churn", "Regular", 400));
for _ in 0..40 {
cat.add_bytes(bytes.clone(), Source::User, &Limits::default()).unwrap();
cat.remove_added(Source::User);
}
let changes = cat.changes_since(before);
assert!(changes.full && changes.added.is_empty() && !changes.is_empty());
assert!(!cat.changes_since(cat.generation() - 10).full);
}
#[test]
fn a_family_loads_once_for_every_thread() {
let root = temp("load");
+7
View File
@@ -550,6 +550,8 @@ struct Typing {
lead: Option<String>,
/// The lead's family was proposed by the pointer, so it ends when the pointer leaves the rows.
lead_by_pointer: bool,
/// The pointer was over the open list's rows in the last pass.
over_rows: bool,
hide_classes: bool,
expanded: Vec<String>,
rested: Vec<String>,
@@ -850,8 +852,13 @@ impl Component for FontPicker<'_> {
let draft = cx.text(&text_key()).and_then(|outcome| outcome.draft.clone());
let before = std::mem::replace(&mut cx.memory::<Typing>().draft, draft.clone());
if before != draft {
// A press on a row can take the focus from the text, which ends the draft: the list stays, filtered by
// the draft, until the release picks the row.
let pressing_rows =
cx.memory::<Typing>().over_rows && cx.response.ctx.input(|input| input.pointer.any_down() || input.pointer.any_released());
match &draft {
Some(_) => list.open(cx),
None if pressing_rows && list.is_open(cx) => cx.memory::<Typing>().draft = before,
None => list.close(cx),
}
}
+8 -3
View File
@@ -665,7 +665,9 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
_ => {}
}
}
cx.memory::<Typing>().hide_classes = hide_classes;
let typing = cx.memory::<Typing>();
typing.hide_classes = hide_classes;
typing.over_rows = over_rows;
// A preview the pointer proposed ends when the pointer leaves the rows (a keyed row keeps its preview). The
// collection keeps its lead on the row, so the pointer coming back to that row reports no move: the row under it
// proposes again.
@@ -708,8 +710,11 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
picker.picked = Some(family.to_owned());
picker.picked_style = style.map(str::to_owned);
end_preview(picker, cx);
cx.propose(family.to_owned());
cx.commit();
// A press on a row can end a typed name first, and that commit may already have set this family.
if cx.value().map(String::as_str) != Some(family) {
cx.propose(family.to_owned());
cx.commit();
}
popup.close(cx);
}
}
+16
View File
@@ -827,6 +827,22 @@ fn a_class_narrows_the_list_and_all_classes_restores_it() {
assert!(fx.by_label("Favorite Inter").is_some(), "every family is back");
}
#[trial]
fn a_click_on_a_rows_sample_picks_its_family() {
let (mut fx, seen) = rig(catalog_of(&[INTER_REGULAR]), vec![]);
open(&mut fx);
let inter = fx.by_label("Inter").expect("the Inter row");
let sample = fx
.texts()
.iter()
.find(|painted| painted.text == "Sample" && inter.rect.contains(painted.rect.center()))
.map(|painted| painted.rect.center())
.expect("Inter's row shows its sample");
fx.click_at(sample);
fx.settle();
assert_eq!(seen.borrow().picks, [("Inter".to_owned(), None)], "the click picks the row");
}
/// The open list loads its rows' faces through the host's jobs, never in a pass, and a list opened again over the
/// same rows loads none of them again.
#[trial]