font-manager: the preview requests are taken in once, after the list's and the sheet's real run; added sources are not asked for

This commit is contained in:
aiongg
2026-11-25 21:23:17 +00:00
parent 6b4e806cba
commit f8ab89d2d0
6 changed files with 166 additions and 51 deletions
+14 -5
View File
@@ -936,24 +936,33 @@ impl<'a> FontsPanelView<'a> {
let search = ui.scope_id().with("search");
let folder = env.folder();
let wake = panel.jobs.waker();
let shown = Stack::new().fill().label(words.panel.clone()).command_scope(FontsCommand::SCOPE).show(ui, |ui, root| {
panel.subsets.begin(root.now(), &wake);
let mut begun = false;
let mut shown = Stack::new().fill().label(words.panel.clone()).command_scope(FontsCommand::SCOPE).show(ui, |ui, root| {
if !std::mem::replace(&mut begun, true) {
panel.subsets.begin(root.now(), &wake);
}
while root.take_command::<FontsCommand>().is_some() {
focus::request(ui.ctx(), FocusTarget::Id(search));
}
root.publish(FontsCommand::Find, CommandState::new());
panel.top_bar(ui, &browse, texts.format, search);
Grid::new(&PANES).fill().show(ui, |ui, _| {
let panes = Grid::new(&PANES).fill().show(ui, |ui, _| {
panel.filters(ui, &texts);
panel.main(ui, &texts, &folder, host.as_ref());
panel.main(ui, &texts, &folder, host.as_ref())
});
panes.inner.flatten()
});
// A measuring run has no rows on screen, and a pass that runs again may have the wrong ones.
let rerun = craft_ui::runtime::frame::will_rerun(ui.ctx());
let real = shown.settle(|_, visible| (!rerun).then(|| panel.request_subsets(visible.take()))).flatten().is_some();
if panel.detail.is_some() {
if DetailsSheet::new(panel).show(ui).closed {
panel.detail = None;
}
} else {
panel.subsets.request_detail(None, &[]);
if real {
panel.subsets.request_detail(None, &[]);
}
panel.detail_axes.clear();
}
if let Some(seconds) = panel.subsets.next_wake() {
+21 -15
View File
@@ -341,8 +341,10 @@ impl FontsPanel {
});
}
pub(crate) fn main(&mut self, ui: &mut Ui, texts: &Texts<'_>, folder: &Folder, host: Option<&Arc<Host>>) {
Stack::new().fill().show(ui, |ui, _| {
/// The toolbar, the notices and the cards; the positions of the catalogue cards on screen, or `None` while it shows
/// none.
pub(crate) fn main(&mut self, ui: &mut Ui, texts: &Texts<'_>, folder: &Folder, host: Option<&Arc<Host>>) -> Option<Range<usize>> {
let shown = Stack::new().fill().show(ui, |ui, _| {
self.toolbar(ui, texts.browse);
self.subsets.typed(format!("{:?}\n{:?}\n{}", self.settings.preset, self.query.language, self.settings.sample));
if let Some(problem) = &self.notice {
@@ -355,14 +357,15 @@ impl FontsPanel {
match self.tab {
Tab::Catalogue => {
self.download_note(ui, texts.browse);
self.catalogue_list(ui, texts, host);
self.catalogue_list(ui, texts, host)
}
Tab::Installed => {
self.subsets.cancel_all();
self.installed_list(ui, texts, folder, host);
None
}
}
});
shown.inner.flatten()
}
fn toolbar(&mut self, ui: &mut Ui, browse: &FontsBrowseWords) {
@@ -409,22 +412,20 @@ impl FontsPanel {
}
}
fn catalogue_list(&mut self, ui: &mut Ui, texts: &Texts<'_>, host: Option<&Arc<Host>>) {
fn catalogue_list(&mut self, ui: &mut Ui, texts: &Texts<'_>, host: Option<&Arc<Host>>) -> Option<Range<usize>> {
let browse = texts.browse;
let index = match &self.catalogue {
Ok(c) => Arc::clone(&c.index),
Err(error) => {
self.subsets.cancel_all();
Notice::new(Tone::Bad, Label::from(browse.indexes_unreadable.fill(&[("error", error.as_str())]))).show(ui);
return;
return None;
}
};
self.source_problems(ui, texts, &index, host);
Text::new(Label::from(texts.families(self.results.len()))).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
if self.results.is_empty() {
self.subsets.cancel_all();
self.empty(ui, browse, &browse.no_match, &browse.no_match_hint, true);
return;
return None;
}
let results = self.results.clone();
let shown = {
@@ -432,7 +433,6 @@ impl FontsPanel {
let keys = CardKeys::new(&results, |i| index.families().get(i).map(|f| f.family.as_str()));
FamilyCards::new(browse.cards.clone()).show_items(ui, &keys, &mut |key, _| FamilyCard::new(me.catalogue_card(&index, *key, texts)))
};
self.request_subsets(&index, &results, shown.visible);
for event in shown.events {
match event {
CollectionEvent::Activate(i) => self.detail = Some(Detail::Family(i)),
@@ -451,13 +451,19 @@ impl FontsPanel {
_ => {}
}
}
Some(shown.visible)
}
/// Asks the preview service for the subsets of the cards on screen and round them.
fn request_subsets(&mut self, index: &Index, results: &[usize], visible: Range<usize>) {
let window = Subsets::window(&visible, results.len());
let rows: Vec<Option<SubsetRow<'_>>> = window.clone().map(|n| self.subset_row(index, *results.get(n)?)).collect();
self.subsets.request(index, window.start, &rows, visible);
/// Asks the preview service for the subsets of the catalogue cards on screen, at the positions `visible` of the
/// results, and round them; cancels what the list asked for when it shows no card.
pub(crate) fn request_subsets(&mut self, visible: Option<Range<usize>>) {
let Some((visible, index)) = visible.zip(self.index()) else {
self.subsets.cancel_all();
return;
};
let window = Subsets::window(&visible, self.results.len());
let rows: Vec<Option<SubsetRow<'_>>> = window.clone().map(|n| self.subset_row(&index, *self.results.get(n)?)).collect();
self.subsets.request(&index, window.start, &rows, visible);
}
/// The family at `i` in the index as a row drawn with a subset: `None` when it is installed or previewed whole.
+5 -3
View File
@@ -396,7 +396,7 @@ impl<'a> DetailsSheet<'a> {
let points = panel.settings.size.max(MIN_SAMPLE_POINTS);
let mut todo: Vec<Do> = Vec::new();
let mut open = true;
let shown = Dialog::prompt(sheet.title.clone())
let mut shown = Dialog::prompt(sheet.title.clone())
.overlay(|overlay| {
let dismiss = overlay.dismiss.outside(Outside::Absorb);
overlay.dismiss(dismiss)
@@ -410,7 +410,9 @@ impl<'a> DetailsSheet<'a> {
});
let index = panel.index();
let family = sheet.index.zip(index.as_deref()).and_then(|(i, index)| Some((index, index.families().get(i)?, sheet.sample.as_str())));
panel.subsets.request_detail(family, &sheet.subset_files);
if !craft_ui::runtime::frame::will_rerun(ui.ctx()) {
shown.settle(|_, ()| panel.subsets.request_detail(family, &sheet.subset_files));
}
let closed = shown.output.closed.is_some();
if closed {
panel.detail = None;
@@ -827,7 +829,7 @@ impl FamilyStyles<'_> {
// A variable file's instances install together: the file's action on its first.
let actions = std::iter::once(action).chain(std::iter::repeat(Action::None));
lines.extend(preview_faces.into_iter().zip(actions).map(|(face, action)| self.line(Owner::Preview, face, action)));
} else if self.panel.subsets.available() {
} else if self.panel.subsets.serves(self.family) {
subset_files.push(n);
self.subset_lines(file, action, &mut lines);
} else {
@@ -22,6 +22,10 @@ impl Subsets {
false
}
pub(crate) fn serves(&self, _: &Family) -> bool {
false
}
pub(crate) fn loading(&self) -> bool {
false
}
@@ -10,7 +10,10 @@
//! variable file's at the `var` instance, which keeps every axis.
//!
//! Drawing only looks subsets up ([`Subsets::font`], [`Subsets::detail_font`]). What the pass showed is taken in once,
//! after the list ([`Subsets::request`]) and the sheet ([`Subsets::request_detail`]).
//! after the real run of the list ([`Subsets::request`]) and of the sheet ([`Subsets::request_detail`]).
//!
//! The service holds the built-in sources' files only, and asking it for another file would tell it the file's hash: a
//! family of a source the user added is never asked for (`key_of`).
use std::collections::{HashMap, HashSet};
use std::ops::Range;
@@ -37,8 +40,10 @@ const DETAIL: u32 = 4;
const PAUSE_SECS: f64 = 0.25;
/// A failed subset is asked for again after this long, not every frame.
const RETRY_SECS: f64 = 30.0;
/// Decoded subsets kept in memory; the disk cache holds more.
/// Decoded subsets kept in memory, more while more are in use; the disk cache holds more.
const MAX_HELD: usize = 256;
/// A subset wanted within this many passes is in use.
const IN_USE: u64 = 2;
/// A decoded subset and the pass it was last wanted in.
struct Held {
@@ -128,6 +133,11 @@ impl Subsets {
self.available
}
/// Whether the details sheet draws the styles of `family` from subsets: a service is set, which holds its files.
pub(crate) fn serves(&self, family: &Family) -> bool {
self.available && family.is_curated()
}
/// Whether rows and the details sheet get their previews from the service: a service is set and previews are on.
/// Otherwise a session download is the only way to see a font.
fn previewing(&self) -> bool {
@@ -178,7 +188,6 @@ impl Subsets {
/// Takes in what the pool fetched, at the pass time `now`. `wake` asks the UI for a pass when a fetch ends.
pub(crate) fn begin(&mut self, now: f64, wake: &Wake) {
self.pass += 1;
self.now = now;
self.waits = false;
if !std::mem::replace(&mut self.woken, true) {
@@ -288,9 +297,10 @@ impl Subsets {
}
/// Asks for the subsets of the files (by position) of `shown`'s family that the sheet draws with its text, before
/// the list's rows; called once a pass, also when the sheet is closed. What it no longer wants goes back to the
/// list, which cancels what it doesn't want either.
/// the list's rows; called at the end of each pass, also when the sheet is closed. What it no longer wants goes back
/// to the list, which cancels what it doesn't want either.
pub(crate) fn request_detail(&mut self, shown: Option<(&Index, &Family, &str)>, files: &[usize]) {
self.pass += 1;
let Some((index, family, text)) = shown.filter(|_| self.available) else {
self.detail.clear();
return;
@@ -342,7 +352,7 @@ impl Subsets {
settled &= self.fonts.contains_key(&sample) || self.has_failed(&sample);
self.want(&mut wanted, sample, VISIBLE);
}
if let Some(ascii) = covers_latin(family).then(|| subset_key(family, Subset::Ascii)).flatten() {
if let Some(ascii) = list_file(family).filter(|_| covers_latin(family)).and_then(|f| key_of(family, f, Instance::List, Subset::Ascii)) {
latin.push(ascii);
}
let Some(key) = self.key(index, row) else { continue };
@@ -437,12 +447,13 @@ impl Subsets {
self.asked.retain(|k, _| detail.contains(k));
}
/// Drops the subsets wanted least recently past [`MAX_HELD`].
/// Drops the subsets wanted least recently past [`MAX_HELD`], but none in use.
fn trim(&mut self) {
if self.fonts.len() <= MAX_HELD {
return;
}
let mut by_use: Vec<(u64, PreviewKey)> = self.fonts.iter().map(|(k, held)| (held.used, k.clone())).collect();
let mut by_use: Vec<(u64, PreviewKey)> =
self.fonts.iter().filter(|(_, held)| held.used + IN_USE < self.pass).map(|(k, held)| (held.used, k.clone())).collect();
by_use.sort_by_key(|(used, _)| *used);
for (_, key) in by_use.into_iter().take(self.fonts.len() - MAX_HELD) {
self.fonts.remove(&key);
@@ -461,8 +472,9 @@ fn detail_instance(file: &FontFile) -> Instance {
if file.is_variable() { Instance::Var } else { Instance::List }
}
fn subset_key(family: &Family, subset: Subset) -> Option<PreviewKey> {
PreviewKey::new(&list_file(family)?.sha256, Instance::List, subset)
/// The key of `subset` of `file` at `instance`; `None` for a family of a source the user added.
fn key_of(family: &Family, file: &FontFile, instance: Instance, subset: Subset) -> Option<PreviewKey> {
family.is_curated().then(|| PreviewKey::new(&file.sha256, instance, subset)).flatten()
}
fn covers_latin(family: &Family) -> bool {
@@ -472,7 +484,7 @@ fn covers_latin(family: &Family) -> bool {
/// The sample subset of `file` at `instance` for the text `index` gives it.
fn sample_subset(index: &Index, family: &Family, file: &FontFile, instance: Instance) -> Option<PreviewKey> {
let text = index.sample_text(family, file)?;
PreviewKey::new(&file.sha256, instance, Subset::Sample(SampleHash::of(text)))
key_of(family, file, instance, Subset::Sample(SampleHash::of(text)))
}
/// The subset that draws `text` in `file`: the sample when the sample subset has every character (the sentence and the
@@ -495,12 +507,12 @@ fn text_key(index: &Index, family: &Family, file: &FontFile, instance: Instance,
} else {
Subset::Codepoints(Codepoints::from_text(text))
};
PreviewKey::new(&file.sha256, instance, subset)
key_of(family, file, instance, subset)
}
/// The subset of the sample text's characters and the family name, which the sample subset holds too. `None` when that
/// is more characters than a request may name.
fn sample_fallback(index: &Index, family: &Family, file: &FontFile, instance: Instance) -> Option<PreviewKey> {
let text = index.sample_text(family, file)?;
PreviewKey::new(&file.sha256, instance, Subset::Codepoints(Codepoints::from_text(&format!("{text}{}", family.family))))
key_of(family, file, instance, Subset::Codepoints(Codepoints::from_text(&format!("{text}{}", family.family))))
}
+97 -15
View File
@@ -4,7 +4,7 @@ use std::cell::RefCell;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
@@ -19,7 +19,7 @@ use craft_i18n::I18n;
use craft_ui::contract::Role;
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::{Fixture, Room, Target, trial};
use egui::{Event, Key, Modifiers, Pos2};
use egui::{Event, Key, Modifiers, Pos2, Vec2};
const HACK: &str = "ofl/hack/Hack-Regular.ttf";
const UBUNTU: &str = "ufl/ubuntu/Ubuntu-Light.ttf";
@@ -348,10 +348,13 @@ fn a_cards_install_menu_chooses_where_the_fonts_go() {
}
/// A preview service that answers every subset with the same small font, and logs what it answered. While held it
/// answers nothing, and a request cancelled meanwhile isn't logged.
/// answers nothing, and a request cancelled meanwhile is logged as cancelled instead.
#[derive(Default)]
struct FakeService {
answered: Mutex<Vec<String>>,
cancelled: Mutex<Vec<String>>,
/// Requests that reached the service.
started: AtomicUsize,
held: AtomicBool,
/// Answers sample subsets with HTTP 404, as for a sample text the service doesn't have.
no_samples: AtomicBool,
@@ -361,13 +364,12 @@ struct FakeService {
impl Fetch for FakeService {
fn get(&self, url: &str, _: u64, cancel: &Cancel) -> Result<Vec<u8>, FetchError> {
while self.held.load(Ordering::SeqCst) {
if cancel.is_cancelled() {
return Err(FetchError::Cancelled);
}
self.started.fetch_add(1, Ordering::SeqCst);
while self.held.load(Ordering::SeqCst) && !cancel.is_cancelled() {
std::thread::sleep(Duration::from_millis(2));
}
if cancel.is_cancelled() {
self.cancelled.lock().unwrap_or_else(PoisonError::into_inner).push(url.to_owned());
return Err(FetchError::Cancelled);
}
self.answered.lock().unwrap_or_else(PoisonError::into_inner).push(url.to_owned());
@@ -406,14 +408,17 @@ const SAMPLE: &str = "Sphinx of black quartz, judge my vow";
/// An index of `families` with `SAMPLE` as the sample text of Latin.
fn service_index(families: &str) -> Index {
let json = format!(
Index::from_json(service_json(families).as_bytes()).unwrap()
}
fn service_json(families: &str) -> String {
format!(
r#"{{"schema":1,"version":"1.2","source":"google/fonts","commit":"45e3d5269e4a17d823f6d84470bc084dc5ae46f6","base_url":"https://cdn.jsdelivr.net/gh/google/fonts@45e3d5269e4a17d823f6d84470bc084dc5ae46f6/",
"languages":[{{"id":"en_Latn","name":"English","script":"Latn","population":1}}],
"scripts":[{{"id":"Latn","name":"Latin"}}],
"samples":{{"Latn":{{"text":"{SAMPLE}","method":"udhr","language":"en_Latn"}}}},
"families":[{families}]}}"#
);
Index::from_json(json.as_bytes()).unwrap()
)
}
/// Sixty Latin families, `Family 01` to `Family 60`, whose one file's sha256 starts with the family's number in hex.
@@ -478,9 +483,8 @@ impl Rig {
/// Scrolls the cards by `points`.
fn scroll(&mut self, points: f32) {
let first = self.numbers()[0];
let card = self.named(Role::LIST_ITEM, &format!("Family {first:02}")).center();
self.fx.frame(vec![Event::PointerMoved(card)]).frame(vec![craft_ui::testing::pointer::wheel(-points)]);
let cards = self.named(Role::LIST, "Families").center();
self.fx.frame(vec![Event::PointerMoved(cards)]).frame(vec![craft_ui::testing::pointer::wheel(-points)]);
for _ in 0..4 {
self.fx.advance(0.5);
self.fx.frame(Vec::new());
@@ -527,15 +531,66 @@ fn previews_follow_the_screen_and_the_typed_text() {
rig.scroll(6.0 * 400.0);
assert!(rig.panel.borrow().loading_previews());
let passed = rig.numbers();
// The first wheel goes to the end of the list as its unshown cards are estimated, the second to its end.
rig.scroll(100_000.0);
rig.scroll(100_000.0);
service.held.store(false, Ordering::SeqCst);
rig.load();
let last = rig.numbers();
assert!(passed[0] > shown[shown.len() - 1] && last[0] > passed[passed.len() - 1], "{shown:?} {passed:?} {last:?}");
assert!(passed[0] > shown[shown.len() - 1] && last[0] > passed[passed.len() - 1] && last.contains(&60), "{shown:?} {passed:?} {last:?}");
let answered = FakeService::numbers(&service.urls(), "u/");
assert!(!answered.is_empty() && answered.iter().all(|n| last.contains(n)), "rows that left were asked for: {answered:?} {last:?}");
}
/// A resize and a search that keep the cards on screen cancel nothing that is being fetched.
#[trial]
fn a_resize_and_a_search_cancel_no_preview() {
let service = Arc::new(FakeService::default());
service.held.store(true, Ordering::SeqCst);
let mut rig = service_rig("previews-kept", &service, latin_index());
rig.set_previews(true);
for _ in 0..500 {
if service.started.load(Ordering::SeqCst) > 0 {
break;
}
std::thread::sleep(Duration::from_millis(1));
}
assert!(service.started.load(Ordering::SeqCst) > 0, "the service was asked");
let shown = rig.numbers();
rig.fx.room(Room::Window.size() + Vec2::new(40.0, 120.0)).settle();
rig.type_into("Search", "Family");
service.held.store(false, Ordering::SeqCst);
rig.load();
assert!(shown.iter().all(|n| rig.numbers().contains(n)), "the cards stayed on screen: {shown:?} {:?}", rig.numbers());
let cancelled = std::mem::take(&mut *service.cancelled.lock().unwrap_or_else(PoisonError::into_inner));
assert!(cancelled.is_empty(), "{cancelled:?}");
let samples = FakeService::numbers(&service.urls(), "sample-");
assert!(shown.iter().all(|n| samples.contains(n)), "{shown:?} {samples:?}");
}
/// The service is not asked for the files of a source the user added, which offer the whole-family preview.
#[trial]
fn a_family_of_an_added_source_is_not_asked_of_the_service() {
let service = Arc::new(FakeService::default());
let file = format!(
r#"{{"path":"ofl/added/Added-Regular.ttf","size":1000,"sha256":"{}","style":"normal","weight":400,"axes":[],"postscript":[]}}"#,
"ef".repeat(32)
);
let family = format!(
r#"{{"family":"Added","categories":["SANS_SERIF"],"languages":[0],"scripts":["Latn"],"license":"OFL","sample_script":"Latn","files":[{file}]}}"#
);
let index = Index::from_user_bytes(service_json(&family).as_bytes(), "https://fonts.example.org/index.json").unwrap();
let mut rig = service_rig("previews-added", &service, index);
rig.set_previews(true);
rig.load();
rig.sample("Hello, world");
assert!(rig.present("Preview"), "the card offers the whole-family preview");
rig.open("Added");
rig.load();
rig.named(Role::BUTTON, "Preview");
assert_eq!(service.started.load(Ordering::SeqCst), 0, "{:?}", service.urls());
}
/// A sample the service has not (another text) is asked for as the sample's characters, once.
#[trial]
fn a_sample_the_service_lacks_falls_back_to_its_characters_once() {
@@ -564,7 +619,8 @@ fn a_failing_preview_service_is_named_and_previews_are_offered() {
assert!(rig.fx.texts().iter().any(|painted| painted.text.contains(SERVICE)), "the notice names the server");
assert!(rig.present("Preview"), "the card offers the whole-family preview");
rig.open("Family 01");
assert!(rig.present("Preview"), "and so does its sheet");
// The sheet's is a button, a card's a link.
rig.named(Role::BUTTON, "Preview");
}
/// One family: a variable upright file with three named instances, whose sha256 is `ab…`, and a static italic, `cd…`.
@@ -620,6 +676,32 @@ fn the_exported_rows_show_the_panel_in_japanese() {
assert!(rig.present("すべてのカテゴリ") && !rig.present("All categories"));
}
/// With downloads off, a family's NOTICE is offered in its sheet and not read until the user asks.
#[trial]
fn a_notice_is_read_only_when_asked_while_downloads_are_off() {
let file = format!(
r#"{{"path":"apache/a/A-Regular.ttf","size":1000,"sha256":"{}","style":"normal","weight":400,"axes":[],"postscript":[]}}"#,
"aa".repeat(32)
);
let notice = format!(r#"{{"path":"apache/a/NOTICE","size":10,"sha256":"{}"}}"#, "bb".repeat(32));
let family = format!(
r#"{{"family":"Noticed","categories":["SANS_SERIF"],"languages":[0],"scripts":["Latn"],"license":"APACHE2","notice_file":{notice},"files":[{file}]}}"#
);
let root = root("notice");
let files = HashMap::from([("apache/a/NOTICE".to_owned(), b"Copyright Noticed".to_vec())]);
let store = Arc::new(FakeStore::new(root.join("store"), files));
let panel = FontsPanel::new(Options::new(catalog(&root), store.clone(), Ok(service_index(&family))));
let mut rig = show(panel, store, host_with(Arc::new(MemorySections::default()), Arc::new(InlineJobs)));
rig.open("Noticed");
assert!(!rig.panel.borrow().downloads_allowed());
rig.named(Role::BUTTON, "Show notice");
assert!(!rig.present("Copyright Noticed"), "the text is not read");
assert!(!rig.present("Retry"), "nor was a read refused");
rig.allow();
assert!(rig.fx.texts().iter().any(|painted| painted.text.contains("Copyright Noticed")), "read once downloads are allowed");
}
#[trial]
fn default_filters_are_sans_serif_and_the_system_language() {
let mut rig = setup("default-filters");