From 52c1f953ea5a76cbddccd4876f7cc19f3b2815f1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 13:31:20 +0000 Subject: [PATCH] craft-ui: env word sets, Units, formats and the host key memoized views by generation A word set written by words! keeps the generation of the Words it was localized in and keys by it. Format, DateFormat and Host get a generation per instance built (clones keep it), and Units keys by its format, words and point size. The scope key and the host's word cache use these generations, not pointers. Checks that captured env words, units or other locals take them as check_with inputs (page range, path field, print preview and font picker stories). --- crates/dialogs/src/ui/path_field.rs | 8 +++--- crates/font-manager/src/picker/stories.rs | 10 +++---- crates/host/src/lib.rs | 20 +++++++++++-- crates/i18n/src/date.rs | 18 ++++++++++-- crates/i18n/src/format.rs | 18 +++++++++++- crates/i18n/src/words.rs | 4 +-- crates/pages/src/ui/range.rs | 13 ++++----- crates/print/src/ui/stories.rs | 11 ++++---- crates/ui-contract/src/contract/memo.rs | 28 +++++++++++++++++++ crates/ui-contract/src/runtime/env.rs | 3 +- .../ui-contract/src/runtime/env/host_words.rs | 20 ++++++------- crates/ui-contract/src/runtime/env/units.rs | 9 ++++++ crates/ui-macros/src/words.rs | 14 ++++++++-- 13 files changed, 130 insertions(+), 46 deletions(-) diff --git a/crates/dialogs/src/ui/path_field.rs b/crates/dialogs/src/ui/path_field.rs index 464c3de04..0aa48b730 100644 --- a/crates/dialogs/src/ui/path_field.rs +++ b/crates/dialogs/src/ui/path_field.rs @@ -72,10 +72,10 @@ impl<'a> PathField<'a> { let before = held.read(cx).unwrap_or_default(); let looks = must_exist && cx.env.shell().caps.contains(Caps::FILE_SYSTEM); let not_found = words.not_found.clone(); - let check = move |path: &String| { - if looks && path_is_missing(path) { Validity::Warn(Message::new(not_found.clone())) } else { Validity::Ok } - }; - let row = PathRow::new(label.clone(), Bind::given(before.clone()).check(check)).pick(request.clone()).show(ui); + let value = Bind::given(before.clone()).check_with((looks, not_found), |(looks, not_found), path| { + if *looks && path_is_missing(path) { Validity::Warn(Message::new(not_found.clone())) } else { Validity::Ok } + }); + let row = PathRow::new(label.clone(), value).pick(request.clone()).show(ui); browsing = row.browsing; let answered = row.picked; let typed = row diff --git a/crates/font-manager/src/picker/stories.rs b/crates/font-manager/src/picker/stories.rs index 2b06cf323..ee355621e 100644 --- a/crates/font-manager/src/picker/stories.rs +++ b/crates/font-manager/src/picker/stories.rs @@ -151,11 +151,11 @@ fn font_picker_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(FontPicker<'static>, covers = [Invalid], drive = Drive::Never)] fn font_picker_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let catalog = catalog(); - let known = catalog.clone(); - let check = move |family: &String| { - if known.styles(family).is_empty() { Validity::Refuse(Message::new("No such font is installed")) } else { Validity::Ok } - }; - FontPicker::new("Font family", Bind::bound(data.value("family", "Gotham".to_owned())).check(check), &catalog).show(ui).into() + // The story's catalog is built once for the process, so the check reads it rather than taking it as an input. + let family = Bind::bound(data.value("family", "Gotham".to_owned())).check(|family| { + if self::catalog().styles(family).is_empty() { Validity::Refuse(Message::new("No such font is installed")) } else { Validity::Ok } + }); + FontPicker::new("Font family", family, &catalog).show(ui).into() } /// A family name far longer than the field. diff --git a/crates/host/src/lib.rs b/crates/host/src/lib.rs index f3b5a8d53..15562e20a 100644 --- a/crates/host/src/lib.rs +++ b/crates/host/src/lib.rs @@ -30,6 +30,14 @@ pub struct Host { commands: Arc, jobs: Arc, files: Arc, + /// Unique per host built (`generation`). + generation: u64, +} + +/// A generation no host built before has. +fn next_generation() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } /// Collects a [`Host`]'s services; each one defaults when not set. @@ -49,6 +57,13 @@ impl Host { HostBuilder { app, i18n: None, lang: None, settings: None, commands: None, jobs: None, files: None } } + /// Which host this is: a host and its clones hold the same services and language, and one built anew + /// ([`HostBuilder::build`], [`Host::with_lang`], [`Host::with_files`]) gets a new generation. What the services + /// hold (settings sections, catalogs) changes inside them without changing the generation. + pub fn generation(&self) -> u64 { + self.generation + } + /// The app's name and version. pub fn app(&self) -> &AppInfo { &self.app @@ -97,12 +112,12 @@ impl Host { /// A copy in another language; install it to switch the interface. pub fn with_lang(&self, lang: Lang) -> Host { - Host { lang, ..self.clone() } + Host { lang, generation: next_generation(), ..self.clone() } } /// A copy with another file service; install it to switch the pickers. pub fn with_files(&self, files: Arc) -> Host { - Host { files, ..self.clone() } + Host { files, generation: next_generation(), ..self.clone() } } /// The stored value of section `S`, or `S::default()` when it is missing or does not fit `S`. @@ -166,6 +181,7 @@ impl HostBuilder { commands: self.commands.unwrap_or_else(|| Arc::new(NoCommands)), jobs: self.jobs.unwrap_or_else(default_jobs), files: self.files.unwrap_or_else(|| Arc::new(NoPickFiles::default())), + generation: next_generation(), } } diff --git a/crates/i18n/src/date.rs b/crates/i18n/src/date.rs index d554d66a3..0b1e33a9d 100644 --- a/crates/i18n/src/date.rs +++ b/crates/i18n/src/date.rs @@ -276,6 +276,8 @@ pub struct DateFormat { latin_digits: bool, /// Formatters and names, built on first use and shared by clones. cache: Arc, + /// Unique per format built; a clone keeps it (`generation`). + generation: u64, } /// One ICU formatter per field set the styles need. @@ -374,13 +376,25 @@ impl PartsWrite for Spliced { impl DateFormat { /// The format for `region`'s time locale and clock. pub fn new(region: &Region) -> DateFormat { - Self { locale: region.time.clone(), hour_cycle: region.hour_cycle, latin_digits: false, cache: Arc::default() } + Self { + locale: region.time.clone(), + hour_cycle: region.hour_cycle, + latin_digits: false, + cache: Arc::default(), + generation: crate::words::next_generation(), + } } /// This format writing `0`–`9` for [`Digits::Latin`], else the locale's own digits. Formatters /// are rebuilt on first use. pub fn with_digits(self, digits: Digits) -> DateFormat { - DateFormat { latin_digits: digits == Digits::Latin, cache: Arc::default(), ..self } + DateFormat { latin_digits: digits == Digits::Latin, cache: Arc::default(), generation: crate::words::next_generation(), ..self } + } + + /// Which format this is: a format and its clones write every date the same, and one built anew gets a new + /// generation. What keys on the dates a format writes keys on this. + pub fn generation(&self) -> u64 { + self.generation } /// The format for a locale tag (`de-CH`), with the locale's clock. diff --git a/crates/i18n/src/format.rs b/crates/i18n/src/format.rs index 163f5ed27..3b3cc78b7 100644 --- a/crates/i18n/src/format.rs +++ b/crates/i18n/src/format.rs @@ -38,6 +38,8 @@ pub struct Format { pub(crate) marks: Marks, /// The decimal and group marks of the written form, read once from a number that shows both. separators: (char, Option), + /// Unique per format built (`generation`). + generation: u64, } impl Format { @@ -50,7 +52,15 @@ impl Format { } let decimal = data::provider() .and_then(|p| DecimalFormatter::try_new_with_buffer_provider(p, (&locale).into(), DecimalFormatterOptions::default()).ok()); - let mut format = Format { decimal, group: None, point: None, percent: ("", "%"), marks: Marks::default(), separators: ('.', None) }; + let mut format = Format { + decimal, + group: None, + point: None, + percent: ("", "%"), + marks: Marks::default(), + separators: ('.', None), + generation: crate::words::next_generation(), + }; // The locale's own separators and digits, read from a number that shows them all. let probe = format.parts(&Decimal::try_from_str("-1234567.5").unwrap_or_default()); let latin = probe.integer.starts_with(|c: char| c.is_ascii_digit()); @@ -84,6 +94,12 @@ impl Format { format } + /// Which format this is: a format writes every number the same for its whole life, and one built anew gets a new + /// generation. What keys on the numbers a format writes keys on this. + pub fn generation(&self) -> u64 { + self.generation + } + /// The decimal and group marks numbers are written with, in the digits of the format. The group mark is /// `None` where the format writes none. pub fn separators(&self) -> (char, Option) { diff --git a/crates/i18n/src/words.rs b/crates/i18n/src/words.rs index 03339d98f..fc704b728 100644 --- a/crates/i18n/src/words.rs +++ b/crates/i18n/src/words.rs @@ -104,8 +104,8 @@ pub struct Words { generation: u64, } -/// A generation no `Words` built before has; English (the default) is 0. -fn next_generation() -> u64 { +/// A generation no `Words`, `Format` or `DateFormat` built before has; English (the default) is 0. +pub(crate) fn next_generation() -> u64 { static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } diff --git a/crates/pages/src/ui/range.rs b/crates/pages/src/ui/range.rs index 413656d2f..abfe9ae5e 100644 --- a/crates/pages/src/ui/range.rs +++ b/crates/pages/src/ui/range.rs @@ -164,19 +164,16 @@ impl<'a> PageRangeField<'a> { let env = Env::of(ui); let words = env.words::(); let units = env.units(); - let refuse = { - let (words, units) = (words.clone(), units.clone()); - move |value: &PageSelection| match &value.error { - Some(error) => Validity::Refuse(Message::new(words.error(error, &units))), - None => Validity::Ok, - } - }; let placeholder = units.number((current.min(count.saturating_sub(1)) + 1) as f64, 0..=0); let mut picked = None; let mut response = None; Field::new(label).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { - let value = Bind::given(PageSelection::of(pages)).check(&refuse); + let value = + Bind::given(PageSelection::of(pages)).check_with((words.clone(), units.clone()), |(words, units), value| match &value.error { + Some(error) => Validity::Refuse(Message::new(words.error(error, units))), + None => Validity::Ok, + }); let field = TextField::with_codec(words.selected_pages.clone(), value, PageRangeCodec::new(count)) .placeholder(Label::from(placeholder.clone())) .show(ui); diff --git a/crates/print/src/ui/stories.rs b/crates/print/src/ui/stories.rs index 8659985a8..4a9597fe2 100644 --- a/crates/print/src/ui/stories.rs +++ b/crates/print/src/ui/stories.rs @@ -9,7 +9,7 @@ use craft_ui::runtime::env::Message; use craft_ui::testing::pictures::sample_picture; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::load::SizedTexture; -use egui::{Color32, ColorImage, Pos2, Rect, Ui, Vec2, pos2}; +use egui::{Color32, ColorImage, Rect, Ui, Vec2, pos2}; fn printers() -> Vec { vec![ @@ -68,11 +68,10 @@ fn print_preview_refused(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let sheet = preview_sheet(ui); let paper = Rect::from_min_size(pos2(0.0, 0.0), sheet.paper); let size = sheet.image.size(); - let on_paper = move |at: &Pos2| { - if paper.contains_rect(Rect::from_min_size(*at, size)) { Validity::Ok } else { Validity::Refuse(Message::new("Off the paper")) } - }; - let position = data.value("position", pos2(400.0, 156.0)); - PrintPreview::new("Print preview", &sheet, Bind::bound(position).check(on_paper)).show(ui).into() + let position = Bind::bound(data.value("position", pos2(400.0, 156.0))).check_with((paper, size), |(paper, size), at| { + if paper.contains_rect(Rect::from_min_size(*at, *size)) { Validity::Ok } else { Validity::Refuse(Message::new("Off the paper")) } + }); + PrintPreview::new("Print preview", &sheet, position).show(ui).into() } #[story(PrintDialog<'static>, covers = [], drive = Drive::Never)] diff --git a/crates/ui-contract/src/contract/memo.rs b/crates/ui-contract/src/contract/memo.rs index 162c8a970..e917c3f4f 100644 --- a/crates/ui-contract/src/contract/memo.rs +++ b/crates/ui-contract/src/contract/memo.rs @@ -746,6 +746,34 @@ impl MemoProps for craft_behavior::Mixed { } } +/// The translator (`Words::generation`): words with the same generation read every word the same. +impl MemoProps for craft_i18n::Words { + fn key(&self, key: &mut MemoKey) { + self.generation().key(key); + } +} + +/// The format (`Format::generation`): a format writes every number the same for its whole life. +impl MemoProps for craft_i18n::Format { + fn key(&self, key: &mut MemoKey) { + self.generation().key(key); + } +} + +/// The format (`DateFormat::generation`): a format and its clones write every date the same. +impl MemoProps for craft_i18n::DateFormat { + fn key(&self, key: &mut MemoKey) { + self.generation().key(key); + } +} + +/// The host (`Host::generation`): a host and its clones hold the same services and language. +impl MemoProps for craft_host::Host { + fn key(&self, key: &mut MemoKey) { + self.generation().key(key); + } +} + impl MemoProps for craft_keymap::CommandRef { fn key(&self, key: &mut MemoKey) { let craft_keymap::CommandRef { id, params } = self; diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index ec3180b4a..2371ae50c 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -414,8 +414,7 @@ impl Scoped { id.key(&mut key); } key.feed_hash(&(std::mem::discriminant(&self.motion.mode), self.canvas_pattern, self.tab_toggles_chrome, self.today)); - key.feed_hash(&(Arc::as_ptr(&self.format) as usize, Arc::as_ptr(&self.dates) as usize)); - key.feed_hash(&self.host.as_ref().map(|host| Arc::as_ptr(host) as usize)); + (&self.format, &self.dates, &self.host).key(&mut key); let value_bytes = self.values.key(&mut key); #[cfg(feature = "testing")] crate::runtime::measure::count_memo_key_bytes(&self.ctx, key.bytes() + value_bytes); diff --git a/crates/ui-contract/src/runtime/env/host_words.rs b/crates/ui-contract/src/runtime/env/host_words.rs index 650d3e121..1cf5091d2 100644 --- a/crates/ui-contract/src/runtime/env/host_words.rs +++ b/crates/ui-contract/src/runtime/env/host_words.rs @@ -7,31 +7,27 @@ use craft_i18n::{WordRows, Words}; use egui::Context; use std::sync::Arc; -/// The words of the installed `Host`, kept until the `Host` changes so that the word sets built from them are -/// built once. +/// The words of the installed `Host`, kept until another host is installed (`Host::generation`; `None` without a +/// host) so that the word sets built from them are built once. #[derive(Default)] struct HostWords { - host: Option>, - words: Option>, + words: Option<(Option, Arc)>, } /// The catalogs of `host` in its language, English without a host or a catalog. pub(super) fn host_words(ctx: &Context, host: Option<&Arc>) -> Arc { + let generation = host.map(|host| host.generation()); Service::::run(ctx, |cached| { - let same = match (&cached.host, host) { - (Some(kept), Some(host)) => std::sync::Weak::ptr_eq(kept, &Arc::downgrade(host)), - (None, None) => true, - _ => false, - }; - if let (true, Some(words)) = (same, &cached.words) { + if let Some((kept, words)) = &cached.words + && *kept == generation + { return Arc::clone(words); } let words = Arc::new(match host.and_then(|host| host.i18n_shared().map(|i18n| (Arc::clone(i18n), host.lang()))) { Some((i18n, lang)) => Words::from_i18n(i18n, lang), None => Words::english(), }); - cached.host = host.map(Arc::downgrade); - cached.words = Some(Arc::clone(&words)); + cached.words = Some((generation, Arc::clone(&words))); words }) } diff --git a/crates/ui-contract/src/runtime/env/units.rs b/crates/ui-contract/src/runtime/env/units.rs index a504fb4b7..914423660 100644 --- a/crates/ui-contract/src/runtime/env/units.rs +++ b/crates/ui-contract/src/runtime/env/units.rs @@ -314,6 +314,15 @@ pub struct Units { point_size: PointSize, } +/// What every number it reads and writes depends on: the format, the unit words and the scope's words (each by its +/// generation) and the point size. +impl crate::contract::MemoProps for Units { + fn key(&self, key: &mut crate::contract::MemoKey) { + let Units { format, words, scope_words, readers: _, point_size } = self; + crate::contract::MemoProps::key(&(format, words, scope_words, point_size), key); + } +} + impl Units { /// The codec of a zoom field in percent: the percent reader, up to two decimals (the zoom ladder has rungs such as /// 66.67 %), with zoom typing (`a/b` as a ratio, a second separator cutting the text), so every zoom field reads diff --git a/crates/ui-macros/src/words.rs b/crates/ui-macros/src/words.rs index 9cc9e9949..ce4a34c9e 100644 --- a/crates/ui-macros/src/words.rs +++ b/crates/ui-macros/src/words.rs @@ -291,6 +291,10 @@ pub(crate) fn expand_words(input: TokenStream) -> syn::Result { #[derive(Clone, Debug)] #vis struct #name { #(#fields,)* + /// The generation of the `Words` the set was localized in (`Words::generation`; English is 0): what a + /// memoized view's key takes for the set. + #[doc(hidden)] + pub __words: u64, } impl #env::WordSet for #name { @@ -298,11 +302,11 @@ pub(crate) fn expand_words(input: TokenStream) -> syn::Result { const COUNTS: &'static [#env::Counted] = &[#(#counts),*]; fn english() -> Self { - Self { #(#english),* } + Self { #(#english,)* __words: 0 } } fn localized_in(self, words: &#env::Words) -> Self { - Self { #(#localized),* } + Self { #(#localized,)* __words: words.generation() } } fn rows(&self) -> #env::WordRows { @@ -310,6 +314,12 @@ pub(crate) fn expand_words(input: TokenStream) -> syn::Result { } } + impl #k::contract::MemoProps for #name { + fn key(&self, key: &mut #k::contract::MemoKey) { + #k::contract::MemoProps::key(&self.__words, key); + } + } + impl ::core::default::Default for #name { fn default() -> Self { ::english()