diff --git a/crates/font-catalog/src/scan.rs b/crates/font-catalog/src/scan.rs index 3705f24f8..d79c83f8f 100644 --- a/crates/font-catalog/src/scan.rs +++ b/crates/font-catalog/src/scan.rs @@ -96,6 +96,8 @@ pub struct FaceInfo { pub fs_type: u16, /// The OS/2 code page bits (`ulCodePageRange1`, `ulCodePageRange2`). pub code_pages: [u32; 2], + /// The OS/2 `usWeightClass` as the file states it; `None` without an OS/2 table. A named instance has its file's. + pub weight_class: Option, /// The OS/2 `sFamilyClass` (high byte: the IBM class; 0 without an OS/2 table). pub family_class: i16, /// The OS/2 PANOSE digits (all 0 without an OS/2 table). @@ -314,6 +316,7 @@ pub(crate) fn font_faces(font: &skrifa::FontRef<'_>, outlines: Outlines, index: }); let fs_type = os2.as_ref().map_or(0, |t| t.fs_type()); let code_pages = os2.as_ref().map_or([0, 0], |t| [t.ul_code_page_range_1().unwrap_or(0), t.ul_code_page_range_2().unwrap_or(0)]); + let weight_class = os2.as_ref().map(|t| t.us_weight_class()); let family_class = os2.as_ref().map_or(0, |t| t.s_family_class()); let mut panose = [0u8; 10]; if let Some(digits) = os2.as_ref().map(|t| t.panose_10()) { @@ -345,6 +348,7 @@ pub(crate) fn font_faces(font: &skrifa::FontRef<'_>, outlines: Outlines, index: outlines, fs_type, code_pages, + weight_class, family_class, panose, fixed_pitch, diff --git a/crates/font-manager/src/panel/faces.rs b/crates/font-manager/src/panel/faces.rs index 254a3915a..655c7e212 100644 --- a/crates/font-manager/src/panel/faces.rs +++ b/crates/font-manager/src/panel/faces.rs @@ -49,8 +49,10 @@ pub(crate) fn shown(at: &impl FacesCx, catalog: &Arc, owner: Owner, fac if face.file_bytes.is_some_and(|bytes| bytes > MAX_FILE_BYTES) { return Shown::Unavailable; } - let (catalog, info) = (Arc::clone(catalog), face.clone()); - at.document_face(&key(owner, face), move || load(&catalog, &info)) + at.document_face(&key(owner, face), || { + let (catalog, info) = (Arc::clone(catalog), face.clone()); + move || load(&catalog, &info) + }) } /// The bytes of `face` once [`shown`] has it ready, for reading its tables without loading the file again. diff --git a/crates/font-manager/src/picker/rank.rs b/crates/font-manager/src/picker/rank.rs index 09113d9b8..98657ddbd 100644 --- a/crates/font-manager/src/picker/rank.rs +++ b/crates/font-manager/src/picker/rank.rs @@ -157,7 +157,7 @@ pub(super) fn shown_name(info: &Info, family: &str, language: &str, english: boo /// A face's class, PANOSE and weight from its `OS/2` and `post` tables, as the catalog's scan recorded them. fn read_traits(face: &FaceInfo) -> Traits { - let weight = face.weight.round().clamp(1.0, 1000.0) as u16; + let weight = face.weight_class.unwrap_or(400).clamp(1, 1000); Traits { class: classify(&face.family, face.family_class, face.panose, face.fixed_pitch), panose: face.panose, weight } } diff --git a/crates/ui-contract/src/contract/faces.rs b/crates/ui-contract/src/contract/faces.rs index b0dcefe9e..380720ad0 100644 --- a/crates/ui-contract/src/contract/faces.rs +++ b/crates/ui-contract/src/contract/faces.rs @@ -6,8 +6,11 @@ use crate::fonts::{FaceBytes, FaceState}; use crate::primitives::FacesCx; impl FacesCx for Cx<'_, C> { - fn document_face(&self, key: &str, load: impl FnOnce() -> Option + Send + 'static) -> FaceState { - DocumentFaces::face(&self.core.ctx, key, load) + fn document_face(&self, key: &str, job: impl FnOnce() -> L) -> FaceState + where + L: FnOnce() -> Option + Send + 'static, + { + DocumentFaces::face(&self.core.ctx, key, job) } fn document_face_bytes(&self, key: &str) -> Option { @@ -16,8 +19,11 @@ impl FacesCx for Cx<'_, C> { } impl FacesCx for MeasureCx<'_, C> { - fn document_face(&self, key: &str, load: impl FnOnce() -> Option + Send + 'static) -> FaceState { - DocumentFaces::face(self.ui.ctx(), key, load) + fn document_face(&self, key: &str, job: impl FnOnce() -> L) -> FaceState + where + L: FnOnce() -> Option + Send + 'static, + { + DocumentFaces::face(self.ui.ctx(), key, job) } fn document_face_bytes(&self, key: &str) -> Option { diff --git a/crates/ui-contract/src/fonts/document.rs b/crates/ui-contract/src/fonts/document.rs index d227f759d..3cf1ff52c 100644 --- a/crates/ui-contract/src/fonts/document.rs +++ b/crates/ui-contract/src/fonts/document.rs @@ -11,27 +11,34 @@ //! way the face reaches egui as a served family (`egui_fonts::serve_face`), which egui parses the first time text is //! laid out in it: a face arriving drops nothing egui has parsed or laid out. //! -//! The registry keeps faces up to [`MAX_DOCUMENT_FACE_BYTES`] of font files; past it the faces drawn longest ago go, -//! and faces drawn in the last frame always stay. +//! The registry keeps faces up to [`MAX_DOCUMENT_FACE_BYTES`] of font files, counted with the files egui still holds +//! for faces taken out; past it the faces drawn longest ago go, and faces drawn in the last frame always stay. A face a +//! settled view shows by replaying its last run counts as drawn: the replay marks it (`runtime::replay::journal`). use std::collections::{HashMap, HashSet}; use std::sync::Arc; use craft_host::queue::{JobQueue, Priority, QueueOptions}; -use craft_host::{Jobs, Wake, default_jobs}; +use craft_host::{Wake, default_jobs}; use egui::epaint::text::{Blob, FontTweak, VariationCoords}; use egui::{Context, FontData}; use super::FontRef; use crate::runtime::egui::{fonts as egui_fonts, memory, pass, repaint}; use crate::runtime::env::Env; -use crate::runtime::frame; +use crate::runtime::{frame, replay}; -/// The font file bytes the registry keeps faces of, a collection counted once. Past it the faces drawn longest ago -/// are taken out; and once the files of faces taken out (which egui keeps parsed until its fonts are made again) pass -/// it too, egui's fonts are made again to free them. +/// The ceiling on the font file bytes of document faces: the files the registry keeps faces of (a collection counted +/// once) plus the files of faces taken out, which egui keeps parsed until its fonts are made again. When the two pass +/// it, the faces drawn longest ago are taken out until the kept files are at most `1 / LOW_MARK_DIVISOR` of it, and +/// egui's fonts are made again once to free what was taken out. The sum passes the ceiling only by the faces drawn in +/// the last frame, which always stay, and by the faces that land in one pass. pub const MAX_DOCUMENT_FACE_BYTES: usize = 512 << 20; +/// Eviction takes the kept files down to the budget divided by this, so egui's fonts are made again once per half a +/// budget of new faces, not for each face that lands past the budget. +const LOW_MARK_DIVISOR: usize = 2; + /// The bytes of a face, its index in a collection and its variation coordinates (axis tag, value). #[derive(Clone)] #[non_exhaustive] @@ -92,15 +99,13 @@ struct Registered { used: u64, } -/// The queue the catalog loads run on, with the `Jobs` it spawns lanes on and its lane count. +/// The queue the catalog loads run on, with its lane count. struct Queue { - jobs: Arc, lanes: usize, queue: Arc>>, } /// The context's document faces, by family name. -#[derive(Default)] struct Registry { faces: HashMap, failed: HashSet, @@ -109,28 +114,47 @@ struct Registry { queue: Option, /// The bytes of files whose faces were taken out since egui's fonts were last made again. withdrawn: usize, + /// [`MAX_DOCUMENT_FACE_BYTES`], or a trial's own (`testing::document_face_budget`). + budget: usize, frame: u64, hooked: bool, } +impl Default for Registry { + fn default() -> Self { + Registry { + faces: HashMap::new(), + failed: HashSet::new(), + loading: HashMap::new(), + queue: None, + withdrawn: 0, + budget: MAX_DOCUMENT_FACE_BYTES, + frame: 0, + hooked: false, + } + } +} + impl Registry { - /// Past the budget, takes out the faces drawn longest ago (never one the last frame drew) and returns their - /// names; the bytes of files no kept face shares count as withdrawn. - fn evict(&mut self, now: u64) -> Vec { + /// When the kept and withdrawn files pass the budget, takes out the faces drawn longest ago (never one the last + /// frame drew) down to the low mark, and returns their names and whether egui's fonts are made again to free the + /// withdrawn files. + fn evict(&mut self, now: u64) -> (Vec, bool) { let mut files: HashMap = HashMap::new(); for face in self.faces.values() { files.entry(face.face.file()).or_insert((face.face.bytes.len(), 0)).1 += 1; } let mut held: usize = files.values().map(|(bytes, _)| bytes).sum(); - if held <= MAX_DOCUMENT_FACE_BYTES { - return Vec::new(); + if held + self.withdrawn <= self.budget { + return (Vec::new(), false); } + let low = self.budget / LOW_MARK_DIVISOR; let mut stale: Vec<(u64, String)> = self.faces.iter().filter(|(_, face)| face.used + 1 < now).map(|(name, face)| (face.used, name.clone())).collect(); stale.sort(); let mut gone = Vec::new(); for (_, name) in stale { - if held <= MAX_DOCUMENT_FACE_BYTES { + if held <= low { break; } let Some(face) = self.faces.remove(&name) else { continue }; @@ -143,7 +167,7 @@ impl Registry { } gone.push(name); } - gone + (gone, std::mem::take(&mut self.withdrawn) > 0) } } @@ -174,25 +198,23 @@ enum Known { New, } -/// The queue of `ctx`'s catalog loads, made again when the host's `Jobs` changes. +/// The queue of `ctx`'s catalog loads: made on first use on the host's `Jobs` (`default_jobs` without a host) and kept +/// for the context's life, as `TextureLoader::in_context` keeps its own. fn queue_of(ctx: &Context, registry: &mut Registry) -> Arc>> { - let jobs = Env::host_of(ctx).map_or_else(default_jobs, |host| Arc::clone(host.jobs_shared())); - match ®istry.queue { - Some(queue) if Arc::ptr_eq(&queue.jobs, &jobs) => Arc::clone(&queue.queue), - _ => { - let wake_ctx = ctx.clone(); - let wake = Wake::new(move || repaint::request(&wake_ctx)); - let lanes = QueueOptions::default_lanes(); - let queue = Arc::new(JobQueue::new(Arc::clone(&jobs), wake, QueueOptions { lanes, name: "craft-document-faces" })); - registry.loading.clear(); - registry.queue = Some(Queue { jobs, lanes, queue: Arc::clone(&queue) }); - queue - } + if let Some(queue) = ®istry.queue { + return Arc::clone(&queue.queue); } + let jobs = Env::host_of(ctx).map_or_else(default_jobs, |host| Arc::clone(host.jobs_shared())); + let wake_ctx = ctx.clone(); + let wake = Wake::new(move || repaint::request(&wake_ctx)); + let lanes = QueueOptions::default_lanes(); + let queue = Arc::new(JobQueue::new(jobs, wake, QueueOptions { lanes, name: "craft-document-faces" })); + registry.queue = Some(Queue { lanes, queue: Arc::clone(&queue) }); + queue } -/// The begin-pass step: drops the loads no frame asked for lately, serves the faces that landed and takes out the faces -/// past the budget. Before anything of the pass is laid out, so a rebuild of egui's fonts it asks for applies at once. +/// The begin-pass step: drops the loads no frame asked for lately, serves the faces that landed, marks unavailable the +/// faces whose load ended without landing (a job that panicked) and takes out the faces past the budget. Before anything of the pass is laid out, so a rebuild of egui's fonts it asks for applies at once. fn begin_pass(ctx: &Context) { let now = pass::root_frame_nr(ctx); let inline = memory::with::(ctx, |registry| { @@ -209,11 +231,19 @@ fn begin_pass(ctx: &Context) { let loading = &mut registry.loading; loading.retain(|_, asked| *asked + 1 >= now); queue.reprioritize(|key, priority| loading.contains_key(key).then_some(priority)); + // A job leaves the running ones and files its result under the queue's one lock, so a key neither queued + // nor running here is among the results taken after, or its job ended without one. + let mut lost: Vec = loading.keys().filter(|key| !queue.contains(key)).cloned().collect(); while let Some(finished) = queue.try_recv() { + lost.retain(|key| *key != finished.key); if loading.remove(&finished.key).is_some() { landed.push((finished.key, finished.result)); } } + for key in lost { + loading.remove(&key); + registry.failed.insert(key); + } } for (name, result) in &landed { match result { @@ -225,11 +255,7 @@ fn begin_pass(ctx: &Context) { } } } - let gone = registry.evict(now); - let rebuild = registry.withdrawn > MAX_DOCUMENT_FACE_BYTES; - if rebuild { - registry.withdrawn = 0; - } + let (gone, rebuild) = registry.evict(now); (landed, gone, rebuild) }); for (name, face) in landed { @@ -245,6 +271,23 @@ fn begin_pass(ctx: &Context) { } } +/// Marks the kept face `name` drawn in this frame: a replay's journal entry. +fn mark_drawn(ctx: &Context, name: &str) { + memory::with::(ctx, |registry| { + let now = registry.frame; + if let Some(face) = registry.faces.get_mut(name) { + face.used = now; + } + }); +} + +/// Sets the budget of `ctx`'s document faces to `bytes` in place of [`MAX_DOCUMENT_FACE_BYTES`], so a trial reaches +/// it with a few faces. +#[cfg(feature = "testing")] +pub fn set_budget(ctx: &Context, bytes: usize) { + memory::with::(ctx, |registry| registry.budget = bytes); +} + /// Hooks the begin-pass step on the context's fonts plugin. fn begin(ctx: &Context) { let hook = memory::with::(ctx, |registry| !std::mem::replace(&mut registry.hooked, true)); @@ -258,11 +301,15 @@ fn begin(ctx: &Context) { pub(crate) struct DocumentFaces; impl DocumentFaces { - /// The face registered under `key` as a family of its own. `load` reads it from a font catalog: it runs as a job, - /// once per key while the face is kept, and the face is ready from the pass after the job ends. A `load` that - /// returns `None`, or bytes egui cannot read, marks the key unavailable for as long as the context lives. Every call + /// The face registered under `key` as a family of its own. The load `job()` makes reads it from a font catalog: + /// `job` is called only for a key the registry does not know, and its load runs as a job, once per key while the + /// face is kept; the face is ready from the pass after the job ends. A load that returns `None`, bytes egui cannot + /// read, or a job that ends without a result marks the key unavailable for as long as the context lives. Every call /// marks the face drawn in this frame; a load no frame asks for any more is dropped. - pub(crate) fn face(ctx: &Context, key: &str, load: impl FnOnce() -> Option + Send + 'static) -> FaceState { + pub(crate) fn face(ctx: &Context, key: &str, job: impl FnOnce() -> L) -> FaceState + where + L: FnOnce() -> Option + Send + 'static, + { let name = Kind::Alone.family_name(key); match Self::known(ctx, &name) { Known::Failed => FaceState::Unavailable, @@ -277,6 +324,7 @@ impl DocumentFaces { // A measuring run starts the load too: the registry is a cache, and a face loads the same whichever // run asks. frame::request_repaint(ctx); + let load = job(); memory::with::(ctx, |registry| { let queue = queue_of(ctx, registry); registry.loading.insert(name.clone(), registry.frame); @@ -328,10 +376,11 @@ impl DocumentFaces { memory::with::(ctx, |registry| registry.faces.get(&name).map(|face| face.face.clone())) } - /// What the registry knows of `name`, marking a kept face drawn and a load asked for in this frame. + /// What the registry knows of `name`, marking a kept face drawn and a load asked for in this frame. The mark of a + /// kept face is journaled, so a settled view's replay marks the faces its run drew. fn known(ctx: &Context, name: &str) -> Known { begin(ctx); - memory::with::(ctx, |registry| { + let known = memory::with::(ctx, |registry| { let now = registry.frame; if registry.failed.contains(name) { Known::Failed @@ -344,7 +393,11 @@ impl DocumentFaces { } else { Known::New } - }) + }); + if matches!(known, Known::Ready) { + replay::journal_distinct(ctx, || name.to_owned(), |ctx, name: &String| mark_drawn(ctx, name)); + } + known } /// A kept face's state: ready once egui lays text out with the served faces. diff --git a/crates/ui-contract/src/primitives/faces.rs b/crates/ui-contract/src/primitives/faces.rs index 27d34eea6..ba3cf7bc0 100644 --- a/crates/ui-contract/src/primitives/faces.rs +++ b/crates/ui-contract/src/primitives/faces.rs @@ -6,10 +6,13 @@ use crate::fonts::{FaceBytes, FaceState}; /// Where a document face is asked for: a component's context, its measure or a content painter. pub trait FacesCx { - /// The face registered under `key` as a family of its own, read from a font catalog. `load` runs as a background - /// job, once while the face is kept, and the face is ready from the pass after it ends. A `load` that returns - /// `None` marks the key unavailable for as long as the context lives. Every call marks the face drawn in this frame. - fn document_face(&self, key: &str, load: impl FnOnce() -> Option + Send + 'static) -> FaceState; + /// The face registered under `key` as a family of its own, read from a font catalog. `job` is called only for a + /// key the registry does not know (a ready face costs nothing) and makes the load, which runs as a background job, + /// once while the face is kept; the face is ready from the pass after it ends. A load that returns `None` marks the + /// key unavailable for as long as the context lives. Every call marks the face drawn in this frame. + fn document_face(&self, key: &str, job: impl FnOnce() -> L) -> FaceState + where + L: FnOnce() -> Option + Send + 'static; /// The bytes of the face `document_face` registered under `key`, once it is ready: for reading its tables without /// loading the file again. @@ -17,8 +20,11 @@ pub trait FacesCx { } impl FacesCx for ContentPainterCx<'_> { - fn document_face(&self, key: &str, load: impl FnOnce() -> Option + Send + 'static) -> FaceState { - DocumentFaces::face(self.painter.ctx(), key, load) + fn document_face(&self, key: &str, job: impl FnOnce() -> L) -> FaceState + where + L: FnOnce() -> Option + Send + 'static, + { + DocumentFaces::face(self.painter.ctx(), key, job) } fn document_face_bytes(&self, key: &str) -> Option { diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index c2a06851e..23c7e051a 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -48,6 +48,8 @@ pub mod wheel; pub mod windows; pub use crate::contract::{Exemption, PatternKind, PatternProbe, Probe, Registration}; +#[cfg(feature = "testing")] +pub use crate::fonts::document::set_budget as document_face_budget; pub use crate::runtime::audit::{in_run as in_audit_run, set as audit_replays}; #[cfg(feature = "testing")] pub use crate::runtime::layout_memory::forget_kept as forget_measurements; diff --git a/crates/ui-contract/tests/it/fonts/document.rs b/crates/ui-contract/tests/it/fonts/document.rs index 892c2545b..310c78c48 100644 --- a/crates/ui-contract/tests/it/fonts/document.rs +++ b/crates/ui-contract/tests/it/fonts/document.rs @@ -1,17 +1,19 @@ //! Document faces read from a catalog: loaded off the pass, ready from the pass after, kept across a definitions -//! replacement and while drawn lately, and served to egui without making its fonts again. +//! replacement and while drawn lately (a settled view's replay counts), served to egui without making its fonts again, +//! and held within one budget. use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, LazyLock, Mutex}; +use std::time::Duration; use craft_behavior::Metrics; use craft_host::{AppInfo, Host, ManualJobs}; -use craft_ui::contract::{Common, Component, Cx, FacesCx as _, MeasureCx, Role, Show as _}; +use craft_ui::contract::{Common, Component, Cx, FacesCx, MeasureCx, MemoView, Role, Show as _}; use craft_ui::fonts::{self, FaceBytes, FaceState}; use craft_ui::primitives::{DocRun, DocText}; use craft_ui::style::{ComponentStyle, DataColor, StyleCx}; -use craft_ui::testing::{Frames, trial}; +use craft_ui::testing::{Frames, MemoRun, document_face_budget, last_frame_memo_runs, trial}; use egui::{Color32, Response, Vec2}; const FONT: &[u8] = include_bytes!("../../fonts/NotoSans-test.ttf"); @@ -44,13 +46,27 @@ impl Tally { } } -/// An owner of document faces: it asks for its keys while it is measured, and lays text out in each ready one. +/// Asks for the face `key`, whose load counts itself in `tally`; a key starting with `panic` names a load that panics. +fn ask(cx: &impl FacesCx, key: &str, tally: &Tally) -> FaceState { + cx.document_face(key, || { + let (loads, panics) = (Arc::clone(&tally.loads), key.starts_with("panic")); + move || { + loads.fetch_add(1, Ordering::Relaxed); + assert!(!panics, "a load that panics"); + Some(FaceBytes::new(Arc::from(FONT), 0)) + } + }) +} + +/// An owner of document faces: it asks for its keys while it is measured, and lays text out in each ready one; or, +/// with `in_run`, asks for them in its run only. #[derive(Component)] struct Owner { #[common] common: Common, keys: Vec, tally: Tally, + in_run: bool, } impl Component for Owner { @@ -63,12 +79,11 @@ impl Component for Owner { } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + if self.in_run { + return Vec2::splat(1.0); + } for key in &self.keys { - let loads = Arc::clone(&self.tally.loads); - let state = cx.document_face(key, move || { - loads.fetch_add(1, Ordering::Relaxed); - Some(FaceBytes::new(Arc::from(FONT), 0)) - }); + let state = ask(cx, key, &self.tally); if let FaceState::Ready(font) = &state { let runs = [DocRun::new("Ag", font.clone(), 14.0, DataColor::new(Color32::BLACK))]; let _ = cx.layout_doc(&DocText::new(&runs)); @@ -79,6 +94,12 @@ impl Component for Owner { } fn finish(self, cx: Cx<'_, Self>) -> Response { + if self.in_run { + for key in &self.keys { + let state = ask(&cx, key, &self.tally); + self.tally.states.lock().expect("the states").insert(key.clone(), state); + } + } cx.response.clone() } } @@ -99,7 +120,7 @@ fn rig() -> (Frames, Arc, Tally) { /// One frame in which an owner asks for `keys`. fn frame(frames: &mut Frames, tally: &Tally, keys: &[String]) { frames.frame(vec![], |ui| { - Owner { common: Common::new(), keys: keys.to_vec(), tally: tally.clone() }.show(ui); + Owner { common: Common::new(), keys: keys.to_vec(), tally: tally.clone(), in_run: false }.show(ui); }); } @@ -165,3 +186,100 @@ fn faces_stay_ready_after_the_definitions_are_replaced() { assert!(tally.all_ready(&wanted), "egui finds the served faces again"); assert_eq!(tally.loads(), 3, "without loading them again"); } + +/// Without a host the loads run on `default_jobs`' threads: every face asked for in one pass lands, each loaded once. +#[trial] +fn without_a_host_every_face_asked_for_in_one_pass_lands() { + let mut frames = Frames::new(); + let tally = Tally::default(); + let wanted = keys(0..8); + for _ in 0..1000 { + frame(&mut frames, &tally, &wanted); + if tally.all_ready(&wanted) { + break; + } + std::thread::sleep(Duration::from_millis(1)); + } + assert!(tally.all_ready(&wanted), "every face lands"); + assert_eq!(tally.loads(), 8, "and none was cancelled and loaded again"); +} + +#[trial] +fn a_load_that_panics_leaves_its_face_unavailable_and_asks_for_no_more_passes() { + let (mut frames, jobs, tally) = rig(); + let wanted = vec!["panic".to_owned()]; + frame(&mut frames, &tally, &wanted); + jobs.run_all(); + frame(&mut frames, &tally, &wanted); + assert_eq!(tally.state("panic"), FaceState::Unavailable); + frame(&mut frames, &tally, &wanted); + assert!(!frames.repaint_requested(), "the row stops asking for passes"); +} + +/// The tally of the memoized view's owner: its `show` is a function, so it reaches the tally by name. +static MEMOIZED: LazyLock = LazyLock::new(Tally::default); + +fn memoized(_: &mut u32, ui: &mut egui::Ui) { + Owner { common: Common::new(), keys: vec!["m0".to_owned(), "m1".to_owned()], tally: MEMOIZED.clone(), in_run: true }.show(ui); +} + +/// One frame of the memoized view beside an owner that asks for `keys`. +fn memo_frame(frames: &mut Frames, tally: &Tally, keys: &[String]) { + frames.frame(vec![], |ui| { + MemoView::new("faces", 1u32, memoized).show(ui); + Owner { common: Common::new(), keys: keys.to_vec(), tally: tally.clone(), in_run: false }.show(ui); + }); +} + +#[trial] +fn a_settled_view_that_replays_keeps_its_faces() { + let (mut frames, jobs, tally) = rig(); + let font = FONT.len(); + document_face_budget(&frames.ctx, 3 * font); + memo_frame(&mut frames, &tally, &[]); + jobs.run_all(); + for _ in 0..3 { + memo_frame(&mut frames, &tally, &[]); + } + assert!(MEMOIZED.all_ready(&["m0".to_owned(), "m1".to_owned()])); + let mut replayed = 0; + for start in (0..8).step_by(2) { + let others = keys(start..start + 2); + memo_frame(&mut frames, &tally, &others); + jobs.run_all(); + memo_frame(&mut frames, &tally, &others); + replayed += last_frame_memo_runs(&frames.ctx).iter().filter(|(_, _, run)| *run == MemoRun::Replayed).count(); + } + assert!(replayed > 0, "the view replays while the other faces push the registry past its budget"); + frame(&mut frames, &tally, &["m0".to_owned(), "m1".to_owned()]); + assert!(tally.all_ready(&["m0".to_owned(), "m1".to_owned()]), "the faces the replays showed are kept"); + assert_eq!(MEMOIZED.loads(), 2, "and were loaded once"); +} + +#[trial] +fn past_the_budget_the_faces_drawn_longest_ago_go_and_the_fonts_are_made_again_once() { + let (mut frames, jobs, tally) = rig(); + let font = FONT.len(); + document_face_budget(&frames.ctx, 6 * font); + // `keep` is drawn in every frame; one more face joins it each step. + let step = |frames: &mut Frames, key: &str| { + let wanted = vec!["keep".to_owned(), key.to_owned()]; + shown(frames, &jobs, &tally, &wanted); + generation(frames) + }; + let before = step(&mut frames, "k0"); + let filling: Vec = ["k1", "k2", "k3", "k4"].iter().map(|key| step(&mut frames, key)).collect(); + assert!(filling.iter().all(|g| *g == before), "within the budget nothing is taken out"); + let after = step(&mut frames, "k5"); + assert_ne!(after, before, "past it, egui's fonts are made again to free what went"); + for _ in 0..3 { + frame(&mut frames, &tally, &["keep".to_owned(), "k5".to_owned()]); + } + assert_eq!(generation(&frames), after, "once, not every frame"); + let all: Vec = ["keep", "k0", "k1", "k2", "k3", "k4", "k5"].iter().map(|key| (*key).to_owned()).collect(); + frame(&mut frames, &tally, &all); + let ready = |key: &str| matches!(tally.state(key), FaceState::Ready(_)); + assert!(ready("keep"), "a face drawn in the last frame stays, the first loaded included"); + assert!(["k0", "k1", "k2", "k3"].iter().all(|key| !ready(key)), "the faces drawn longest ago went"); + assert!(ready("k4") && ready("k5"), "down to half the budget, the faces drawn last stay"); +}