diff --git a/crates/cms/src/lutfile.rs b/crates/cms/src/lutfile.rs index b640c8dd7..bdc13e7f7 100644 --- a/crates/cms/src/lutfile.rs +++ b/crates/cms/src/lutfile.rs @@ -124,6 +124,34 @@ impl Format { } } +/// Most files [`list_folder`] lists. +const MAX_FILES: usize = 500; +/// Largest file [`list_folder`] lists: a 129³ `.cube` is about 60 MB. +const MAX_BYTES: u64 = 64 << 20; + +/// The `.cube`, `.3dl` and `.look` files directly in `dir` as (file name, path), sorted by name +/// without regard to case. An unreadable folder lists nothing; hidden files, subfolders and files +/// too large to be a LUT are skipped, and a symlink to a LUT file is listed. +pub fn list_folder(dir: &std::path::Path) -> Vec<(String, std::path::PathBuf)> { + let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut out: Vec<(String, std::path::PathBuf)> = entries + .flatten() + .filter_map(|entry| { + let name = entry.file_name().into_string().ok()?; + let extension = name.rsplit_once('.')?.1.to_ascii_lowercase(); + if name.starts_with('.') || !matches!(extension.as_str(), "cube" | "3dl" | "look") { + return None; + } + let path = entry.path(); + let meta = std::fs::metadata(&path).ok()?; + (meta.is_file() && meta.len() <= MAX_BYTES).then_some((name, path)) + }) + .collect(); + out.sort_by_key(|(name, _)| name.to_lowercase()); + out.truncate(MAX_FILES); + out +} + /// Parses a LUT, picking the format from `file_name`'s extension (falls back to sniffing). pub fn parse(file_name: &str, bytes: &[u8]) -> Result { parse_as(Format::detect(file_name, bytes), bytes) diff --git a/crates/color-ui/src/ui/lut_picker.rs b/crates/color-ui/src/ui/lut_picker.rs index afdb6a71d..2937f1207 100644 --- a/crates/color-ui/src/ui/lut_picker.rs +++ b/crates/color-ui/src/ui/lut_picker.rs @@ -4,8 +4,7 @@ //! [`Files`](craft_host::Files) and reads and parses it as a [`Jobs`](craft_host::Jobs) job. use std::path::{Path, PathBuf}; -use std::sync::{Arc, OnceLock}; -use std::time::Instant; +use std::sync::Arc; use craft_behavior::{EditEvent, EditEvents, Metrics, Mixed, Proposal, Sense}; use craft_cms::lutfile::{LutError, LutFile}; @@ -16,6 +15,7 @@ use craft_ui::contract::{ }; use craft_ui::pickers::Select; use craft_ui::runtime::env::Label; +use craft_ui::runtime::frame; use craft_ui::style::{ComponentStyle, StyleCx}; use egui::{Response, Vec2}; @@ -154,12 +154,6 @@ impl Default for Parsed { } } -/// The seconds since the first scan of the process, for the rescan interval. -fn seconds() -> u64 { - static START: OnceLock = OnceLock::new(); - START.get_or_init(Instant::now).elapsed().as_secs() -} - /// A select of LUTs. /// /// - Rows: Load 3D LUT…, None, the eight built-in looks, the LUT folder's files by name (in the language's @@ -269,9 +263,11 @@ impl Component for LutPicker<'_> { state = LutState { folder: self.folder.clone(), load: state.load, ..LutState::default() }; } if let Some(folder) = self.folder.clone() { - let key = ("lut-scan", folder.clone(), seconds() / RESCAN); + let key = ("lut-scan", folder.clone(), frame::stepped_clock(&cx.response.ctx, RESCAN as f64) as u64 / RESCAN); let started = folder.clone(); - if let Pending::Ready(found) = cx.pending(key, move || Job::new(move |_, _| Ok::<_, ()>(Arc::new(list_folder(&started))))) { + if let Pending::Ready(found) = + cx.pending(key, move || Job::new(move |_, _| Ok::<_, ()>(Arc::new(craft_cms::lutfile::list_folder(&started))))) + { let mut files = (**found).clone(); cx.env.collator().sort_by_key(&mut files, |(name, _)| name.as_str()); state.files = Arc::new(files); @@ -378,30 +374,3 @@ fn builtin_name(words: &LutWords, id: &str) -> Label { fn file_name(path: &Path) -> String { path.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned()) } -/// Most files [`list_folder`] lists. -const MAX_FILES: usize = 500; -/// Largest file [`list_folder`] lists: a 129³ `.cube` is about 60 MB. -const MAX_BYTES: u64 = 64 << 20; - -/// The `.cube`, `.3dl` and `.look` files directly in `dir` as (file name, path), sorted by name -/// without regard to case. An unreadable folder lists nothing; hidden files, subfolders and files -/// too large to be a LUT are skipped, and a symlink to a LUT file is listed. -fn list_folder(dir: &Path) -> FolderFiles { - let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; - let mut out: FolderFiles = entries - .flatten() - .filter_map(|entry| { - let name = entry.file_name().into_string().ok()?; - let extension = name.rsplit_once('.')?.1.to_ascii_lowercase(); - if name.starts_with('.') || !matches!(extension.as_str(), "cube" | "3dl" | "look") { - return None; - } - let path = entry.path(); - let meta = std::fs::metadata(&path).ok()?; - (meta.is_file() && meta.len() <= MAX_BYTES).then_some((name, path)) - }) - .collect(); - out.sort_by_key(|(name, _)| name.to_lowercase()); - out.truncate(MAX_FILES); - out -} diff --git a/crates/design-lint/README.md b/crates/design-lint/README.md index 7751a0f6c..20ac95787 100644 --- a/crates/design-lint/README.md +++ b/crates/design-lint/README.md @@ -75,7 +75,7 @@ reason = "document-space drawing" | `contract/entry` | in layers 5 and 6 (not layer 8): an inherent `pub fn show`, `show_at`, `show_in` or `ui` on a `pub` type that the file does not make a `Component` or `Pattern`; a `pub fn` taking `&mut Ui` and returning a `*Response` | | `contract/shadow`, `contract/widget`, `contract/overlay-flag` | an inherent `show`, `show_at`, `show_in`, `show_with_tip` or `show_at_with_tip` on a component; `impl egui::Widget`; an `overlay` override on a type without `#[component(overlay)]`. Derive output is the only allowed place, so no file is | | `contract/registration` | an `impl Component for` or `impl Pattern for` a type defined in the file that neither derives that trait nor appears in a `register_contract!(..)` invocation of the file. | -| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__split_for_bind` (only the `bind_tracked!` expansion calls it; no allowed location). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed per-item list `NO_GLOBAL_STATE` in `workspace.rs` (a file and the item's identifier or `std::fs`), each entry with the fact or later task that covers it. Clocks, called or passed as a fn value, are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | +| `contract/no-global-state` | every `static` (including `static mut` and statics inside functions), `thread_local!` and `lazy_static!`; `std::fs` by path or `use`; `impl MemoProps for` and `impl PlainData for` (only the derives implement them; no allowed location); any source occurrence of `__split_for_bind` (only the `bind_tracked!` expansion calls it; no allowed location). Skipped: `#[cfg(test)]` modules, `build.rs`, `src/bin/`. Allowed in: stories and `ui-contract`'s `testing`, and the reviewed per-item list `NO_GLOBAL_STATE` in `workspace.rs` (a file and the item's identifier or `std::fs`), each entry with the fact or test-data cache that covers it. Clocks, called or passed as a fn value, are `contract/motion:clock`; `unsafe_code` is the workspace `forbid` plus `contract/unsafe-allow` | Egui paths are resolved through the file's `use` items (one table per file, grouped, renamed and glob imports), so a craft type that shares a name with an egui type is not flagged unless it is imported from egui. diff --git a/crates/design-lint/src/workspace.rs b/crates/design-lint/src/workspace.rs index 22cafcd4f..93407230a 100644 --- a/crates/design-lint/src/workspace.rs +++ b/crates/design-lint/src/workspace.rs @@ -138,8 +138,8 @@ const NO_GLOBAL_STATE_PREFIXES: &[&str] = &[ ]; /// The reviewed per-item allowlist of `contract/no-global-state`: a file and what it may hold, either the identifier of -/// a `static` or `thread_local!` item or [`FS`] for `std::fs`. Each group names the settled fact or environment key that -/// covers it, or the later task of craft-libs#2336 that removes the state. A new item in these files is flagged. +/// a `static` or `thread_local!` item or [`FS`] for `std::fs`. Each group names the settled fact, environment key or test-data +/// cache that covers it. A new item in these files is flagged. const NO_GLOBAL_STATE: &[(&str, &str)] = &[ // Compile-time registry discovery reads the defining crate's source, never a view input. ("crates/ui-macros/src/registry.rs", FS), @@ -200,30 +200,8 @@ const NO_GLOBAL_STATE: &[(&str, &str)] = &[ ("crates/imaging/src/ui/layer_style/hosted.rs", "PAINT"), // Settled fact: a test fake of the font store; it writes a temporary folder. ("crates/font-manager/src/store/fake.rs", FS), - // later task of #2336: the brush trail id counter is hidden state. - ("crates/ui-canvas/src/canvas_controls/brush/trail.rs", "NEXT_ID"), - // later task of #2336: the outline hover generation counter is hidden state. - ("crates/ui-canvas/src/canvas_controls/outline/hover.rs", "GENERATIONS"), - // later task of #2336: the texture serial counter is hidden state. - ("crates/imaging/src/ui/transform_preview/textures.rs", "SERIAL"), - // later task of #2336: the mock image read cache is hidden state. + // A cache of pure test data: MockImage is used only by stories and trials. ("crates/imaging/src/ui/mock_image.rs", "READS"), - // later task of #2336: the ranking cache is hidden state. - ("crates/font-manager/src/picker/rank.rs", "CACHE"), - // later task of #2336: the face loader reads file sizes during the pass. - ("crates/font-manager/src/panel/faces.rs", FS), - // later task of #2336: the gallery's set of seen names is hidden state. - ("crates/ui-gallery/src/viewer/layout.rs", "NAMES"), - // later task of #2336: the LUT picker reads the process clock and scans folders during the pass. - ("crates/color-ui/src/ui/lut_picker.rs", "START"), - ("crates/color-ui/src/ui/lut_picker.rs", FS), -]; - -/// Files that may read a clock (`contract/motion:clock`) beyond the runtime's motion module. A file key, because -/// color-ui has no layer map. -const MOTION_CLOCK_FILES: &[&str] = &[ - // later task of #2336: the LUT picker reads the process clock during the pass. - "crates/color-ui/src/ui/lut_picker.rs", ]; /// Whether `what` (an item identifier or [`FS`]) may be declared or used in `file` for `contract/no-global-state`. @@ -405,9 +383,6 @@ impl RuleScope for WorkspaceScope { if let Some(what) = key.strip_prefix("contract/no-global-state:") { return no_global_state_allows(what, file); } - if key == "contract/motion:clock" && MOTION_CLOCK_FILES.iter().any(|f| file == Path::new(f)) { - return true; - } if key == "test/layout" { return file.starts_with(krate.dir.join("tests").join("it")); } diff --git a/crates/font-catalog/src/catalog.rs b/crates/font-catalog/src/catalog.rs index 10663e6af..a3464fed4 100644 --- a/crates/font-catalog/src/catalog.rs +++ b/crates/font-catalog/src/catalog.rs @@ -307,6 +307,7 @@ type FamilyLoad = Arc>>; /// Each family's files load once ([`Catalog::load_family`]): other threads asking for the same /// family wait for that load, other families load at the same time. pub struct Catalog { + id: u64, env: FontEnv, config: RwLock, index: RwLock>, @@ -331,7 +332,9 @@ impl Catalog { /// A catalog of the fonts installed on the system `env` describes, the font store, and the /// files the platform's font service lists (with the `system` feature). pub fn new(env: FontEnv) -> Self { + static NEXT_ID: AtomicU64 = AtomicU64::new(1); Self { + id: NEXT_ID.fetch_add(1, Ordering::Relaxed), env, config: RwLock::new(Config { app_dirs: Vec::new(), listers: Vec::new(), font_service: cfg!(feature = "system") }), index: RwLock::new(Arc::new(Index::default())), @@ -475,6 +478,13 @@ impl Catalog { Watch { stop } } + /// The catalog's identity: unique among the catalogs of the process, fixed at construction. Clones of the `Arc` + /// share it. A holder of derived data keys it by the id and the [`generation`](Catalog::generation), which counts + /// changes of this catalog only. + pub fn id(&self) -> u64 { + self.id + } + /// Counts the catalog's changes: each scan, and each face added or removed. pub fn generation(&self) -> u64 { self.generation.load(Ordering::Acquire) diff --git a/crates/font-catalog/src/scan.rs b/crates/font-catalog/src/scan.rs index 9afd1ac88..5466024e5 100644 --- a/crates/font-catalog/src/scan.rs +++ b/crates/font-catalog/src/scan.rs @@ -98,6 +98,9 @@ pub struct FaceInfo { pub code_pages: [u32; 2], /// The file the face is in; `None` for a face added as bytes. pub path: Option, + /// The size in bytes of the file when it was scanned; `None` for a face added as bytes. A caller that draws with the + /// face checks it before loading, so no file system read happens while it paints. + pub file_bytes: Option, /// The face's number in its file: its index in a collection (0 in a single font), or for a /// Mac suitcase font the number of its `sfnt` resource. pub index: u32, @@ -329,6 +332,7 @@ pub(crate) fn font_faces(font: &skrifa::FontRef<'_>, outlines: Outlines, index: fs_type, code_pages, path: path.map(Path::to_path_buf), + file_bytes: None, index, source, blob: None, @@ -430,9 +434,11 @@ pub(crate) fn file_faces(path: &Path, max_read: u64, source: Source) -> Vec String { /// The bytes of `face` from `catalog`, unless its file is too large to draw with. fn load(catalog: &Catalog, face: &FaceInfo) -> Option { - let too_large = face.path.as_ref().and_then(|path| std::fs::metadata(path).ok()).is_some_and(|meta| meta.len() > MAX_FILE_BYTES); + let too_large = face.file_bytes.is_some_and(|bytes| bytes > MAX_FILE_BYTES); if too_large { return None; } diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index dea1d1d7b..1521d943b 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -28,7 +28,8 @@ use egui::{Rect, Response, Vec2}; use serde::{Deserialize, Serialize}; use crate::missing::{DocumentFont, FontStatus, MissingFontsWords, document_fonts}; -use rank::{Info, infos, shown_name}; +pub use rank::FamilyInfos; +use rank::{Info, shown_name}; craft_ui::words! { /// The picker's words, English by default. @@ -288,9 +289,11 @@ pub struct FamilyRow { /// The families `listing` would show, in list order: recents first (when the query is empty and no filter is on), /// then the matching families, the best match first and ties in the order of `language` (its code, `ja`, `pt-BR`). -/// For apps that draw their own list from the picker's filtering. +/// For apps that draw their own list from the picker's filtering. `infos` is [`FamilyInfos::of`] of `catalog`, built +/// again by the app when the catalog's generation moves. pub fn family_rows( catalog: &Arc, + infos: &FamilyInfos, query: &str, settings: Option<&FontPickerSettings>, filters: &FontFilters, @@ -299,7 +302,12 @@ pub fn family_rows( ) -> Vec { let (folder, collator) = (craft_i18n::Folder::new(language), craft_i18n::Collator::new(language)); let listing = rank::Listing { query, settings, filters, current, language, served: &[] }; - rank::list(catalog, &infos(catalog), &listing, &rank::Language { folder: &folder, collator: &collator }, true).0 + rank::list(catalog, infos, &listing, &rank::Language { folder: &folder, collator: &collator }, true).0 +} + +/// The family data of `catalog` for the component `cx`: kept across passes while the catalog and its generation are unchanged. +pub(super) fn infos_of(ctx: &egui::Context, id: egui::Id, catalog: &Catalog) -> Arc { + craft_ui::runtime::derived::derived(ctx, id, &(catalog.id(), catalog.generation()), || FamilyInfos::of(catalog)) } /// How a [`FontPicker`] lays out its list. @@ -380,7 +388,7 @@ fn text_key() -> TextKey { /// The family field's text: the family's name in the interface language, and a typed name read back as a family. #[derive(Clone)] struct FamilyCodec { - infos: Arc, + infos: Arc, language: String, /// A typed name that is no installed family is a value too (Word's font box applies it as typed). free: bool, @@ -566,13 +574,13 @@ impl<'a> FontPicker<'a> { Some(Label::from(note)) } - fn codec(&self, env: &EnvView<'_>) -> FamilyCodec { - FamilyCodec { infos: infos(self.catalog), language: ui_language(env), free: self.kind == FontPickerKind::Plain } + fn codec(&self, infos: Arc, env: &EnvView<'_>) -> FamilyCodec { + FamilyCodec { infos, language: ui_language(env), free: self.kind == FontPickerKind::Plain } } /// The families in list order without filters or recents, which the arrows and the wheel step through. fn ordered(&self, cx: &Cx<'_, Self>, settings: Option<&FontPickerSettings>) -> Vec { - let infos = infos(self.catalog); + let infos = infos_of(&cx.response.ctx, cx.id, self.catalog); let (folder, collator) = (cx.env.folder(), cx.env.collator()); let filters = FontFilters::default(); let language = ui_language(&cx.env); @@ -631,7 +639,7 @@ impl Component for FontPicker<'_> { .pointer_only("Alt+Down opens the list") .toggles(POPUP); } - let codec = self.codec(&cx.env); + let codec = self.codec(infos_of(cx.ui.ctx(), cx.id, self.catalog), &cx.env); let mut options = TextOptions::new(); options.select_on_focus = true; cx.text(text_key(), placed.text, &codec, &family, &options); diff --git a/crates/font-manager/src/picker/rank.rs b/crates/font-manager/src/picker/rank.rs index 7d6637864..fa1f3f65a 100644 --- a/crates/font-manager/src/picker/rank.rs +++ b/crates/font-manager/src/picker/rank.rs @@ -2,7 +2,7 @@ //! traits read from the faces' tables, the filtered list and its order, and the sample text of a row. use std::collections::HashMap; -use std::sync::{Arc, Mutex, PoisonError, Weak}; +use std::sync::{Arc, Mutex, PoisonError}; use craft_font_catalog::{Catalog, FaceInfo, LocalizedName, Outlines}; use craft_i18n::matcher::{Matcher, Rank}; @@ -53,8 +53,10 @@ impl Traits { } } -/// The families of one catalog generation with their traits and sample texts, filled on first use. -pub(super) struct Infos { +/// The families of one catalog generation with their traits and sample texts, filled on first use. Built by +/// [`FamilyInfos::of`] and held by the one that lists with it: the picker keeps it in a derived value keyed by the +/// catalog's generation, and an app that calls [`family_rows`](super::family_rows) keeps its own while the catalog is unchanged. +pub struct FamilyInfos { pub(super) families: HashMap, traits: Mutex>>, samples: Mutex>, @@ -78,8 +80,9 @@ fn has_arabic_sample(drawn: &dyn Fn(&str) -> bool, latin: &str, arabic: &str) -> drawn(latin) && drawn(ARABIC_CORE) && drawn(arabic) } -impl Infos { - fn build(catalog: &Catalog) -> Infos { +impl FamilyInfos { + /// The family data of `catalog` as it is now; build it again when the catalog's generation moves. + pub fn of(catalog: &Catalog) -> FamilyInfos { let mut groups: HashMap> = HashMap::new(); for face in catalog.faces().iter() { groups.entry(face.family.clone()).or_default().push(face.clone()); @@ -99,7 +102,7 @@ impl Infos { Some((family, Info { localized, format, styles: faces.len(), regular })) }) .collect(); - Infos { families, traits: Mutex::new(HashMap::new()), samples: Mutex::new(HashMap::new()) } + FamilyInfos { families, traits: Mutex::new(HashMap::new()), samples: Mutex::new(HashMap::new()) } } /// The family's traits, read from its regular face on first use. @@ -147,24 +150,6 @@ fn draws(catalog: &Catalog, face: &FaceInfo, sample: &str, arabic: &str, shown: Some(Samples { latin: first, arabic: None }) } -type CacheEntry = (Weak, u64, Arc); -static CACHE: Mutex> = Mutex::new(Vec::new()); - -/// The family data of `catalog`, rebuilt when its generation moves. -pub(super) fn infos(catalog: &Arc) -> Arc { - let generation = catalog.generation(); - let same = |w: &Weak| std::ptr::eq(w.as_ptr(), Arc::as_ptr(catalog)); - let mut cache = lock(&CACHE); - cache.retain(|(w, _, _)| w.strong_count() > 0); - if let Some((_, _, infos)) = cache.iter().find(|(w, g, _)| *g == generation && same(w)) { - return Arc::clone(infos); - } - cache.retain(|(w, _, _)| !same(w)); - let infos = Arc::new(Infos::build(catalog)); - cache.push((Arc::downgrade(catalog), generation, Arc::clone(&infos))); - infos -} - /// The upright face nearest weight 400. pub(super) fn regular_face(faces: &[FaceInfo]) -> Option<&FaceInfo> { faces.iter().min_by_key(|f| (f.italic, (f.weight - 400.0).abs() as u32)) @@ -291,7 +276,13 @@ pub(super) struct Language<'a> { /// The rows the list shows for `listing` and whether Show Similar Fonts had a reference to compare with: recents /// first (when the query is empty and no filter is on), then the matching families, the best match first and ties /// in the interface language's order. A list that is not `narrowed` has no filters and no recents. -pub(super) fn list(catalog: &Arc, infos: &Infos, listing: &Listing<'_>, language: &Language<'_>, narrowed: bool) -> (Vec, bool) { +pub(super) fn list( + catalog: &Arc, + infos: &FamilyInfos, + listing: &Listing<'_>, + language: &Language<'_>, + narrowed: bool, +) -> (Vec, bool) { let default_filters = FontFilters::default(); let filters = if narrowed { listing.filters } else { &default_filters }; let settings = listing.settings; diff --git a/crates/font-manager/src/picker/rows.rs b/crates/font-manager/src/picker/rows.rs index bd76e0aa5..c35f4cac9 100644 --- a/crates/font-manager/src/picker/rows.rs +++ b/crates/font-manager/src/picker/rows.rs @@ -22,10 +22,10 @@ use craft_ui::primitives::{ContentPainterCx, IconSpec}; use craft_ui::runtime::env::Label; use egui::Rect; -use super::rank::{Infos, Language, Listing, list, shown_name}; +use super::rank::{FamilyInfos, Language, Listing, list, shown_name}; use super::{ - FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, POPUP, STAR, Typing, infos, read, - ui_language, write, + FamilyRow, FontClass, FontFilters, FontFormat, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, POPUP, STAR, Typing, infos_of, + read, ui_language, write, }; use crate::panel::faces::{Owner, Shown, paint_sample, shown}; use craft_ui::style::DataColor; @@ -256,7 +256,7 @@ fn class_column(ui: &mut egui::Ui, filters: &mut FontFilters, words: &FontPicker /// A thumbnail painting `text` in the regular face of `family`; nothing for a family the catalog lacks or an empty /// text, and nothing until the face is loaded. -fn face_thumb<'a>(catalog: &'a Arc, infos: &'a Infos, family: &'a str, text: String) -> impl Fn(&ContentPainterCx<'_>, Rect) + 'a { +fn face_thumb<'a>(catalog: &'a Arc, infos: &'a FamilyInfos, family: &'a str, text: String) -> impl Fn(&ContentPainterCx<'_>, Rect) + 'a { move |cx, rect| { let Some(info) = infos.families.get(family) else { return }; if text.is_empty() { @@ -270,7 +270,7 @@ fn face_thumb<'a>(catalog: &'a Arc, infos: &'a Infos, family: &'a str, } /// The banner: `text` in the face of `family`, on one line cut at the end, in a picture as high as the large thumbnail. -fn banner(ui: &mut egui::Ui, catalog: &Arc, infos: &Infos, family: &str, shown_name: &str, text: &str) { +fn banner(ui: &mut egui::Ui, catalog: &Arc, infos: &FamilyInfos, family: &str, shown_name: &str, text: &str) { Picture::painter(shown_name.to_owned(), ThumbAspect::new(BANNER_ASPECT.0, BANNER_ASPECT.1), face_thumb(catalog, infos, family, text.to_owned())) .extent(PictureSize::Thumb(ThumbSize::Large)) .show(ui); @@ -278,7 +278,7 @@ fn banner(ui: &mut egui::Ui, catalog: &Arc, infos: &Infos, family: &str /// 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: &Infos, family: &str, language: &str, settings: Option<&FontPickerSettings>) -> String { +fn banner_shown_name(slots: &[Slot], infos: &FamilyInfos, family: &str, language: &str, settings: Option<&FontPickerSettings>) -> String { let row = slots.iter().find_map(|slot| match slot { Slot::Family { row, .. } if row.family == family => Some(row.shown.clone()), _ => None, @@ -338,7 +338,7 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: let has_filters = filters.is_some(); let narrowing = filters.clone().unwrap_or_default(); let catalog = picker.catalog; - let infos = infos(catalog); + let infos = infos_of(&cx.response.ctx, cx.id, catalog); let language_code = ui_language(&cx.env); let (folder, collator) = (cx.env.folder(), cx.env.collator()); let listing = Listing { diff --git a/crates/font-manager/tests/it/picker.rs b/crates/font-manager/tests/it/picker.rs index 33c4f4775..8ef2bc258 100644 --- a/crates/font-manager/tests/it/picker.rs +++ b/crates/font-manager/tests/it/picker.rs @@ -9,7 +9,7 @@ use craft_behavior::{PartKey, Preview}; use craft_font_manager::craft_font_catalog::{Limits, Os, Source}; use craft_font_manager::missing::MissingFontsWords; use craft_font_manager::picker::{ - FontFilters, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, MissingAdvice, SIMILAR_COUNT, family_rows, + FamilyInfos, FontFilters, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, MissingAdvice, SIMILAR_COUNT, family_rows, }; use craft_font_manager::{Catalog, FontEnv}; use craft_ui::buttons::ControlPlace; @@ -18,7 +18,7 @@ use craft_ui::contract::{Bind, Show as _}; use craft_ui::runtime::env::{Label, with_env}; use craft_ui::testing::focus::AccessActionKind; use craft_ui::testing::pointer::moved; -use craft_ui::testing::{Fixture, Room, trial}; +use craft_ui::testing::{Fixture, Room, last_frame_derived_builds, trial}; use egui::{Event, Key, Modifiers}; const INTER_REGULAR: &[u8] = include_bytes!("../../../ui-contract/fonts/inter/Inter-Regular.ttf"); @@ -125,14 +125,15 @@ fn similar_fonts_put_the_current_family_first_and_leave_the_list_alone_without_a let catalog = catalog_of(&[epaint_default_fonts::HACK_REGULAR, epaint_default_fonts::UBUNTU_LIGHT, INTER_REGULAR]); let mut similar = FontFilters::default(); similar.similar = true; - let rows = family_rows(&catalog, "", None, &similar, "Inter", "en"); + let infos = FamilyInfos::of(&catalog); + let rows = family_rows(&catalog, &infos, "", None, &similar, "Inter", "en"); let names: Vec<&str> = rows.iter().map(|row| row.family.as_str()).collect(); assert_eq!(names.first(), Some(&"Inter"), "the current family first, though it is not first by name"); assert!(rows.len() <= SIMILAR_COUNT); // A current family the catalog lacks has no traits: the list stays as unfiltered. - let unfiltered = family_rows(&catalog, "", None, &FontFilters::default(), "", "en"); - assert_eq!(family_rows(&catalog, "", None, &similar, "Missing", "en"), unfiltered); + let unfiltered = family_rows(&catalog, &infos, "", None, &FontFilters::default(), "", "en"); + assert_eq!(family_rows(&catalog, &infos, "", None, &similar, "Missing", "en"), unfiltered); } #[trial] @@ -360,3 +361,42 @@ fn a_squeezed_ribbon_font_box_keeps_a_short_fields_name() { assert!(squeezed > short, "the squeezed font box keeps a name field {short} wide and its arrow: {squeezed}"); assert!(squeezed <= picker_width("Inter", true) + 0.5, "and is no wider than where the room allows"); } + +/// The family data builds of the last frame. +fn family_builds(fx: &Fixture) -> u32 { + last_frame_derived_builds(fx.ctx()).iter().map(|(_, builds)| builds).sum() +} + +#[trial] +fn the_family_data_builds_when_the_catalog_changes_and_not_while_it_is_idle() { + let catalog = catalog_of(&[INTER_REGULAR]); + let (mut fx, _) = rig(Arc::clone(&catalog), vec![]); + open(&mut fx); + fx.frame(vec![]); + assert_eq!(family_builds(&fx), 0, "an idle open list builds nothing"); + catalog.add_bytes(INTER_SEMIBOLD.to_vec(), Source::Bundled, &Limits::default()).expect("a font file"); + fx.frame(vec![]); + assert_eq!(family_builds(&fx), 1, "a changed catalog builds the data once, whatever reads it"); +} + +#[trial] +fn a_picker_handed_another_catalog_at_the_same_generation_builds_its_family_data_once() { + let (one, two) = (catalog_of(&[INTER_REGULAR]), catalog_of(&[INTER_REGULAR])); + assert_eq!(one.generation(), two.generation(), "the two catalogs count alike"); + assert_ne!(one.id(), two.id()); + let shown = Rc::new(RefCell::new(Arc::clone(&one))); + let held = Rc::clone(&shown); + let mut family = String::new(); + let mut fx = Fixture::new(move |ui| { + let catalog = Arc::clone(&held.borrow()); + FontPicker::new("Font family", Bind::bound(&mut family), &catalog).show(ui); + }); + fx.in_room(Room::Window); + fx.settle(); + open(&mut fx); + fx.frame(vec![]); + assert_eq!(family_builds(&fx), 0, "the first catalog's data is kept"); + *shown.borrow_mut() = Arc::clone(&two); + fx.frame(vec![]); + assert_eq!(family_builds(&fx), 1, "the second catalog builds the data once"); +} diff --git a/crates/imaging/src/ui/transform_preview/mod.rs b/crates/imaging/src/ui/transform_preview/mod.rs index 3c2af1c32..0834d3b6a 100644 --- a/crates/imaging/src/ui/transform_preview/mod.rs +++ b/crates/imaging/src/ui/transform_preview/mod.rs @@ -11,9 +11,11 @@ //! ```no_run //! use craft_imaging::ui::transform_preview::{PreviewMap, PreviewPixels, PreviewTextures, TransformPreview}; //! use craft_ui::contract::Show as _; +//! use craft_ui::primitives::Serials; //! # fn demo(ui: &mut egui::Ui, canvas_rect: egui::Rect, image: egui::ColorImage, quad: [kurbo::Point; 4]) { -//! // Once per session: -//! let textures = PreviewTextures::new("ft-preview", PreviewPixels::new(image, [1.0, 1.0])); +//! // Once per session, with the `Serials` the owner of the previews holds: +//! let mut serials = Serials::default(); +//! let textures = PreviewTextures::new(&mut serials, "ft-preview", PreviewPixels::new(image, [1.0, 1.0])); //! // Every pass, in the canvas body under the guides and the box: //! TransformPreview::new("Moving layer", &textures).map(PreviewMap::quad(quad)).opacity(0.8).clip([800, 600]).show_at(ui, canvas_rect); //! # } diff --git a/crates/imaging/src/ui/transform_preview/stories.rs b/crates/imaging/src/ui/transform_preview/stories.rs index 66588c15b..27ee1c2ff 100644 --- a/crates/imaging/src/ui/transform_preview/stories.rs +++ b/crates/imaging/src/ui/transform_preview/stories.rs @@ -9,6 +9,7 @@ use std::sync::{Arc, Mutex, OnceLock, PoisonError}; use craft_behavior::kurbo::{Point, Rect}; use craft_ui::canvas::{PixelRect, RasterSource}; use craft_ui::contract::Show as _; +use craft_ui::primitives::Serials; use craft_ui::testing::canvas_story::StoryDocument; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::{Color32, ColorImage, Ui}; @@ -102,7 +103,7 @@ impl Document { return Arc::clone(textures); } let name = format!("transform-story-{}x{}", size[0], size[1]); - let textures = Arc::new(PreviewTextures::from_levels(name, pyramid(size), [1.0, 1.0])); + let textures = Arc::new(PreviewTextures::from_levels(&mut Serials::default(), name, pyramid(size), [1.0, 1.0])); kept.push((size, Arc::clone(&textures))); textures } diff --git a/crates/imaging/src/ui/transform_preview/textures.rs b/crates/imaging/src/ui/transform_preview/textures.rs index d39c301af..d21bb5683 100644 --- a/crates/imaging/src/ui/transform_preview/textures.rs +++ b/crates/imaging/src/ui/transform_preview/textures.rs @@ -1,12 +1,11 @@ //! [`PreviewPixels`] and [`PreviewTextures`]: the moving pixels of a transform, read once and //! uploaded as a mip chain built on demand, off the UI thread where a finer level can stand in. -use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use craft_host::queue::Cancel; use craft_ui::primitives::{ - LoadFailure, LoadResult, LoadedPicture, LoaderOptions, Priority, Revision, TextureLoader, TextureState, TextureStatistics, TextureStore, + LoadFailure, LoadResult, LoadedPicture, LoaderOptions, Priority, Revision, Serials, TextureLoader, TextureState, TextureStatistics, TextureStore, TextureStoreOptions, }; use egui::{Color32, ColorImage, Context, TextureId, TextureOptions}; @@ -114,9 +113,6 @@ pub struct TextureChoice { /// The key of a preview's level in the shared stores: the preview's name and the level. type LevelKey = (Arc, u32); -/// Tells previews apart in the store revisions: a preview made under an old name with new pixels gets a new serial. -static SERIAL: AtomicU64 = AtomicU64::new(0); - /// The moving pixels uploaded for the preview: level 0 at once, the other mip levels (2 × 2 box filtered) and the /// nearest-filtered level 0 on first use. The CPU levels are kept for the session. /// @@ -137,21 +133,22 @@ pub struct PreviewTextures { } impl PreviewTextures { - /// The preview of `pixels`, named `name`: the store entries are keyed by it. Nothing is - /// uploaded until the preview is painted. - pub fn new(name: impl Into, pixels: PreviewPixels) -> Self { + /// The preview of `pixels`, named `name`: the store entries are keyed by it. `serials` tells this preview from an + /// earlier one of the same name (new pixels under an old name replace its textures); the previews of one owner + /// share it. Nothing is uploaded until the preview is painted. + pub fn new(serials: &mut Serials, name: impl Into, pixels: PreviewPixels) -> Self { let base_uv = pixels.base_uv; - Self::over(name, vec![Arc::new(pixels.image)], base_uv) + Self::over(serials, name, vec![Arc::new(pixels.image)], base_uv) } /// The preview over `levels` already built, level 0 first, covering the source with `base_uv`. #[cfg(feature = "screen-testing")] - pub(crate) fn from_levels(name: impl Into, levels: Vec>, base_uv: [f32; 2]) -> Self { - Self::over(name, levels, base_uv) + pub(crate) fn from_levels(serials: &mut Serials, name: impl Into, levels: Vec>, base_uv: [f32; 2]) -> Self { + Self::over(serials, name, levels, base_uv) } - fn over(name: impl Into, levels: Vec>, base_uv: [f32; 2]) -> Self { - let serial = SERIAL.fetch_add(1, Ordering::Relaxed); + fn over(serials: &mut Serials, name: impl Into, levels: Vec>, base_uv: [f32; 2]) -> Self { + let serial = serials.next(); Self { name: Arc::from(name.into()), serial, images: Arc::new(Mutex::new(levels)), base_uv } } diff --git a/crates/imaging/tests/it/transform_preview.rs b/crates/imaging/tests/it/transform_preview.rs index 882771cb6..ff6757207 100644 --- a/crates/imaging/tests/it/transform_preview.rs +++ b/crates/imaging/tests/it/transform_preview.rs @@ -15,6 +15,7 @@ use craft_imaging::ui::transform_preview::{ use craft_imaging::ui::warp::WarpMesh; use craft_ui::canvas::{Canvas, PixelRect}; use craft_ui::contract::{MemoProps, MemoView, PlainData, Show as _, ShowContainer as _, Tracked}; +use craft_ui::primitives::Serials; use craft_ui::testing::{Fixture, trial}; use egui::{Color32, ColorImage, Shape}; @@ -31,7 +32,7 @@ fn shown(map: fn() -> PreviewMap<'static>, opacity: f32, clip: Option<[u32; 2]>, let meshes = Rc::new(RefCell::new(Vec::new())); let seen_view = Rc::new(Cell::new(None)); let (sink, view_sink) = (Rc::clone(&meshes), Rc::clone(&seen_view)); - let textures = PreviewTextures::new("t", PreviewPixels::new(solid([2, 2], Color32::from_gray(u8::MAX)), [1.0, 1.0])); + let textures = PreviewTextures::new(&mut Serials::default(), "t", PreviewPixels::new(solid([2, 2], Color32::from_gray(u8::MAX)), [1.0, 1.0])); let mut fixture = Fixture::new(move |ui| { let room = ui.available_rect_before_wrap(); let view = CanvasView::new(room, pt(100.0, 100.0), 1.0).rotation(rotation); @@ -224,7 +225,7 @@ fn a_style_plan_stays_within_its_budget_at_screen_size_and_refuses_hostile_boxes fn a_monitor_conversion_changes_only_the_shown_upload() { let ctx = egui::Context::default(); let raw = solid([2, 2], Color32::from_rgb(140, 89, 51)); - let textures = PreviewTextures::new("monitor", PreviewPixels::new(raw.clone(), [1.0, 1.0])); + let textures = PreviewTextures::new(&mut Serials::default(), "monitor", PreviewPixels::new(raw.clone(), [1.0, 1.0])); // The trial stands in for the renderer: it takes the texture deltas it reads and applies none. let uploaded = |id: egui::TextureId| { let mut delta = ctx.tex_manager().write().take_delta(); @@ -316,7 +317,7 @@ fn frame(textures: &PreviewTextures, quad: [Point; 4], zoom: f32) -> StyledFrame } fn styled_textures() -> PreviewTextures { - PreviewTextures::new("styled", PreviewPixels::new(solid([4, 4], Color32::from_rgb(200, 100, 50)), [1.0, 1.0])) + PreviewTextures::new(&mut Serials::default(), "styled", PreviewPixels::new(solid([4, 4], Color32::from_rgb(200, 100, 50)), [1.0, 1.0])) } fn context() -> (Fixture, egui::Context) { @@ -424,7 +425,7 @@ struct Mips { } fn white(name: &str) -> Rc { - Rc::new(PreviewTextures::new(name, PreviewPixels::new(solid([5, 3], Color32::WHITE), [1.0, 1.0]))) + Rc::new(PreviewTextures::new(&mut Serials::default(), name, PreviewPixels::new(solid([5, 3], Color32::WHITE), [1.0, 1.0]))) } impl Mips { @@ -597,11 +598,12 @@ fn a_new_preview_under_the_same_name_shows_its_own_pixels() { delta.clear(); texel }; - let first = PreviewTextures::new("same", PreviewPixels::new(solid([2, 2], Color32::WHITE), [1.0, 1.0])); + let mut serials = Serials::default(); + let first = PreviewTextures::new(&mut serials, "same", PreviewPixels::new(solid([2, 2], Color32::WHITE), [1.0, 1.0])); let (id, _) = first.pick(&ctx, TextureChoice::new(0, false), None).expect("uploaded"); assert_eq!(uploaded(id), Some(Color32::WHITE)); drop(first); - let second = PreviewTextures::new("same", PreviewPixels::new(solid([2, 2], Color32::BLACK), [1.0, 1.0])); + let second = PreviewTextures::new(&mut serials, "same", PreviewPixels::new(solid([2, 2], Color32::BLACK), [1.0, 1.0])); let (id, _) = second.pick(&ctx, TextureChoice::new(0, false), None).expect("uploaded"); assert_eq!(uploaded(id), Some(Color32::BLACK), "the new pixels go up"); } diff --git a/crates/ui-canvas/src/canvas_controls/brush/mod.rs b/crates/ui-canvas/src/canvas_controls/brush/mod.rs index a71511bc2..02b2588b3 100644 --- a/crates/ui-canvas/src/canvas_controls/brush/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/brush/mod.rs @@ -30,6 +30,8 @@ pub(crate) mod source_marker; pub(crate) mod stories; mod tip; pub(crate) mod trail; +#[cfg(feature = "testing")] +pub(crate) mod trials; pub use cursor::{BrushCursor, BrushCursorOptions, PaintingCursor, TipCell, TipCellStyle}; pub use falloff::{FalloffPreview, FalloffPreviewStyle, TipFalloff}; diff --git a/crates/ui-canvas/src/canvas_controls/brush/stories.rs b/crates/ui-canvas/src/canvas_controls/brush/stories.rs index 36eaaac89..068089e44 100644 --- a/crates/ui-canvas/src/canvas_controls/brush/stories.rs +++ b/crates/ui-canvas/src/canvas_controls/brush/stories.rs @@ -11,7 +11,7 @@ use crate::canvas::testing::tool_story::{StoryHost, ToolScript, ToolStory, tool_ use crate::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer}; use crate::canvas_controls::CanvasControlWords; use crate::contract::Show as _; -use crate::primitives::Draw; +use crate::primitives::{Draw, Serials}; use crate::runtime::env::Env; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2}; @@ -56,8 +56,8 @@ fn hard_tip(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { } /// A drag-shaped mask whose stroke runs at height `y`. -fn stamped(y: f64) -> CoverageMask { - let mut mask = CoverageMask::new(DocRect::new(40.0, 60.0, 160.0, 140.0), 256); +fn stamped(serials: &mut Serials, y: f64) -> CoverageMask { + let mut mask = CoverageMask::new(serials, DocRect::new(40.0, 60.0, 160.0, 140.0), 256); mask.begin_stroke(); mask.stamp_capsule(Point::new(60.0, y), Point::new(100.0, y + 6.0), 5.0); mask.stamp_capsule(Point::new(100.0, y + 6.0), Point::new(140.0, y - 4.0), 5.0); @@ -66,7 +66,11 @@ fn stamped(y: f64) -> CoverageMask { /// The footprint of one tone. The mask is kept across passes (stamped once), so the trail uploads only what changed. fn footprint_of(ui: &mut Ui, data: &mut StoryData, label: &'static str, tone: TrailTone, y: f64) -> StoryOutput { - let mask = data.note::>("footprint", None).get_or_insert_with(|| stamped(y)); + if data.note::>("footprint", None).is_none() { + let made = stamped(data.note("serials", Serials::default()), y); + *data.note::>("footprint", None) = Some(made); + } + let mask = data.note::>("footprint", None).as_mut().expect("stamped above"); on_canvas_view(ui, brush_view, Some(&StoryDocument::STANDARD), |ui, rect, _| StrokeTrail::new(label, mask).tone(tone).show_at(ui, rect)) } diff --git a/crates/ui-canvas/src/canvas_controls/brush/trail.rs b/crates/ui-canvas/src/canvas_controls/brush/trail.rs index d4998e710..cc79d38f1 100644 --- a/crates/ui-canvas/src/canvas_controls/brush/trail.rs +++ b/crates/ui-canvas/src/canvas_controls/brush/trail.rs @@ -2,26 +2,23 @@ use crate::canvas::canvas_space; use crate::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role}; -use crate::primitives::{Revision, TextureState, TextureStore, TextureStoreOptions}; +use crate::primitives::{Revision, Serials, TextureState, TextureStore, TextureStoreOptions}; use crate::runtime::env::Label; use crate::style::{ComponentStyle, StyleColor, StyleCx}; use craft_behavior::kurbo::{Point, Rect}; use craft_behavior::{Input, Metrics}; use egui::epaint::{Mesh, Vertex}; use egui::{Color32, ColorImage, Response, Shape, pos2}; -use std::sync::atomic::{AtomicU64, Ordering}; /// The share of the tone's colour a full-coverage texel shows; the texture holds coverage only. const LIGHT_SHARE: f32 = 0.25; const SHADE_SHARE: f32 = 0.5; const DANGER_SHARE: f32 = 0.45; -/// The texture store's salt: one store for every trail of the context, keyed by the mask's id. +/// The texture store's salt: one store for every trail of the context, keyed by the trail's component id and the +/// mask's serial (serials are unique per owner, not per context). const STORE_SALT: &str = "canvas_controls.stroke_trail"; -/// Hands out the ids that keep two masks' textures apart. -static NEXT_ID: AtomicU64 = AtomicU64::new(1); - /// A coverage raster over a document rect: one byte per texel, `scale` document units wide, stamped by the tool as the /// stroke grows and uploaded by [`StrokeTrail`] by its changed rows. #[derive(Debug)] @@ -58,8 +55,9 @@ fn byte(coverage: f32) -> u8 { } impl CoverageMask { - /// A mask over `bounds` with no side longer than `max_side` texels. - pub fn new(bounds: Rect, max_side: u32) -> Self { + /// A mask over `bounds` with no side longer than `max_side` texels. Its texture's key comes from `serials`, which + /// the masks of one owner share. + pub fn new(serials: &mut Serials, bounds: Rect, max_side: u32) -> Self { let bounds = bounds.abs(); let finite = [bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite()); let bounds = if finite { bounds } else { Rect::ZERO }; @@ -68,16 +66,7 @@ impl CoverageMask { let extent = |side: f64| (side / scale).ceil().max(1.0) as u32; let size = (extent(bounds.width()), extent(bounds.height())); let len = size.0 as usize * size.1 as usize; - CoverageMask { - bounds, - scale, - size, - texels: vec![0; len], - base: vec![0; len], - dirty: None, - revision: 0, - id: NEXT_ID.fetch_add(1, Ordering::Relaxed), - } + CoverageMask { bounds, scale, size, texels: vec![0; len], base: vec![0; len], dirty: None, revision: 0, id: serials.next() } } /// Stamps the capsule from `from` to `to` (document units) of radius `radius`, keeping the larger coverage. @@ -270,8 +259,8 @@ impl Component for StrokeTrail<'_> { } let painter = ui.content_painter(cx); let ctx = painter.painter.ctx(); - let store = TextureStore::::in_context(ctx, STORE_SALT, TextureStoreOptions::frames()); - let (key, revision) = (self.mask.id, Revision::new(self.mask.revision)); + let store = TextureStore::<(egui::Id, u64)>::in_context(ctx, STORE_SALT, TextureStoreOptions::frames()); + let (key, revision) = ((cx.id, self.mask.id), Revision::new(self.mask.revision)); // A second paint of the pass finds the entry at this revision and nothing dirty. let texture = match store.state(ctx, &key, revision) { TextureState::Ready(texture) => texture, diff --git a/crates/ui-canvas/src/canvas_controls/brush/trials.rs b/crates/ui-canvas/src/canvas_controls/brush/trials.rs new file mode 100644 index 000000000..6727e6e70 --- /dev/null +++ b/crates/ui-canvas/src/canvas_controls/brush/trials.rs @@ -0,0 +1,48 @@ +//! Trials of the stroke trail's texture keys. +#![allow(clippy::panic, clippy::expect_used, reason = "trials assert by panicking")] + +use super::{CoverageMask, StrokeTrail}; +use crate::canvas::testing::canvas_story::{on_canvas_view, story_view}; +use crate::contract::Show as _; +use crate::primitives::Serials; +use crate::testing::{Frames, trial}; +use craft_behavior::kurbo::{Point, Rect as DocRect}; +use egui::{Shape, Ui}; + +fn stamped(serials: &mut Serials) -> CoverageMask { + let mut mask = CoverageMask::new(serials, DocRect::new(40.0, 60.0, 160.0, 140.0), 256); + mask.stamp_capsule(Point::new(60.0, 100.0), Point::new(140.0, 100.0), 5.0); + mask +} + +/// Two owners each count from one: their masks have the same serial and revision, and the trials they show at once +/// still upload a texture each. +#[trial] +fn two_owners_masks_with_one_serial_show_two_textures() { + let (mut first, mut second) = (stamped(&mut Serials::default()), stamped(&mut Serials::default())); + let mut frames = Frames::new(); + let mut ui = |ui: &mut Ui| { + for (name, mask) in [("Trail A", &mut first), ("Trail B", &mut second)] { + crate::testing::memory::scoped_by(ui, name, |ui| { + on_canvas_view( + ui, + |room, scale| story_view(room, scale, Point::new(100.0, 100.0), 1.0), + None, + |ui, rect, _| StrokeTrail::new(name, mask).show_at(ui, rect), + ); + }); + } + }; + frames.idle(3, &mut ui); + let shapes = frames.frame_shapes(&mut ui); + let mut textures: Vec<_> = shapes + .iter() + .filter_map(|shape| match shape { + Shape::Mesh(mesh) => Some(mesh.texture_id), + _ => None, + }) + .collect(); + textures.sort_by_key(|id| format!("{id:?}")); + textures.dedup(); + assert_eq!(textures.len(), 2, "two trials with one serial each show their own texture: {textures:?}"); +} diff --git a/crates/ui-canvas/src/canvas_controls/outline/hover.rs b/crates/ui-canvas/src/canvas_controls/outline/hover.rs index fac1fb985..29e69d8dd 100644 --- a/crates/ui-canvas/src/canvas_controls/outline/hover.rs +++ b/crates/ui-canvas/src/canvas_controls/outline/hover.rs @@ -1,8 +1,8 @@ //! `HoverMask`: an object's coverage, reduced for the hover tint. +use crate::primitives::Serials; use craft_behavior::kurbo::Rect; use std::sync::Arc; -use std::sync::atomic::{AtomicU64, Ordering}; /// An object's coverage reduced for the hover tint: at most [`HoverMask::MAX_TEXELS`] texels on its long side, /// sampled once when the mask is made. Cheap to clone (the texels are shared) and `Send + Sync`, so a lookup job can @@ -16,7 +16,7 @@ pub struct HoverMask { size: [usize; 2], /// Coverage 0..=255 per texel, row by row. coverage: Arc<[u8]>, - /// Unique per mask made, for the texture store. + /// Unique per mask made by one `Serials`, for the texture store. generation: u64, } @@ -35,9 +35,8 @@ impl HoverMask { /// corner of each texel's cell, with one texel per document unit until the long side passes /// [`MAX_TEXELS`](Self::MAX_TEXELS), then `ceil(long side / 768)` units per texel. Coverage outside 0..=1 is /// clamped; one that is not finite reads as 0. Empty or non-finite `bounds` give a 1 × 1 mask with no coverage. - pub fn sampled(bounds: Rect, coverage: impl Fn(f64, f64) -> f32) -> HoverMask { - static GENERATIONS: AtomicU64 = AtomicU64::new(0); - let generation = GENERATIONS.fetch_add(1, Ordering::Relaxed); + pub fn sampled(serials: &mut Serials, bounds: Rect, coverage: impl Fn(f64, f64) -> f32) -> HoverMask { + let generation = serials.next(); let finite = bounds.x0.is_finite() && bounds.y0.is_finite() && bounds.x1.is_finite() && bounds.y1.is_finite(); if !finite || bounds.width() <= 0.0 || bounds.height() <= 0.0 { return HoverMask { bounds, size: [1, 1], coverage: Arc::from(vec![0u8]), generation }; diff --git a/crates/ui-canvas/src/canvas_controls/outline/mod.rs b/crates/ui-canvas/src/canvas_controls/outline/mod.rs index a0a71e84c..c5a13fc07 100644 --- a/crates/ui-canvas/src/canvas_controls/outline/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/outline/mod.rs @@ -179,10 +179,10 @@ fn tint(mask: &HoverMask, color: Color32) -> ColorImage { ColorImage::new([width, height], pixels) } -fn paint_mask(painter: &ContentPainterCx<'_>, view: &CanvasView, mask: &HoverMask, color: Color32) { +fn paint_mask(painter: &ContentPainterCx<'_>, id: egui::Id, view: &CanvasView, mask: &HoverMask, color: Color32) { let ctx = painter.painter.ctx(); - let store = TextureStore::::in_context(ctx, "canvas_controls.hover_mask", TextureStoreOptions::frames()); - let texture = store.get_or_put(ctx, mask.generation(), Revision::of(&color.to_array()), || tint(mask, color)); + let store = TextureStore::<(egui::Id, u64)>::in_context(ctx, "canvas_controls.hover_mask", TextureStoreOptions::frames()); + let texture = store.get_or_put(ctx, (id, mask.generation()), Revision::of(&color.to_array()), || tint(mask, color)); let uvs = [pos2(0.0, 0.0), pos2(1.0, 0.0), pos2(1.0, 1.0), pos2(0.0, 1.0)]; let mut mesh = Mesh::with_texture(texture.sized().id); for (pos, uv) in view.quad(mask.bounds()).into_iter().zip(uvs) { @@ -250,7 +250,7 @@ impl Component for HoverOutline { stroke_run(&painter, points, closed, self.color, style.medium); } } - HoverShape::Mask(mask) => paint_mask(&painter, &view, mask, self.color.map_or(style.line.egui(), |color| color.0)), + HoverShape::Mask(mask) => paint_mask(&painter, cx.id, &view, mask, self.color.map_or(style.line.egui(), |color| color.0)), } } diff --git a/crates/ui-canvas/src/canvas_controls/outline/stories.rs b/crates/ui-canvas/src/canvas_controls/outline/stories.rs index 8019fbb83..f52ac4ecd 100644 --- a/crates/ui-canvas/src/canvas_controls/outline/stories.rs +++ b/crates/ui-canvas/src/canvas_controls/outline/stories.rs @@ -4,6 +4,7 @@ use super::{HoverMask, HoverOutline, HoverShape, SelectionOutline}; use crate::canvas::RasterSource as _; use crate::canvas::testing::canvas_story::{StoryDocument, StoryPicture, StoryShape, accent, on_canvas, on_picture, paint_shapes}; use crate::contract::Show as _; +use crate::primitives::Serials; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_behavior::kurbo::{self, BezPath, Circle, Point, Rect, Shape as _}; use egui::{Color32, Ui}; @@ -36,8 +37,9 @@ fn rollover(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { } #[story(HoverOutline, covers = [Default], drive = Drive::Never)] -fn coverage_tint(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - let mask = HoverMask::sampled(bounds(), |x, y| if DISC.contains(Point::new(x, y)) { 1.0 } else { 0.0 }); +fn coverage_tint(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let disc = |x, y| if DISC.contains(Point::new(x, y)) { 1.0 } else { 0.0 }; + let mask = HoverMask::sampled(data.note("serials", Serials::default()), bounds(), disc); let picture = objects(ui, &DISC); on_picture(ui, &picture, |ui, at, _| HoverOutline::new("Object", Some(HoverShape::Mask(mask.clone()))).show_at(ui, at)) } diff --git a/crates/ui-canvas/tests/it/canvas_controls/brush.rs b/crates/ui-canvas/tests/it/canvas_controls/brush.rs index 2ea1284ec..c0d0026b9 100644 --- a/crates/ui-canvas/tests/it/canvas_controls/brush.rs +++ b/crates/ui-canvas/tests/it/canvas_controls/brush.rs @@ -2,10 +2,11 @@ use craft_behavior::kurbo::{Point, Rect}; use craft_ui::canvas_controls::brush::CoverageMask; +use craft_ui::primitives::Serials; use craft_ui::testing::trial; fn mask() -> CoverageMask { - CoverageMask::new(Rect::new(0.0, 0.0, 100.0, 100.0), 100) + CoverageMask::new(&mut Serials::default(), Rect::new(0.0, 0.0, 100.0, 100.0), 100) } #[trial] @@ -44,7 +45,7 @@ fn a_restamp_keeps_earlier_strokes_and_stays_inside_its_rect() { #[trial] fn a_thin_stamp_on_a_large_document_still_shows() { - let mut mask = CoverageMask::new(Rect::new(0.0, 0.0, 20_000.0, 20_000.0), 1000); + let mut mask = CoverageMask::new(&mut Serials::default(), Rect::new(0.0, 0.0, 20_000.0, 20_000.0), 1000); assert_eq!((mask.scale(), mask.size()), (20.0, (1000, 1000))); // A one-unit line on a texel's edge, away from every texel centre. mask.restamp(Rect::new(5000.0, 5000.0, 5200.0, 5020.0), |at| if (at.y - 5000.5).abs() <= 0.5 { 1.0 } else { 0.0 }); diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index 895da0217..bb5a5056b 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -67,9 +67,9 @@ pub use tool::ToolIcon; #[cfg(feature = "testing")] pub use textures::FakeThumbSource; pub use textures::{ - CachedTexture, LoadFailure, LoadResult, LoadedPicture, LoaderOptions, MAX_TEXTURE, Priority, Revision, TextureBudget, TextureKey, TextureLoader, - TextureState, TextureStatistics, TextureStore, TextureStoreOptions, TextureWords, ThumbFit, ThumbJob, ThumbPaint, ThumbRender, ThumbRequest, - ThumbSource, ThumbnailOptions, Thumbnails, fit_image, fit_rect, reduce_image, texture_factor, texture_side, thumb_image, + CachedTexture, LoadFailure, LoadResult, LoadedPicture, LoaderOptions, MAX_TEXTURE, Priority, Revision, Serials, TextureBudget, TextureKey, + TextureLoader, TextureState, TextureStatistics, TextureStore, TextureStoreOptions, TextureWords, ThumbFit, ThumbJob, ThumbPaint, ThumbRender, + ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails, fit_image, fit_rect, reduce_image, texture_factor, texture_side, thumb_image, }; pub(crate) use draw::DataMode; diff --git a/crates/ui-contract/src/primitives/textures/mod.rs b/crates/ui-contract/src/primitives/textures/mod.rs index faabf4501..df9a52a57 100644 --- a/crates/ui-contract/src/primitives/textures/mod.rs +++ b/crates/ui-contract/src/primitives/textures/mod.rs @@ -8,7 +8,7 @@ mod words; pub use limits::{MAX_TEXTURE, fit_image, reduce_image, texture_factor, texture_side}; pub use loader::{LoadFailure, LoadResult, LoadedPicture, LoaderOptions, Priority, TextureLoader}; -pub use store::{CachedTexture, Revision, TextureBudget, TextureKey, TextureState, TextureStatistics, TextureStore, TextureStoreOptions}; +pub use store::{CachedTexture, Revision, Serials, TextureBudget, TextureKey, TextureState, TextureStatistics, TextureStore, TextureStoreOptions}; pub use words::TextureWords; /// The tint that leaves a texture's own colours as they are: every texel is multiplied by white. diff --git a/crates/ui-contract/src/primitives/textures/store.rs b/crates/ui-contract/src/primitives/textures/store.rs index 35fc6c92f..c1b230925 100644 --- a/crates/ui-contract/src/primitives/textures/store.rs +++ b/crates/ui-contract/src/primitives/textures/store.rs @@ -371,6 +371,22 @@ impl Default for Stores { } } +/// The numbers that keep apart the textures one owner makes: a mask or preview made anew gets a number no earlier one +/// of the same `Serials` had, so an entry kept under its key is never taken for the new one's. The owner of what the +/// textures show (a tool's state, a model) holds the `Serials`. The numbers are unique per owner, not per context: a +/// texture store that several owners share keys each entry by the owner's component id as well as the serial. Plain +/// data, so it can sit in tracked or model state. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Serials(u64); + +impl Serials { + /// The next number: never one this `Serials` gave before. + pub fn next(&mut self) -> u64 { + self.0 += 1; + self.0 + } +} + /// Textures by key and revision, with byte and entry budgets: the one place an app's pictures become egui /// textures. The app never holds a `TextureHandle`. The state lives in runtime memory of the context under the /// salt; the value is a cheap handle that clones share.