From 67409c465f481ba0c753af92f8089f2a7a7d9ea4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 23 Nov 2026 03:00:47 +0000 Subject: [PATCH 1/6] Font picker: sample faces load off the UI thread and stay while drawn lately Opening the font list read and parsed every visible row's font file on the UI thread, re-read a collection for each family it holds, rebuilt egui's whole font set for each face added, and dropped off-screen faces after 64, so scrolling back loaded them again. - Document faces reach egui through one served-faces provider: egui parses a face the first time text is laid out in it, so a face arriving keeps the parsed faces, the atlas and the galley caches. Faces over the interface fonts use the same provider; edit_faces' add path and MAX_INTERFACE_FACE_BYTES go. - Catalog faces load as jobs on a per-context JobQueue (the host's jobs) and are ready from the pass after they land; loads no frame asks for are dropped. Faces whose bytes the app holds register in the same pass. - The registry keeps faces up to MAX_DOCUMENT_FACE_BYTES (512 MiB of distinct file bytes), least recently drawn out first; past the same budget of withdrawn files egui's fonts are made again to free them. - The picker's coverage check reads the registry's loaded bytes instead of the file; traits come from FaceInfo, which the scan now fills with sFamilyClass, PANOSE and the post fixed-pitch flag. - Catalog::file_bytes shares one read per file across threads. --- crates/font-catalog/src/catalog.rs | 19 +- crates/font-catalog/src/scan.rs | 17 + crates/font-manager/README.md | 4 +- crates/font-manager/src/panel/faces.rs | 26 +- crates/font-manager/src/panel/specimen.rs | 3 +- crates/font-manager/src/picker.rs | 2 +- crates/font-manager/src/picker/rank.rs | 71 ++-- crates/font-manager/src/picker/rows.rs | 40 +- crates/font-manager/tests/it/picker.rs | 20 + crates/ui-contract/src/contract/faces.rs | 12 +- crates/ui-contract/src/fonts/document.rs | 346 ++++++++++++------ crates/ui-contract/src/fonts/mod.rs | 2 +- crates/ui-contract/src/primitives/content.rs | 10 +- crates/ui-contract/src/primitives/draw.rs | 4 +- crates/ui-contract/src/primitives/faces.rs | 19 +- .../ui-contract/src/runtime/egui/fixture.rs | 2 +- crates/ui-contract/src/runtime/egui/fonts.rs | 167 +++++++-- .../ui-contract/src/runtime/layout_memory.rs | 1 + crates/ui-contract/tests/it/fonts/document.rs | 126 +++++-- crates/ui-contract/tests/it/fonts/face_run.rs | 5 +- 20 files changed, 611 insertions(+), 285 deletions(-) diff --git a/crates/font-catalog/src/catalog.rs b/crates/font-catalog/src/catalog.rs index 32631a3c8..1dd9f0f3f 100644 --- a/crates/font-catalog/src/catalog.rs +++ b/crates/font-catalog/src/catalog.rs @@ -319,7 +319,9 @@ pub struct Catalog { generation: AtomicU64, added: Mutex, loaded: Mutex>, - files: Mutex>>, + /// 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 + /// one collection loading on several threads read it once and share the bytes. + files: Mutex>>>>>, } fn lock(m: &Mutex) -> MutexGuard<'_, T> { @@ -581,7 +583,16 @@ impl Catalog { } fn file_bytes(&self, path: &Path) -> Result, FontFileError> { - if let Some(bytes) = lock(&self.files).get(path).and_then(Weak::upgrade) { + let slot = { + let mut files = lock(&self.files); + // A slot another thread holds (it reads the file) stays; the others go once their bytes are dropped. + files.retain(|_, slot| { + Arc::strong_count(slot) > 1 || slot.try_lock().ok().is_none_or(|held| held.as_ref().is_some_and(|w| w.strong_count() > 0)) + }); + Arc::clone(files.entry(path.to_path_buf()).or_default()) + }; + let mut held = lock(&slot); + if let Some(bytes) = held.as_ref().and_then(Weak::upgrade) { return Ok(bytes); } let size = std::fs::metadata(path)?.len(); @@ -589,9 +600,7 @@ impl Catalog { return Err(FontFileError::TooLarge { size, max: MAX_LOAD }); } let bytes: Arc<[u8]> = read_capped(path, MAX_LOAD)?.into(); - let mut files = lock(&self.files); - files.retain(|_, w| w.strong_count() > 0); - files.insert(path.to_path_buf(), Arc::downgrade(&bytes)); + *held = Some(Arc::downgrade(&bytes)); Ok(bytes) } diff --git a/crates/font-catalog/src/scan.rs b/crates/font-catalog/src/scan.rs index 5466024e5..3705f24f8 100644 --- a/crates/font-catalog/src/scan.rs +++ b/crates/font-catalog/src/scan.rs @@ -96,6 +96,12 @@ pub struct FaceInfo { pub fs_type: u16, /// The OS/2 code page bits (`ulCodePageRange1`, `ulCodePageRange2`). pub code_pages: [u32; 2], + /// The OS/2 `sFamilyClass` (high byte: the IBM class; 0 without an OS/2 table). + pub family_class: i16, + /// The OS/2 PANOSE digits (all 0 without an OS/2 table). + pub panose: [u8; 10], + /// The `post` table marks the face fixed-pitch. + pub fixed_pitch: bool, /// The file the face is in; `None` for a face added as bytes. pub path: Option, /// The size in bytes of the file when it was scanned; `None` for a face added as bytes. A caller that draws with the @@ -308,6 +314,14 @@ pub(crate) fn font_faces(font: &skrifa::FontRef<'_>, outlines: Outlines, index: }); let fs_type = os2.as_ref().map_or(0, |t| t.fs_type()); let code_pages = os2.as_ref().map_or([0, 0], |t| [t.ul_code_page_range_1().unwrap_or(0), t.ul_code_page_range_2().unwrap_or(0)]); + let family_class = os2.as_ref().map_or(0, |t| t.s_family_class()); + let mut panose = [0u8; 10]; + if let Some(digits) = os2.as_ref().map(|t| t.panose_10()) { + for (slot, digit) in panose.iter_mut().zip(digits.iter()) { + *slot = *digit; + } + } + let fixed_pitch = font.post().ok().is_some_and(|p| p.is_fixed_pitch() != 0); let axes = font.axes(); let legacy_pair = has_typo_family .then(|| name(font, &[StringId::FAMILY_NAME])) @@ -331,6 +345,9 @@ pub(crate) fn font_faces(font: &skrifa::FontRef<'_>, outlines: Outlines, index: outlines, fs_type, code_pages, + family_class, + panose, + fixed_pitch, path: path.map(Path::to_path_buf), file_bytes: None, index, diff --git a/crates/font-manager/README.md b/crates/font-manager/README.md index e77d6a981..ba54bbce7 100644 --- a/crates/font-manager/README.md +++ b/crates/font-manager/README.md @@ -45,8 +45,8 @@ The layout follows Adobe Fonts' and Google Fonts' browse pages. `FontsPanel` fills the `Ui` it is given and has no window, menu or interface fonts of its own; the craft-ui's theme gives it the colours and interface fonts. The faces it draws samples in come from -craft-ui's document-face registry, which loads them a few per pass and evicts the ones off screen, -without touching the host's fonts. Right-to-left interfaces mirror through the layout; sample text +craft-ui's document-face registry, which loads them on the host's jobs, keeps the ones drawn lately +up to a budget of font file bytes, and never touches the host's fonts. Right-to-left interfaces mirror through the layout; sample text keeps its own direction. The panel follows the `craft_host::Host` installed in the egui context (`Host::builder(..).install(ctx)`): diff --git a/crates/font-manager/src/panel/faces.rs b/crates/font-manager/src/panel/faces.rs index 4871e8c78..254a3915a 100644 --- a/crates/font-manager/src/panel/faces.rs +++ b/crates/font-manager/src/panel/faces.rs @@ -1,5 +1,7 @@ -//! Drawing text in a font face itself: each face shown is a document face of craft-ui's registry, which loads -//! them a few per pass, keeps the ones on screen and wakes the UI while one loads. +//! Drawing text in a font face itself: each face shown is a document face of craft-ui's registry, which loads them +//! in the background, keeps the ones drawn lately and wakes the UI when one lands. + +use std::sync::Arc; use craft_i18n::{Direction, base_direction}; use craft_ui::fonts::{FaceBytes, FontRef}; @@ -37,17 +39,23 @@ fn key(owner: Owner, face: &FaceInfo) -> String { /// The bytes of `face` from `catalog`, unless its file is too large to draw with. fn load(catalog: &Catalog, face: &FaceInfo) -> Option { - let too_large = face.file_bytes.is_some_and(|bytes| bytes > MAX_FILE_BYTES); - if too_large { - return None; - } let data = catalog.load(face).ok()?; Some(FaceBytes::new(data.bytes, data.index).coords(face.variations.iter().map(|(tag, v)| (*tag, *v)))) } -/// The font that draws `face`, once the registry has loaded it. `at` is the context the caller draws or measures in. -pub(crate) fn shown(at: &impl FacesCx, catalog: &Catalog, owner: Owner, face: &FaceInfo) -> Shown { - at.document_face(&key(owner, face), || load(catalog, face)) +/// The font that draws `face`, once the registry has loaded it in the background. `at` is the context the caller +/// draws or measures in. +pub(crate) fn shown(at: &impl FacesCx, catalog: &Arc, owner: Owner, face: &FaceInfo) -> Shown { + if face.file_bytes.is_some_and(|bytes| bytes > MAX_FILE_BYTES) { + return Shown::Unavailable; + } + let (catalog, info) = (Arc::clone(catalog), face.clone()); + at.document_face(&key(owner, face), move || load(&catalog, &info)) +} + +/// The bytes of `face` once [`shown`] has it ready, for reading its tables without loading the file again. +pub(crate) fn bytes(at: &impl FacesCx, owner: Owner, face: &FaceInfo) -> Option { + at.document_face_bytes(&key(owner, face)) } /// The layout of a sample's `runs`: one row, cut with an ellipsis where `room` does not fit it. Measure and paint both diff --git a/crates/font-manager/src/panel/specimen.rs b/crates/font-manager/src/panel/specimen.rs index 64e4a50a4..9b876a865 100644 --- a/crates/font-manager/src/panel/specimen.rs +++ b/crates/font-manager/src/panel/specimen.rs @@ -1,6 +1,7 @@ //! `FontSample`: text in a font face at the user's sample size, on one line at the reading start of its rect. use std::borrow::Cow; +use std::sync::Arc; use craft_behavior::Sense; use craft_ui::contract::{Common, Component, Cx, DisabledLook, MeasureCx, PaintUi, Props as _, Role}; @@ -36,7 +37,7 @@ pub(crate) struct FontSampleStyle { #[derive(Clone, Copy)] pub(crate) enum SampleFace<'a> { /// A face of `catalog`, which the document-face registry loads when the sample is measured or painted. - Face { catalog: &'a Catalog, owner: Owner, face: &'a FaceInfo }, + Face { catalog: &'a Arc, owner: Owner, face: &'a FaceInfo }, /// No face is here to draw with: the sample keeps its band and shows nothing. Missing, } diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index 269e149ce..71a159146 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -276,7 +276,7 @@ pub struct FamilyRow { pub shown: String, /// The family is a favourite. pub starred: bool, - /// The family's class once it has been read: by a class filter, or by the list drawing the row. + /// The family's class; `None` for a served row and a family no class fits. pub class: Option, /// The family's format; `None` only for a served row. pub format: Option, diff --git a/crates/font-manager/src/picker/rank.rs b/crates/font-manager/src/picker/rank.rs index 636d5fcdd..09113d9b8 100644 --- a/crates/font-manager/src/picker/rank.rs +++ b/crates/font-manager/src/picker/rank.rs @@ -7,6 +7,7 @@ use std::sync::{Arc, Mutex, PoisonError}; use craft_font_catalog::{Catalog, FaceInfo, LocalizedName, Outlines, is_private_family}; use craft_i18n::matcher::{Matcher, Rank}; use craft_i18n::{Collator, Folder}; +use craft_ui::fonts::FaceBytes; use skrifa::GlyphId; use skrifa::MetadataProvider as _; use skrifa::raw::{FontRef, TableProvider}; @@ -54,12 +55,11 @@ impl Traits { } } -/// The families of one catalog generation with their traits and sample texts, filled on first use. Built by +/// The families of one catalog generation with their sample texts, filled on first use. Built by /// [`FamilyInfos::of`] and held by the one that lists with it: the picker keeps it in a derived value keyed by the /// catalog's generation, and an app that calls [`family_rows`](super::family_rows) keeps its own while the catalog is unchanged. pub struct FamilyInfos { pub(super) families: HashMap, - traits: Mutex>>, samples: Mutex>, } @@ -85,40 +85,30 @@ impl FamilyInfos { Some((family, Info { localized, format, styles: faces.len(), regular })) }) .collect(); - FamilyInfos { families, traits: Mutex::new(HashMap::new()), samples: Mutex::new(HashMap::new()) } + FamilyInfos { families, samples: Mutex::new(HashMap::new()) } } - /// The family's traits, read from its regular face on first use. - pub(super) fn traits(&self, catalog: &Catalog, family: &str) -> Option { - if let Some(t) = lock(&self.traits).get(family) { - return t.clone(); - } - let traits = self.families.get(family).and_then(|i| read_traits(catalog, &i.regular)); - lock(&self.traits).insert(family.to_owned(), traits.clone()); - traits + /// The family's traits, from its regular face's record. + pub(super) fn traits(&self, family: &str) -> Option { + self.families.get(family).map(|i| read_traits(&i.regular)) } - /// The class if the family's traits were read already. - pub(super) fn known_class(&self, family: &str) -> Option { - lock(&self.traits).get(family).and_then(|t| t.as_ref()).and_then(|t| t.class) - } - - /// What a family's sample says, in its row and in the banner: `sample` when the family's face draws it, else its - /// name, else the first glyphs the face has (a symbol face, or a face without the sample's script). - pub(super) fn sample_text(&self, catalog: &Catalog, family: &str, sample: &str, shown: &str) -> String { + /// What a family's sample says, in its row and in the banner: `sample` when the family's regular face (`face`, as + /// the face registry loaded it) draws it, else its name, else the first glyphs the face has (a symbol face, or a + /// face without the sample's script). + pub(super) fn sample_text(&self, family: &str, sample: &str, shown: &str, face: &FaceBytes) -> String { let key = (family.to_owned(), sample.to_owned()); if let Some(text) = lock(&self.samples).get(&key) { return text.clone(); } - let text = self.families.get(family).and_then(|info| draws(catalog, &info.regular, sample, shown)).unwrap_or_default(); + let text = draws(face, sample, shown).unwrap_or_default(); lock(&self.samples).insert(key, text.clone()); text } } -fn draws(catalog: &Catalog, face: &FaceInfo, sample: &str, shown: &str) -> Option { - let data = catalog.load(face).ok()?; - let font = FontRef::from_index(&data.bytes, face.index).ok()?; +fn draws(face: &FaceBytes, sample: &str, shown: &str) -> Option { + let font = FontRef::from_index(&face.bytes, face.index).ok()?; let map = font.charmap(); let inked = inked(&font); let drawn = |t: &str| t.chars().filter(|c| !c.is_whitespace()).all(|c| map.map(c).is_some_and(&inked)); @@ -165,28 +155,16 @@ pub(super) fn shown_name(info: &Info, family: &str, language: &str, english: boo info.localized.iter().find(exact).or_else(|| info.localized.iter().find(same_language)).map_or_else(|| family.to_owned(), |n| n.name.clone()) } -/// A face's class, PANOSE and weight from its `OS/2` and `post` tables. -fn read_traits(catalog: &Catalog, face: &FaceInfo) -> Option { - let data = catalog.load(face).ok()?; - let font = FontRef::from_index(&data.bytes, face.index).ok()?; - let os2 = font.os2().ok(); - let family_class = os2.as_ref().map_or(0, |t| t.s_family_class()); - let mut panose = [0u8; 10]; - if let Some(bytes) = os2.as_ref().map(|t| t.panose_10()) { - for (slot, b) in panose.iter_mut().zip(bytes.iter()) { - *slot = *b; - } - } - let weight = os2.as_ref().map_or(400, |t| t.us_weight_class()).clamp(1, 1000); - let fixed_pitch = font.post().ok().is_some_and(|p| p.is_fixed_pitch() != 0); - Some(Traits { class: classify(&face.family, family_class, panose, fixed_pitch), panose, weight }) +/// A face's class, PANOSE and weight from its `OS/2` and `post` tables, as the catalog's scan recorded them. +fn read_traits(face: &FaceInfo) -> Traits { + let weight = face.weight.round().clamp(1.0, 1000.0) as u16; + Traits { class: classify(&face.family, face.family_class, face.panose, face.fixed_pitch), panose: face.panose, weight } } -/// The class of a family from its regular face, `None` when the face can't be read. +/// The class of a family from its regular face, `None` when the catalog lacks it. pub(super) fn class_of(catalog: &Catalog, family: &str) -> Option { let faces = catalog.styles(family); - let face = regular_face(&faces)?; - read_traits(catalog, face)?.class + read_traits(regular_face(&faces)?).class } /// Name fragments (lowercase) that mark a blackletter face; the tables have no class for it. @@ -299,7 +277,7 @@ pub(super) fn list( let row = FamilyRow { family: family.clone(), starred: settings.is_some_and(|s| s.favorites.iter().any(|f| f == family)), - class: infos.known_class(family), + class: infos.traits(family).and_then(|t| t.class), format: Some(info.format), styles: info.styles, recent: false, @@ -327,19 +305,16 @@ pub(super) fn list( rows.retain(|r| r.format == Some(FontFormat::Variable)); } if let Some(class) = filters.class { - rows.retain_mut(|r| { - r.class = infos.traits(catalog, &r.family).and_then(|t| t.class); - r.class == Some(class) - }); + rows.retain(|r| r.class == Some(class)); } let mut comparable = true; if filters.similar { - let reference = infos.traits(catalog, listing.current).filter(|t| t.class.is_some() || t.panose.iter().any(|d| *d > 1)); + let reference = infos.traits(listing.current).filter(|t| t.class.is_some() || t.panose.iter().any(|d| *d > 1)); if let Some(reference) = reference { let mut scored: Vec<(f32, FamilyRow)> = rows .drain(..) .filter_map(|r| { - let traits = infos.traits(catalog, &r.family)?; + let traits = infos.traits(&r.family)?; let distance = if r.family == listing.current { -1.0 } else { reference.difference(&traits) }; Some((distance, r)) }) diff --git a/crates/font-manager/src/picker/rows.rs b/crates/font-manager/src/picker/rows.rs index 2bd3298cc..cb2581f13 100644 --- a/crates/font-manager/src/picker/rows.rs +++ b/crates/font-manager/src/picker/rows.rs @@ -5,6 +5,7 @@ use std::borrow::Cow; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; +use std::sync::Arc; use craft_behavior::{ColumnKey, ColumnWidth, DisplayOrder, IconId, ItemSource, Preview, Selection, SizeHint}; use craft_font_catalog::Catalog; @@ -18,6 +19,7 @@ use craft_ui::contract::{ use craft_ui::display::{Divider, Text}; use craft_ui::layout_components::{Row, Stack}; use craft_ui::list::{List, ListRow, ThumbSize, ToggleCell, ToggleFace, ToggleState, TreeLeaves}; +use craft_ui::primitives::FacesCx; use craft_ui::runtime::env::Label; use super::banner::FontPreviewBanner; @@ -26,7 +28,7 @@ use super::{ FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, POPUP, SAMPLE_EM, Typing, infos_of, read, ui_language, write, }; -use crate::panel::faces::Owner; +use crate::panel::faces::{self, Owner, Shown}; use crate::panel::specimen::{FontSample, SampleFace}; /// The sample column is this many times as wide as the sample band is high. @@ -279,15 +281,36 @@ fn class_column(ui: &mut egui::Ui, filters: &mut FontFilters, words: &FontPicker filters.class = usize::from(picked).checked_sub(1).and_then(|i| FontClass::ALL.get(i).copied()); } -/// The sample of a family row: `text` in the regular face of `family` at `points`, named "{shown}: {text}" as the font -/// manager names its samples, so the row keeps the family's name to itself; no face for a family the catalog -/// lacks. -fn sample<'a>(catalog: &'a Catalog, infos: &'a FamilyInfos, family: &str, shown: &str, text: String, points: f32) -> FontSample<'a> { +/// The sample of a family row: its text ([`row_text`]) in the regular face of `family` at `points`, named +/// "{shown}: {text}" as the font manager names its samples, so the row keeps the family's name to itself; no face for +/// a family the catalog lacks. +fn sample<'a>( + at: &impl FacesCx, + catalog: &'a Arc, + infos: &'a FamilyInfos, + family: &str, + shown: &str, + text: &str, + points: f32, +) -> FontSample<'a> { + let text = row_text(at, catalog, infos, family, text, shown); let face = infos.families.get(family).map_or(SampleFace::Missing, |info| SampleFace::Face { catalog, owner: Owner::Installed, face: &info.regular }); FontSample::new(format!("{shown}: {text}"), text, face, points) } +/// What `family`'s sample says ([`FamilyInfos::sample_text`]) once its regular face is ready; `text` while it loads, +/// when the sample shows nothing yet. +fn row_text(at: &impl FacesCx, catalog: &Arc, infos: &FamilyInfos, family: &str, text: &str, shown: &str) -> String { + let Some(info) = infos.families.get(family) else { return text.to_owned() }; + match faces::shown(at, catalog, Owner::Installed, &info.regular) { + Shown::Ready(_) => { + faces::bytes(at, Owner::Installed, &info.regular).map_or_else(|| text.to_owned(), |face| infos.sample_text(family, text, shown, &face)) + } + _ => text.to_owned(), + } +} + /// The name the banner shows for `family`: its row's shown name when the list holds one, else its name in the /// interface language, else the family key. fn banner_shown_name(slots: &[Slot], infos: &FamilyInfos, family: &str, language: &str, settings: Option<&FontPickerSettings>) -> String { @@ -392,6 +415,7 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: // The field's list keys go to the family list, not to the class column beside it. let families = cx.id.with("families"); let overlay = Overlay::dropdown().dismiss(Dismiss::new().focus_left(true)).list(families); + let faces_at = &*cx; let events = ui.show(popup, overlay, |ui, _| { let mut events = Vec::new(); Stack::new().show(ui, |ui, _| { @@ -404,7 +428,7 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: }); let label = words.preview_of.fill(&[("family", shown_name.as_str())]); // What the family's row shows: the text, or its name or first glyphs when the face can't draw it. - let shown_text = infos.sample_text(catalog, &banner_family, text, &shown_name); + let shown_text = row_text(faces_at, catalog, &infos, &banner_family, text, &shown_name); FontPreviewBanner::new(label, &shown_name, &shown_text, face).show(ui); } if let Some(filters) = filters.as_mut() { @@ -472,8 +496,8 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: if size == ThumbSize::None { return line; } - let text = infos.sample_text(catalog, &row.family, sample_text, &row.shown); - line.cell_field(SAMPLE, sample(catalog, &infos, &row.family, &row.shown, text, points), |_| {}) + let sample = sample(faces_at, catalog, &infos, &row.family, &row.shown, sample_text, points); + line.cell_field(SAMPLE, sample, |_| {}) } }); over_rows = rows.response.contains_pointer(); diff --git a/crates/font-manager/tests/it/picker.rs b/crates/font-manager/tests/it/picker.rs index c1c4b8160..72f026cf6 100644 --- a/crates/font-manager/tests/it/picker.rs +++ b/crates/font-manager/tests/it/picker.rs @@ -677,3 +677,23 @@ fn a_class_narrows_the_list_and_all_classes_restores_it() { fx.settle(); assert!(fx.by_label("Favorite Inter").is_some(), "every family is back"); } + +/// 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] +fn the_list_loads_its_sample_faces_off_the_pass_and_once() { + let jobs = Arc::new(craft_host::ManualJobs::new()); + let host = craft_host::Host::builder(craft_host::AppInfo { id: "trial", name: "Trial", version: "0" }).jobs(jobs.clone()).build(); + let (mut fx, _) = rig(catalog_of(&[INTER_REGULAR, epaint_default_fonts::HACK_REGULAR]), vec![]); + fx.host(Arc::new(host)); + open(&mut fx); + assert!(present(&fx, "Inter"), "the rows show while their faces load"); + assert!(jobs.waiting() > 0, "the rows' faces wait for the host's jobs"); + jobs.run_all(); + fx.settle(); + fx.key(Key::Escape, Modifiers::NONE); + fx.settle(); + open(&mut fx); + fx.frame(vec![]); + assert_eq!(jobs.waiting(), 0, "the list opened again loads no face"); +} diff --git a/crates/ui-contract/src/contract/faces.rs b/crates/ui-contract/src/contract/faces.rs index 530a7e795..b0dcefe9e 100644 --- a/crates/ui-contract/src/contract/faces.rs +++ b/crates/ui-contract/src/contract/faces.rs @@ -6,13 +6,21 @@ use crate::fonts::{FaceBytes, FaceState}; use crate::primitives::FacesCx; impl FacesCx for Cx<'_, C> { - fn document_face(&self, key: &str, load: impl FnOnce() -> Option) -> FaceState { + fn document_face(&self, key: &str, load: impl FnOnce() -> Option + Send + 'static) -> FaceState { DocumentFaces::face(&self.core.ctx, key, load) } + + fn document_face_bytes(&self, key: &str) -> Option { + DocumentFaces::bytes(&self.core.ctx, key) + } } impl FacesCx for MeasureCx<'_, C> { - fn document_face(&self, key: &str, load: impl FnOnce() -> Option) -> FaceState { + fn document_face(&self, key: &str, load: impl FnOnce() -> Option + Send + 'static) -> FaceState { DocumentFaces::face(self.ui.ctx(), key, load) } + + fn document_face_bytes(&self, key: &str) -> Option { + DocumentFaces::bytes(self.ui.ctx(), key) + } } diff --git a/crates/ui-contract/src/fonts/document.rs b/crates/ui-contract/src/fonts/document.rs index f3bf236da..d227f759d 100644 --- a/crates/ui-contract/src/fonts/document.rs +++ b/crates/ui-contract/src/fonts/document.rs @@ -1,36 +1,36 @@ //! Faces drawn as families of their own, for text set in a document's fonts. //! -//! One registry per context serves every caller, so the faces of a frame are counted together. A face is added a few -//! per frame; past [`MAX_DOCUMENT_FACES`] the faces the previous frame did not draw are taken out again, which keeps -//! memory to the faces on screen. Faces still on screen stay, however many there are. +//! One registry per context serves every caller, so the faces of a frame are counted together. A face is drawn alone +//! ([`DocumentFaces::face`]: a font sample shows what the face itself has) or over the interface fonts +//! ([`DocumentFaces::over_interface`]: document text such as an input method's composition, whose characters the face +//! lacks come from the interface stack, CJK included). //! -//! A face is drawn alone ([`DocumentFaces::face`]: a font sample shows what the face itself has) or over the interface -//! fonts ([`DocumentFaces::over_interface`]: document text such as an input method's composition, whose characters -//! the face lacks come from the interface stack, CJK included). A face over the interface fonts is installed by the -//! begin-pass step of the frame after it is asked for, as a family whose chain is the face followed by the -//! proportional family's: egui builds a family's chain from the definitions alone, so the chain is written into them -//! where nothing of the pass has queued definitions of its own. +//! A face drawn alone is read from a font catalog: its `load` runs as a job on the context's queue of face loads, and +//! the face is ready from the pass after it lands. A face over the interface fonts comes from bytes the app holds: its +//! `load` runs at once and the face is ready in the same pass, so document text never draws a frame without it. Either +//! way the face reaches egui as a served family (`egui_fonts::serve_face`), which egui parses the first time text is +//! laid out in it: a face arriving drops nothing egui has parsed or laid out. +//! +//! The registry keeps faces up to [`MAX_DOCUMENT_FACE_BYTES`] of font files; past it the faces drawn longest ago go, +//! and faces drawn in the last frame always stay. use std::collections::{HashMap, HashSet}; use std::sync::Arc; +use craft_host::queue::{JobQueue, Priority, QueueOptions}; +use craft_host::{Jobs, Wake, default_jobs}; use egui::epaint::text::{Blob, FontTweak, VariationCoords}; use egui::{Context, FontData}; use super::FontRef; -use crate::runtime::egui::{fonts as egui_fonts, memory, pass}; +use crate::runtime::egui::{fonts as egui_fonts, memory, pass, repaint}; +use crate::runtime::env::Env; use crate::runtime::frame; -/// The faces one frame may add; a new face past it waits for the next frame. -pub const DOCUMENT_FACES_PER_PASS: usize = 6; - -/// The faces kept before the ones the previous frame did not draw are taken out. -pub const MAX_DOCUMENT_FACES: usize = 64; - -/// The largest font file a face over the interface fonts is drawn from, in bytes (16 MiB). egui parses every face of -/// the definitions again whenever they change, and a document's CJK fallback can be far larger (Microsoft YaHei is -/// about 19 MB): text in a larger face is drawn in the interface fonts. -pub const MAX_INTERFACE_FACE_BYTES: usize = 16 << 20; +/// The font file bytes the registry keeps faces of, a collection counted once. Past it the faces drawn longest ago +/// are taken out; and once the files of faces taken out (which egui keeps parsed until its fonts are made again) pass +/// it too, egui's fonts are made again to free them. +pub const MAX_DOCUMENT_FACE_BYTES: usize = 512 << 20; /// The bytes of a face, its index in a collection and its variation coordinates (axis tag, value). #[derive(Clone)] @@ -62,6 +62,16 @@ impl FaceBytes { let tweak = FontTweak { coords: VariationCoords::new(self.coords.iter().copied()), ..FontTweak::default() }; FontData::from_blob(blob, self.index).tweak(tweak) } + + /// Whether egui can draw the face: egui stops on a face it cannot read. + fn parses(&self) -> bool { + skrifa::FontRef::from_index(&self.bytes, self.index).is_ok() + } + + /// The file's identity: faces of one collection share their bytes. + fn file(&self) -> usize { + Arc::as_ptr(&self.bytes).cast::() as usize + } } /// What drawing a document face finds. @@ -70,16 +80,23 @@ impl FaceBytes { pub enum FaceState { /// The family that draws the face. Ready(FontRef), - /// The face is being added; a repaint is asked. + /// The face is being loaded; the asking view runs again in the next pass. Loading, /// The face could not be loaded. Unavailable, } -/// A registered face: the frame it was last drawn in and the frame it was added in. +/// A registered face: its bytes and the frame it was last drawn in. struct Registered { + face: FaceBytes, used: u64, - added: u64, +} + +/// The queue the catalog loads run on, with the `Jobs` it spawns lanes on and its lane count. +struct Queue { + jobs: Arc, + lanes: usize, + queue: Arc>>, } /// The context's document faces, by family name. @@ -87,38 +104,46 @@ struct Registered { struct Registry { faces: HashMap, failed: HashSet, - /// Faces over the interface fonts waiting for the next begin-pass step: family name and face. - pending: Vec<(String, FontData)>, - budget: usize, + /// Loads queued or running, with the frame each was last asked for in. + loading: HashMap, + queue: Option, + /// The bytes of files whose faces were taken out since egui's fonts were last made again. + withdrawn: usize, frame: u64, - begun: bool, - evicted: Option, hooked: bool, } impl Registry { - /// Starts frame `now` unless it has started: the budget is full again. - fn begin(&mut self, now: u64) { - if self.begun && self.frame == now { - return; - } - self.begun = true; - self.frame = now; - self.budget = DOCUMENT_FACES_PER_PASS; - } - - /// Past the cap, drops the faces the previous frame did not draw and returns them. Once per frame. + /// Past the budget, takes out the faces drawn longest ago (never one the last frame drew) and returns their + /// names; the bytes of files no kept face shares count as withdrawn. fn evict(&mut self, now: u64) -> Vec { - if self.evicted == Some(now) || self.faces.len() <= MAX_DOCUMENT_FACES { + let mut files: HashMap = HashMap::new(); + for face in self.faces.values() { + files.entry(face.face.file()).or_insert((face.face.bytes.len(), 0)).1 += 1; + } + let mut held: usize = files.values().map(|(bytes, _)| bytes).sum(); + if held <= MAX_DOCUMENT_FACE_BYTES { return Vec::new(); } - self.evicted = Some(now); - let stale: Vec = self.faces.iter().filter(|(_, face)| face.used + 1 < now).map(|(name, _)| name.clone()).collect(); - for name in &stale { - self.faces.remove(name); + let mut stale: Vec<(u64, String)> = + self.faces.iter().filter(|(_, face)| face.used + 1 < now).map(|(name, face)| (face.used, name.clone())).collect(); + stale.sort(); + let mut gone = Vec::new(); + for (_, name) in stale { + if held <= MAX_DOCUMENT_FACE_BYTES { + break; + } + let Some(face) = self.faces.remove(&name) else { continue }; + if let Some((bytes, count)) = files.get_mut(&face.face.file()) { + *count -= 1; + if *count == 0 { + held -= *bytes; + self.withdrawn += *bytes; + } + } + gone.push(name); } - self.pending.retain(|(name, _)| !stale.contains(name)); - stale + gone } } @@ -144,106 +169,191 @@ impl Kind { /// What the registry knew of a key. enum Known { Failed, - Added(u64), + Ready, + Loading, New, } -/// The begin-pass step: starts the frame, evicts the faces past the cap and installs the faces over the interface fonts -/// the last frame loaded. Both happen only here, in one edit, before any install of the pass can queue its -/// definitions, because they rebuild them from the applied ones. -fn begin_pass(ctx: &Context) { - let now = pass::root_frame_nr(ctx); - let (stale, pending) = memory::with::(ctx, |registry| { - registry.begin(now); - let stale = registry.evict(now); - (stale, std::mem::take(&mut registry.pending)) - }); - if !stale.is_empty() || !pending.is_empty() { - egui_fonts::edit_faces(ctx, &stale, pending); +/// The queue of `ctx`'s catalog loads, made again when the host's `Jobs` changes. +fn queue_of(ctx: &Context, registry: &mut Registry) -> Arc>> { + let jobs = Env::host_of(ctx).map_or_else(default_jobs, |host| Arc::clone(host.jobs_shared())); + match ®istry.queue { + Some(queue) if Arc::ptr_eq(&queue.jobs, &jobs) => Arc::clone(&queue.queue), + _ => { + let wake_ctx = ctx.clone(); + let wake = Wake::new(move || repaint::request(&wake_ctx)); + let lanes = QueueOptions::default_lanes(); + let queue = Arc::new(JobQueue::new(Arc::clone(&jobs), wake, QueueOptions { lanes, name: "craft-document-faces" })); + registry.loading.clear(); + registry.queue = Some(Queue { jobs, lanes, queue: Arc::clone(&queue) }); + queue + } } } -/// Hooks the begin-pass step on the context's fonts plugin and starts the frame's budget. +/// The begin-pass step: drops the loads no frame asked for lately, serves the faces that landed and takes out the faces +/// past the budget. Before anything of the pass is laid out, so a rebuild of egui's fonts it asks for applies at once. +fn begin_pass(ctx: &Context) { + let now = pass::root_frame_nr(ctx); + let inline = memory::with::(ctx, |registry| { + registry.frame = now; + registry.queue.as_ref().filter(|queue| queue.lanes == 0).map(|queue| Arc::clone(&queue.queue)) + }); + // Without lanes (wasm32) one load runs per pass, here. + if let Some(queue) = inline { + queue.run_inline(1); + } + let (landed, gone, rebuild) = memory::with::(ctx, |registry| { + let mut landed = Vec::new(); + if let Some(queue) = registry.queue.as_ref().map(|queue| Arc::clone(&queue.queue)) { + let loading = &mut registry.loading; + loading.retain(|_, asked| *asked + 1 >= now); + queue.reprioritize(|key, priority| loading.contains_key(key).then_some(priority)); + while let Some(finished) = queue.try_recv() { + if loading.remove(&finished.key).is_some() { + landed.push((finished.key, finished.result)); + } + } + } + for (name, result) in &landed { + match result { + Some(face) => { + registry.faces.insert(name.clone(), Registered { face: face.clone(), used: now }); + } + None => { + registry.failed.insert(name.clone()); + } + } + } + let gone = registry.evict(now); + let rebuild = registry.withdrawn > MAX_DOCUMENT_FACE_BYTES; + if rebuild { + registry.withdrawn = 0; + } + (landed, gone, rebuild) + }); + for (name, face) in landed { + if let Some(face) = face { + egui_fonts::serve_face(ctx, &FontRef::named(&name), face.data(), false); + } + } + if !gone.is_empty() { + egui_fonts::withdraw_faces(ctx, &gone); + } + if rebuild { + egui_fonts::reload_providers(ctx); + } +} + +/// Hooks the begin-pass step on the context's fonts plugin. fn begin(ctx: &Context) { let hook = memory::with::(ctx, |registry| !std::mem::replace(&mut registry.hooked, true)); if hook { egui_fonts::on_begin_pass(ctx, begin_pass); + memory::with::(ctx, |registry| registry.frame = pass::root_frame_nr(ctx)); } - let now = pass::root_frame_nr(ctx); - memory::with::(ctx, |registry| registry.begin(now)); } /// The document faces: the families drawn from font files a document names. Reached through `FacesCx`. pub(crate) struct DocumentFaces; impl DocumentFaces { - /// The face registered under `key` as a family of its own. `load` runs only for a new key within the frame's budget - /// of [`DOCUMENT_FACES_PER_PASS`], and for a key whose family a replacement of the definitions removed. A `load` - /// that returns `None` marks the key unavailable for as long as the context lives. Every call marks the face drawn - /// in this frame. - pub(crate) fn face(ctx: &Context, key: &str, load: impl FnOnce() -> Option) -> FaceState { - Self::register(ctx, key, Kind::Alone, load) + /// The face registered under `key` as a family of its own. `load` reads it from a font catalog: it runs as a job, + /// once per key while the face is kept, and the face is ready from the pass after the job ends. A `load` that + /// returns `None`, or bytes egui cannot read, marks the key unavailable for as long as the context lives. Every call + /// marks the face drawn in this frame; a load no frame asks for any more is dropped. + pub(crate) fn face(ctx: &Context, key: &str, load: impl FnOnce() -> Option + Send + 'static) -> FaceState { + let name = Kind::Alone.family_name(key); + match Self::known(ctx, &name) { + Known::Failed => FaceState::Unavailable, + Known::Ready => Self::ready(ctx, &name), + Known::Loading => { + // The asking view runs again in the next pass (its replay would hold the loading state) and keeps the + // load asked for. + frame::request_repaint(ctx); + FaceState::Loading + } + Known::New => { + // A measuring run starts the load too: the registry is a cache, and a face loads the same whichever + // run asks. + frame::request_repaint(ctx); + memory::with::(ctx, |registry| { + let queue = queue_of(ctx, registry); + registry.loading.insert(name.clone(), registry.frame); + queue.submit(name, Priority::VISIBLE, move |cancel| { + if cancel.is_cancelled() { + return None; + } + load().filter(FaceBytes::parses) + }); + }); + FaceState::Loading + } + } } /// The face registered under `key` as a family of its own whose characters the face lacks come from the interface - /// fonts (the proportional family's chain, CJK included). As [`face`](Self::face), with two differences: the face - /// is ready from the frame after the one that loaded it, and a file larger than [`MAX_INTERFACE_FACE_BYTES`] marks - /// the key unavailable. Its keys are apart from `face`'s: the same key may name a face drawn alone too. + /// fonts (the proportional family's chain, CJK included). `load` gives bytes the app holds: it runs at once, the + /// first time the key is drawn while the face is kept, and the face is ready in the same pass. A `load` that returns + /// `None`, or bytes egui cannot read, marks the key unavailable. Its keys are apart from `face`'s: the same key may + /// name a face drawn alone too. pub(crate) fn over_interface(ctx: &Context, key: &str, load: impl FnOnce() -> Option) -> FaceState { - Self::register(ctx, key, Kind::OverInterface, load) + let name = Kind::OverInterface.family_name(key); + match Self::known(ctx, &name) { + Known::Failed => FaceState::Unavailable, + Known::Ready => Self::ready(ctx, &name), + Known::Loading | Known::New => { + let Some(face) = load().filter(FaceBytes::parses) else { + memory::with::(ctx, |registry| registry.failed.insert(name)); + return FaceState::Unavailable; + }; + let data = face.data(); + memory::with::(ctx, |registry| { + let used = registry.frame; + registry.faces.insert(name.clone(), Registered { face, used }); + }); + if egui_fonts::serve_face(ctx, &FontRef::named(&name), data, true) { + FaceState::Ready(FontRef::named(&name)) + } else { + frame::request_repaint(ctx); + FaceState::Loading + } + } + } } - fn register(ctx: &Context, key: &str, kind: Kind, load: impl FnOnce() -> Option) -> FaceState { + /// The bytes of the face registered under `key` to be drawn alone, once it is ready. + pub(crate) fn bytes(ctx: &Context, key: &str) -> Option { + let name = Kind::Alone.family_name(key); + memory::with::(ctx, |registry| registry.faces.get(&name).map(|face| face.face.clone())) + } + + /// What the registry knows of `name`, marking a kept face drawn and a load asked for in this frame. + fn known(ctx: &Context, name: &str) -> Known { begin(ctx); - let name = kind.family_name(key); - let family = FontRef::named(&name); - let (now, known) = memory::with::(ctx, |registry| { - let known = if registry.failed.contains(&name) { + memory::with::(ctx, |registry| { + let now = registry.frame; + if registry.failed.contains(name) { Known::Failed - } else if let Some(face) = registry.faces.get_mut(&name) { - face.used = registry.frame; - Known::Added(face.added) + } else if let Some(face) = registry.faces.get_mut(name) { + face.used = now; + Known::Ready + } else if let Some(asked) = registry.loading.get_mut(name) { + *asked = now; + Known::Loading } else { Known::New - }; - (registry.frame, known) - }); - match known { - Known::Failed => return FaceState::Unavailable, - Known::Added(_) if egui_fonts::has_family(ctx, &family) => return FaceState::Ready(family), - Known::Added(added) if added == now => { - frame::request_repaint(ctx); - return FaceState::Loading; } - Known::Added(_) | Known::New => {} + }) + } + + /// A kept face's state: ready once egui lays text out with the served faces. + fn ready(ctx: &Context, name: &str) -> FaceState { + if egui_fonts::is_served(ctx) { + FaceState::Ready(FontRef::named(name)) + } else { + frame::request_repaint(ctx); + FaceState::Loading } - frame::request_repaint(ctx); - let allowed = memory::with::(ctx, |registry| { - let allowed = registry.budget > 0; - registry.budget = registry.budget.saturating_sub(1); - allowed - }); - if !allowed { - return FaceState::Loading; - } - let loaded = load().filter(|bytes| kind == Kind::Alone || bytes.bytes.len() <= MAX_INTERFACE_FACE_BYTES); - let Some(bytes) = loaded else { - memory::with::(ctx, |registry| { - registry.faces.remove(&name); - registry.failed.insert(name.clone()); - }); - return FaceState::Unavailable; - }; - if kind == Kind::Alone { - egui_fonts::add_family_face(ctx, &family, bytes.data()); - } - memory::with::(ctx, |registry| { - if kind == Kind::OverInterface { - registry.pending.retain(|(pending, _)| *pending != name); - registry.pending.push((name.clone(), bytes.data())); - } - registry.faces.insert(name.clone(), Registered { used: now, added: now }) - }); - FaceState::Loading } } diff --git a/crates/ui-contract/src/fonts/mod.rs b/crates/ui-contract/src/fonts/mod.rs index 826e69ffc..a77b31d9f 100644 --- a/crates/ui-contract/src/fonts/mod.rs +++ b/crates/ui-contract/src/fonts/mod.rs @@ -8,7 +8,7 @@ pub(crate) mod script; pub(crate) mod system; pub use defaults::{deflated_default_definitions, emoji_icon_font, noto_emoji}; -pub use document::{DOCUMENT_FACES_PER_PASS, FaceBytes, FaceState, MAX_DOCUMENT_FACES, MAX_INTERFACE_FACE_BYTES}; +pub use document::{FaceBytes, FaceState, MAX_DOCUMENT_FACE_BYTES}; pub use faces::{FaceList, RegularWeight, set_weight}; pub use on_demand::{FontCandidates, MAX_SCRIPT_READS, NoCandidates, OnDemandFonts, SystemCandidates, han_for_locale, on_demand_registered}; pub use system::system_font_provider; diff --git a/crates/ui-contract/src/primitives/content.rs b/crates/ui-contract/src/primitives/content.rs index d6945d11b..ab67b0e9d 100644 --- a/crates/ui-contract/src/primitives/content.rs +++ b/crates/ui-contract/src/primitives/content.rs @@ -215,11 +215,11 @@ pub struct DocRun<'a> { /// baseline: an input method's composition in the face and size of the text it goes into, as Word draws it. /// /// - **Face.** `key` names the face among the context's document faces, one key per font file, face index and -/// variation setting (a font database's face id). The caller gives the face's bytes and index through the `load` of -/// `face_run`, which runs only the first time the key is drawn, so a face is installed once, not every frame. -/// - **Fallback.** Characters the face lacks are drawn by the interface fonts, in their order, CJK included. The run -/// is drawn in the interface face until its face is installed (the frame after it loads) and for a face that does -/// not load or whose file is larger than [`MAX_INTERFACE_FACE_BYTES`](crate::fonts::MAX_INTERFACE_FACE_BYTES). +/// variation setting (a font database's face id). The caller gives the face's bytes and index, which it holds, +/// through the `load` of `face_run`; it runs only the first time the key is drawn, so a face is installed once, not +/// every frame, and the run is drawn in its face in that same pass. +/// - **Fallback.** Characters the face lacks are drawn by the interface fonts, in their order, CJK included. A face +/// that does not load is drawn in the interface face. /// - **Size.** `size` points on screen (the document size times the view's zoom), at least 1 and at most /// [`largest_size`](Self::largest_size): egui draws each glyph into its font atlas and fails on one wider than the /// atlas, so a larger run is drawn smaller, at the cap. diff --git a/crates/ui-contract/src/primitives/draw.rs b/crates/ui-contract/src/primitives/draw.rs index 3408e3581..a2bbb5191 100644 --- a/crates/ui-contract/src/primitives/draw.rs +++ b/crates/ui-contract/src/primitives/draw.rs @@ -330,8 +330,8 @@ impl<'a> Draw<'a> { /// Paints `run` in its document face with the start of its first baseline at `start`, and returns its layout, whose /// top lies at `start.y - layout.first_baseline` ([`FaceRun`] says how the face, its fallback and the size are - /// chosen). `load` gives the face's bytes and index the first time `run.key` is drawn, and again only after the - /// fonts were replaced; a `None` leaves the run in the interface face. The paragraph is left to right. A disabled + /// chosen). `load` gives the face's bytes and index, which the caller holds, the first time `run.key` is drawn while + /// the face is kept; a `None` leaves the run in the interface face. The paragraph is left to right. A disabled /// component's run paints at `Opacity::DISABLED`, as `doc` does. pub fn face_run(&self, start: Pos2, run: &FaceRun<'_>, load: impl FnOnce() -> Option) -> TextLayout { let ctx = self.painter.ctx(); diff --git a/crates/ui-contract/src/primitives/faces.rs b/crates/ui-contract/src/primitives/faces.rs index 4deb5a3ed..27d34eea6 100644 --- a/crates/ui-contract/src/primitives/faces.rs +++ b/crates/ui-contract/src/primitives/faces.rs @@ -6,15 +6,22 @@ use crate::fonts::{FaceBytes, FaceState}; /// Where a document face is asked for: a component's context, its measure or a content painter. pub trait FacesCx { - /// The face registered under `key` as a family of its own. `load` runs only for a new key within the frame's - /// budget of `DOCUMENT_FACES_PER_PASS`, and for a key whose family a replacement of the definitions removed. A - /// `load` that returns `None` marks the key unavailable for as long as the context lives. Every call marks the - /// face drawn in this frame. - fn document_face(&self, key: &str, load: impl FnOnce() -> Option) -> FaceState; + /// The face registered under `key` as a family of its own, read from a font catalog. `load` runs as a background + /// job, once while the face is kept, and the face is ready from the pass after it ends. A `load` that returns + /// `None` marks the key unavailable for as long as the context lives. Every call marks the face drawn in this frame. + fn document_face(&self, key: &str, load: impl FnOnce() -> Option + Send + 'static) -> FaceState; + + /// The bytes of the face `document_face` registered under `key`, once it is ready: for reading its tables without + /// loading the file again. + fn document_face_bytes(&self, key: &str) -> Option; } impl FacesCx for ContentPainterCx<'_> { - fn document_face(&self, key: &str, load: impl FnOnce() -> Option) -> FaceState { + fn document_face(&self, key: &str, load: impl FnOnce() -> Option + Send + 'static) -> FaceState { DocumentFaces::face(self.painter.ctx(), key, load) } + + fn document_face_bytes(&self, key: &str) -> Option { + DocumentFaces::bytes(self.painter.ctx(), key) + } } diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index f21e99a85..ee72c0bd5 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -396,7 +396,7 @@ pub(crate) fn click_options(ctx: &Context) -> (f32, f64) { /// A fresh context with no plugin and AccessKit on. pub(crate) fn bare_context() -> Context { let ctx = Context::default(); - ctx.set_fonts(test_fonts()); + super::fonts::set_definitions(&ctx, test_fonts()); ctx.enable_accesskit(); ctx } diff --git a/crates/ui-contract/src/runtime/egui/fonts.rs b/crates/ui-contract/src/runtime/egui/fonts.rs index e5887ef15..8dc291dfc 100644 --- a/crates/ui-contract/src/runtime/egui/fonts.rs +++ b/crates/ui-contract/src/runtime/egui/fonts.rs @@ -3,8 +3,14 @@ //! One fonts plugin is registered per context, on first need. Its begin-pass hook runs the steps added with //! `on_begin_pass`; its output hook runs the on-demand scan. The plugin holds no state: the provider list, the steps //! and the loader live in the runtime store. +//! +//! The faces served one family at a time (`serve_face`: the document faces) reach egui through one provider that is +//! always last in the context's list. egui asks a provider for a family's faces the first time text is laid out in +//! it, so serving a face drops nothing egui has parsed, laid out or put in its atlas, as adding it to the definitions +//! would. -use std::sync::Arc; +use std::collections::HashMap; +use std::sync::{Arc, PoisonError, RwLock}; use egui::epaint::ClippedShape; use egui::epaint::text::{Fonts, TextOptions}; @@ -12,16 +18,87 @@ use egui::{Context, FontData, FontDefinitions, FontFamily, FontId, FontInsert, F use egui::{Plugin, Ui, ViewportId}; use crate::fonts::FontRef; -use crate::runtime::egui::{memory, repaint}; +use crate::runtime::egui::{memory, pass, repaint}; +use crate::runtime::frame; -/// Gives egui `definitions`; the next pass lays text out with them. +/// Gives egui `definitions`; the next pass lays text out with them. The first definitions bring the served faces' +/// provider with them, so the served faces are found from the first pass that lays text out. pub(crate) fn set_definitions(ctx: &Context, definitions: FontDefinitions) { + let (served, providers) = memory::with::(ctx, |providers| { + let first = providers.served_since.is_none(); + (Arc::clone(&providers.served), first.then(|| providers.all(ctx))) + }); + served.set_interface(&definitions); ctx.set_fonts(definitions); + if let Some(providers) = providers { + ctx.set_font_providers(providers); + } } -/// The context's font providers, in the order egui asks them. +/// A face served as a family of its own. +struct ServedFace { + data: FontData, + /// The proportional family's faces follow the face in its family. + over_interface: bool, +} + +/// The faces served one family at a time, by family name, and the proportional family's faces as the definitions +/// last given to egui list them (`None` until definitions are given or a face over them is served). #[derive(Default)] -struct Providers(Vec>); +struct Served { + families: RwLock>, + interface: RwLock>>, +} + +impl Served { + fn set_interface(&self, definitions: &FontDefinitions) { + let names = definitions.families.get(&FontFamily::Proportional).map(Vec::as_slice).unwrap_or_default(); + let faces = + names.iter().filter_map(|name| definitions.font_data.get(name).map(|data| FontInsert::new(name, (**data).clone(), Vec::new()))).collect(); + *self.interface.write().unwrap_or_else(PoisonError::into_inner) = Some(faces); + } +} + +impl FontProvider for Served { + fn fonts_for_family(&self, family: &FontFamily) -> Vec { + let FontFamily::Name(name) = family else { return Vec::new() }; + let families = self.families.read().unwrap_or_else(PoisonError::into_inner); + let Some(face) = families.get(&**name) else { return Vec::new() }; + let mut faces = vec![FontInsert::new(name, face.data.clone(), Vec::new())]; + if face.over_interface { + let interface = self.interface.read().unwrap_or_else(PoisonError::into_inner); + faces.extend(interface.iter().flatten().filter(|face| *face.name != **name).cloned()); + } + faces + } +} + +/// The context's font providers, in the order egui asks them, and the served faces' provider, which follows them. +#[derive(Default)] +struct Providers { + kept: Vec>, + served: Arc, + /// The root frame in which the served faces' provider was given to egui, and whether that was inside a pass. + served_since: Option<(u64, bool)>, +} + +impl Providers { + /// The providers egui is given: the kept ones, then the served faces'. + fn all(&mut self, ctx: &Context) -> Vec> { + self.mark_served(ctx); + self.kept.iter().cloned().chain(std::iter::once(Arc::clone(&self.served) as Arc)).collect() + } + + fn mark_served(&mut self, ctx: &Context) { + if self.served_since.is_none() { + self.served_since = Some((pass::root_frame_nr(ctx), frame::in_pass(ctx))); + } + } +} + +fn served(ctx: &Context) -> Arc { + memory::with::(ctx, |providers| Arc::clone(&providers.served)) +} /// The steps the fonts plugin runs at the start of every pass. #[derive(Default)] @@ -29,20 +106,26 @@ struct Steps(Vec); /// Sets the context's font providers and remembers them for [`reload_providers`]. pub(crate) fn set_providers(ctx: &Context, providers: Vec>) { - memory::with::(ctx, |kept| kept.0.clone_from(&providers)); - ctx.set_font_providers(providers); + let all = memory::with::(ctx, |kept| { + kept.kept.clone_from(&providers); + kept.all(ctx) + }); + ctx.set_font_providers(all); } /// Adds a font provider after the context's others. pub(crate) fn add_provider(ctx: &Context, provider: Arc) { - memory::with::(ctx, |kept| kept.0.push(Arc::clone(&provider))); - ctx.add_font_provider(provider); + let all = memory::with::(ctx, |kept| { + kept.kept.push(Arc::clone(&provider)); + kept.all(ctx) + }); + ctx.set_font_providers(all); } -/// Sets the context's providers again, so egui forgets the characters they had no font for and repaints. Callable -/// from any thread. +/// Sets the context's providers again, so egui forgets the characters they had no font for, drops the faces it +/// parsed (the served faces no longer served among them) and repaints. Callable from any thread. pub(crate) fn reload_providers(ctx: &Context) { - let providers = memory::with::(ctx, |kept| kept.0.clone()); + let providers = memory::with::(ctx, |kept| kept.all(ctx)); ctx.set_font_providers(providers); } @@ -54,38 +137,52 @@ pub(crate) fn add_face(ctx: &Context, name: String, data: FontData) { families.push(family); } } + if let Some(interface) = served(ctx).interface.write().unwrap_or_else(PoisonError::into_inner).as_mut() { + interface.push(FontInsert::new(&name, data.clone(), Vec::new())); + } let families = families.into_iter().map(|family| InsertFontFamily { family, priority: FontPriority::Lowest }).collect(); ctx.add_font(FontInsert { name, data, families }); } -/// Adds `data` as a face named after `family` and makes it the highest-priority face of `family` alone. The face is -/// loaded at the next pass. -pub(crate) fn add_family_face(ctx: &Context, family: &FontRef, data: FontData) { - let insert = InsertFontFamily { family: family.family(), priority: FontPriority::Highest }; - ctx.add_font(FontInsert { name: family.family().to_string(), data, families: vec![insert] }); +/// Serves `data` as the family `family` (its face's name too): the face alone, or with `over_interface` the face +/// followed by the proportional family's faces, so what the face lacks the interface fonts draw. Returns whether text +/// laid out in the family in this pass finds it: false in the pass that first gives egui the served faces' provider. +pub(crate) fn serve_face(ctx: &Context, family: &FontRef, data: FontData, over_interface: bool) -> bool { + let FontFamily::Name(name) = family.family() else { return false }; + let (served, since) = memory::with::(ctx, |providers| (Arc::clone(&providers.served), providers.served_since)); + let unset = served.interface.read().unwrap_or_else(PoisonError::into_inner).is_none(); + if over_interface && unset { + ctx.fonts(|fonts| served.set_interface(fonts.definitions())); + } + served.families.write().unwrap_or_else(PoisonError::into_inner).insert(name.to_string(), ServedFace { data, over_interface }); + match since { + Some(since) => served_live(ctx, since), + None => { + reload_providers(ctx); + !frame::in_pass(ctx) + } + } } -/// Whether egui's definitions hold the family `family`. -pub(crate) fn has_family(ctx: &Context, family: &FontRef) -> bool { - ctx.fonts(|fonts| fonts.definitions().families.contains_key(&family.family())) +/// Whether the served faces' provider, given to egui in `since`, is the one this pass lays text out with. +fn served_live(ctx: &Context, (frame_nr, in_pass): (u64, bool)) -> bool { + !in_pass || frame_nr < pass::root_frame_nr(ctx) } -/// Takes the faces called `gone`, and the families of those names, out of egui's definitions, and adds each face of -/// `over_interface` under its name with a family of that name: the face, then the proportional family's chain, so -/// what the face lacks the interface fonts draw. -/// It rebuilds the definitions from the applied ones, so call it only from a begin-pass step, before an install of the -/// pass can queue its own. -pub(crate) fn edit_faces(ctx: &Context, gone: &[String], over_interface: Vec<(String, FontData)>) { - let mut definitions = ctx.fonts(|fonts| fonts.definitions().clone()); - definitions.font_data.retain(|name, _| !gone.contains(name)); - definitions.families.retain(|family, _| !matches!(family, FontFamily::Name(name) if gone.iter().any(|gone| gone.as_str() == &**name))); - let interface = definitions.families.get(&FontFamily::Proportional).cloned().unwrap_or_default(); - for (name, data) in over_interface { - let chain = std::iter::once(name.clone()).chain(interface.iter().filter(|face| **face != name).cloned()).collect(); - definitions.families.insert(FontFamily::Name(name.as_str().into()), chain); - definitions.font_data.insert(name, Arc::new(data)); +/// Whether text laid out in this pass finds the served faces: false before any is served and in the pass that first +/// gives egui their provider. +pub(crate) fn is_served(ctx: &Context) -> bool { + memory::with::(ctx, |providers| providers.served_since).is_some_and(|since| served_live(ctx, since)) +} + +/// Stops serving the families `gone`. egui keeps the faces it parsed from them until its fonts are made again +/// (`reload_providers`, or a change of the definitions or providers). +pub(crate) fn withdraw_faces(ctx: &Context, gone: &[String]) { + let served = served(ctx); + let mut families = served.families.write().unwrap_or_else(PoisonError::into_inner); + for name in gone { + families.remove(name); } - set_definitions(ctx, definitions); } /// Whether egui's definitions hold the face called `name`. diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index f4d56fd8a..32f622d66 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1324,6 +1324,7 @@ pub(crate) mod guard { ("primitives::textures::loader::Pools", "texture loaders: cache; one per salt, made on first use, and the store's uploads"), ("primitives::textures::thumbnails::Hubs", "thumbnails: cache; one per salt, made on first use, and its per-frame render budget"), ("fonts::document::Registry", "document faces: cache; a face loads the same whichever run asks, and its repaint request is harmless"), + ("runtime::egui::fonts::Providers", "font providers and the served faces: cache; a face is served the same whichever run asks"), ("runtime::egui::fonts::Steps", "fonts plugin begin-pass steps: cache; a step added twice runs once"), // Testing logs. ("runtime::measure::", "measuring-run counts and the skipped-effect log (testing)"), diff --git a/crates/ui-contract/tests/it/fonts/document.rs b/crates/ui-contract/tests/it/fonts/document.rs index 33bf0e127..892c2545b 100644 --- a/crates/ui-contract/tests/it/fonts/document.rs +++ b/crates/ui-contract/tests/it/fonts/document.rs @@ -1,21 +1,21 @@ -//! Document faces: registering again after the definitions are replaced. +//! Document faces read from a catalog: loaded off the pass, ready from the pass after, kept across a definitions +//! replacement and while drawn lately, and served to egui without making its fonts again. use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use craft_behavior::Metrics; -use craft_ui::contract::{Common, Component, Cx, FacesCx as _, MeasureCx, Props as _, Role, Show as _}; +use craft_host::{AppInfo, Host, ManualJobs}; +use craft_ui::contract::{Common, Component, Cx, FacesCx as _, MeasureCx, Role, Show as _}; use craft_ui::fonts::{self, FaceBytes, FaceState}; -use craft_ui::style::{ComponentStyle, StyleCx}; +use craft_ui::primitives::{DocRun, DocText}; +use craft_ui::style::{ComponentStyle, DataColor, StyleCx}; use craft_ui::testing::{Frames, trial}; -use egui::{Response, Vec2}; +use egui::{Color32, Response, Vec2}; const FONT: &[u8] = include_bytes!("../../fonts/NotoSans-test.ttf"); -/// The frames a face may take to become ready. -const FRAMES_TO_READY: usize = 20; - #[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct PlainStyle { @@ -38,15 +38,18 @@ impl Tally { fn state(&self, key: &str) -> FaceState { self.states.lock().expect("the states").get(key).cloned().unwrap_or_else(|| panic!("{key} was asked for")) } + + fn all_ready(&self, keys: &[String]) -> bool { + keys.iter().all(|key| matches!(self.state(key), FaceState::Ready(_))) + } } -/// An owner of document faces: it asks for its keys while it is measured. +/// An owner of document faces: it asks for its keys while it is measured, and lays text out in each ready one. #[derive(Component)] struct Owner { #[common] common: Common, keys: Vec, - loads_fail: bool, tally: Tally, } @@ -61,10 +64,15 @@ impl Component for Owner { fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { for key in &self.keys { - let state = cx.document_face(key, || { - self.tally.loads.fetch_add(1, Ordering::Relaxed); - (!self.loads_fail).then(|| FaceBytes::new(Arc::from(FONT), 0)) + let loads = Arc::clone(&self.tally.loads); + let state = cx.document_face(key, move || { + loads.fetch_add(1, Ordering::Relaxed); + Some(FaceBytes::new(Arc::from(FONT), 0)) }); + if let FaceState::Ready(font) = &state { + let runs = [DocRun::new("Ag", font.clone(), 14.0, DataColor::new(Color32::BLACK))]; + let _ = cx.layout_doc(&DocText::new(&runs)); + } self.tally.states.lock().expect("the states").insert(key.clone(), state); } Vec2::splat(1.0) @@ -79,39 +87,81 @@ fn keys(range: std::ops::Range) -> Vec { range.map(|n| format!("k{n}")).collect() } -/// One frame in which each `(salt, keys)` owner asks for its keys. -fn frame(frames: &mut Frames, tally: &Tally, owners: &[(&'static str, Vec)], loads_fail: bool) { +/// Frames whose host runs background jobs only when the trial says so. +fn rig() -> (Frames, Arc, Tally) { + let jobs = Arc::new(ManualJobs::new()); + let host = Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).jobs(jobs.clone()).build()); + let mut frames = Frames::new(); + frames.host(host); + (frames, jobs, Tally::default()) +} + +/// One frame in which an owner asks for `keys`. +fn frame(frames: &mut Frames, tally: &Tally, keys: &[String]) { frames.frame(vec![], |ui| { - for (salt, keys) in owners { - Owner { common: Common::new(), keys: keys.clone(), loads_fail, tally: tally.clone() }.id_salt(*salt).show(ui); - } + Owner { common: Common::new(), keys: keys.to_vec(), tally: tally.clone() }.show(ui); }); } -/// Frames until every key of `owners` is ready. -fn until_ready(frames: &mut Frames, tally: &Tally, owners: &[(&'static str, Vec)]) { - for _ in 0..FRAMES_TO_READY { - frame(frames, tally, owners, false); - if owners.iter().flat_map(|(_, keys)| keys).all(|key| matches!(tally.state(key), FaceState::Ready(_))) { - return; - } - } - panic!("the faces did not become ready in {FRAMES_TO_READY} frames"); +/// Asks for `keys`, runs the loads and shows the frame after: every key is ready. +fn shown(frames: &mut Frames, jobs: &ManualJobs, tally: &Tally, keys: &[String]) { + frame(frames, tally, keys); + jobs.run_all(); + frame(frames, tally, keys); + assert!(tally.all_ready(keys), "the faces are ready in the pass after their loads"); +} + +/// The atlas generation, after the owners laid text out in their ready faces: egui makes its fonts again, and a new +/// atlas with them, when a face changes its definitions. +fn generation(frames: &Frames) -> u64 { + frames.ctx.fonts(|fonts| fonts.atlas_generation()) } -/// A stack install sets the whole definitions and drops the faces added one by one: the registry notices and adds -/// them again, within the budget. #[trial] -fn faces_are_registered_again_after_the_definitions_are_replaced() { - let (mut frames, tally) = (Frames::new(), Tally::default()); - let owners = [("owner", keys(0..3))]; - until_ready(&mut frames, &tally, &owners); - assert_eq!(tally.loads(), 3); +fn a_catalog_face_loads_off_the_pass_and_is_ready_in_the_pass_after_its_load() { + let (mut frames, jobs, tally) = rig(); + let wanted = keys(0..3); + frame(&mut frames, &tally, &wanted); + frame(&mut frames, &tally, &wanted); + assert_eq!(tally.loads(), 0, "no pass loads a face itself"); + assert!(wanted.iter().all(|key| tally.state(key) == FaceState::Loading)); + jobs.run_all(); + frame(&mut frames, &tally, &wanted); + assert!(tally.all_ready(&wanted)); + assert_eq!(tally.loads(), 3, "each face loads once, however many passes asked"); +} +#[trial] +fn faces_arriving_keep_the_fonts_egui_made() { + let (mut frames, jobs, tally) = rig(); + let first = keys(0..2); + shown(&mut frames, &jobs, &tally, &first); + let before = generation(&frames); + let more = keys(0..8); + shown(&mut frames, &jobs, &tally, &more); + frame(&mut frames, &tally, &more); + assert_eq!(generation(&frames), before, "the new faces join the fonts egui has, which it keeps"); +} + +#[trial] +fn scrolling_back_over_faces_drawn_before_loads_none_again() { + let (mut frames, jobs, tally) = rig(); + for start in (0..120).step_by(20) { + shown(&mut frames, &jobs, &tally, &keys(start..start + 20)); + } + assert_eq!(tally.loads(), 120); + frame(&mut frames, &tally, &keys(0..20)); + assert!(tally.all_ready(&keys(0..20)), "the first faces are still kept"); + assert_eq!(tally.loads(), 120, "and load nothing again"); +} + +#[trial] +fn faces_stay_ready_after_the_definitions_are_replaced() { + let (mut frames, jobs, tally) = rig(); + let wanted = keys(0..3); + shown(&mut frames, &jobs, &tally, &wanted); fonts::load(&frames.ctx, craft_ui::fonts::deflated_default_definitions()); - frame(&mut frames, &tally, &owners, false); - assert!(keys(0..3).iter().all(|key| tally.state(key) == FaceState::Loading), "the replaced faces wait for their registration"); - assert_eq!(tally.loads(), 6, "each face loads again"); - until_ready(&mut frames, &tally, &owners); - assert_eq!(tally.loads(), 6); + frame(&mut frames, &tally, &wanted); + assert!(tally.all_ready(&wanted), "egui finds the served faces again"); + assert_eq!(tally.loads(), 3, "without loading them again"); } diff --git a/crates/ui-contract/tests/it/fonts/face_run.rs b/crates/ui-contract/tests/it/fonts/face_run.rs index 98a1eaf0b..a4933d03b 100644 --- a/crates/ui-contract/tests/it/fonts/face_run.rs +++ b/crates/ui-contract/tests/it/fonts/face_run.rs @@ -102,9 +102,8 @@ fn first_baseline(galley: &Galley) -> f32 { #[trial] fn a_face_run_draws_in_its_face_at_its_size_on_its_baseline() { let (mut frames, loads) = (Frames::new(), Arc::default()); - let first = frame(&mut frames, "Typed", 30.0, &loads); - assert_eq!(font_of(&first).family, FontFamily::Proportional, "until its face is installed the run is in the interface face"); - let shape = until_in_face(&mut frames, "Typed", 30.0, &loads); + // The app holds the face's bytes, so the run is drawn in its face in the pass that registers it. + let shape = frame(&mut frames, "Typed", 30.0, &loads); let font = font_of(&shape); assert!(matches!(font.family, FontFamily::Name(_)), "the face's own family: {:?}", font.family); assert_eq!(font.size, 30.0, "the run's own size"); From de01d25a5292795aefbb1339b62c2a5c9398f462 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 23 Nov 2026 03:06:37 +0000 Subject: [PATCH 2/6] font-catalog: name the per-file slot type (clippy type_complexity) --- crates/font-catalog/src/catalog.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/font-catalog/src/catalog.rs b/crates/font-catalog/src/catalog.rs index 1dd9f0f3f..a1325a56e 100644 --- a/crates/font-catalog/src/catalog.rs +++ b/crates/font-catalog/src/catalog.rs @@ -321,9 +321,12 @@ pub struct Catalog { loaded: Mutex>, /// 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 /// one collection loading on several threads read it once and share the bytes. - files: Mutex>>>>>, + files: Mutex>, } +/// One file's shared bytes while any face of it is loaded, behind the lock held while the file is read. +type FileSlot = Arc>>>; + fn lock(m: &Mutex) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(PoisonError::into_inner) } From 1fadb034530c0c056aee6c20146cfa5d8f7d98ec Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 23 Nov 2026 03:25:59 +0000 Subject: [PATCH 3/6] Document faces: one queue per context, lost loads fail, replays mark faces drawn, one byte budget - The load queue is made once per context, as TextureLoader's is: without a host, default_jobs() returned a new Arc each call, so every new face made a new queue and dropped the loads before it. - The begin-pass step marks a face unavailable when its load is neither queued nor running and delivered no result (a job that panicked), so the row stops asking for passes. - A kept face's draw mark is journaled, so a settled view's replay marks the faces its run drew and eviction keeps them while on screen. - One budget over the files the registry keeps plus the files egui still holds for faces taken out. Past it, the faces drawn longest ago go down to half the budget and egui's fonts are made again once. The budget is a registry field; trials set it with testing::document_face_budget. - FacesCx::document_face takes a closure that makes the load, called only for a new key, so a ready face clones no FaceInfo or catalog. - Similar fonts weigh a family by its file's raw usWeightClass again (FaceInfo::weight_class, None without OS/2; 400 then), not the scan's weight. The review point that families without OS/2 data now join Similar fonts was checked: the old read_traits listed them too, with zero PANOSE and weight 400, so they stay. --- crates/font-catalog/src/scan.rs | 4 + crates/font-manager/src/panel/faces.rs | 6 +- crates/font-manager/src/picker/rank.rs | 2 +- crates/ui-contract/src/contract/faces.rs | 14 +- crates/ui-contract/src/fonts/document.rs | 141 ++++++++++++------ crates/ui-contract/src/primitives/faces.rs | 18 ++- crates/ui-contract/src/testing/mod.rs | 2 + crates/ui-contract/tests/it/fonts/document.rs | 140 +++++++++++++++-- 8 files changed, 259 insertions(+), 68 deletions(-) diff --git a/crates/font-catalog/src/scan.rs b/crates/font-catalog/src/scan.rs index 3705f24f8..d79c83f8f 100644 --- a/crates/font-catalog/src/scan.rs +++ b/crates/font-catalog/src/scan.rs @@ -96,6 +96,8 @@ pub struct FaceInfo { pub fs_type: u16, /// The OS/2 code page bits (`ulCodePageRange1`, `ulCodePageRange2`). pub code_pages: [u32; 2], + /// The OS/2 `usWeightClass` as the file states it; `None` without an OS/2 table. A named instance has its file's. + pub weight_class: Option, /// The OS/2 `sFamilyClass` (high byte: the IBM class; 0 without an OS/2 table). pub family_class: i16, /// The OS/2 PANOSE digits (all 0 without an OS/2 table). @@ -314,6 +316,7 @@ pub(crate) fn font_faces(font: &skrifa::FontRef<'_>, outlines: Outlines, index: }); let fs_type = os2.as_ref().map_or(0, |t| t.fs_type()); let code_pages = os2.as_ref().map_or([0, 0], |t| [t.ul_code_page_range_1().unwrap_or(0), t.ul_code_page_range_2().unwrap_or(0)]); + let weight_class = os2.as_ref().map(|t| t.us_weight_class()); let family_class = os2.as_ref().map_or(0, |t| t.s_family_class()); let mut panose = [0u8; 10]; if let Some(digits) = os2.as_ref().map(|t| t.panose_10()) { @@ -345,6 +348,7 @@ pub(crate) fn font_faces(font: &skrifa::FontRef<'_>, outlines: Outlines, index: outlines, fs_type, code_pages, + weight_class, family_class, panose, fixed_pitch, diff --git a/crates/font-manager/src/panel/faces.rs b/crates/font-manager/src/panel/faces.rs index 254a3915a..655c7e212 100644 --- a/crates/font-manager/src/panel/faces.rs +++ b/crates/font-manager/src/panel/faces.rs @@ -49,8 +49,10 @@ pub(crate) fn shown(at: &impl FacesCx, catalog: &Arc, owner: Owner, fac if face.file_bytes.is_some_and(|bytes| bytes > MAX_FILE_BYTES) { return Shown::Unavailable; } - let (catalog, info) = (Arc::clone(catalog), face.clone()); - at.document_face(&key(owner, face), move || load(&catalog, &info)) + at.document_face(&key(owner, face), || { + let (catalog, info) = (Arc::clone(catalog), face.clone()); + move || load(&catalog, &info) + }) } /// The bytes of `face` once [`shown`] has it ready, for reading its tables without loading the file again. diff --git a/crates/font-manager/src/picker/rank.rs b/crates/font-manager/src/picker/rank.rs index 09113d9b8..98657ddbd 100644 --- a/crates/font-manager/src/picker/rank.rs +++ b/crates/font-manager/src/picker/rank.rs @@ -157,7 +157,7 @@ pub(super) fn shown_name(info: &Info, family: &str, language: &str, english: boo /// A face's class, PANOSE and weight from its `OS/2` and `post` tables, as the catalog's scan recorded them. fn read_traits(face: &FaceInfo) -> Traits { - let weight = face.weight.round().clamp(1.0, 1000.0) as u16; + let weight = face.weight_class.unwrap_or(400).clamp(1, 1000); Traits { class: classify(&face.family, face.family_class, face.panose, face.fixed_pitch), panose: face.panose, weight } } diff --git a/crates/ui-contract/src/contract/faces.rs b/crates/ui-contract/src/contract/faces.rs index b0dcefe9e..380720ad0 100644 --- a/crates/ui-contract/src/contract/faces.rs +++ b/crates/ui-contract/src/contract/faces.rs @@ -6,8 +6,11 @@ use crate::fonts::{FaceBytes, FaceState}; use crate::primitives::FacesCx; impl FacesCx for Cx<'_, C> { - fn document_face(&self, key: &str, load: impl FnOnce() -> Option + Send + 'static) -> FaceState { - DocumentFaces::face(&self.core.ctx, key, load) + fn document_face(&self, key: &str, job: impl FnOnce() -> L) -> FaceState + where + L: FnOnce() -> Option + Send + 'static, + { + DocumentFaces::face(&self.core.ctx, key, job) } fn document_face_bytes(&self, key: &str) -> Option { @@ -16,8 +19,11 @@ impl FacesCx for Cx<'_, C> { } impl FacesCx for MeasureCx<'_, C> { - fn document_face(&self, key: &str, load: impl FnOnce() -> Option + Send + 'static) -> FaceState { - DocumentFaces::face(self.ui.ctx(), key, load) + fn document_face(&self, key: &str, job: impl FnOnce() -> L) -> FaceState + where + L: FnOnce() -> Option + Send + 'static, + { + DocumentFaces::face(self.ui.ctx(), key, job) } fn document_face_bytes(&self, key: &str) -> Option { diff --git a/crates/ui-contract/src/fonts/document.rs b/crates/ui-contract/src/fonts/document.rs index d227f759d..3cf1ff52c 100644 --- a/crates/ui-contract/src/fonts/document.rs +++ b/crates/ui-contract/src/fonts/document.rs @@ -11,27 +11,34 @@ //! way the face reaches egui as a served family (`egui_fonts::serve_face`), which egui parses the first time text is //! laid out in it: a face arriving drops nothing egui has parsed or laid out. //! -//! The registry keeps faces up to [`MAX_DOCUMENT_FACE_BYTES`] of font files; past it the faces drawn longest ago go, -//! and faces drawn in the last frame always stay. +//! The registry keeps faces up to [`MAX_DOCUMENT_FACE_BYTES`] of font files, counted with the files egui still holds +//! for faces taken out; past it the faces drawn longest ago go, and faces drawn in the last frame always stay. A face a +//! settled view shows by replaying its last run counts as drawn: the replay marks it (`runtime::replay::journal`). use std::collections::{HashMap, HashSet}; use std::sync::Arc; use craft_host::queue::{JobQueue, Priority, QueueOptions}; -use craft_host::{Jobs, Wake, default_jobs}; +use craft_host::{Wake, default_jobs}; use egui::epaint::text::{Blob, FontTweak, VariationCoords}; use egui::{Context, FontData}; use super::FontRef; use crate::runtime::egui::{fonts as egui_fonts, memory, pass, repaint}; use crate::runtime::env::Env; -use crate::runtime::frame; +use crate::runtime::{frame, replay}; -/// The font file bytes the registry keeps faces of, a collection counted once. Past it the faces drawn longest ago -/// are taken out; and once the files of faces taken out (which egui keeps parsed until its fonts are made again) pass -/// it too, egui's fonts are made again to free them. +/// The ceiling on the font file bytes of document faces: the files the registry keeps faces of (a collection counted +/// once) plus the files of faces taken out, which egui keeps parsed until its fonts are made again. When the two pass +/// it, the faces drawn longest ago are taken out until the kept files are at most `1 / LOW_MARK_DIVISOR` of it, and +/// egui's fonts are made again once to free what was taken out. The sum passes the ceiling only by the faces drawn in +/// the last frame, which always stay, and by the faces that land in one pass. pub const MAX_DOCUMENT_FACE_BYTES: usize = 512 << 20; +/// Eviction takes the kept files down to the budget divided by this, so egui's fonts are made again once per half a +/// budget of new faces, not for each face that lands past the budget. +const LOW_MARK_DIVISOR: usize = 2; + /// The bytes of a face, its index in a collection and its variation coordinates (axis tag, value). #[derive(Clone)] #[non_exhaustive] @@ -92,15 +99,13 @@ struct Registered { used: u64, } -/// The queue the catalog loads run on, with the `Jobs` it spawns lanes on and its lane count. +/// The queue the catalog loads run on, with its lane count. struct Queue { - jobs: Arc, lanes: usize, queue: Arc>>, } /// The context's document faces, by family name. -#[derive(Default)] struct Registry { faces: HashMap, failed: HashSet, @@ -109,28 +114,47 @@ struct Registry { queue: Option, /// The bytes of files whose faces were taken out since egui's fonts were last made again. withdrawn: usize, + /// [`MAX_DOCUMENT_FACE_BYTES`], or a trial's own (`testing::document_face_budget`). + budget: usize, frame: u64, hooked: bool, } +impl Default for Registry { + fn default() -> Self { + Registry { + faces: HashMap::new(), + failed: HashSet::new(), + loading: HashMap::new(), + queue: None, + withdrawn: 0, + budget: MAX_DOCUMENT_FACE_BYTES, + frame: 0, + hooked: false, + } + } +} + impl Registry { - /// Past the budget, takes out the faces drawn longest ago (never one the last frame drew) and returns their - /// names; the bytes of files no kept face shares count as withdrawn. - fn evict(&mut self, now: u64) -> Vec { + /// When the kept and withdrawn files pass the budget, takes out the faces drawn longest ago (never one the last + /// frame drew) down to the low mark, and returns their names and whether egui's fonts are made again to free the + /// withdrawn files. + fn evict(&mut self, now: u64) -> (Vec, bool) { let mut files: HashMap = HashMap::new(); for face in self.faces.values() { files.entry(face.face.file()).or_insert((face.face.bytes.len(), 0)).1 += 1; } let mut held: usize = files.values().map(|(bytes, _)| bytes).sum(); - if held <= MAX_DOCUMENT_FACE_BYTES { - return Vec::new(); + if held + self.withdrawn <= self.budget { + return (Vec::new(), false); } + let low = self.budget / LOW_MARK_DIVISOR; let mut stale: Vec<(u64, String)> = self.faces.iter().filter(|(_, face)| face.used + 1 < now).map(|(name, face)| (face.used, name.clone())).collect(); stale.sort(); let mut gone = Vec::new(); for (_, name) in stale { - if held <= MAX_DOCUMENT_FACE_BYTES { + if held <= low { break; } let Some(face) = self.faces.remove(&name) else { continue }; @@ -143,7 +167,7 @@ impl Registry { } gone.push(name); } - gone + (gone, std::mem::take(&mut self.withdrawn) > 0) } } @@ -174,25 +198,23 @@ enum Known { New, } -/// The queue of `ctx`'s catalog loads, made again when the host's `Jobs` changes. +/// The queue of `ctx`'s catalog loads: made on first use on the host's `Jobs` (`default_jobs` without a host) and kept +/// for the context's life, as `TextureLoader::in_context` keeps its own. fn queue_of(ctx: &Context, registry: &mut Registry) -> Arc>> { - let jobs = Env::host_of(ctx).map_or_else(default_jobs, |host| Arc::clone(host.jobs_shared())); - match ®istry.queue { - Some(queue) if Arc::ptr_eq(&queue.jobs, &jobs) => Arc::clone(&queue.queue), - _ => { - let wake_ctx = ctx.clone(); - let wake = Wake::new(move || repaint::request(&wake_ctx)); - let lanes = QueueOptions::default_lanes(); - let queue = Arc::new(JobQueue::new(Arc::clone(&jobs), wake, QueueOptions { lanes, name: "craft-document-faces" })); - registry.loading.clear(); - registry.queue = Some(Queue { jobs, lanes, queue: Arc::clone(&queue) }); - queue - } + if let Some(queue) = ®istry.queue { + return Arc::clone(&queue.queue); } + let jobs = Env::host_of(ctx).map_or_else(default_jobs, |host| Arc::clone(host.jobs_shared())); + let wake_ctx = ctx.clone(); + let wake = Wake::new(move || repaint::request(&wake_ctx)); + let lanes = QueueOptions::default_lanes(); + let queue = Arc::new(JobQueue::new(jobs, wake, QueueOptions { lanes, name: "craft-document-faces" })); + registry.queue = Some(Queue { lanes, queue: Arc::clone(&queue) }); + queue } -/// The begin-pass step: drops the loads no frame asked for lately, serves the faces that landed and takes out the faces -/// past the budget. Before anything of the pass is laid out, so a rebuild of egui's fonts it asks for applies at once. +/// The begin-pass step: drops the loads no frame asked for lately, serves the faces that landed, marks unavailable the +/// faces whose load ended without landing (a job that panicked) and takes out the faces past the budget. Before anything of the pass is laid out, so a rebuild of egui's fonts it asks for applies at once. fn begin_pass(ctx: &Context) { let now = pass::root_frame_nr(ctx); let inline = memory::with::(ctx, |registry| { @@ -209,11 +231,19 @@ fn begin_pass(ctx: &Context) { let loading = &mut registry.loading; loading.retain(|_, asked| *asked + 1 >= now); queue.reprioritize(|key, priority| loading.contains_key(key).then_some(priority)); + // A job leaves the running ones and files its result under the queue's one lock, so a key neither queued + // nor running here is among the results taken after, or its job ended without one. + let mut lost: Vec = loading.keys().filter(|key| !queue.contains(key)).cloned().collect(); while let Some(finished) = queue.try_recv() { + lost.retain(|key| *key != finished.key); if loading.remove(&finished.key).is_some() { landed.push((finished.key, finished.result)); } } + for key in lost { + loading.remove(&key); + registry.failed.insert(key); + } } for (name, result) in &landed { match result { @@ -225,11 +255,7 @@ fn begin_pass(ctx: &Context) { } } } - let gone = registry.evict(now); - let rebuild = registry.withdrawn > MAX_DOCUMENT_FACE_BYTES; - if rebuild { - registry.withdrawn = 0; - } + let (gone, rebuild) = registry.evict(now); (landed, gone, rebuild) }); for (name, face) in landed { @@ -245,6 +271,23 @@ fn begin_pass(ctx: &Context) { } } +/// Marks the kept face `name` drawn in this frame: a replay's journal entry. +fn mark_drawn(ctx: &Context, name: &str) { + memory::with::(ctx, |registry| { + let now = registry.frame; + if let Some(face) = registry.faces.get_mut(name) { + face.used = now; + } + }); +} + +/// Sets the budget of `ctx`'s document faces to `bytes` in place of [`MAX_DOCUMENT_FACE_BYTES`], so a trial reaches +/// it with a few faces. +#[cfg(feature = "testing")] +pub fn set_budget(ctx: &Context, bytes: usize) { + memory::with::(ctx, |registry| registry.budget = bytes); +} + /// Hooks the begin-pass step on the context's fonts plugin. fn begin(ctx: &Context) { let hook = memory::with::(ctx, |registry| !std::mem::replace(&mut registry.hooked, true)); @@ -258,11 +301,15 @@ fn begin(ctx: &Context) { pub(crate) struct DocumentFaces; impl DocumentFaces { - /// The face registered under `key` as a family of its own. `load` reads it from a font catalog: it runs as a job, - /// once per key while the face is kept, and the face is ready from the pass after the job ends. A `load` that - /// returns `None`, or bytes egui cannot read, marks the key unavailable for as long as the context lives. Every call + /// The face registered under `key` as a family of its own. The load `job()` makes reads it from a font catalog: + /// `job` is called only for a key the registry does not know, and its load runs as a job, once per key while the + /// face is kept; the face is ready from the pass after the job ends. A load that returns `None`, bytes egui cannot + /// read, or a job that ends without a result marks the key unavailable for as long as the context lives. Every call /// marks the face drawn in this frame; a load no frame asks for any more is dropped. - pub(crate) fn face(ctx: &Context, key: &str, load: impl FnOnce() -> Option + Send + 'static) -> FaceState { + pub(crate) fn face(ctx: &Context, key: &str, job: impl FnOnce() -> L) -> FaceState + where + L: FnOnce() -> Option + Send + 'static, + { let name = Kind::Alone.family_name(key); match Self::known(ctx, &name) { Known::Failed => FaceState::Unavailable, @@ -277,6 +324,7 @@ impl DocumentFaces { // A measuring run starts the load too: the registry is a cache, and a face loads the same whichever // run asks. frame::request_repaint(ctx); + let load = job(); memory::with::(ctx, |registry| { let queue = queue_of(ctx, registry); registry.loading.insert(name.clone(), registry.frame); @@ -328,10 +376,11 @@ impl DocumentFaces { memory::with::(ctx, |registry| registry.faces.get(&name).map(|face| face.face.clone())) } - /// What the registry knows of `name`, marking a kept face drawn and a load asked for in this frame. + /// What the registry knows of `name`, marking a kept face drawn and a load asked for in this frame. The mark of a + /// kept face is journaled, so a settled view's replay marks the faces its run drew. fn known(ctx: &Context, name: &str) -> Known { begin(ctx); - memory::with::(ctx, |registry| { + let known = memory::with::(ctx, |registry| { let now = registry.frame; if registry.failed.contains(name) { Known::Failed @@ -344,7 +393,11 @@ impl DocumentFaces { } else { Known::New } - }) + }); + if matches!(known, Known::Ready) { + replay::journal_distinct(ctx, || name.to_owned(), |ctx, name: &String| mark_drawn(ctx, name)); + } + known } /// A kept face's state: ready once egui lays text out with the served faces. diff --git a/crates/ui-contract/src/primitives/faces.rs b/crates/ui-contract/src/primitives/faces.rs index 27d34eea6..ba3cf7bc0 100644 --- a/crates/ui-contract/src/primitives/faces.rs +++ b/crates/ui-contract/src/primitives/faces.rs @@ -6,10 +6,13 @@ use crate::fonts::{FaceBytes, FaceState}; /// Where a document face is asked for: a component's context, its measure or a content painter. pub trait FacesCx { - /// The face registered under `key` as a family of its own, read from a font catalog. `load` runs as a background - /// job, once while the face is kept, and the face is ready from the pass after it ends. A `load` that returns - /// `None` marks the key unavailable for as long as the context lives. Every call marks the face drawn in this frame. - fn document_face(&self, key: &str, load: impl FnOnce() -> Option + Send + 'static) -> FaceState; + /// The face registered under `key` as a family of its own, read from a font catalog. `job` is called only for a + /// key the registry does not know (a ready face costs nothing) and makes the load, which runs as a background job, + /// once while the face is kept; the face is ready from the pass after it ends. A load that returns `None` marks the + /// key unavailable for as long as the context lives. Every call marks the face drawn in this frame. + fn document_face(&self, key: &str, job: impl FnOnce() -> L) -> FaceState + where + L: FnOnce() -> Option + Send + 'static; /// The bytes of the face `document_face` registered under `key`, once it is ready: for reading its tables without /// loading the file again. @@ -17,8 +20,11 @@ pub trait FacesCx { } impl FacesCx for ContentPainterCx<'_> { - fn document_face(&self, key: &str, load: impl FnOnce() -> Option + Send + 'static) -> FaceState { - DocumentFaces::face(self.painter.ctx(), key, load) + fn document_face(&self, key: &str, job: impl FnOnce() -> L) -> FaceState + where + L: FnOnce() -> Option + Send + 'static, + { + DocumentFaces::face(self.painter.ctx(), key, job) } fn document_face_bytes(&self, key: &str) -> Option { diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index c2a06851e..23c7e051a 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -48,6 +48,8 @@ pub mod wheel; pub mod windows; pub use crate::contract::{Exemption, PatternKind, PatternProbe, Probe, Registration}; +#[cfg(feature = "testing")] +pub use crate::fonts::document::set_budget as document_face_budget; pub use crate::runtime::audit::{in_run as in_audit_run, set as audit_replays}; #[cfg(feature = "testing")] pub use crate::runtime::layout_memory::forget_kept as forget_measurements; diff --git a/crates/ui-contract/tests/it/fonts/document.rs b/crates/ui-contract/tests/it/fonts/document.rs index 892c2545b..310c78c48 100644 --- a/crates/ui-contract/tests/it/fonts/document.rs +++ b/crates/ui-contract/tests/it/fonts/document.rs @@ -1,17 +1,19 @@ //! Document faces read from a catalog: loaded off the pass, ready from the pass after, kept across a definitions -//! replacement and while drawn lately, and served to egui without making its fonts again. +//! replacement and while drawn lately (a settled view's replay counts), served to egui without making its fonts again, +//! and held within one budget. use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, LazyLock, Mutex}; +use std::time::Duration; use craft_behavior::Metrics; use craft_host::{AppInfo, Host, ManualJobs}; -use craft_ui::contract::{Common, Component, Cx, FacesCx as _, MeasureCx, Role, Show as _}; +use craft_ui::contract::{Common, Component, Cx, FacesCx, MeasureCx, MemoView, Role, Show as _}; use craft_ui::fonts::{self, FaceBytes, FaceState}; use craft_ui::primitives::{DocRun, DocText}; use craft_ui::style::{ComponentStyle, DataColor, StyleCx}; -use craft_ui::testing::{Frames, trial}; +use craft_ui::testing::{Frames, MemoRun, document_face_budget, last_frame_memo_runs, trial}; use egui::{Color32, Response, Vec2}; const FONT: &[u8] = include_bytes!("../../fonts/NotoSans-test.ttf"); @@ -44,13 +46,27 @@ impl Tally { } } -/// An owner of document faces: it asks for its keys while it is measured, and lays text out in each ready one. +/// Asks for the face `key`, whose load counts itself in `tally`; a key starting with `panic` names a load that panics. +fn ask(cx: &impl FacesCx, key: &str, tally: &Tally) -> FaceState { + cx.document_face(key, || { + let (loads, panics) = (Arc::clone(&tally.loads), key.starts_with("panic")); + move || { + loads.fetch_add(1, Ordering::Relaxed); + assert!(!panics, "a load that panics"); + Some(FaceBytes::new(Arc::from(FONT), 0)) + } + }) +} + +/// An owner of document faces: it asks for its keys while it is measured, and lays text out in each ready one; or, +/// with `in_run`, asks for them in its run only. #[derive(Component)] struct Owner { #[common] common: Common, keys: Vec, tally: Tally, + in_run: bool, } impl Component for Owner { @@ -63,12 +79,11 @@ impl Component for Owner { } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + if self.in_run { + return Vec2::splat(1.0); + } for key in &self.keys { - let loads = Arc::clone(&self.tally.loads); - let state = cx.document_face(key, move || { - loads.fetch_add(1, Ordering::Relaxed); - Some(FaceBytes::new(Arc::from(FONT), 0)) - }); + let state = ask(cx, key, &self.tally); if let FaceState::Ready(font) = &state { let runs = [DocRun::new("Ag", font.clone(), 14.0, DataColor::new(Color32::BLACK))]; let _ = cx.layout_doc(&DocText::new(&runs)); @@ -79,6 +94,12 @@ impl Component for Owner { } fn finish(self, cx: Cx<'_, Self>) -> Response { + if self.in_run { + for key in &self.keys { + let state = ask(&cx, key, &self.tally); + self.tally.states.lock().expect("the states").insert(key.clone(), state); + } + } cx.response.clone() } } @@ -99,7 +120,7 @@ fn rig() -> (Frames, Arc, Tally) { /// One frame in which an owner asks for `keys`. fn frame(frames: &mut Frames, tally: &Tally, keys: &[String]) { frames.frame(vec![], |ui| { - Owner { common: Common::new(), keys: keys.to_vec(), tally: tally.clone() }.show(ui); + Owner { common: Common::new(), keys: keys.to_vec(), tally: tally.clone(), in_run: false }.show(ui); }); } @@ -165,3 +186,100 @@ fn faces_stay_ready_after_the_definitions_are_replaced() { assert!(tally.all_ready(&wanted), "egui finds the served faces again"); assert_eq!(tally.loads(), 3, "without loading them again"); } + +/// Without a host the loads run on `default_jobs`' threads: every face asked for in one pass lands, each loaded once. +#[trial] +fn without_a_host_every_face_asked_for_in_one_pass_lands() { + let mut frames = Frames::new(); + let tally = Tally::default(); + let wanted = keys(0..8); + for _ in 0..1000 { + frame(&mut frames, &tally, &wanted); + if tally.all_ready(&wanted) { + break; + } + std::thread::sleep(Duration::from_millis(1)); + } + assert!(tally.all_ready(&wanted), "every face lands"); + assert_eq!(tally.loads(), 8, "and none was cancelled and loaded again"); +} + +#[trial] +fn a_load_that_panics_leaves_its_face_unavailable_and_asks_for_no_more_passes() { + let (mut frames, jobs, tally) = rig(); + let wanted = vec!["panic".to_owned()]; + frame(&mut frames, &tally, &wanted); + jobs.run_all(); + frame(&mut frames, &tally, &wanted); + assert_eq!(tally.state("panic"), FaceState::Unavailable); + frame(&mut frames, &tally, &wanted); + assert!(!frames.repaint_requested(), "the row stops asking for passes"); +} + +/// The tally of the memoized view's owner: its `show` is a function, so it reaches the tally by name. +static MEMOIZED: LazyLock = LazyLock::new(Tally::default); + +fn memoized(_: &mut u32, ui: &mut egui::Ui) { + Owner { common: Common::new(), keys: vec!["m0".to_owned(), "m1".to_owned()], tally: MEMOIZED.clone(), in_run: true }.show(ui); +} + +/// One frame of the memoized view beside an owner that asks for `keys`. +fn memo_frame(frames: &mut Frames, tally: &Tally, keys: &[String]) { + frames.frame(vec![], |ui| { + MemoView::new("faces", 1u32, memoized).show(ui); + Owner { common: Common::new(), keys: keys.to_vec(), tally: tally.clone(), in_run: false }.show(ui); + }); +} + +#[trial] +fn a_settled_view_that_replays_keeps_its_faces() { + let (mut frames, jobs, tally) = rig(); + let font = FONT.len(); + document_face_budget(&frames.ctx, 3 * font); + memo_frame(&mut frames, &tally, &[]); + jobs.run_all(); + for _ in 0..3 { + memo_frame(&mut frames, &tally, &[]); + } + assert!(MEMOIZED.all_ready(&["m0".to_owned(), "m1".to_owned()])); + let mut replayed = 0; + for start in (0..8).step_by(2) { + let others = keys(start..start + 2); + memo_frame(&mut frames, &tally, &others); + jobs.run_all(); + memo_frame(&mut frames, &tally, &others); + replayed += last_frame_memo_runs(&frames.ctx).iter().filter(|(_, _, run)| *run == MemoRun::Replayed).count(); + } + assert!(replayed > 0, "the view replays while the other faces push the registry past its budget"); + frame(&mut frames, &tally, &["m0".to_owned(), "m1".to_owned()]); + assert!(tally.all_ready(&["m0".to_owned(), "m1".to_owned()]), "the faces the replays showed are kept"); + assert_eq!(MEMOIZED.loads(), 2, "and were loaded once"); +} + +#[trial] +fn past_the_budget_the_faces_drawn_longest_ago_go_and_the_fonts_are_made_again_once() { + let (mut frames, jobs, tally) = rig(); + let font = FONT.len(); + document_face_budget(&frames.ctx, 6 * font); + // `keep` is drawn in every frame; one more face joins it each step. + let step = |frames: &mut Frames, key: &str| { + let wanted = vec!["keep".to_owned(), key.to_owned()]; + shown(frames, &jobs, &tally, &wanted); + generation(frames) + }; + let before = step(&mut frames, "k0"); + let filling: Vec = ["k1", "k2", "k3", "k4"].iter().map(|key| step(&mut frames, key)).collect(); + assert!(filling.iter().all(|g| *g == before), "within the budget nothing is taken out"); + let after = step(&mut frames, "k5"); + assert_ne!(after, before, "past it, egui's fonts are made again to free what went"); + for _ in 0..3 { + frame(&mut frames, &tally, &["keep".to_owned(), "k5".to_owned()]); + } + assert_eq!(generation(&frames), after, "once, not every frame"); + let all: Vec = ["keep", "k0", "k1", "k2", "k3", "k4", "k5"].iter().map(|key| (*key).to_owned()).collect(); + frame(&mut frames, &tally, &all); + let ready = |key: &str| matches!(tally.state(key), FaceState::Ready(_)); + assert!(ready("keep"), "a face drawn in the last frame stays, the first loaded included"); + assert!(["k0", "k1", "k2", "k3"].iter().all(|key| !ready(key)), "the faces drawn longest ago went"); + assert!(ready("k4") && ready("k5"), "down to half the budget, the faces drawn last stay"); +} From 8c4e115ea457c67ea53ecda38e8bbdce53ff40cc Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 23 Nov 2026 03:27:14 +0000 Subject: [PATCH 4/6] docs/contract-api.md: regenerated (document_face's job and the face bytes; also ColumnSpec::at_least and data_fill_tiled, which next's copy lacked) --- docs/contract-api.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/docs/contract-api.md b/docs/contract-api.md index 29fb7ce0c..8165c19bf 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -1971,7 +1971,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::BodyLayout`: `pub enum BodyLayout { Stack, Row { wrap: bool, align: RowAlign }, Grid { columns: Cow<'static, [ColumnWidth]>, fit: GridFit, cells: CellAlign } }`. How a body lays out its children, in reading order: mirrored under a right-to-left direction. - `pub const fn stack() -> Self`. Children one under another. - `pub const fn row() -> Self`. Children side by side from the start edge, with no wrap. - - `pub fn grid(columns: impl Into>) -> Self`. Children row-major over `columns`: a `'static` slice, or columns built in the pass. + - `pub fn grid(columns: impl Into>) -> Self`. Children row-major over `columns`: a `'static` slice, or columns built in the pass. The cells are the body's - `pub fn fit(self, fit: GridFit) -> Self`. A `Grid` with `fit`; any other layout is unchanged. - `pub fn cells(self, cells: CellAlign) -> Self`. A `Grid` with `cells`; any other layout is unchanged. - `pub fn wrap(self, on: bool) -> Self`. A `Row` that wraps; any other layout is unchanged. @@ -2038,7 +2038,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub const fn new(key: ColumnKey, descending: bool) -> Self`. Rows sorted by `key`, descending when `descending`. - `pub const fn ascending(key: ColumnKey) -> Self`. Rows sorted by `key`, ascending. - `pub const fn descending(key: ColumnKey) -> Self`. Rows sorted by `key`, descending. -- `craft_ui::contract::ColumnSpec`: `pub struct ColumnSpec { pub key: ColumnKey, pub header: Label, pub width: ColumnWidth, pub resizable: bool, pub sortable: bool, pub movable: bool, pub frozen: bool, pub kind: ColumnKind, pub align: ColumnAlign, pub tabular: bool, pub first_descending: bool, pub icon: Option, pub tip: Option