diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 9d9810c240..e0a81abb40 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -875,6 +875,12 @@ pub(crate) fn catalog_index() -> &'static std::collections::HashMap<&'static str INDEX.get_or_init(|| effect_catalog().into_iter().map(|e| (e.id, e)).collect()) } +/// The id and menu label of built-in effect `id`, as the catalogue holds them (no plug-in +/// effects). +pub fn built_in_effect(id: &str) -> Option<(&'static str, &'static str)> { + catalog_index().get(id).map(|e| (e.id, e.label)) +} + /// Catalogue entry for `id` (built-in, or an installed plug-in effect). pub fn effect_info(id: &str) -> Option { catalog_index().get(id).cloned().or_else(|| plugin_info(id)) diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index c46ab0c76e..efb7dcfa6a 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -124,7 +124,9 @@ mod catalog; mod geometry; mod params; -pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range}; +pub use catalog::{ + EffectInfo, Lengths, WARP_STYLES, built_in_effect, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range, +}; pub(crate) use geometry::{Budget, apply_one}; pub use geometry::{ Carry, GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_bez_carrying, apply_geometry_carrying, apply_geometry_with, diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 703d81ddc3..78bbd437e0 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -173,7 +173,7 @@ fn filter(s: &mut Session, p: &Value) -> Result { let label = effects::effect_info(id).map_or("Apply as Filter", |e| e.label.trim_end_matches('…')); let kinds = effects::addons::duotone::swatch_kinds(&s.doc()?.doc); let swatches = |name: &str| kinds.get(name).copied(); - recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches)) + s.edit_effect(id, |s| recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))) } /// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index ccebbfac88..36a2ac461d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -808,6 +808,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { let selection = shared_selection(selection, st.history.redo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; + turned.effect = e.effect; let paints = e.color_mode_paints.clone(); turned.color_mode_paints = e.color_mode_paints; turned.recost_paints(); @@ -844,6 +845,7 @@ fn redo(s: &mut Session, _: &Value) -> Result { let selection = shared_selection(selection, st.history.undo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; + turned.effect = e.effect; let paints = e.color_mode_paints.clone(); turned.color_mode_paints = e.color_mode_paints; turned.recost_paints(); diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index edb5561796..2fd764fe8f 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -509,11 +509,13 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { let label = effects::effect_info(id).map(|e| e.label.trim_end_matches('…').to_string()).unwrap_or_default(); aligned(p, C)?; if let Some(loose) = loose_for_pathfinder(s, p, id)? { - let gid = s.edit(&label, |d, sel| { - let gid = super::object::group_nodes(d, &loose)?; - d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone()); - sel.set([gid]); - Ok(gid) + let gid = s.edit_effect(id, |s| { + s.edit(&label, |d, sel| { + let gid = super::object::group_nodes(d, &loose)?; + d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone()); + sel.set([gid]); + Ok(gid) + }) })?; return Ok(json!({ "ids": [gid.0], "index": 0, "item": null, "grouped": true })); } @@ -544,9 +546,11 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { } } } - let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| { - fx.push(effect.clone()); - true + let ids = s.edit_effect(id, |s| { + edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| { + fx.push(effect.clone()); + true + }) })?; // The item the effect landed on in the object whose row the item is (the first selected object // for the active item, which applies where it fits), and the effect's index in that object. @@ -887,32 +891,36 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { } } } - let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| { - let Some(e) = fx.get_mut(index) else { return false }; - if let Some(id) = &warp_id { - e.id.clone_from(id); - } - if let Some(to) = kind - && e.id != to - { - e.params = effects::three_d_params_as(&e.id, &e.params, to); - e.id = to.to_string(); - } - if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) { - if !cur.is_object() { - *cur = effects::merged_params(&e.id, &Value::Null); + // The effect edited, when every target has the same one: a dialog's preview names its step after it. + let one = edited.first().filter(|e| edited.iter().all(|other| other == *e)).cloned().unwrap_or_default(); + let ids = s.edit_effect(&one, |s| { + edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| { + let Some(e) = fx.get_mut(index) else { return false }; + if let Some(id) = &warp_id { + e.id.clone_from(id); } - // Earlier parameters (a Perspective strength, a light by azimuth and elevation) take - // their current form first, so the new values replace them and the rest is kept. - *cur = effects::upgrade_params(&e.id, cur); - if let Value::Object(m) = cur { - m.extend(new); + if let Some(to) = kind + && e.id != to + { + e.params = effects::three_d_params_as(&e.id, &e.params, to); + e.id = to.to_string(); } - } - if let Some(v) = visible { - e.visible = v; - } - true + if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) { + if !cur.is_object() { + *cur = effects::merged_params(&e.id, &Value::Null); + } + // Earlier parameters (a Perspective strength, a light by azimuth and elevation) take + // their current form first, so the new values replace them and the rest is kept. + *cur = effects::upgrade_params(&e.id, cur); + if let Value::Object(m) = cur { + m.extend(new); + } + } + if let Some(v) = visible { + e.visible = v; + } + true + }) })?; Ok(json!({ "ids": ids_json(&ids) })) } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index cabc774737..7491f39f5c 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -52,6 +52,9 @@ pub struct DocState { pub interaction: Option, /// Edits made while this is open are one undo step (a scrubbed numeric field). pub undo_group: Option, + /// The built-in effect the edit in progress applies ([`crate::Session::edit_effect`]): the + /// undo step it records keeps it ([`DocState::push_undo`]). + pub(crate) effect_step: Option<&'static str>, /// For Object → Transform → Transform Again (⌘D): what the last transformation was. A /// transform command keeps the `copy`, `typeAreas` and `patterns` it used, and `strokes` and /// `corners` when it scales; a drag keeps the params of its last preview with the values that @@ -336,6 +339,7 @@ impl DocState { symbol_edit_return: Default::default(), interaction: None, undo_group: None, + effect_step: None, last_transform: None, last_selection_cmd: None, recalled_selection: RecalledSelection::default(), @@ -453,7 +457,9 @@ impl DocState { Some(l) if l.selection == it.selection => l.selection.clone(), _ => it.selection, }; + let effect = std::mem::replace(&mut self.effect_step, it.effect); self.push_undo(it.label, it.doc, selection); + self.effect_step = effect; if let Some(paints) = it.color_mode_paints && let Some(e) = self.history.undo.last_mut() { @@ -469,8 +475,10 @@ impl DocState { } /// Record an undo step: `doc` and `selection` as they were before an edit (the document now is /// the one after it). In an undo group only the group's first edit records one: the edits - /// after it extend that step. + /// after it extend that step. A new step named after the effect in [`DocState::effect_step`] + /// keeps that effect ([`HistoryEntry::effect`]); a step an undo group names keeps none. pub(crate) fn push_undo(&mut self, mut label: String, doc: Arc, selection: Arc) { + let mut effect = self.effect_step; if let Some(g) = &mut self.undo_group { let recorded = |first: &Arc| self.history.undo.last().is_some_and(|l| Arc::ptr_eq(&l.doc, first)); if g.first.as_ref().is_some_and(recorded) { @@ -481,9 +489,11 @@ impl DocState { g.first = Some(doc.clone()); if let Some(l) = &g.label { label = l.clone(); + effect = None; } } - let e = HistoryEntry::kept(label, doc, selection, &self.doc); + let mut e = HistoryEntry::kept(label, doc, selection, &self.doc); + e.effect = effect.filter(|id| crate::history::effect_step_label(id) == Some(e.label.as_str())); self.history.undo.push(e); self.history.clear_redo(); self.history.trim(); diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index d472ec760c..8ec2a5b395 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -25,6 +25,9 @@ pub struct HistoryEntry { next: usize, /// The template and name `label` was made from ([`Session::edit_named`]). pub(crate) named: Option, + /// The built-in effect the step applied or edited, when the step is named after it + /// ([`Session::edit_effect`]). + pub(crate) effect: Option<&'static str>, /// A number no other step takes ([`History::step`]). serial: u64, /// Original and changed new-art paints, only for steps that change them: a document color mode @@ -49,6 +52,7 @@ impl Clone for HistoryEntry { next_bytes: self.next_bytes, next: self.next, named: self.named.clone(), + effect: self.effect, serial: self.serial, color_mode_paints: self.color_mode_paints.clone(), color_mode_bytes: self.color_mode_bytes, @@ -63,6 +67,12 @@ fn next_serial() -> u64 { NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } +/// The name of the undo step that applies or edits built-in effect `id`: its menu label without +/// the ellipsis. `None` for an id no built-in effect has. +pub(crate) fn effect_step_label(id: &str) -> Option<&'static str> { + vectorcraft_render::effects::built_in_effect(id).map(|(_, label)| label.trim_end_matches('…')) +} + /// A step name made by filling the `{name}` placeholder of a template with a name /// ([`Session::edit_named`]). #[derive(Clone, Debug, PartialEq, Eq)] @@ -95,6 +105,7 @@ impl HistoryEntry { next_bytes, next: std::ptr::from_ref(next) as usize, named: None, + effect: None, serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, @@ -109,6 +120,13 @@ impl HistoryEntry { self.named.as_ref().filter(|n| n.label() == self.label) } + /// The id of the built-in effect the step applied or edited, while the step's label is still + /// the effect's name: `None` for any other step, and for one whose label was changed since it + /// was recorded. + pub fn effect(&self) -> Option<&'static str> { + self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str())) + } + /// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the /// document before the undo, whose next state is now `now` (that step's document). Its figures /// are that step's the other way round when `doc` is still the document they were taken @@ -128,6 +146,7 @@ impl HistoryEntry { next_bytes: costs.bytes, next: Arc::as_ptr(now) as usize, named: None, + effect: None, serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 99a2569005..9e0f68c543 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -4,6 +4,9 @@ use super::{Affine, Arc, Document, NodeId, Selection, Value}; #[derive(Clone, Debug)] pub struct Interaction { pub label: String, + /// The built-in effect the last preview applied or edited ([`crate::Session::edit_effect`]): + /// the step the interaction records keeps it when `label` is the effect's name. + pub(crate) effect: Option<&'static str>, pub doc: Arc, /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index bbd20fa5bb..5b28f17293 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -195,6 +195,29 @@ impl Session { Ok(v) } + /// Run `f`, an edit that applies or edits built-in effect `effect`. The undo step it records, + /// when named after the effect, keeps the effect's id ([`crate::HistoryEntry::effect`]), so a + /// frontend names it as the Effect menu names the effect. Run as an interaction's preview + /// itself, not as one command of a batch the preview runs, the step the interaction records + /// keeps it instead, while that preview is the last one. A later edit of an undo group keeps + /// none. + pub(crate) fn edit_effect(&mut self, effect: &str, f: impl FnOnce(&mut Self) -> Result) -> Result { + let id = vectorcraft_render::effects::built_in_effect(effect).map(|(id, _)| id); + let previewed = self.previewing && self.depth == 1; + let outer = std::mem::replace(&mut self.doc_mut()?.effect_step, id); + let v = f(self); + if let Ok(st) = self.doc_mut() { + st.effect_step = outer; + if v.is_ok() + && previewed + && let Some(it) = &mut st.interaction + { + it.effect = id; + } + } + v + } + /// Change only the selection (not an undo step). pub fn select(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> { self.active_appearance_item = None; @@ -297,6 +320,7 @@ impl Session { } st.interaction = Some(Interaction { label: label.to_string(), + effect: None, doc: st.doc.clone(), selection: Arc::new(st.selection.clone()), preview: None, @@ -346,6 +370,8 @@ impl Session { it.color_mode_paints = None; it.deferred_color_mode = None; it.plane_placed = false; + // The effect the preview below applies or edits marks the step, not an earlier one's. + it.effect = None; if selection_changed { st.selection.clone_from(&it.selection); } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..e86d5aad6c 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -403,6 +403,7 @@ impl Session { st.doc = doc; st.selection = selection; st.interaction = interaction; + st.effect_step = None; if let Some(history) = history { st.history = history; } diff --git a/crates/engine/src/tests/history_mem.rs b/crates/engine/src/tests/history_mem.rs index 279020432d..b26f970966 100644 --- a/crates/engine/src/tests/history_mem.rs +++ b/crates/engine/src/tests/history_mem.rs @@ -461,3 +461,43 @@ fn color_mode_paint_snapshots_count_toward_the_history_budget() { original.appearance.unwrap().effects[0].params["retainedTemplateData"] ); } + +/// A step that applies an effect keeps the effect, through undo and redo too. A step named like an +/// effect by anything else keeps none: a plain edit, an undo group named like the effect, and a +/// group another command started that an effect only extends. +#[test] +fn only_steps_an_effect_records_keep_the_effect() { + let mut s = session_with_rects(2); + let last = |s: &Session| s.doc().unwrap().history.undo.last().map(|e| (e.label.clone(), e.effect())); + assert_eq!(last(&s), Some(("Add".into(), None)), "a plain edit named like Pathfinder › Add"); + s.execute("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather")))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.redo.last().and_then(|e| e.effect()), Some("stylize.feather"), "an undone step"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "a redone step"); + s.begin_named_undo_group(Some("Feather".into())); + s.execute("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + s.end_undo_group(false); + assert_eq!(last(&s), Some(("Feather".into(), None)), "a group named like the effect"); + s.begin_undo_group(); + s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.transform"})).unwrap(); + s.end_undo_group(false); + assert_eq!(last(&s), Some(("Transform".into(), None)), "a group a transform started"); + // An interaction's step keeps the effect its last preview applied, and none when a later + // preview replaced it with another command. + s.begin_interaction("Feather").unwrap(); + s.preview("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "a kept preview"); + s.begin_interaction("Transform").unwrap(); + s.preview("effect.apply", &json!({"effect": "distort.transform"})).unwrap(); + s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Transform".into(), None)), "a replaced preview"); + s.begin_interaction("Feather").unwrap(); + s.preview("command.batch", &json!({"commands": [{"command": "effect.apply", "params": {"effect": "stylize.feather"}}]})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), None)), "a batch the preview ran"); +} diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 8857378855..5c8284ad99 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -3208,6 +3208,24 @@ fn ending_deferred_typing_for_another_edit_keeps_the_typing() { }); } +/// An effect applied while typing waits for its session to end keeps the typing as its own step +/// first, and the effect's own step still keeps the effect it applied. +#[test] +fn an_effect_applied_while_typing_waits_keeps_its_effect_on_its_step() { + let mut s = session(); + s.prefs.real_time_drawing = false; + let v = ViewInfo::default(); + let id = text(&mut s, "Hello"); + s.select_tool("type", v).unwrap(); + let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap(); + click(&mut s, b.x1 - 1.0, b.center().y); + s.tool_text(" world", v).unwrap(); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [id.0]})).unwrap(); + assert_eq!(undo_labels(&s).iter().rev().take(2).collect::>(), ["Feather", "Typing"]); + let h = s.doc().unwrap().history.undo.last().unwrap(); + assert_eq!(h.effect(), Some("stylize.feather")); +} + /// #1950: a colour previewed while typing (the Color Picker, a Color panel slider) colours the /// typed text: its interaction used to join the typing session and preview from the document /// before the typing, so the new type came back as its placeholder text. diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index df5789e649..094d703206 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -67,16 +67,14 @@ fn three_d_refusal(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, } } -/// The effect's name (`__label`, English) in the UI language: the catalog may carry it with or -/// without its trailing ellipsis. A plug-in effect's name is shown as it is. +/// The effect's name in the UI language as the Effect menu shows it ([`crate::i18n::effect_name`] +/// of `__effect`), else `__label` as it is. A plug-in effect's name is shown as it is. fn heading_label(d: &Dialog) -> String { let label = d.str("__label"); if vectorcraft_plugins::effect::plugin_id(&d.str("__effect")).is_some() { return label; } - let dotted = format!("{label}…"); - let shown = tl!(&dotted); - if shown != dotted { shown.trim_end_matches('…').to_string() } else { tl!(&label).to_string() } + crate::i18n::effect_name(crate::i18n::current(), &d.str("__effect")).unwrap_or(label) } /// The dialog kind asking whether to edit an effect that is already applied or add another. diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index 39c2dc6c7c..874562245d 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -368,7 +368,7 @@ fn stack_preview_row(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog } fn effect_label(id: &str) -> String { - vectorcraft_effects::effect_info(id).map(|e| tl!(e.label).trim_end_matches('…').to_string()).unwrap_or_else(|| id.to_string()) + crate::i18n::effect_name(crate::i18n::current(), id).unwrap_or_else(|| id.to_string()) } /// Where the preview rasters sit: one document point per pixel, origin at the top-left. @@ -614,7 +614,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { for e in &effects { let picked = e.id == sel; - let name = tl!(e.label).trim_end_matches('…').to_string(); + let name = effect_label(e.id); let image = egui::Image::from_texture(&thumb_tex(ui.ctx(), e.id)).fit_to_exact_size(egui::vec2(THUMB as f32, THUMB as f32)); #[cfg(test)] THUMBS_PAINTED.with(|c| c.set(c.get() + 1)); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index eb9a7b10ec..980bbf2785 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -662,6 +662,33 @@ pub fn t_id<'a>(id: &str, label: &'a str) -> &'a str { tr_id(current(), id, label) } +/// The Effect menu's label of effect `id` in `lang`: an `@id` row for the effect's id, else the +/// row of its English menu label. A plug-in effect's label is the plug-in's own text. `None` for +/// an id that names no effect. The Effect menu, History, Edit › Undo and Redo, the Appearance +/// panel and the effect dialogs all name an effect through this lookup. +pub fn effect_menu_label(lang: Lang, id: &str) -> Option { + match built_in_effect_label(id) { + Some(label) => Some(tr_id(lang, id, label).to_string()), + None => vectorcraft_plugins::effect::plugin_id(id).and_then(|_| vectorcraft_effects::effect_info(id)).map(|info| info.label.to_string()), + } +} + +/// [`effect_menu_label`] without its trailing ellipsis: an effect's name in `lang`. +pub fn effect_name(lang: Lang, id: &str) -> Option { + effect_menu_label(lang, id).map(|s| s.trim_end_matches('…').to_string()) +} + +/// Does `lang`'s catalog name built-in effect `id`: an `@id` row for the id, or a row for its +/// English menu label? +pub fn has_effect_name(lang: Lang, id: &str) -> bool { + built_in_effect_label(id).is_some_and(|label| lang.catalog().id(id).is_some() || has(lang, label)) +} + +/// The English Effect menu label of built-in effect `id`. +fn built_in_effect_label(id: &str) -> Option<&'static str> { + vectorcraft_effects::built_in_effect(id).map(|(_, label)| label) +} + /// Fill `{name}` placeholders. Unknown placeholders are left as written. pub fn fmt(template: &str, args: &[(&str, &str)]) -> String { let mut out = template.to_string(); diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..8c0e0587dc 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2456,14 +2456,15 @@ fn untranslated_report() { assert!(strings.len() > 500, "menu scan found only {} strings", strings.len()); let literals = tl_literals(); assert!(literals.len() > 300, "scan found only {} tl! literals", literals.len()); - // Undo step names: the recorded names, every effect's name without its ellipsis, and the - // Liquify tools' step names (`{} Tool`). A name's row is its plain row or the row of the same - // name with an ellipsis (`panels::history::step_name`); a template made with - // `Session::edit_named` needs a plain row, which `panels::history::entry_name` fills. + // Undo step names: the recorded names and the Liquify tools' step names (`{} Tool`). A name's + // row is its plain row or the row of the same name with an ellipsis + // (`panels::history::step_name`); a template made with `Session::edit_named` needs a plain + // row, which `panels::history::entry_name` fills. A step that applies an effect is named as + // the Effect menu names it (`i18n::has_effect_name`), listed under "effect names". let scan = undo_scan(); let mut undo = scan.labels; assert!(undo.len() > 300, "scan found only {} undo labels", undo.len()); - undo.extend(vectorcraft_effects::effect_catalog().iter().map(|e| e.label.trim_end_matches('…').to_string())); + let effect_ids: Vec<&'static str> = vectorcraft_effects::effect_catalog().iter().map(|e| e.id).collect(); let liquify = ["warp", "twirl", "pucker", "bloat", "scallop", "crystallize", "wrinkle"]; undo.extend(liquify.iter().filter_map(|k| vectorcraft_tools::distort::liquify::LiquifyKind::parse(k)).map(|k| format!("{} Tool", k.label()))); assert_eq!(scan.formatted.iter().collect::>(), ["{} Tool"], "step names built with format! (make them with Session::edit_named)"); @@ -2488,6 +2489,11 @@ fn untranslated_report() { add(l.code, "menu strings", strings.iter().filter(|s| !kept(s) && cat.plain(s).is_none()).cloned().collect::>()); add(l.code, "tl! strings", literals.iter().filter(|s| cat.plain(s).is_none()).cloned().collect::>()); add(l.code, "undo labels", undo.iter().filter(|s| crate::panels::history::step_name(lang, s).is_none()).cloned().collect::>()); + add( + l.code, + "effect names", + effect_ids.iter().filter(|id| !crate::i18n::has_effect_name(lang, id)).map(|id| id.to_string()).collect::>(), + ); add(l.code, "undo label templates", scan.templates.iter().filter(|t| cat.plain(t).is_none()).cloned().collect::>()); let (entries, _) = parse_entries(l.source); let rows: BTreeSet<(&str, &str)> = entries.iter().map(|(ctx, src, _)| (ctx.as_str(), src.as_str())).collect(); diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 61a4bf5872..dd73c842f7 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -187,8 +187,8 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { } "effect.last" => match &app.last_effect { Some((e, _)) => { - let name = vectorcraft_effects::effect_info(e).map(|i| i.label).unwrap_or(e.as_str()); - fmt(tl!("Last Effect: {name}"), &[("name", crate::i18n::tr_id(lang, e, name))]) + let name = crate::i18n::effect_menu_label(lang, e).unwrap_or_else(|| e.clone()); + fmt(tl!("Last Effect: {name}"), &[("name", &name)]) } None => crate::i18n::tr_id(lang, id, label).to_string(), }, @@ -199,17 +199,19 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { } } -/// The label of an Effect menu item in the UI language, by the effect's own id. Every effect item -/// runs `effect.apply` or `effect.dialog`, so the command id can't tell them apart; an `@id` row -/// for the effect id (for example `pathfinder.add`) wins over the plain row of the English label. -/// `None` when the catalog has no such row, and the plain translation applies. +/// The label of an Effect menu item in the UI language, by the effect's own id +/// ([`crate::i18n::effect_menu_label`]). Every effect item runs `effect.apply` or `effect.dialog`, +/// so the command id can't tell them apart. `None` for any other item, and for a plug-in effect, +/// whose item shows the plug-in's own text. pub(super) fn effect_item_label(id: &str, p: &Value) -> Option { if !matches!(id, "effect.apply" | "effect.dialog") { return None; } let effect = p.get("effect")?.as_str()?; - let shown = crate::i18n::tr_id(crate::i18n::current(), effect, ""); - (!shown.is_empty()).then(|| shown.to_string()) + if vectorcraft_plugins::effect::plugin_id(effect).is_some() { + return None; + } + crate::i18n::effect_menu_label(crate::i18n::current(), effect) } /// The label of an item of the canvas context menu's Unlock submenu (`layer.setProps` with one id diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 52b36b4535..fe843d00e5 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -242,11 +242,11 @@ fn built_in_effect(id: &str) -> bool { catalog().iter().any(|c| c.0 == id) } -/// [`effect_label`] as shown: a built-in effect's in the UI language (an `@id` row for the -/// effect's id wins over the plain row of its English label), a plug-in's as it is. +/// [`effect_label`] as shown: a built-in effect's name in the UI language as the Effect menu +/// shows it ([`crate::i18n::effect_name`]), a plug-in's as it is. pub(crate) fn shown_effect_label(id: &str) -> String { - match catalog().iter().find(|c| c.0 == id) { - Some(c) => crate::i18n::t_id(id, &c.1).to_string(), + match built_in_effect(id).then(|| crate::i18n::effect_name(crate::i18n::current(), id)).flatten() { + Some(name) => name, None => effect_label(id), } } @@ -1816,9 +1816,10 @@ fn delete_selected(app: &mut VectorcraftApp, ui: &Ui, node: Option<&Node>, sel: pub(crate) fn fx_menu(app: &mut VectorcraftApp, ui: &mut Ui) { let mut groups: Vec<(String, Vec<(String, String)>)> = vec![]; let plugins: Vec<_> = vectorcraft_effects::plugin_effects().into_iter().map(catalog_entry).collect(); - // Built-in effects in the UI language; a plug-in's by the name it gives. - let built_in = catalog().iter().map(|(id, label, menu)| (id, tl!(label), menu)); - for (id, label, menu) in built_in.chain(plugins.iter().map(|(id, label, menu)| (id, label.as_str(), menu))) { + // Built-in effects named as the Effect menu names them; a plug-in's by the name it gives. + let lang = crate::i18n::current(); + let built_in = catalog().iter().map(|(id, label, menu)| (id, crate::i18n::effect_name(lang, id).unwrap_or_else(|| label.clone()), menu)); + for (id, label, menu) in built_in.chain(plugins.iter().map(|(id, label, menu)| (id, label.clone(), menu))) { let g = menu.get(1).cloned().unwrap_or_else(|| "Other".into()); match groups.iter_mut().find(|(n, _)| *n == g) { Some((_, v)) => v.push((id.clone(), label.to_string())), diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index cc0c609868..b75b831d1c 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -27,10 +27,15 @@ pub fn step_name(lang: crate::i18n::Lang, label: &str) -> Option { /// A step's name in `lang`. A name made from a template (`Apply {name}`, /// [`vectorcraft_engine::HistoryEntry::named`]) takes the template's plain row with the name in its /// placeholder. A name VectorCraft gives is shown in `lang`, and any other name is shown as the -/// document holds it. It returns `None` when the catalog has no row for the template. Any other step -/// takes [`step_name`] of its label. +/// document holds it. It returns `None` when the catalog has no row for the template. A step that +/// applied or edited a built-in effect ([`vectorcraft_engine::HistoryEntry::effect`]) takes the +/// effect's name as the Effect menu shows it ([`crate::i18n::effect_name`]), `None` when the +/// catalog has no row for it. Any other step takes [`step_name`] of its label. pub fn entry_name(lang: crate::i18n::Lang, h: &vectorcraft_engine::HistoryEntry) -> Option { - use crate::i18n::{fmt, has, label_or_name, tr}; + use crate::i18n::{effect_name, fmt, has, has_effect_name, label_or_name, tr}; + if let Some(effect) = h.effect() { + return has_effect_name(lang, effect).then(|| effect_name(lang, effect)).flatten(); + } match h.named() { Some(n) => has(lang, n.template).then(|| fmt(tr(lang, n.template), &[("name", label_or_name(lang, &n.name, n.built_in))])), None => step_name(lang, &h.label), @@ -183,20 +188,95 @@ mod tests { assert_eq!(listed(&mut app)[rows.len() - 6..rows.len() - 4], ["Apply Body", "Apply {name}"]); } - /// A step named after an effect whose catalog row has only the menu label with its ellipsis - /// takes that row's translation without the ellipsis; a name with no row has none. + /// A step name with no catalog row has no translation. #[test] - fn effect_steps_read_the_menu_row() { + fn unknown_steps_have_no_name() { let ja = crate::i18n::Lang::from_code("ja").expect("ja registered"); - for effect in ["Revolve", "Feather"] { - let menu_row = - crate::i18n::has(ja, &format!("{effect}…")).then(|| crate::i18n::tr(ja, &format!("{effect}…")).trim_end_matches('…').to_string()); - let plain_row = crate::i18n::has(ja, effect).then(|| crate::i18n::tr(ja, effect).to_string()); - assert_eq!(step_name(ja, effect), plain_row.or(menu_row), "{effect}"); - } assert_eq!(step_name(ja, "No Such Step"), None); } + /// Every built-in effect has one name in each language: History (and Edit › Undo and Redo) + /// names the step that applied it, and the Appearance panel its row, with the text of its + /// Effect menu item without the ellipsis, which is the effect's `@id` row or the row of its + /// menu label with the ellipsis. + #[test] + fn effects_have_the_same_name_in_history_appearance_and_the_effect_menu() { + let mut app = app_with_two_rectangles(); + // The step each effect that applies to a rectangle with its defaults records. + let mut steps = Vec::new(); + for e in vectorcraft_effects::effect_catalog() { + if app.session.execute("effect.apply", &json!({ "effect": e.id })).is_ok() { + let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); + assert_eq!(h.effect(), Some(e.id), "{} names its step after the effect", e.id); + steps.push((e, h)); + app.session.execute("edit.undo", &json!({})).unwrap(); + } + } + assert!(steps.len() * 2 > vectorcraft_effects::effect_catalog().len(), "only {} effects applied", steps.len()); + let mut differ = Vec::new(); + for lang in crate::i18n::Lang::all() { + crate::i18n::set_current(lang); + for (e, h) in &steps { + let cmd = if e.defaults.as_object().is_some_and(|o| o.is_empty()) { "effect.apply" } else { "effect.dialog" }; + let item = crate::menus::shown_label(&app, cmd, &json!({ "effect": e.id }), e.label); + let menu = item.trim_end_matches('…'); + let row = crate::i18n::tr_id(lang, e.id, e.label).trim_end_matches('…').to_string(); + let step = shown(h); + let shown_row = super::super::appearance::shown_effect_label(e.id); + if menu != row || step != menu || shown_row != menu { + differ.push(format!("{} {}: catalog {row:?}, menu {menu:?}, History {step:?}, Appearance {shown_row:?}", lang.code(), e.id)); + } + } + } + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(differ.is_empty(), "{differ:#?}"); + } + + /// A step another command names like an effect (Object › Transform's `Transform`, the name of + /// Distort & Transform › Transform) keeps its own name in every language. + #[test] + fn a_step_named_like_an_effect_keeps_its_own_name() { + let mut app = app_with_two_rectangles(); + app.session.execute("object.transform", &json!({ "matrix": [1, 0, 0, 1, 5, 0] })).unwrap(); + let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); + assert_eq!((h.label.as_str(), h.effect()), ("Transform", None)); + for lang in crate::i18n::Lang::all() { + assert_eq!(entry_name(lang, &h), step_name(lang, "Transform"), "{}", lang.code()); + } + } + + /// The Feather dialog's preview, kept with OK, records a step that History and Edit › Undo and + /// Redo name as the Effect menu names Feather, in French as in English. + #[test] + fn an_effect_kept_from_its_dialog_preview_is_named_after_the_effect() { + let fr = crate::i18n::Lang::from_code("fr").expect("fr registered"); + let mut app = app_with_two_rectangles(); + crate::i18n::set_current(fr); + let item = crate::menus::shown_label(&app, "effect.dialog", &json!({ "effect": "stylize.feather" }), "Feather…"); + crate::i18n::set_current(crate::i18n::Lang::EN); + let menu = item.trim_end_matches('…').to_string(); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + }; + app.run("effect.dialog", json!({ "effect": "stylize.feather", "item": null })).unwrap(); + frame(&mut app, vec![]); + assert!(app.session.in_interaction(), "the dialog previews"); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame(&mut app, vec![enter]); + assert!(app.ui.dialog.is_none(), "OK closed the dialog"); + let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); + assert_eq!(h.effect(), Some("stylize.feather")); + app.session.execute("edit.undo", &json!({})).unwrap(); + let undone = app.session.active().unwrap().history.redo.last().cloned().unwrap(); + crate::i18n::set_current(fr); + let names = (shown(&h), shown(&undone)); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(names, (menu.clone(), menu), "the step, and the step undone"); + } + fn app_with_two_rectangles() -> VectorcraftApp { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 200, "height": 150})).unwrap();