mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 02:09:00 +00:00
Merge pull request #3145 from aiongg/font-picker-speed
Fonts: load faces off the UI thread and serve them to egui without a rebuild (font picker speed)
This commit is contained in:
@@ -319,9 +319,14 @@ 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, FileSlot>>,
|
||||
}
|
||||
|
||||
/// One file's shared bytes while any face of it is loaded, behind the lock held while the file is read.
|
||||
type FileSlot = Arc<Mutex<Option<Weak<[u8]>>>>;
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
@@ -581,7 +586,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 +603,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,14 @@ 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<u16>,
|
||||
/// 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 +316,15 @@ 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()) {
|
||||
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 +348,10 @@ pub(crate) fn font_faces(font: &skrifa::FontRef<'_>, outlines: Outlines, index:
|
||||
outlines,
|
||||
fs_type,
|
||||
code_pages,
|
||||
weight_class,
|
||||
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,25 @@ 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;
|
||||
}
|
||||
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.
|
||||
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_class.unwrap_or(400).clamp(1, 1000);
|
||||
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();
|
||||
|
||||
@@ -50,13 +50,16 @@ fn host_with(sections: Arc<MemorySections>, jobs: Arc<dyn Jobs>) -> Arc<Host> {
|
||||
|
||||
type Task = Box<dyn FnOnce() + Send>;
|
||||
|
||||
// The job name of the framework's document-face loads (`craft_ui::fonts`), which the panel's specimens start.
|
||||
const FACE_JOBS: &str = "craft-document-faces";
|
||||
|
||||
/// Keeps the spawned jobs until the test runs them.
|
||||
#[derive(Default)]
|
||||
struct Deferred(Mutex<Vec<Task>>);
|
||||
struct Deferred(Mutex<Vec<(String, Task)>>);
|
||||
|
||||
impl Jobs for Deferred {
|
||||
fn spawn(&self, _: &str, job: Task) {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner).push(job);
|
||||
fn spawn(&self, name: &str, job: Task) {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner).push((name.to_owned(), job));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,7 +209,12 @@ fn queued_installs_run_one_runner_in_request_order() {
|
||||
rig.click("Install");
|
||||
rig.click("Install");
|
||||
|
||||
let mut spawned = std::mem::take(&mut *deferred.0.lock().unwrap_or_else(PoisonError::into_inner));
|
||||
// The cards' specimens load their faces through the same jobs; only the install runners count here.
|
||||
let mut spawned: Vec<Task> = std::mem::take(&mut *deferred.0.lock().unwrap_or_else(PoisonError::into_inner))
|
||||
.into_iter()
|
||||
.filter(|(name, _)| name != FACE_JOBS)
|
||||
.map(|(_, job)| job)
|
||||
.collect();
|
||||
assert_eq!(spawned.len(), 1, "one runner drains the queue");
|
||||
assert!(rig.store.calls().is_empty(), "nothing runs before the runner does");
|
||||
spawned.remove(0)();
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
//! Stories of the in-ribbon gallery.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_host::InlineJobs;
|
||||
use craft_ui::contract::Show as _;
|
||||
use craft_ui::list::{ThumbAspect, ThumbSize};
|
||||
use craft_ui::primitives::textures::Revision;
|
||||
@@ -171,10 +168,8 @@ fn gallery_painted(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
|
||||
#[story(Gallery<'static, usize>, covers = [], drive = Drive::Never)]
|
||||
fn gallery_rendered(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
// The source renders as a `Later` job: each tile shows the store's placeholder, then its picture. The jobs run
|
||||
// inline, so the pictures land in the next frame and not whenever a thread ends: the suite's settled frames are
|
||||
// the same on every run.
|
||||
let options = ThumbnailOptions::new().jobs(Arc::new(InlineJobs));
|
||||
// The source renders as a `Later` job: each tile shows the store's placeholder, then its picture.
|
||||
let options = ThumbnailOptions::new();
|
||||
let thumbnails = Thumbnails::<u64>::in_context(ui.ctx(), "craft_menu.gallery.story", options);
|
||||
let source = FakeThumbSource::<u64>::new().later(true);
|
||||
let items: Vec<GalleryItem<'_, usize>> = (0..COUNT)
|
||||
|
||||
@@ -6,13 +6,27 @@ 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 {
|
||||
DocumentFaces::face(&self.core.ctx, key, load)
|
||||
fn document_face<L>(&self, key: &str, job: impl FnOnce() -> L) -> FaceState
|
||||
where
|
||||
L: FnOnce() -> Option<FaceBytes> + Send + 'static,
|
||||
{
|
||||
DocumentFaces::face(&self.core.ctx, key, job)
|
||||
}
|
||||
|
||||
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 {
|
||||
DocumentFaces::face(self.ui.ctx(), key, load)
|
||||
fn document_face<L>(&self, key: &str, job: impl FnOnce() -> L) -> FaceState
|
||||
where
|
||||
L: FnOnce() -> Option<FaceBytes> + Send + 'static,
|
||||
{
|
||||
DocumentFaces::face(self.ui.ctx(), key, job)
|
||||
}
|
||||
|
||||
fn document_face_bytes(&self, key: &str) -> Option<FaceBytes> {
|
||||
DocumentFaces::bytes(self.ui.ctx(), key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,36 +1,43 @@
|
||||
//! 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, 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::Wake;
|
||||
use craft_host::queue::{JobQueue, Priority, QueueOptions};
|
||||
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::frame;
|
||||
use crate::runtime::egui::{fonts as egui_fonts, memory, pass, repaint};
|
||||
use crate::runtime::env::Env;
|
||||
use crate::runtime::{frame, replay};
|
||||
|
||||
/// 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 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;
|
||||
|
||||
/// 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;
|
||||
/// 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)]
|
||||
@@ -62,6 +69,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,55 +87,87 @@ 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 its lane count.
|
||||
struct Queue {
|
||||
lanes: usize,
|
||||
queue: Arc<JobQueue<String, Option<FaceBytes>>>,
|
||||
}
|
||||
|
||||
/// The context's document faces, by family name.
|
||||
#[derive(Default)]
|
||||
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)>,
|
||||
/// 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,
|
||||
/// [`MAX_DOCUMENT_FACE_BYTES`], or a trial's own (`testing::document_face_budget`).
|
||||
budget: 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;
|
||||
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,
|
||||
}
|
||||
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.
|
||||
fn evict(&mut self, now: u64) -> Vec<String> {
|
||||
if self.evicted == Some(now) || self.faces.len() <= MAX_DOCUMENT_FACES {
|
||||
return Vec::new();
|
||||
impl Registry {
|
||||
/// 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<String>, bool) {
|
||||
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;
|
||||
}
|
||||
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 held: usize = files.values().map(|(bytes, _)| bytes).sum();
|
||||
if held + self.withdrawn <= self.budget {
|
||||
return (Vec::new(), false);
|
||||
}
|
||||
self.pending.retain(|(name, _)| !stale.contains(name));
|
||||
stale
|
||||
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 <= low {
|
||||
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);
|
||||
}
|
||||
(gone, std::mem::take(&mut self.withdrawn) > 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,106 +193,220 @@ 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.
|
||||
/// The queue of `ctx`'s catalog loads: made on first use on the context's jobs (`Env::jobs_of`) and kept
|
||||
/// for the context's life, as `TextureLoader::in_context` keeps its own.
|
||||
fn queue_of(ctx: &Context, registry: &mut Registry) -> Arc<JobQueue<String, Option<FaceBytes>>> {
|
||||
if let Some(queue) = ®istry.queue {
|
||||
return Arc::clone(&queue.queue);
|
||||
}
|
||||
let jobs = Env::jobs_of(ctx);
|
||||
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, 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 (stale, pending) = memory::with::<Registry, _>(ctx, |registry| {
|
||||
registry.begin(now);
|
||||
let stale = registry.evict(now);
|
||||
(stale, std::mem::take(&mut registry.pending))
|
||||
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))
|
||||
});
|
||||
if !stale.is_empty() || !pending.is_empty() {
|
||||
egui_fonts::edit_faces(ctx, &stale, pending);
|
||||
// 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));
|
||||
// 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<String> = 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 {
|
||||
Some(face) => {
|
||||
registry.faces.insert(name.clone(), Registered { face: face.clone(), used: now });
|
||||
}
|
||||
None => {
|
||||
registry.failed.insert(name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let (gone, rebuild) = registry.evict(now);
|
||||
(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 and starts the frame's budget.
|
||||
/// Marks the kept face `name` drawn in this frame: a replay's journal entry.
|
||||
fn mark_drawn(ctx: &Context, name: &str) {
|
||||
memory::with::<Registry, _>(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::<Registry, _>(ctx, |registry| registry.budget = bytes);
|
||||
}
|
||||
|
||||
/// 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. 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<L>(ctx: &Context, key: &str, job: impl FnOnce() -> L) -> FaceState
|
||||
where
|
||||
L: FnOnce() -> Option<FaceBytes> + Send + 'static,
|
||||
{
|
||||
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);
|
||||
let load = job();
|
||||
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. 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);
|
||||
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) {
|
||||
let known = 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 => {}
|
||||
}
|
||||
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;
|
||||
if matches!(known, Known::Ready) {
|
||||
replay::journal_distinct(ctx, || name.to_owned(), |ctx, name: &String| mark_drawn(ctx, name));
|
||||
}
|
||||
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());
|
||||
known
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
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,28 @@ 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. `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<L>(&self, key: &str, job: impl FnOnce() -> L) -> FaceState
|
||||
where
|
||||
L: FnOnce() -> Option<FaceBytes> + 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.
|
||||
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 {
|
||||
DocumentFaces::face(self.painter.ctx(), key, load)
|
||||
fn document_face<L>(&self, key: &str, job: impl FnOnce() -> L) -> FaceState
|
||||
where
|
||||
L: FnOnce() -> Option<FaceBytes> + Send + 'static,
|
||||
{
|
||||
DocumentFaces::face(self.painter.ctx(), key, job)
|
||||
}
|
||||
|
||||
fn document_face_bytes(&self, key: &str) -> Option<FaceBytes> {
|
||||
DocumentFaces::bytes(self.painter.ctx(), key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::runtime::egui::{memory, pass, repaint};
|
||||
use crate::runtime::env::Env;
|
||||
use crate::runtime::replay;
|
||||
use craft_host::queue::{Cancel, JobQueue, QueueOptions};
|
||||
use craft_host::{Jobs, Wake, default_jobs};
|
||||
use craft_host::{Jobs, Wake};
|
||||
use egui::{Color32, ColorImage, Context};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Debug;
|
||||
@@ -23,9 +23,9 @@ pub struct LoaderOptions {
|
||||
pub store: TextureStoreOptions,
|
||||
/// Jobs running at once; 0 runs one job per frame on the UI thread (wasm32).
|
||||
pub lanes: usize,
|
||||
/// Where the lanes run. `None`: the installed host's `Jobs`, or `craft_host::default_jobs()` when no host is
|
||||
/// installed (threads on native targets, one job per frame on wasm32). Stories and tests pass a `ManualJobs` to
|
||||
/// finish one job at a time.
|
||||
/// Where the lanes run. `None`: the installed host's `Jobs`, else the jobs the runtime was installed with (inline
|
||||
/// in tests and story trials), else `craft_host::default_jobs()` (threads on native targets, one job per frame on
|
||||
/// wasm32). Stories and tests pass a `ManualJobs` to finish one job at a time.
|
||||
pub jobs: Option<Arc<dyn Jobs>>,
|
||||
}
|
||||
|
||||
@@ -188,7 +188,7 @@ impl<K: TextureKey> TextureLoader<K> {
|
||||
let (queue, lanes) = match known {
|
||||
Some(known) => known,
|
||||
None => {
|
||||
let jobs = options.jobs.unwrap_or_else(|| Env::host_of(ctx).map_or_else(default_jobs, |host| Arc::clone(host.jobs_shared())));
|
||||
let jobs = options.jobs.unwrap_or_else(|| Env::jobs_of(ctx));
|
||||
let wake = {
|
||||
let ctx = ctx.clone();
|
||||
Wake::new(move || repaint::request(&ctx))
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -12,14 +12,14 @@ pub use shell::{BodyMode, PageBandRoom, RevealEdge, ShellCx, ShellRegions, SlotK
|
||||
pub use units::{ColumnSize, LengthUnits, PointSize, UnitKind, UnitWords, Units};
|
||||
|
||||
use crate::runtime::commands::CommandChain;
|
||||
use crate::runtime::egui::memory::FastMap;
|
||||
use crate::runtime::egui::memory::{self, FastMap};
|
||||
use crate::runtime::egui::{pass, repaint, scale, stack, style};
|
||||
use crate::runtime::frame::PerViewport;
|
||||
use crate::runtime::windows;
|
||||
use crate::style::{EnvKey, GlyphRole, Ink, SurfaceKind, UiTokens};
|
||||
use craft_behavior::{CanvasTransform, MotionMode};
|
||||
use craft_host::Host;
|
||||
use craft_host::target::{Os, ShellInfo};
|
||||
use craft_host::{Host, Jobs};
|
||||
pub use craft_i18n::Direction;
|
||||
pub use craft_i18n::{AgeStyle, Count, Counted, WordRows, WordSet, WordTemplate, Words};
|
||||
use craft_i18n::{CalendarDate, DateFormat, Format};
|
||||
@@ -750,6 +750,15 @@ impl Env {
|
||||
PerViewport::<ViewportEnvs>::with(ctx, pass::current_viewport(ctx), |envs| envs.root.as_ref().and_then(|env| env.host.clone()))
|
||||
}
|
||||
|
||||
/// Where `ctx`'s background work runs: the host's jobs, else the jobs `install` was given, else
|
||||
/// `craft_host::default_jobs()`.
|
||||
pub(crate) fn jobs_of(ctx: &Context) -> Arc<dyn Jobs> {
|
||||
if let Some(host) = Self::host_of(ctx) {
|
||||
return Arc::clone(host.jobs_shared());
|
||||
}
|
||||
memory::with::<InstalledJobs, _>(ctx, |installed| installed.0.clone()).unwrap_or_else(craft_host::default_jobs)
|
||||
}
|
||||
|
||||
/// A clone of the innermost app value, else `T::root()`. Large values hold an `Arc`.
|
||||
pub fn get<T: EnvValue>(&self) -> T {
|
||||
self.values.get::<T>()
|
||||
@@ -895,3 +904,13 @@ impl Drop for Restore<'_> {
|
||||
fn motion_mode(ctx: &Context, motion: MotionMode) -> MotionMode {
|
||||
if repaint::animation_time(ctx) > 0.0 { motion } else { motion.lowered_by(MotionMode::Off) }
|
||||
}
|
||||
|
||||
/// The jobs `install` was given, for a context with no host.
|
||||
#[derive(Default)]
|
||||
struct InstalledJobs(Option<Arc<dyn Jobs>>);
|
||||
|
||||
/// Keeps `jobs` as where `ctx`'s background work runs while no host is installed; `None` leaves
|
||||
/// `craft_host::default_jobs()`.
|
||||
pub(crate) fn install_jobs(ctx: &Context, jobs: Option<Arc<dyn Jobs>>) {
|
||||
memory::with::<InstalledJobs, _>(ctx, |installed| installed.0 = jobs);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! `runtime::install`: adds the runtime plugin once and sets the egui options the runtime owns.
|
||||
|
||||
use crate::runtime::egui::{clipboard, input, plugin};
|
||||
use crate::runtime::env::{SystemReader, system};
|
||||
use crate::runtime::env::{self, SystemReader, system};
|
||||
use crate::runtime::pen::PenSource;
|
||||
use crate::runtime::{commands, frame, pen, windows};
|
||||
use crate::style::{DuplicateStyle, StyleReplacements};
|
||||
use craft_host::Jobs;
|
||||
use craft_host::target::ShellInfo;
|
||||
use craft_window::policy::Decision;
|
||||
use craft_window::restore::Store;
|
||||
@@ -45,6 +46,9 @@ pub struct InstallSpec {
|
||||
/// The clipboard the host installs (system, browser event, memory); without one the runtime uses
|
||||
/// `Clipboard::new(EguiClipboard)`.
|
||||
pub clipboard: Option<craft_platform::clipboard::Clipboard>,
|
||||
/// Where the context's background work (document faces, texture loads) runs while no host is installed; none
|
||||
/// runs it on `craft_host::default_jobs()`. A host's jobs come first.
|
||||
pub jobs: Option<Arc<dyn Jobs>>,
|
||||
}
|
||||
|
||||
/// The modifiers the mouse wheel zooms and scrolls sideways with.
|
||||
@@ -86,9 +90,16 @@ impl InstallSpec {
|
||||
pen: None,
|
||||
stories: false,
|
||||
clipboard: None,
|
||||
jobs: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the context's background work on `jobs` while no host is installed.
|
||||
pub fn jobs(mut self, jobs: Arc<dyn Jobs>) -> Self {
|
||||
self.jobs = Some(jobs);
|
||||
self
|
||||
}
|
||||
|
||||
/// Installs the host's clipboard (system, browser event, memory) in place of the runtime's own.
|
||||
pub fn clipboard(mut self, clipboard: craft_platform::clipboard::Clipboard) -> Self {
|
||||
self.clipboard = Some(clipboard);
|
||||
@@ -211,6 +222,7 @@ pub fn install(ctx: &Context, spec: InstallSpec) -> Result<(), InstallError> {
|
||||
input::set_wheel_modifiers(ctx, spec.wheel.zoom, spec.wheel.sideways);
|
||||
system::install(ctx, spec.system);
|
||||
pen::install(ctx, spec.pen);
|
||||
env::install_jobs(ctx, spec.jobs);
|
||||
clipboard::install(ctx, spec.clipboard);
|
||||
windows::install(ctx, with_browser_caps(spec.shell_info), spec.window_system, spec.placement, spec.frame, spec.app_id);
|
||||
frame::set_frame_layers(ctx, spec.frame_layers);
|
||||
|
||||
@@ -1324,7 +1324,9 @@ 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"),
|
||||
("runtime::env::InstalledJobs", "the jobs install was given: set once at install, only read after"),
|
||||
// Testing logs.
|
||||
("runtime::measure::", "measuring-run counts and the skipped-effect log (testing)"),
|
||||
("runtime::pass_state::Parked", "pass state between passes: moved into the thread and back, not read"),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -221,14 +221,14 @@ fn motion_modes_settle(subject: &Subject) -> Result<(), String> {
|
||||
|
||||
/// A host whose catalogs offer `ja`, in English.
|
||||
fn hosts() -> Option<(Arc<craft_host::Host>, Arc<craft_host::Host>)> {
|
||||
use craft_host::{AppInfo, Host};
|
||||
use craft_host::{AppInfo, Host, InlineJobs};
|
||||
let (i18n, problems) = craft_i18n::I18n::from_owned([("ja".to_owned(), String::new(), String::new())], &["ja"]);
|
||||
if !problems.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let i18n = Arc::new(i18n);
|
||||
let japanese = i18n.from_code("ja")?;
|
||||
let english = Arc::new(Host::builder(AppInfo { id: "suite", name: "Suite", version: "0" }).i18n(i18n).build());
|
||||
let english = Arc::new(Host::builder(AppInfo { id: "suite", name: "Suite", version: "0" }).i18n(i18n).jobs(Arc::new(InlineJobs)).build());
|
||||
Some((english.clone(), Arc::new(english.with_lang(japanese))))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The window host's fixtures: install inputs that open no OS windows, and the scripted system.
|
||||
|
||||
use crate::runtime::InstallSpec;
|
||||
use craft_host::InlineJobs;
|
||||
use craft_host::target::ShellInfo;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -9,8 +10,10 @@ pub use crate::runtime::egui::fixture::{FullOutput, RawInput, dragged_id, record
|
||||
pub use craft_window::system::{FakeSystem, NoWindows};
|
||||
|
||||
/// An install spec for the running build's shell and a system with no OS services, with the stories' command sets.
|
||||
/// Background work runs inline, so what a pass asks for lands in the next pass on every machine and a settled frame
|
||||
/// is the same on every run.
|
||||
pub fn install_spec() -> InstallSpec {
|
||||
InstallSpec::new(ShellInfo::default(), Arc::new(NoWindows)).stories()
|
||||
InstallSpec::new(ShellInfo::default(), Arc::new(NoWindows)).stories().jobs(Arc::new(InlineJobs))
|
||||
}
|
||||
|
||||
/// Makes the shell of `ctx` run on `os`, for a test of the OS matrix: the key table, the chords shown, the chrome,
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
//! 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 (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::thread::ThreadId;
|
||||
|
||||
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, MeasureCx, MemoView, Role, Show as _};
|
||||
use craft_ui::fonts::{self, FaceBytes, FaceState};
|
||||
use craft_ui::style::{ComponentStyle, StyleCx};
|
||||
use craft_ui::testing::{Frames, trial};
|
||||
use egui::{Response, Vec2};
|
||||
use craft_ui::primitives::{DocRun, DocText};
|
||||
use craft_ui::style::{ComponentStyle, DataColor, StyleCx};
|
||||
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");
|
||||
|
||||
/// 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 {
|
||||
@@ -23,10 +25,11 @@ pub struct PlainStyle {
|
||||
metrics: Metrics,
|
||||
}
|
||||
|
||||
/// What the probes asked for: how often a face was loaded and the state each key was last given.
|
||||
/// What the probes asked for: how often a face was loaded, on which threads, and the state each key was last given.
|
||||
#[derive(Clone, Default)]
|
||||
struct Tally {
|
||||
loads: Arc<AtomicUsize>,
|
||||
threads: Arc<Mutex<Vec<ThreadId>>>,
|
||||
states: Arc<Mutex<HashMap<String, FaceState>>>,
|
||||
}
|
||||
|
||||
@@ -38,16 +41,34 @@ 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.
|
||||
/// 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, threads, panics) = (Arc::clone(&tally.loads), Arc::clone(&tally.threads), key.starts_with("panic"));
|
||||
move || {
|
||||
loads.fetch_add(1, Ordering::Relaxed);
|
||||
threads.lock().expect("the threads").push(std::thread::current().id());
|
||||
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<String>,
|
||||
loads_fail: bool,
|
||||
tally: Tally,
|
||||
in_run: bool,
|
||||
}
|
||||
|
||||
impl Component for Owner {
|
||||
@@ -60,17 +81,27 @@ 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 state = cx.document_face(key, || {
|
||||
self.tally.loads.fetch_add(1, Ordering::Relaxed);
|
||||
(!self.loads_fail).then(|| 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));
|
||||
}
|
||||
self.tally.states.lock().expect("the states").insert(key.clone(), state);
|
||||
}
|
||||
Vec2::splat(1.0)
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -79,39 +110,176 @@ 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(), in_run: false }.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");
|
||||
}
|
||||
|
||||
/// Without a host the loads run on the jobs the runtime was installed with, inline in a trial: every face asked for in
|
||||
/// one pass is ready in the next on every machine, each loaded once.
|
||||
#[trial]
|
||||
fn without_a_host_every_face_asked_for_in_one_pass_is_ready_in_the_next() {
|
||||
let mut frames = Frames::new();
|
||||
let tally = Tally::default();
|
||||
let wanted = keys(0..8);
|
||||
frame(&mut frames, &tally, &wanted);
|
||||
frame(&mut frames, &tally, &wanted);
|
||||
assert!(tally.all_ready(&wanted), "every face lands in the next pass");
|
||||
assert_eq!(tally.loads(), 8, "and none was cancelled and loaded again");
|
||||
let me = std::thread::current().id();
|
||||
assert!(tally.threads.lock().expect("the threads").iter().all(|thread| *thread == me), "the loads ran on the trial's thread");
|
||||
}
|
||||
|
||||
#[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<Tally> = 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<u64> = ["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<String> = ["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");
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
//! Stories of `Picture`.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_host::InlineJobs;
|
||||
|
||||
use super::{Picture, PictureSize};
|
||||
use crate::contract::Show as _;
|
||||
use crate::list::{ThumbAspect, ThumbSize};
|
||||
@@ -36,11 +32,10 @@ fn picture_thumbnail(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
}
|
||||
|
||||
/// A picture made off the frame: its source renders as a `Later` job, so the picture shows the placeholder until the
|
||||
/// job lands on the loader's lanes, then the picture. The job runs inline, so the picture lands in the next frame and
|
||||
/// not whenever a thread ends: the suite's settled frames are the same on every run.
|
||||
/// job lands on the loader's lanes, then the picture.
|
||||
#[story(Picture<'static>, covers = [], drive = Drive::Never)]
|
||||
fn picture_rendered(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let options = ThumbnailOptions::new().jobs(Arc::new(InlineJobs));
|
||||
let options = ThumbnailOptions::new();
|
||||
let thumbnails = Thumbnails::<u64>::in_context(ui.ctx(), "craft_ui::stories::picture_rendered", options);
|
||||
let source = FakeThumbSource::<u64>::new().later(true).opaque(true);
|
||||
Picture::rendered("Rendered", 1, &thumbnails, &source).extent(PictureSize::Thumb(ThumbSize::Large)).show(ui).into()
|
||||
|
||||
+13
-7
@@ -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<Cow<'static, [ColumnWidth]>>) -> Self`. Children row-major over `columns`: a `'static` slice, or columns built in the pass.
|
||||
- `pub fn grid(columns: impl Into<Cow<'static, [ColumnWidth]>>) -> 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<craft_behavior::IconId>, pub tip: Option<Label>, pub max_share: Option<f32>, pub hideable: bool, pub remove: Option<ColumnRemove> }`. One column of a collection.
|
||||
- `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<craft_behavior::IconId>, pub tip: Option<Label>, pub max_share: Option<f32>, pub min_width: f32, pub hideable: bool, pub remove: Option<ColumnRemove> }`. One column of a collection.
|
||||
- `pub fn removable(mut self, name: impl Into<Label>, enabled: bool) -> Self`. The column gets a remove control named `name` at its header's end, disabled unless `enabled`.
|
||||
- `pub fn new(key: ColumnKey, header: impl Into<Label>, width: ColumnWidth) -> Self`. A content column with a header and a width; the other settings off.
|
||||
- `pub fn toggle(key: ColumnKey, header: impl Into<Label>, toggle: ToggleColumn) -> Self`. A toggle column as wide as a toggle cell, with a header; the other settings off.
|
||||
@@ -2051,6 +2051,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st
|
||||
- `pub fn numeric(mut self) -> Self`. A column of numbers: content at the end edge, tabular figures.
|
||||
- `pub fn hideable(mut self) -> Self`. The user can hide the column from the header menu.
|
||||
- `pub fn at_most(mut self, share: f32) -> Self`. A `Content` column takes at most `share` of the collection's width.
|
||||
- `pub fn at_least(mut self, width: f32) -> Self`. A `Content` column is at least `width` wide.
|
||||
- `pub fn tip(mut self, tip: impl Into<Label>) -> Self`. The header's tooltip.
|
||||
- `pub fn icon(mut self, icon: craft_behavior::IconId) -> Self`. The icon the column's cells show. A cell of a column with no header text is named after it.
|
||||
- `pub fn first_descending(mut self) -> Self`. The first press on the header sorts descending.
|
||||
@@ -2184,7 +2185,8 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st
|
||||
- `pub fn is_heading(&self) -> bool`. Whether the entry is a heading.
|
||||
- `pub fn is_item(&self) -> bool`. Whether the entry is an item, which reports a value: neither a heading nor a separator.
|
||||
- `craft_ui::contract::FacesCx`: `pub trait FacesCx`. Where a document face is asked for: a component's context, its measure or a content painter.
|
||||
- `fn document_face(&self, key: &str, load: impl FnOnce() -> Option<FaceBytes>) -> FaceState`. The face registered under `key` as a family of its own. `load` runs only for a new key within the frame's
|
||||
- `fn document_face<L>(&self, key: &str, job: impl FnOnce() -> L) -> FaceState where L: FnOnce() -> Option<FaceBytes> + Send + 'static`. The face registered under `key` as a family of its own, read from a font catalog. `job` is called only for a
|
||||
- `fn document_face_bytes(&self, key: &str) -> Option<FaceBytes>`. The bytes of the face `document_face` registered under `key`, once it is ready: for reading its tables without
|
||||
- `craft_ui::contract::FieldLabel`: `pub struct FieldLabel { pub id: Id, pub rect: Rect, pub press: PressState, pub hovered: bool, pub text: String, pub role: FieldLabelRole, pub detail: Option<String>, pub activated: bool, pub status: bool }`. The label a container shows beside its body.
|
||||
- `pub fn new(id: Id, rect: Rect, text: impl Into<String>) -> Self`. A label of `text` at `rect`, the node `id`.
|
||||
- `pub fn role(mut self, role: FieldLabelRole) -> Self`. Whether the label names or describes the controls.
|
||||
@@ -2807,7 +2809,7 @@ The layout services: `LabelColumn`, `ColumnGroup`, the `Grid` cursor, `measure_s
|
||||
- `craft_ui::layout::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<Cow<'static, [ColumnWidth]>>) -> Self`. Children row-major over `columns`: a `'static` slice, or columns built in the pass.
|
||||
- `pub fn grid(columns: impl Into<Cow<'static, [ColumnWidth]>>) -> 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.
|
||||
@@ -2922,6 +2924,7 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`.
|
||||
- `pub fn fill(&self, shape: &PaintShape, color: StyleColor)`. Fills `shape`.
|
||||
- `pub fn stroke(&self, shape: &PaintShape, width: impl Into<DataStrokeWidth>, color: impl Into<StrokeColor>)`. Strokes `shape` at a theme width or a width from the document, in a theme colour or a colour from data (a
|
||||
- `pub fn data_fill(&self, shape: &PaintShape, color: DataColor)`. Fills `shape` with a colour from data (a swatch well, a layer label dot, an avatar). A component that paints its
|
||||
- `pub fn data_fill_tiled(&self, pieces: &[Vec<Pos2>], color: DataColor)`. Fills the polygons `pieces`, which tile one area edge to edge, as one mesh with no feathered edges, in a colour
|
||||
- `pub fn texture(&self, rect: Rect, texture: TextureId, uv: Rect)`. Paints the part `uv` of `texture` (from `TextureCache` or a `TextureStore`) into `rect`, untinted. The picture
|
||||
- `pub fn texture_quad(&self, corners: [Pos2; 4], texture: TextureId, uv: Rect)`. Paints `uv` of `texture` onto the clockwise quad `corners` (from `uv`'s top left), untinted, as data: a
|
||||
- `pub fn checker(&self, checker: &super::Checker, rect: Rect, radius: CornerRadius)`. Paints `checker` over `rect` with corners `radius`, a light cell at the rect's top left. It shows through data,
|
||||
@@ -2946,7 +2949,8 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`.
|
||||
- `pub fn largest_size(ctx: &Context) -> f32`. The largest size, in points, a face run is drawn at on `ctx`'s display: a glyph stays within a quarter of the
|
||||
- `pub fn drawn_size(&self, ctx: &Context) -> f32`. The size the run is drawn at on `ctx`'s display: its own, within 1 point and [`largest_size`](Self::largest_size).
|
||||
- `craft_ui::primitives::FacesCx`: `pub trait FacesCx`. Where a document face is asked for: a component's context, its measure or a content painter.
|
||||
- `fn document_face(&self, key: &str, load: impl FnOnce() -> Option<FaceBytes>) -> FaceState`. The face registered under `key` as a family of its own. `load` runs only for a new key within the frame's
|
||||
- `fn document_face<L>(&self, key: &str, job: impl FnOnce() -> L) -> FaceState where L: FnOnce() -> Option<FaceBytes> + Send + 'static`. The face registered under `key` as a family of its own, read from a font catalog. `job` is called only for a
|
||||
- `fn document_face_bytes(&self, key: &str) -> Option<FaceBytes>`. The bytes of the face `document_face` registered under `key`, once it is ready: for reading its tables without
|
||||
- `craft_ui::primitives::FakeThumbSource`: `pub struct FakeThumbSource<K>`. A [`ThumbSource`] for stories and tests in every crate: pictures made from the key and a revision the test sets,
|
||||
- `pub fn new() -> Self`. Synchronous square pictures at revision 0.
|
||||
- `pub fn later(mut self, later: bool) -> Self`. Renders as `Later` jobs.
|
||||
@@ -3756,7 +3760,7 @@ One-shot screenshot slots and the facts a screenshot is measured against.
|
||||
- `pub fn effective_tone(&self, warn: bool) -> Tone`. The tone the message shows in: its own, else `Warn` when it belongs to a `Validity::Warn` (`warn`), else `Bad`.
|
||||
- `craft_ui::runtime::env::MotionPolicy`: `pub struct MotionPolicy { pub mode: MotionMode, pub tokens: MotionTokens }`. The motion mode in effect, carried in `Env.motion`.
|
||||
- `pub const fn new(mode: MotionMode, tokens: MotionTokens) -> Self`. The policy that runs animations at `mode` with `tokens`.
|
||||
- `craft_ui::runtime::env::Overrides`: `pub struct Overrides { pub size: Option<ControlSize>, pub enabled: Option<bool>, pub read_only: Option<bool>, pub wheel: Option<WheelScope>, pub motion: Option<MotionMode>, pub direction: Option<Direction>, pub words: Option<WordsOverride>, pub values: AppValues }`. Changes to the inherited values for a stretch of code.
|
||||
- `craft_ui::runtime::env::Overrides`: `pub struct Overrides { pub size: Option<ControlSize>, pub enabled: Option<bool>, pub read_only: Option<bool>, pub wheel: Option<WheelScope>, pub motion: Option<MotionMode>, pub direction: Option<Direction>, pub words: Option<WordsOverride>, pub values: AppValues, pub id_salt: Option<egui::Id> }`. Changes to the inherited values for a stretch of code.
|
||||
- `craft_ui::runtime::env::PageBandRoom`: `pub struct PageBandRoom { pub rect: Rect, pub start: f32, pub end: f32 }`. The room of the page band while a full-window page shows: the title-bar-high strip at the window's top and the room
|
||||
- `pub const fn new(rect: Rect, start: f32, end: f32) -> Self`. The band at `rect`, the window's start end taking `start` of it and its end end `end`.
|
||||
- `craft_ui::runtime::env::PaneEdge`: `pub enum PaneEdge { Center, Start, End, Top, Bottom }`. Where a shell pane sits.
|
||||
@@ -4011,8 +4015,9 @@ Decision records and findings. Inspected regions ([`record`]) collect pipeline s
|
||||
`runtime::install`: adds the runtime plugin once and sets the egui options the runtime owns.
|
||||
|
||||
- `craft_ui::runtime::install::InstallError`: `pub enum InstallError { AlreadyInstalled, DuplicateStyle(DuplicateStyle), Commands(commands::CommandDefError), DuringPass }`. Why `install` refused a spec.
|
||||
- `craft_ui::runtime::install::InstallSpec`: `pub struct InstallSpec { pub shell_info: ShellInfo, pub window_system: Arc<dyn WindowSystem>, pub placement: Option<Arc<Mutex<Store>>>, pub frame_layers: Option<fn(&Context)>, pub looks: StyleReplacements, pub frame: Option<Decision>, pub system: SystemReader, pub wheel: WheelModifiers, pub app_id: String, pub pen: Option<PenSource>, pub stories: bool, pub clipboard: Option<craft_platform::clipboard::Clipboard> }`. What `install` takes.
|
||||
- `craft_ui::runtime::install::InstallSpec`: `pub struct InstallSpec { pub shell_info: ShellInfo, pub window_system: Arc<dyn WindowSystem>, pub placement: Option<Arc<Mutex<Store>>>, pub frame_layers: Option<fn(&Context)>, pub looks: StyleReplacements, pub frame: Option<Decision>, pub system: SystemReader, pub wheel: WheelModifiers, pub app_id: String, pub pen: Option<PenSource>, pub stories: bool, pub clipboard: Option<craft_platform::clipboard::Clipboard>, pub jobs: Option<Arc<dyn Jobs>> }`. What `install` takes.
|
||||
- `pub fn new(shell_info: ShellInfo, window_system: Arc<dyn WindowSystem>) -> Self`. A spec for `shell_info` and `window_system`, with no ghost-layer painter.
|
||||
- `pub fn jobs(mut self, jobs: Arc<dyn Jobs>) -> Self`. Runs the context's background work on `jobs` while no host is installed.
|
||||
- `pub fn clipboard(mut self, clipboard: craft_platform::clipboard::Clipboard) -> Self`. Installs the host's clipboard (system, browser event, memory) in place of the runtime's own.
|
||||
- `pub fn stories(mut self) -> Self`. Loads the stories' command sets too, for an install that shows stories.
|
||||
- `pub fn placement(mut self, store: Arc<Mutex<Store>>) -> Self`. Sets the store viewport mounts save their window placement in.
|
||||
@@ -4508,6 +4513,7 @@ The fixture, the suite runner and the story helpers.
|
||||
- `craft_ui::testing::Room`: re-export of `craft_ui::testing::fixture::Room`.
|
||||
- `craft_ui::testing::Target`: re-export of `craft_ui::testing::fixture::Target`.
|
||||
- `craft_ui::testing::audit_replays`: `pub fn set(ctx: &Context, on: bool)`. Turns the audit on or off in `ctx`, in place of `CRAFT_UI_AUDIT_REPLAY`.
|
||||
- `craft_ui::testing::document_face_budget`: `pub fn set_budget(ctx: &Context, bytes: usize)`. Sets the budget of `ctx`'s document faces to `bytes` in place of [`MAX_DOCUMENT_FACE_BYTES`], so a trial reaches
|
||||
- `craft_ui::testing::forget_measurements`: re-export of `craft_ui::runtime::layout_memory::forget_kept`.
|
||||
- `craft_ui::testing::in_audit_run`: `pub fn in_run(ctx: &Context) -> bool`. Whether the code running in `ctx` is a run of the audit: a test that counts its own runs of a view counts none in
|
||||
- `craft_ui::testing::install_spec`: re-export of `craft_ui::testing::windows::install_spec`.
|
||||
|
||||
Reference in New Issue
Block a user