Cache translated UI menu entries

This commit is contained in:
FredApps committed 2026-11-19 08:59:56 +01:00
1 parent 5e6b4c0945
commit c4ffecba76
6 files changed
+112 -56

No files matched your search

+20
View File
@@ -371,6 +371,26 @@ pub fn current() -> Lang {
CURRENT.get()
}
/// Values built for a language and a caller-provided key. Catalog identity keeps test and
/// preview catalogs separate even when they use the same language code.
pub(crate) struct LangCache<K, V> {
entries: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<(&'static str, usize, K), V>>>,
}
impl<K: Eq + std::hash::Hash, V: Clone> LangCache<K, V> {
pub const fn new() -> Self {
Self { entries: std::sync::OnceLock::new() }
}
pub fn get_or_build(&self, key: K, build: impl FnOnce() -> V) -> V {
let lang = current();
let catalog = std::ptr::from_ref(lang.i18n()) as usize;
let mut entries =
self.entries.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new())).lock().unwrap_or_else(std::sync::PoisonError::into_inner);
entries.entry((lang.code(), catalog, key)).or_insert_with(build).clone()
}
}
/// Temporarily draw in another language, restoring the previous one even on unwinding.
/// Preferences previews use this without changing the saved setting or other dialogs.
pub fn with_language<R>(lang: Lang, draw: impl FnOnce() -> R) -> R {
+14
View File
@@ -456,3 +456,17 @@ fn bundled_catalogs_are_consistent() {
}
}
}
#[test]
fn language_cache_separates_catalogs_and_keys() {
let cache = LangCache::<u8, String>::new();
let first = fixture_lang("de", "\tAll\tfirst\n");
let second = fixture_lang("de", "\tAll\tsecond\n");
with_language(first, || {
assert_eq!(cache.get_or_build(1, || t("All").to_owned()), "first");
assert_eq!(cache.get_or_build(1, || "unexpected rebuild".to_owned()), "first");
assert_eq!(cache.get_or_build(2, || "other key".to_owned()), "other key");
});
with_language(second, || assert_eq!(cache.get_or_build(1, || t("All").to_owned()), "second"));
with_language(first, || assert_eq!(cache.get_or_build(1, || "unexpected rebuild".to_owned()), "first"));
}
+28 -19
View File
@@ -382,15 +382,20 @@ impl LayerTree for PhotoLayers<'_> {
}
fn blend_modes(&self, group: bool, current: &str) -> Vec<Entry<String>> {
static CACHE: crate::i18n::LangCache<(bool, BlendMode), Vec<Entry<String>>> = crate::i18n::LangCache::new();
let current = BlendMode::from_key(current).or_else(|| blend_of(current)).unwrap_or(BlendMode::Normal);
let modes: Vec<BlendKeyEntry<BlendMode>> = super::layers::blend_options(group, current).into_iter().map(|(m, _)| super::blend_entry(m, m)).collect();
blend_entries(&modes, |mode| Label::from(tl!(mode.key.label()).to_string()))
.into_iter()
.map(|entry| match entry.value() {
Some(mode) => Entry::new(mode.key().to_string(), entry.label().clone()),
None => Entry::separator(),
})
.collect()
let current = if current.has_psd_equivalent() { BlendMode::Normal } else { current };
CACHE.get_or_build((group, current), || {
let modes: Vec<BlendKeyEntry<BlendMode>> =
super::layers::blend_options(group, current).into_iter().map(|(m, _)| super::blend_entry(m, m)).collect();
blend_entries(&modes, |mode| Label::from(tl!(mode.key.label()).to_string()))
.into_iter()
.map(|entry| match entry.value() {
Some(mode) => Entry::new(mode.key().to_string(), entry.label().clone()),
None => Entry::separator(),
})
.collect()
})
}
fn footer(&self) -> LayersFooterState {
@@ -413,18 +418,22 @@ impl LayerTree for PhotoLayers<'_> {
crate::i18n::fmt(tl!("Add a mask (from the selection; {key} inverts)"), &[("key", &crate::shortcuts::pretty("Alt"))])
}
});
let mut adjustments: Vec<Entry<String>> = photocraft_engine::command_specs()
.iter()
.filter(|c| c.id.starts_with("layer.newAdjustmentLayer."))
.map(|c| Entry::new(c.id.to_string(), tl!(c.label).trim_end_matches('…').to_string()))
.collect();
adjustments.push(Entry::separator());
adjustments.push(Entry::new("layer.newFillLayer.solidColor".to_string(), tl!("Solid Color…").to_string()));
adjustments.push(Entry::new("layer.newFillLayer.gradient".to_string(), tl!("Gradient…").to_string()));
adjustments.push(Entry::new("layer.newFillLayer.pattern".to_string(), tl!("Pattern…").to_string()));
static MENUS: crate::i18n::LangCache<(), (Vec<Entry<String>>, Vec<Entry<String>>)> = crate::i18n::LangCache::new();
let (adjustments, styles) = MENUS.get_or_build((), || {
let mut adjustments: Vec<Entry<String>> = photocraft_engine::command_specs()
.iter()
.filter(|c| c.id.starts_with("layer.newAdjustmentLayer."))
.map(|c| Entry::new(c.id.to_string(), tl!(c.label).trim_end_matches('…').to_string()))
.collect();
adjustments.push(Entry::separator());
adjustments.push(Entry::new("layer.newFillLayer.solidColor".to_string(), tl!("Solid Color…").to_string()));
adjustments.push(Entry::new("layer.newFillLayer.gradient".to_string(), tl!("Gradient…").to_string()));
adjustments.push(Entry::new("layer.newFillLayer.pattern".to_string(), tl!("Pattern…").to_string()));
let mut styles = vec![Entry::new(String::new(), tl!("Blending Options…").to_string()), Entry::separator()];
styles.extend(crate::layer_style::KINDS.iter().map(|&(kind, label)| Entry::new(kind.to_string(), format!("{}…", tl!(label)))));
(adjustments, styles)
});
footer.adjustment_menu = adjustments;
let mut styles = vec![Entry::new(String::new(), tl!("Blending Options…").to_string()), Entry::separator()];
styles.extend(crate::layer_style::KINDS.iter().map(|&(kind, label)| Entry::new(kind.to_string(), format!("{}…", tl!(label)))));
footer.style_menu = styles;
footer
}
+28 -25
View File
@@ -24,32 +24,35 @@ fn label_of(mode: PaintMode) -> String {
/// "Threshold", as the reference does for the stamps in an Indexed Color document. Empty for a tool without a blend
/// mode control.
pub(crate) fn mode_entries(tool: Tool, behind_enabled: bool, threshold: bool) -> Vec<Entry<PaintMode>> {
let keyed: Vec<BlendKeyEntry<PaintMode>> = if tool == Tool::PatternStamp {
crate::brush_mode_menu::pattern_stamp_choices()
.into_iter()
.filter_map(|((mode, behind), _)| match (mode, behind) {
(Some(blend), false) => Some(crate::panels::blend_entry(PaintMode::Blend(blend), blend)),
(None, true) => Some(BlendKeyEntry::behind(PaintMode::Behind)),
_ => None,
})
.collect()
} else {
crate::blend_keys::tool_modes(tool)
.unwrap_or_default()
.into_iter()
.map(|mode| match mode {
Some(blend) => crate::panels::blend_entry(PaintMode::Blend(blend), blend),
None => BlendKeyEntry::clear(PaintMode::Clear),
})
.collect()
};
blend_entries(&keyed, |entry| match entry.key {
PaintMode::Blend(BlendMode::Normal) if threshold => tl!("Threshold").to_owned().into(),
key => label_of(key).into(),
static CACHE: crate::i18n::LangCache<(Tool, bool, bool), Vec<Entry<PaintMode>>> = crate::i18n::LangCache::new();
CACHE.get_or_build((tool, behind_enabled, threshold), || {
let keyed: Vec<BlendKeyEntry<PaintMode>> = if tool == Tool::PatternStamp {
crate::brush_mode_menu::pattern_stamp_choices()
.into_iter()
.filter_map(|((mode, behind), _)| match (mode, behind) {
(Some(blend), false) => Some(crate::panels::blend_entry(PaintMode::Blend(blend), blend)),
(None, true) => Some(BlendKeyEntry::behind(PaintMode::Behind)),
_ => None,
})
.collect()
} else {
crate::blend_keys::tool_modes(tool)
.unwrap_or_default()
.into_iter()
.map(|mode| match mode {
Some(blend) => crate::panels::blend_entry(PaintMode::Blend(blend), blend),
None => BlendKeyEntry::clear(PaintMode::Clear),
})
.collect()
};
blend_entries(&keyed, |entry| match entry.key {
PaintMode::Blend(BlendMode::Normal) if threshold => tl!("Threshold").to_owned().into(),
key => label_of(key).into(),
})
.into_iter()
.map(|entry| if entry.value() == Some(&PaintMode::Behind) { entry.enabled(behind_enabled) } else { entry })
.collect()
})
.into_iter()
.map(|entry| if entry.value() == Some(&PaintMode::Behind) { entry.enabled(behind_enabled) } else { entry })
.collect()
}
/// The Mode select over `entries` (from [`mode_entries`]) and the bound `mode`.
+12 -9
View File
@@ -72,15 +72,18 @@ fn eraser_mode_name(mode: EraserMode) -> &'static str {
/// Shift+right-click menu and the Pattern Stamp's list, it keeps both on the Background, so the wheel steps through
/// them there too.
fn mode_entries() -> Vec<Entry<PaintMode>> {
let keys: Vec<BlendKeyEntry<PaintMode>> = brush_mode_menu::choices()
.into_iter()
.map(|((mode, behind), _)| match (mode, behind) {
(Some(m), _) => crate::panels::blend_entry(PaintMode::Blend(m), m),
(None, true) => BlendKeyEntry::behind(PaintMode::Behind),
(None, false) => BlendKeyEntry::clear(PaintMode::Clear),
})
.collect();
blend_entries(&keys, |entry| Label::from(tl!(entry.key.text()).to_string()))
static CACHE: crate::i18n::LangCache<(), Vec<Entry<PaintMode>>> = crate::i18n::LangCache::new();
CACHE.get_or_build((), || {
let keys: Vec<BlendKeyEntry<PaintMode>> = brush_mode_menu::choices()
.into_iter()
.map(|((mode, behind), _)| match (mode, behind) {
(Some(m), _) => crate::panels::blend_entry(PaintMode::Blend(m), m),
(None, true) => BlendKeyEntry::behind(PaintMode::Behind),
(None, false) => BlendKeyEntry::clear(PaintMode::Clear),
})
.collect();
blend_entries(&keys, |entry| Label::from(tl!(entry.key.text()).to_string()))
})
}
/// The bar's values for `tool` from its brush `b` and the tool options. Opacity, Flow and Hardness
+10 -3
View File
@@ -18,9 +18,16 @@ use crate::{PhotocraftApp, panel_docking};
/// The blend modes the Classic gradient lists, with a rule above each group.
fn blend_modes() -> Vec<Entry<BlendMode>> {
let keys: Vec<BlendKeyEntry<BlendMode>> =
crate::blend_keys::tool_modes(Tool::Gradient).unwrap_or_default().into_iter().flatten().map(|mode| crate::panels::blend_entry(mode, mode)).collect();
blend_entries(&keys, |entry| Label::from(tl!(entry.key.label()).to_string()))
static CACHE: crate::i18n::LangCache<(), Vec<Entry<BlendMode>>> = crate::i18n::LangCache::new();
CACHE.get_or_build((), || {
let keys: Vec<BlendKeyEntry<BlendMode>> = crate::blend_keys::tool_modes(Tool::Gradient)
.unwrap_or_default()
.into_iter()
.flatten()
.map(|mode| crate::panels::blend_entry(mode, mode))
.collect();
blend_entries(&keys, |entry| Label::from(tl!(entry.key.label()).to_string()))
})
}
/// `add` captioned `label` as a field of the bar.