mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 00:57:26 +00:00
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.
This commit is contained in:
@@ -319,7 +319,9 @@ pub struct Catalog {
|
||||
generation: AtomicU64,
|
||||
added: Mutex<Added>,
|
||||
loaded: Mutex<HashMap<String, FamilyLoad>>,
|
||||
files: Mutex<HashMap<PathBuf, Weak<[u8]>>>,
|
||||
/// 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<HashMap<PathBuf, Arc<Mutex<Option<Weak<[u8]>>>>>>,
|
||||
}
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
@@ -581,7 +583,16 @@ impl Catalog {
|
||||
}
|
||||
|
||||
fn file_bytes(&self, path: &Path) -> Result<Arc<[u8]>, 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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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<PathBuf>,
|
||||
/// 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,
|
||||
|
||||
@@ -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)`):
|
||||
|
||||
@@ -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<FaceBytes> {
|
||||
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<Catalog>, 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<FaceBytes> {
|
||||
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
|
||||
|
||||
@@ -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<Catalog>, owner: Owner, face: &'a FaceInfo },
|
||||
/// No face is here to draw with: the sample keeps its band and shows nothing.
|
||||
Missing,
|
||||
}
|
||||
|
||||
@@ -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<FontClass>,
|
||||
/// The family's format; `None` only for a served row.
|
||||
pub format: Option<FontFormat>,
|
||||
|
||||
@@ -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<String, Info>,
|
||||
traits: Mutex<HashMap<String, Option<Traits>>>,
|
||||
samples: Mutex<HashMap<(String, String), String>>,
|
||||
}
|
||||
|
||||
@@ -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<Traits> {
|
||||
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<Traits> {
|
||||
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<FontClass> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<Traits> {
|
||||
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<FontClass> {
|
||||
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))
|
||||
})
|
||||
|
||||
@@ -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<Catalog>,
|
||||
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<Catalog>, 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();
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -6,13 +6,21 @@ use crate::fonts::{FaceBytes, FaceState};
|
||||
use crate::primitives::FacesCx;
|
||||
|
||||
impl<C: Component> FacesCx for Cx<'_, C> {
|
||||
fn document_face(&self, key: &str, load: impl FnOnce() -> Option<FaceBytes>) -> FaceState {
|
||||
fn document_face(&self, key: &str, load: impl FnOnce() -> Option<FaceBytes> + Send + 'static) -> FaceState {
|
||||
DocumentFaces::face(&self.core.ctx, key, load)
|
||||
}
|
||||
|
||||
fn document_face_bytes(&self, key: &str) -> Option<FaceBytes> {
|
||||
DocumentFaces::bytes(&self.core.ctx, key)
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Component> FacesCx for MeasureCx<'_, C> {
|
||||
fn document_face(&self, key: &str, load: impl FnOnce() -> Option<FaceBytes>) -> FaceState {
|
||||
fn document_face(&self, key: &str, load: impl FnOnce() -> Option<FaceBytes> + Send + 'static) -> FaceState {
|
||||
DocumentFaces::face(self.ui.ctx(), key, load)
|
||||
}
|
||||
|
||||
fn document_face_bytes(&self, key: &str) -> Option<FaceBytes> {
|
||||
DocumentFaces::bytes(self.ui.ctx(), key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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::<u8>() 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<dyn Jobs>,
|
||||
lanes: usize,
|
||||
queue: Arc<JobQueue<String, Option<FaceBytes>>>,
|
||||
}
|
||||
|
||||
/// The context's document faces, by family name.
|
||||
@@ -87,38 +104,46 @@ struct Registered {
|
||||
struct Registry {
|
||||
faces: HashMap<String, Registered>,
|
||||
failed: HashSet<String>,
|
||||
/// 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<String, u64>,
|
||||
queue: Option<Queue>,
|
||||
/// 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<u64>,
|
||||
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<String> {
|
||||
if self.evicted == Some(now) || self.faces.len() <= MAX_DOCUMENT_FACES {
|
||||
let mut files: HashMap<usize, (usize, usize)> = 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<String> = 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::<Registry, _>(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<JobQueue<String, Option<FaceBytes>>> {
|
||||
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::<Registry, _>(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::<Registry, _>(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::<Registry, _>(ctx, |registry| !std::mem::replace(&mut registry.hooked, true));
|
||||
if hook {
|
||||
egui_fonts::on_begin_pass(ctx, begin_pass);
|
||||
memory::with::<Registry, _>(ctx, |registry| registry.frame = pass::root_frame_nr(ctx));
|
||||
}
|
||||
let now = pass::root_frame_nr(ctx);
|
||||
memory::with::<Registry, _>(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<FaceBytes>) -> 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<FaceBytes> + 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::<Registry, _>(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<FaceBytes>) -> 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::<Registry, _>(ctx, |registry| registry.failed.insert(name));
|
||||
return FaceState::Unavailable;
|
||||
};
|
||||
let data = face.data();
|
||||
memory::with::<Registry, _>(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<FaceBytes>) -> 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<FaceBytes> {
|
||||
let name = Kind::Alone.family_name(key);
|
||||
memory::with::<Registry, _>(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::<Registry, _>(ctx, |registry| {
|
||||
let known = if registry.failed.contains(&name) {
|
||||
memory::with::<Registry, _>(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::<Registry, _>(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::<Registry, _>(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::<Registry, _>(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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<FaceBytes>) -> TextLayout {
|
||||
let ctx = self.painter.ctx();
|
||||
|
||||
@@ -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<FaceBytes>) -> 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<FaceBytes> + 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<FaceBytes>;
|
||||
}
|
||||
|
||||
impl FacesCx for ContentPainterCx<'_> {
|
||||
fn document_face(&self, key: &str, load: impl FnOnce() -> Option<FaceBytes>) -> FaceState {
|
||||
fn document_face(&self, key: &str, load: impl FnOnce() -> Option<FaceBytes> + Send + 'static) -> FaceState {
|
||||
DocumentFaces::face(self.painter.ctx(), key, load)
|
||||
}
|
||||
|
||||
fn document_face_bytes(&self, key: &str) -> Option<FaceBytes> {
|
||||
DocumentFaces::bytes(self.painter.ctx(), key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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::<Providers, _>(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<Arc<dyn FontProvider>>);
|
||||
struct Served {
|
||||
families: RwLock<HashMap<String, ServedFace>>,
|
||||
interface: RwLock<Option<Vec<FontInsert>>>,
|
||||
}
|
||||
|
||||
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<FontInsert> {
|
||||
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<Arc<dyn FontProvider>>,
|
||||
served: Arc<Served>,
|
||||
/// 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<Arc<dyn FontProvider>> {
|
||||
self.mark_served(ctx);
|
||||
self.kept.iter().cloned().chain(std::iter::once(Arc::clone(&self.served) as Arc<dyn FontProvider>)).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<Served> {
|
||||
memory::with::<Providers, _>(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<fn(&Context)>);
|
||||
|
||||
/// Sets the context's font providers and remembers them for [`reload_providers`].
|
||||
pub(crate) fn set_providers(ctx: &Context, providers: Vec<Arc<dyn FontProvider>>) {
|
||||
memory::with::<Providers, _>(ctx, |kept| kept.0.clone_from(&providers));
|
||||
ctx.set_font_providers(providers);
|
||||
let all = memory::with::<Providers, _>(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<dyn FontProvider>) {
|
||||
memory::with::<Providers, _>(ctx, |kept| kept.0.push(Arc::clone(&provider)));
|
||||
ctx.add_font_provider(provider);
|
||||
let all = memory::with::<Providers, _>(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::<Providers, _>(ctx, |kept| kept.0.clone());
|
||||
let providers = memory::with::<Providers, _>(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::<Providers, _>(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::<Providers, _>(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`.
|
||||
|
||||
@@ -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)"),
|
||||
|
||||
@@ -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<String>,
|
||||
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<usize>) -> Vec<String> {
|
||||
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<String>)], loads_fail: bool) {
|
||||
/// Frames whose host runs background jobs only when the trial says so.
|
||||
fn rig() -> (Frames, Arc<ManualJobs>, 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<String>)]) {
|
||||
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");
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
Reference in New Issue
Block a user