From fb1c4ec562d752b93e91b8f99ecd90a530f0b683 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:25:55 -0800 Subject: [PATCH 1/9] Edit: Find and Replace steps through matches in a dialog that stays open Edit > Find and Replace... opens a dialog of its own with Find and Replace With fields, Match Case, Find Whole Word, Search Backwards, Check Hidden Layers and Check Locked Layers, and Find, Replace, Replace & Find, Replace All and Done. Find shows the match in its line of text with its place among the matches and selects its type object. edit.findNext returns the match (id, start, end, index, count, selected) and takes backwards, hiddenLayers, lockedLayers and from. The new edit.replaceMatch replaces one match as one undo step. edit.findReplace takes the two layer switches and reports how many matches it replaced. Ruby after a replaced match moves with the text. Edit > Find Next goes on from the dialog's last search in the same document, and is no longer offered as an action step. --- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/cmd/typemenu.rs | 262 +++++++++--- .../engine/src/tests/ids_without_selection.rs | 2 +- crates/engine/src/tests/menucmds.rs | 183 ++++++++- crates/mcp/src/ui_catalog.rs | 7 +- crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/dialogs/find_replace.rs | 358 +++++++++++++++++ .../ui-egui/src/dialogs/find_replace/tests.rs | 377 ++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 10 + crates/ui-egui/src/i18n/bs.tsv | 10 + crates/ui-egui/src/i18n/ca.tsv | 13 + crates/ui-egui/src/i18n/cs.tsv | 13 + crates/ui-egui/src/i18n/da.tsv | 10 + crates/ui-egui/src/i18n/de.tsv | 13 + crates/ui-egui/src/i18n/el.tsv | 13 + crates/ui-egui/src/i18n/es.tsv | 13 + crates/ui-egui/src/i18n/fi.tsv | 13 + crates/ui-egui/src/i18n/fr.tsv | 13 + crates/ui-egui/src/i18n/hi.tsv | 13 + crates/ui-egui/src/i18n/hu.tsv | 13 + crates/ui-egui/src/i18n/id.tsv | 10 + crates/ui-egui/src/i18n/it.tsv | 13 + crates/ui-egui/src/i18n/ja.tsv | 13 + crates/ui-egui/src/i18n/ka.tsv | 13 + crates/ui-egui/src/i18n/ko.tsv | 13 + crates/ui-egui/src/i18n/nl.tsv | 13 + crates/ui-egui/src/i18n/pl.tsv | 13 + crates/ui-egui/src/i18n/pt-br.tsv | 13 + crates/ui-egui/src/i18n/ru.tsv | 13 + crates/ui-egui/src/i18n/sv.tsv | 13 + crates/ui-egui/src/i18n/tr.tsv | 13 + crates/ui-egui/src/i18n/uk.tsv | 13 + crates/ui-egui/src/i18n/vi.tsv | 13 + crates/ui-egui/src/i18n/zh-hans.tsv | 13 + crates/ui-egui/src/i18n/zh-hant.tsv | 13 + crates/ui-egui/src/menus/entries.rs | 7 +- crates/ui-egui/src/menus/invoke.rs | 12 + crates/ui-egui/src/menus/run.rs | 4 + crates/ui-egui/src/menus/tree.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 7 +- crates/ui-egui/src/palette.rs | 2 +- crates/ui-egui/src/state.rs | 6 + docs/mcp.md | 46 +++ docs/target-app-parity.md | 1 + 44 files changed, 1542 insertions(+), 76 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/find_replace.rs create mode 100644 crates/ui-egui/src/dialogs/find_replace/tests.rs diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 5329f23331..f11724dc1e 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -165,6 +165,7 @@ pub(super) const ALLOWED: &[&str] = &[ "edit.duplicate", "edit.findNext", "edit.findReplace", + "edit.replaceMatch", "effect.apply", "effect.deferredStatus", "effect.duplicate", diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index c140ba6572..0797991bf2 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -10,8 +10,8 @@ use super::object::choice; use super::threads::ThreadIndex; use super::typecmd::{area_text, block_gaps, needed_room, refresh_bounds}; use super::{ - CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or, - switch_or, targets, text_param, + CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, index_opt, + number_or, object_param, switch_or, targets, text_param, }; pub fn specs() -> Vec { @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Find and Replace…", ["Edit"], None, - "{find, replace?: \"\", matchCase?: false, wholeWord?: false, ids?} replace in every text object (or ids) → {count}. Matches never span style runs.", + "{find, replace?: \"\", matchCase?: false, wholeWord?: false, hiddenLayers?: false, lockedLayers?: false, ids?} replace every match in the type the search reaches (or in ids, whatever their layers), as one undo step → {count (every match), replaced (the matches that did not already read as `replace`)}. The search reaches visible, unlocked type on visible, unlocked layers, off locked artboards; hiddenLayers adds the type of hidden layers and sublayers and lockedLayers that of locked ones, while a hidden or locked object or group keeps its type out. Matches never span style runs. When nothing matches, or every match already reads as `replace`, nothing changes and no undo step is recorded.", has_doc, find_replace ), @@ -129,10 +129,19 @@ pub fn specs() -> Vec { "Find Next", ["Edit"], None, - "{find, matchCase?, wholeWord?} select the next text object (after the selected one, wrapping) containing `find` → {id|null}", + "{find, matchCase?: false, wholeWord?: false, backwards?: false, hiddenLayers?: false, lockedLayers?: false, from?: {id, start, end} (a match this command returned, or the range edit.replaceMatch returned)} find the next match of `find` in the type edit.findReplace reaches and select its type object → {id, start, end (the match's bytes in the object's plain text), index (its place among all the matches, from 1), count, selected} or {id: null, count: 0}. The search visits type objects from the top of the stacking order down and each object's matches in reading order; backwards visits the objects from the bottom up and each object's matches from the last. It goes on after `from` and, past the last match, starts again at the first. Without `from` it goes on after the first selected type object, and with no type selected it starts at the first match. A match on a hidden or locked layer is returned with selected false and the selection stays as it is. Nothing is recorded for undo.", has_doc, find_next ), + cmd!( + "edit.replaceMatch", + "Replace", + [], + None, + "{find, replace?: \"\", matchCase?: false, wholeWord?: false, id, start, end} replace one match of `find`, the bytes start..end of type object id as edit.findNext returns them, with `replace`, as one undo step → {id, start, end (the replacement's bytes; pass them to edit.findNext as `from` to go on), replaced}. Bytes that are no match of `find` are refused. When the match already reads as `replace`, nothing changes, no undo step is recorded and replaced is false.", + has_doc, + replace_one + ), cmd!( "edit.pasteWithoutFormatting", "Paste without Formatting", @@ -1305,14 +1314,9 @@ fn is_word(c: char) -> bool { c.is_alphanumeric() || c == '_' } -/// Byte ranges of `needle` in `hay`. -pub(crate) fn find_all(hay: &str, needle: &str, match_case: bool, whole_word: bool) -> Vec<(usize, usize)> { - find_all_between(hay, needle, match_case, whole_word, None, None) -} - -/// [`find_all`] in run `i` of `runs`: a whole word looks past the run's ends at the characters -/// next to it, so a change of style inside a word is not a word boundary (#5901). Matches stay -/// inside the run. +/// Byte ranges of `needle` in run `i` of `runs`: a whole word looks past the run's ends at the +/// characters next to it, so a change of style inside a word is not a word boundary (#5901). +/// Matches stay inside the run. fn find_in_run(runs: &[TextRun], i: usize, needle: &str, match_case: bool, whole_word: bool) -> Vec<(usize, usize)> { let Some(run) = runs.get(i) else { return vec![] }; let before = runs.get(..i).and_then(|r| r.iter().rev().find_map(|r| r.text.chars().next_back())); @@ -1320,8 +1324,8 @@ fn find_in_run(runs: &[TextRun], i: usize, needle: &str, match_case: bool, whole find_all_between(&run.text, needle, match_case, whole_word, before, after) } -/// [`find_all`], with `before` and `after` the characters on either side of `hay` (none at the -/// text's ends), which a whole word must not touch either. +/// Byte ranges of `needle` in `hay`, with `before` and `after` the characters on either side of +/// `hay` (none at the text's ends), which a whole word must not touch either. fn find_all_between(hay: &str, needle: &str, match_case: bool, whole_word: bool, before: Option, after: Option) -> Vec<(usize, usize)> { let nc: Vec = needle.chars().collect(); if nc.is_empty() { @@ -1353,102 +1357,232 @@ fn find_all_between(hay: &str, needle: &str, match_case: bool, whole_word: bool, /// The visible, unlocked type objects of visible, unlocked layers, off locked artboards, in paint /// order: the text Find and Replace and Check Spelling go through. pub(crate) fn all_texts(d: &Document) -> Vec { - fn visit(n: &Node, locks: &LockedArtboards<'_>, v: &mut Vec) { - if !n.visible || n.locked { + searched_texts(d, false, false) +} + +/// [`all_texts`], with the type of hidden layers (`hidden_layers`) and of locked layers +/// (`locked_layers`) as well, as Check Hidden Layers and Check Locked Layers of Find and Replace +/// ask. The switches are about layers and sublayers: a hidden or locked object or group keeps its +/// type out, and so does a locked artboard. +fn searched_texts(d: &Document, hidden_layers: bool, locked_layers: bool) -> Vec { + fn visit(n: &Node, locks: &LockedArtboards<'_>, layers: (bool, bool), v: &mut Vec) { + let layer = matches!(n.kind, NodeKind::Layer { .. }); + if (!n.visible && !(layer && layers.0)) || (n.locked && !(layer && layers.1)) { return; } if matches!(n.kind, NodeKind::Text(_)) && !locks.holds_id(n.id) { v.push(n.id); } for c in n.children().into_iter().flatten() { - visit(c, locks, v); + visit(c, locks, layers, v); } } let mut v = vec![]; let locks = d.locked_artboards(); for l in &d.layers { - visit(l, &locks, &mut v); + visit(l, &locks, (hidden_layers, locked_layers), &mut v); } v } +/// What Find and Replace looks for: the text, Match Case and Find Whole Word. +struct Query { + find: String, + match_case: bool, + whole_word: bool, +} + +impl Query { + /// The `find`, `matchCase` and `wholeWord` params of command `c`. An empty or missing `find` + /// is an error. + fn of(p: &Value, c: &str) -> Result { + let find = text_param(p, "find", c)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(c, "missing `find`"))?.to_string(); + Ok(Self { find, match_case: switch_or(p, "matchCase", false, c)?, whole_word: switch_or(p, "wholeWord", false, c)? }) + } + + /// The matches in `t`, in reading order, each as (run, start, end) with `start..end` the bytes + /// of the match in the object's plain text. A match stays inside one style run, and an inline + /// graphic is art, not characters to find. + fn matches(&self, t: &TextObject) -> Vec<(usize, usize, usize)> { + let mut hits = vec![]; + let mut base = 0; + for (ri, r) in t.runs.iter().enumerate() { + if r.inline.is_none() { + hits.extend( + find_in_run(&t.runs, ri, &self.find, self.match_case, self.whole_word).into_iter().map(|(a, b)| (ri, base + a, base + b)), + ); + } + base += r.text.len(); + } + hits + } +} + +/// Replace bytes `start..end` of the plain text of `t`, which lie inside run `run`, with `rep`. +/// The paragraph styles and the ruby follow the edit, as `text.editRange` moves them. The caller +/// refreshes the bounds. +fn replace_match(t: &mut TextObject, run: usize, start: usize, end: usize, rep: &str) { + let base: usize = t.runs.iter().take(run).map(|r| r.text.len()).sum(); + let (Some(a), Some(b)) = (start.checked_sub(base), end.checked_sub(base)) else { return }; + if !t.runs.get(run).is_some_and(|r| a <= b && r.text.is_char_boundary(a) && r.text.is_char_boundary(b)) { + return; + } + t.splice_paras(start, end, rep); + if let Some(r) = t.runs.get_mut(run) { + r.text.replace_range(a..b, rep); + } + t.ruby_after_replace(start, end, rep.len()); +} + fn find_replace(s: &mut Session, p: &Value) -> Result { const C: &str = "edit.findReplace"; - let find = text_param(p, "find", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `find`"))?.to_string(); + let q = Query::of(p, C)?; let rep = text_param(p, "replace", C)?.unwrap_or("").to_string(); - let (mc, ww) = (switch_or(p, "matchCase", false, C)?, switch_or(p, "wholeWord", false, C)?); + let (hidden, locked) = (switch_or(p, "hiddenLayers", false, C)?, switch_or(p, "lockedLayers", false, C)?); let ids = match p.get("ids").filter(|v| !v.is_null()) { Some(_) => text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?), - None => all_texts(&s.doc()?.doc), + None => searched_texts(&s.doc()?.doc, hidden, locked), }; let st = s.doc()?; - let total: usize = ids + // Every match, and the matches that do not already read as the replacement. + let (total, replaced) = ids .iter() .filter_map(|id| match &st.doc.node(*id)?.kind { - NodeKind::Text(t) => Some((0..t.runs.len()).map(|i| find_in_run(&t.runs, i, &find, mc, ww).len()).sum::()), + NodeKind::Text(t) => { + let plain = t.plain_text(); + let hits = q.matches(t); + Some((hits.len(), hits.iter().filter(|(_, a, b)| plain.get(*a..*b) != Some(rep.as_str())).count())) + } _ => None, }) - .sum(); - if total == 0 { - return Ok(json!({ "count": 0 })); + .fold((0, 0), |(n, r), (hn, hr)| (n + hn, r + hr)); + if replaced == 0 { + return Ok(json!({ "count": total, "replaced": 0 })); } super::overprint::edit_counted(s, "Replace", |d| { let mut changed = 0; for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; - // Matches as (run, start, end) with offsets inside the run. Inline graphics are art, not - // characters to rewrite. - let mut hits = vec![]; - let mut base = 0; - for (ri, r) in t.runs.iter().enumerate() { - if r.inline.is_none() { - for (a, b) in find_in_run(&t.runs, ri, &find, mc, ww) { - if r.text.get(a..b) != Some(rep.as_str()) { - hits.push((ri, base + a, base + b, a, b)); - } - } - } - base += r.text.len(); - } + let plain = t.plain_text(); + let hits: Vec<_> = q.matches(t).into_iter().filter(|(_, a, b)| plain.get(*a..*b) != Some(rep.as_str())).collect(); if hits.is_empty() { continue; } - // Last match first, so the offsets of earlier ones stay valid. The paragraph styles follow - // each edit, as `text.editRange` does. - for (ri, ta, tb, a, b) in hits.into_iter().rev() { - t.splice_paras(ta, tb, &rep); - if let Some(r) = t.runs.get_mut(ri) { - r.text.replace_range(a..b, &rep); - } + // Last match first, so the offsets of earlier ones stay valid. + for (ri, a, b) in hits.into_iter().rev() { + replace_match(t, ri, a, b, &rep); } changed += 1; refresh_bounds(t); } Ok(changed) })?; - Ok(json!({ "count": total })) + Ok(json!({ "count": total, "replaced": replaced })) +} + +/// A match of Find and Replace: bytes `start..end` of the plain text of type object `id`. +#[derive(Clone, Copy)] +struct Match { + id: NodeId, + start: usize, + end: usize, +} + +impl Match { + /// The `id`, `start` and `end` that `p` gives for a match, under command `c`: an object id and + /// two byte offsets, put in order as `text.editRange` orders its own. + fn of(p: &Value, c: &str) -> Result { + let whole = |key: &str| index_opt(p, key, c)?.ok_or_else(|| bad(c, format!("missing `{key}`"))); + let id = object_param(p, "id", c)?.ok_or_else(|| bad(c, "missing `id`"))?; + let (start, end) = (whole("start")?, whole("end")?); + Ok(Self { id, start: start.min(end), end: start.max(end) }) + } } fn find_next(s: &mut Session, p: &Value) -> Result { const C: &str = "edit.findNext"; - let find = text_param(p, "find", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `find`"))?.to_string(); - let (mc, ww) = (switch_or(p, "matchCase", false, C)?, switch_or(p, "wholeWord", false, C)?); + let q = Query::of(p, C)?; + let backwards = switch_or(p, "backwards", false, C)?; + let (hidden, locked) = (switch_or(p, "hiddenLayers", false, C)?, switch_or(p, "lockedLayers", false, C)?); + // A `from` that is no object gives no `id`, and is refused as one without it. + let from = match p.get("from") { + None | Some(Value::Null) => None, + Some(v) => Some(Match::of(v, C)?), + }; let st = s.doc()?; - let all = all_texts(&st.doc); - let cur = st.selection.objects.first().and_then(|id| all.iter().position(|x| x == id)); - let n = all.len(); - let start = cur.map(|c| c + 1).unwrap_or(0); - let hit = (0..n).map(|k| all[(start + k) % n.max(1)]).find(|id| match st.doc.node(*id).map(|n| &n.kind) { - Some(NodeKind::Text(t)) => !find_all(&t.plain_text(), &find, mc, ww).is_empty(), - _ => false, - }); - match hit { - Some(id) => { - s.select(|_, sel| sel.set([id]))?; - Ok(json!({ "id": id.0 })) - } - None => Ok(json!({ "id": null })), + // The objects in the order the search visits them: from the top of the stacking order down, + // or with Search Backwards from the bottom up. + let mut order = searched_texts(&st.doc, hidden, locked); + if !backwards { + order.reverse(); } + // Every match in that order as (object's place, match): inside an object in reading order, or + // with Search Backwards from its end. + let mut all: Vec<(usize, Match)> = vec![]; + for (place, id) in order.iter().enumerate() { + let Some(NodeKind::Text(t)) = st.doc.node(*id).map(|n| &n.kind) else { continue }; + let mut hits = q.matches(t); + if backwards { + hits.reverse(); + } + all.extend(hits.into_iter().map(|(_, start, end)| (place, Match { id: *id, start, end }))); + } + if all.is_empty() { + return Ok(json!({ "id": null, "count": 0 })); + } + // The search goes on from `from`, or from the whole of the first selected type object it + // visits, so that the same call again reaches the next object. From anywhere else it starts + // at the first match. + let from = from.or_else(|| { + st.selection.objects.iter().filter(|id| order.contains(id)).find_map(|id| match &st.doc.node(*id)?.kind { + NodeKind::Text(t) => Some(Match { id: *id, start: 0, end: t.runs.iter().map(|r| r.text.len()).sum() }), + _ => None, + }) + }); + let after = |(place, m): &(usize, Match), at: usize, f: &Match| { + *place > at || (*place == at && if backwards { m.end <= f.start } else { m.start >= f.end }) + }; + let k = from + .and_then(|f| order.iter().position(|id| *id == f.id).map(|at| (at, f))) + .and_then(|(at, f)| all.iter().position(|hit| after(hit, at, &f))) + .unwrap_or(0); + let Some((_, m)) = all.get(k).copied() else { return Ok(json!({ "id": null, "count": 0 })) }; + let count = all.len(); + // Type that a selection tool can't reach (on a hidden or locked layer) is found without being + // selected. + let selected = all_texts(&st.doc).contains(&m.id); + if selected && st.selection.objects != [m.id] { + s.select(|_, sel| sel.set([m.id]))?; + } + let index = if backwards { count - k } else { k + 1 }; + Ok(json!({ "id": m.id.0, "start": m.start, "end": m.end, "index": index, "count": count, "selected": selected })) +} + +fn replace_one(s: &mut Session, p: &Value) -> Result { + const C: &str = "edit.replaceMatch"; + let q = Query::of(p, C)?; + let rep = text_param(p, "replace", C)?.unwrap_or("").to_string(); + let m = Match::of(p, C)?; + let st = s.doc()?; + let t = match st.doc.node(m.id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => t, + Some(_) => return Err(bad(C, format!("node {} is not text", m.id.0))), + None => return Err(EngineError::NoNode(m.id)), + }; + let Some((run, ..)) = q.matches(t).into_iter().find(|(_, a, b)| (*a, *b) == (m.start, m.end)) else { + return Err(bad(C, format!("no match of `find` at bytes {}..{} of object {}", m.start, m.end, m.id.0))); + }; + let end = m.start + rep.len(); + if t.plain_text().get(m.start..m.end) == Some(rep.as_str()) { + return Ok(json!({ "id": m.id.0, "start": m.start, "end": end, "replaced": false })); + } + s.edit("Replace", |d, _| { + let Some(NodeKind::Text(t)) = d.node_mut(m.id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(m.id)) }; + replace_match(t, run, m.start, m.end, &rep); + refresh_bounds(t); + Ok(()) + })?; + Ok(json!({ "id": m.id.0, "start": m.start, "end": end, "replaced": true })) } // ---------- Paste without Formatting ---------- diff --git a/crates/engine/src/tests/ids_without_selection.rs b/crates/engine/src/tests/ids_without_selection.rs index b274e7956f..9a48655468 100644 --- a/crates/engine/src/tests/ids_without_selection.rs +++ b/crates/engine/src/tests/ids_without_selection.rs @@ -377,7 +377,7 @@ fn ids_cases(d: u64) -> Vec<(&'static str, &'static str, serde_json::Value, Unse ("addon.color.filter", "ids", json!({"effect": "addon.color.invert"}), Selected), ("addon.color.applyNearestSwatch", "ids", json!({}), Selected), ("edit.colors.overprintBlack", "ids", json!({}), Selected), - ("edit.findReplace", "ids", json!({"find": "A", "replace": "B"}), Gives(json!({"count": 1}))), + ("edit.findReplace", "ids", json!({"find": "A", "replace": "B"}), Gives(json!({"count": 1, "replaced": 1}))), ("layer.highlight", "ids", json!({}), Fails("missing ids")), ("layer.move", "ids", json!({ "target": d }), Fails("missing ids")), ("library.add", "ids", json!({"kind": "graphic"}), Selected), diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index abb0bf31eb..939f36269c 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -2140,7 +2140,8 @@ fn find_and_replace_leaves_type_on_a_locked_artboard() { /// Find and Replace that replaces each match with the text it is (`CAT` found in `cat`, ignoring /// case, and replaced by `cat`) records no undo step: the step to redo stays and the document stays -/// unmodified. It still replies with the count. A replacement that changes the text is one undo step. +/// unmodified. It still replies with the count, and with no match replaced. A replacement that +/// changes the text is one undo step. #[test] fn find_and_replace_that_changes_nothing_records_no_undo_step() { let mut s = session(); @@ -2148,9 +2149,9 @@ fn find_and_replace_that_changes_nothing_records_no_undo_step() { select_with_a_step_to_redo(&mut s, &[a]); let before = history(&s); assert_eq!((before.1, before.2), (1, false), "a step to redo, and nothing unsaved"); - assert_eq!(s.execute("edit.findReplace", &json!({"find": "CAT", "replace": "cat"})).unwrap(), json!({"count": 2})); + assert_eq!(s.execute("edit.findReplace", &json!({"find": "CAT", "replace": "cat"})).unwrap(), json!({"count": 2, "replaced": 0})); assert_eq!((history(&s), plain(&s, a)), (before, "cat cat".to_string())); - assert_eq!(s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog"})).unwrap(), json!({"count": 2})); + assert_eq!(s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog"})).unwrap(), json!({"count": 2, "replaced": 2})); assert_eq!((history(&s), plain(&s, a)), ((before.0 + 1, 0, true), "dog dog".to_string())); } @@ -2187,12 +2188,186 @@ fn find_next_cycles_through_text_objects() { let _ = text(&mut s, "banana"); let c = text(&mut s, "pineapple"); s.execute("select.none", &json!({})).unwrap(); - assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "APPLE"})).unwrap()), a); + // From the top of the stacking order down, then round again. + assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "APPLE"})).unwrap()), c); + assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "apple"})).unwrap()), a); assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "apple"})).unwrap()), c); + // A selection that starts with a shape goes on after its first type object. + let shape = rect(&mut s, 300.0, 300.0, 20.0, 20.0); + sel(&mut s, &[shape, c]); assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "apple"})).unwrap()), a); assert!(s.execute("edit.findNext", &json!({"find": "zzz"})).unwrap()["id"].is_null()); } +/// The match `r` (an `edit.findNext` result) as (object, start, end, index, count). +fn found(r: &Value) -> (u64, u64, u64, u64, u64) { + let n = |k: &str| r[k].as_u64().unwrap_or_else(|| panic!("no `{k}` in {r}")); + (n("id"), n("start"), n("end"), n("index"), n("count")) +} + +/// Find Next steps through the matches one by one when each call is given the match before it: +/// the objects from the top of the stacking order down, each object's matches in reading order, +/// and round again after the last. Search Backwards visits them the other way. Each match is +/// returned with its bytes and its object is selected; nothing is recorded for undo. +#[test] +fn find_next_steps_through_the_matches_in_both_directions() { + let mut s = session(); + let bottom = text(&mut s, "cat éa cat"); + let _ = text(&mut s, "dog"); + let top = text(&mut s, "a cat"); + s.execute("select.none", &json!({})).unwrap(); + let before = history(&s); + let step = |s: &mut Session, from: &Value, backwards: bool| { + let from = if from.is_null() { Value::Null } else { json!({"id": from["id"], "start": from["start"], "end": from["end"]}) }; + s.execute("edit.findNext", &json!({"find": "cat", "from": from, "backwards": backwards})).unwrap() + }; + // "é" is two bytes, so the second match of the bottom object is at bytes 8..11. + let forward = [(top.0, 2, 5, 1, 3), (bottom.0, 0, 3, 2, 3), (bottom.0, 8, 11, 3, 3), (top.0, 2, 5, 1, 3)]; + let mut at = Value::Null; + for want in forward { + at = step(&mut s, &at, false); + assert_eq!((found(&at), selected(&s), at["selected"].clone()), (want, vec![NodeId(want.0)], json!(true))); + } + let backward = [(bottom.0, 8, 11, 3, 3), (bottom.0, 0, 3, 2, 3), (top.0, 2, 5, 1, 3), (bottom.0, 8, 11, 3, 3)]; + s.execute("select.none", &json!({})).unwrap(); + let mut at = Value::Null; + for want in backward { + at = step(&mut s, &at, true); + assert_eq!((found(&at), selected(&s)), (want, vec![NodeId(want.0)])); + } + assert_eq!(history(&s), before, "finding is no undo step"); + // A `from` in an object the search does not visit starts at the first match. + let r = s.execute("edit.findNext", &json!({"find": "cat", "from": {"id": 999_999, "start": 0, "end": 0}})).unwrap(); + assert_eq!(found(&r), (top.0, 2, 5, 1, 3)); + // Nothing found: no match, and the selection stays. + let r = s.execute("edit.findNext", &json!({"find": "zebra"})).unwrap(); + assert_eq!((r, selected(&s)), (json!({"id": null, "count": 0}), vec![top])); +} + +/// Check Hidden Layers and Check Locked Layers: Find Next and Find and Replace leave the type of +/// a hidden layer and of a locked layer alone unless the switch for it is on. A match on such a +/// layer is returned without being selected. A hidden or locked object keeps its type out with +/// the switches on. +#[test] +fn find_and_replace_reach_hidden_and_locked_layers_only_when_asked() { + for (prop, switch, other) in [("visible", "hiddenLayers", "lockedLayers"), ("locked", "lockedLayers", "hiddenLayers")] { + let mut s = session(); + let open = text(&mut s, "cat one"); + let layer = id_of(&s.execute("layer.new", &json!({})).unwrap()); + let closed = text(&mut s, "cat two"); + let object = text(&mut s, "cat three"); + let off = |id: NodeId| if prop == "visible" { json!({"id": id.0, "visible": false}) } else { json!({"id": id.0, "locked": true}) }; + s.execute("object.setProps", &off(object)).unwrap(); + s.execute("layer.setProps", &off(layer)).unwrap(); + sel(&mut s, &[open]); + // Without the switch, and with only the other one, the one reachable match is found. + for p in [json!({"find": "cat"}), json!({"find": "cat", other: true})] { + let r = s.execute("edit.findNext", &p).unwrap(); + assert_eq!(found(&r), (open.0, 0, 3, 1, 1), "{prop} {p}"); + } + // With it, the layer's type is searched (it is above, so it comes first) and not selected. + s.execute("select.none", &json!({})).unwrap(); + let r = s.execute("edit.findNext", &json!({"find": "cat", switch: true})).unwrap(); + assert_eq!((found(&r), r["selected"].clone(), selected(&s)), ((closed.0, 0, 3, 1, 2), json!(false), vec![]), "{prop}"); + let r = s.execute("edit.findNext", &json!({"find": "cat", switch: true, "from": {"id": closed.0, "start": 0, "end": 3}})).unwrap(); + assert_eq!((found(&r), r["selected"].clone(), selected(&s)), ((open.0, 0, 3, 2, 2), json!(true), vec![open]), "{prop}"); + // Replace All: the same reach. + let n = undo_len(&s); + assert_eq!( + s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog", other: true})).unwrap(), + json!({"count": 1, "replaced": 1}), + "{prop}" + ); + assert_eq!((plain(&s, open), plain(&s, closed), plain(&s, object)), ("dog one".into(), "cat two".into(), "cat three".into()), "{prop}"); + assert_eq!( + s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog", switch: true})).unwrap(), + json!({"count": 1, "replaced": 1}), + "{prop}" + ); + assert_eq!((plain(&s, closed), plain(&s, object), undo_len(&s)), ("dog two".into(), "cat three".into(), n + 2), "{prop}"); + } +} + +/// Replace changes one match, the bytes Find Next returned, as one undo step, and returns the +/// replacement's bytes to go on from. Bytes that are no match are refused, and a match that +/// already reads as the replacement is left with no undo step. +#[test] +fn replace_match_replaces_the_one_match_found() { + let mut s = session(); + let t = text(&mut s, "cat cat Cat"); + s.execute("select.none", &json!({})).unwrap(); + let first = s.execute("edit.findNext", &json!({"find": "cat"})).unwrap(); + assert_eq!(found(&first), (t.0, 0, 3, 1, 3)); + let n = undo_len(&s); + let r = s.execute("edit.replaceMatch", &json!({"find": "cat", "replace": "horse", "id": t.0, "start": 0, "end": 3})).unwrap(); + assert_eq!(r, json!({"id": t.0, "start": 0, "end": 5, "replaced": true})); + assert_eq!((plain(&s, t), undo_len(&s)), ("horse cat Cat".to_string(), n + 1)); + // Replace & Find: on from the replacement, so text put in is not searched again. + let r = s.execute("edit.replaceMatch", &json!({"find": "cat", "replace": "a cat", "id": t.0, "start": 6, "end": 9})).unwrap(); + let next = s.execute("edit.findNext", &json!({"find": "cat", "from": {"id": r["id"], "start": r["start"], "end": r["end"]}})).unwrap(); + assert_eq!((plain(&s, t), found(&next)), ("horse a cat Cat".to_string(), (t.0, 12, 15, 2, 2))); + // Match Case decides what a match is. + let shape = rect(&mut s, 300.0, 300.0, 20.0, 20.0); + s.execute("select.none", &json!({})).unwrap(); + let before = (history(&s), plain(&s, t)); + for (p, want) in [ + (json!({"find": "cat", "replace": "x", "matchCase": true, "id": t.0, "start": 12, "end": 15}), "at bytes 12..15 of object"), + (json!({"find": "cat", "replace": "x", "id": t.0, "start": 1, "end": 4}), "at bytes 1..4 of object"), + (json!({"find": "cat", "replace": "x", "id": t.0, "start": 4, "end": 1}), "at bytes 1..4 of object"), + (json!({"find": "cat", "replace": "x", "id": t.0, "start": 0}), "missing `end`"), + (json!({"find": "cat", "replace": "x", "start": 0, "end": 3}), "missing `id`"), + (json!({"find": "cat", "replace": "x", "id": t.0, "start": "0", "end": 3}), "`start` must be a whole number"), + (json!({"find": "", "replace": "x", "id": t.0, "start": 0, "end": 3}), "missing `find`"), + (json!({"find": "cat", "replace": 5, "id": t.0, "start": 8, "end": 11}), "`replace` must be a string"), + (json!({"find": "cat", "replace": "x", "id": shape.0, "start": 0, "end": 3}), "is not text"), + ] { + let r = s.execute("edit.replaceMatch", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(want)), "{p}: {r:?}"); + assert_eq!((history(&s), plain(&s, t)), before, "{p}"); + } + let r = s.execute("edit.replaceMatch", &json!({"find": "cat", "replace": "x", "id": 999_999, "start": 0, "end": 3})); + assert!(matches!(r, Err(EngineError::NoNode(NodeId(999_999)))), "{r:?}"); + // A match that already reads as the replacement: nothing to undo. + let r = s.execute("edit.replaceMatch", &json!({"find": "CAT", "replace": "Cat", "id": t.0, "start": 12, "end": 15})).unwrap(); + assert_eq!((r, history(&s)), (json!({"id": t.0, "start": 12, "end": 15, "replaced": false}), before.0)); + // Find Next refuses a `from` that is not a match. + for (from, want) in [ + (json!(5), "missing `id`"), + (json!({"id": t.0, "start": 2}), "missing `end`"), + (json!({"id": "x", "start": 0, "end": 1}), "`id` must be a whole number"), + ] { + let r = s.execute("edit.findNext", &json!({"find": "cat", "from": from})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(want)), "{from}: {r:?}"); + } + for key in ["backwards", "hiddenLayers", "lockedLayers"] { + let r = s.execute("edit.findNext", &json!({"find": "cat", key: "yes"})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == format!("`{key}` must be true or false")), "{key}: {r:?}"); + } + for key in ["hiddenLayers", "lockedLayers"] { + let r = s.execute("edit.findReplace", &json!({"find": "cat", key: 1})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == format!("`{key}` must be true or false")), "{key}: {r:?}"); + } +} + +/// Ruby over text after a replaced match moves with the text, for Replace and for Replace All, as +/// it does when the text is typed. +#[test] +fn find_and_replace_moves_the_ruby_after_a_match() { + for all in [false, true] { + let mut s = session(); + let t = text(&mut s, "ab 漢字"); + sel(&mut s, &[t]); + s.execute("type.ruby", &json!({"text": "かんじ", "start": 3, "end": 9})).unwrap(); + if all { + s.execute("edit.findReplace", &json!({"find": "ab", "replace": "abcd"})).unwrap(); + } else { + s.execute("edit.replaceMatch", &json!({"find": "ab", "replace": "abcd", "id": t.0, "start": 0, "end": 2})).unwrap(); + } + let NodeKind::Text(tt) = &node(&s, t).kind else { panic!() }; + assert_eq!((tt.plain_text().as_str(), tt.ruby.first().map(|r| (r.start, r.end))), ("abcd 漢字", Some((5, 11))), "all: {all}"); + } +} + /// The Type menu's commands and Find and Replace and Find Next refuse a param of the wrong type, or /// `ids` that name no object, with an error naming the param, and leave the text, the selection and /// the undo history as they were, even when Insert Character is also given a source it would use diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 616a11498d..8bc2cf9d36 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -801,7 +801,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{effect: id, index?: int (edit that applied effect in place, prefilled; OK runs effect.setParams), item?: appearance item index|null (the fill/stroke whose effects, null the object's; default: the Appearance panel's active item), aligned?: bool (index and item are rows of the first selected object's stack, which OK edits in each object where it has them, as effect.setParams does)} open the effect's dialog with live preview; without `index`, an effect already in that list first opens `effectExists` (confirm edits it, discard adds another) → {pending: \"effectExists\"}", ), - ("ui.paramDialog", "Command Dialog", "", "{command, label?, params} open a parameter dialog for any command"), + ( + "ui.paramDialog", + "Command Dialog", + "", + "{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place, and Edit › Find Next goes on from it in the same document while the dialog is closed", + ), ( "ui.recolorDialog", "Recolor Artwork…", diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 5afad21b0d..5a0b3da355 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -47,6 +47,7 @@ mod export_for_screens; pub mod eyedropper; pub mod file_info; pub mod find_links; +pub mod find_replace; pub mod flare_options; pub mod flatten; pub mod flattener_presets; @@ -387,6 +388,7 @@ registry! { MissingLinks: [missing_links::KIND] => missing_links::SPEC, MissingFonts: [missing_fonts::KIND] => missing_fonts::SPEC, FindLinks: [find_links::KIND] => find_links::SPEC, + FindReplace: [find_replace::KIND] => find_replace::SPEC, TextImport: [text_import::KIND] => text_import::SPEC, PdfPresets: [pdf_presets::KIND] => pdf_presets::SPEC, PdfPreset: [save_pdf::PRESET_KIND] => save_pdf::PRESET_SPEC, diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs new file mode 100644 index 0000000000..a43e737e18 --- /dev/null +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -0,0 +1,358 @@ +//! Edit › Find and Replace…: the Find and Replace With fields, Match Case, Find Whole Word, Search +//! Backwards, Check Hidden Layers and Check Locked Layers, and the Find, Replace, Replace & Find, +//! Replace All and Done buttons, as "Find and replace text" in the public +//! [reference](https://helpx.adobe.com/pdf/illustrator_reference.pdf) describes them. The dialog +//! stays open: Find goes to the next match (`edit.findNext`), Replace changes that match +//! (`edit.replaceMatch`), Replace & Find changes it and goes to the next, and Replace All changes +//! every match (`edit.findReplace`). Each Replace is one undo step, and so is Replace All. +//! +//! These rules are VectorCraft's own. A match is shown in the dialog in its line of text with its +//! place among the matches, and its type object is selected, unless it is on a hidden or locked +//! layer. Enter runs Find. Replace and Replace & Find wait for a match that Find reached with the +//! Find text and the options as they are now. Edit › Find Next goes on from the last search while +//! the dialog is closed, and opens the dialog when there has been none. +//! +//! Fields: `find`, `replace`, `matchCase`, `wholeWord`, `backwards`, `hiddenLayers`, +//! `lockedLayers` and `action` (what `ui.dialog.confirm` does: `find`, `replace`, `replaceFind`, +//! `replaceAll` or `done`; a button sets it and confirms). The dialog keeps the place the search +//! reached in `__at`, the `uid` of its document in `__doc` and the Find text and switches it was +//! reached with in `__atQuery`, the match found in `__found` and the line under the fields in +//! `__note`. A place in a document other than the active one, or reached with other Find text or +//! switches, is not used: the search starts again. + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use super::{DialogAction, DialogSpec, form}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Find and Replace. +pub const KIND: &str = "findReplace"; + +/// The command of its menu item, which Replace All runs. +pub const COMMAND: &str = "edit.findReplace"; + +/// The command Find runs, and Edit › Find Next. +pub const NEXT: &str = "edit.findNext"; + +/// The command Replace runs. +const REPLACE: &str = "edit.replaceMatch"; + +/// The switches that decide what a match is and which type is searched. +const SWITCHES: [&str; 4] = ["matchCase", "wholeWord", "hiddenLayers", "lockedLayers"]; + +/// The place the search reached: `{id, start, end}`, a match or the text that replaced one. +const AT: &str = "__at"; +/// The match Find reached, which Replace changes: `{index, count, query}`, with `query` the Find +/// text and the switches it was found with. +const FOUND: &str = "__found"; +/// The line under the fields, in English: no matches, or how many Replace All replaced. +const NOTE: &str = "__note"; + +/// The characters of a match's line shown on either side of it. +const CONTEXT: usize = 24; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Find and Replace").into(), + body_with_actions: Some(body), + confirm, + ok: None, + min_width: 480.0, + ..DialogSpec::FORM +}; + +/// The document a place in [`AT`] or the last search's `from` belongs to: its `uid`. +const DOC: &str = "__doc"; +/// The Find text and switches the place in [`AT`] was reached with ([`query`]). +const AT_QUERY: &str = "__atQuery"; + +/// The params of the Edit menu's Find and Replace… item: a `find` of null, which gives the dialog +/// no field, so that it opens on the last search. +pub fn menu_params() -> Value { + json!({"find": null}) +} + +/// The `uid` of the active document. +fn active_uid(app: &VectorcraftApp) -> Option { + app.session.active().map(|d| d.uid) +} + +/// Open Find and Replace on the last search when there has been one, with the fields that +/// `params` gives in its place. A value of another type than the field's, such as the menu item's +/// null `find` ([`menu_params`]), gives none. +pub fn open(app: &mut VectorcraftApp, params: &Map) -> Result { + let mut fields = Map::new(); + fields.insert("find".into(), json!("")); + fields.insert("replace".into(), json!("")); + for key in SWITCHES.into_iter().chain(["backwards"]) { + fields.insert(key.into(), json!(false)); + } + let last = app.ui.last_find.as_ref().and_then(Value::as_object).cloned().unwrap_or_default(); + for (k, v) in last.iter().chain(params) { + // Only the dialog's own fields, each of its own type. + if fields.get(k).is_some_and(|f| f.is_string() == v.is_string() && f.is_boolean() == v.is_boolean()) { + fields.insert(k.clone(), v.clone()); + } + } + // The place the last search reached, while its document is the active one. + let uid = active_uid(app); + if let Some(at) = last.get("from").filter(|v| v.is_object() && uid.is_some() && last.get("doc").and_then(Value::as_u64) == uid) { + fields.insert(AT.into(), at.clone()); + fields.insert(DOC.into(), json!(uid)); + fields.insert(AT_QUERY.into(), query_in(&last)); + } + fields.insert("action".into(), json!("find")); + fields.insert("__command".into(), json!(COMMAND)); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + Ok(Value::Null) +} + +/// Edit › Find Next with no text to find: the next match of the last search, from the place it +/// reached, with the options the dialog had. With no search yet, it opens the dialog. +pub fn find_next(app: &mut VectorcraftApp) -> Result { + let Some(mut last) = app.ui.last_find.clone().filter(|l| l.get("find").and_then(Value::as_str).is_some_and(|f| !f.is_empty())) else { + return open(app, &Map::new()); + }; + let uid = active_uid(app); + if let Some(o) = last.as_object_mut() { + o.remove("replace"); + // A place in another document is no place in this one. + if uid.is_none() || o.remove("doc").and_then(|d| d.as_u64()) != uid { + o.remove("from"); + } + } + let r = app.run(NEXT, last)?; + if r["id"].is_null() { + app.status("No matches found"); + return Ok(r); + } + if let Some(l) = app.ui.last_find.as_mut() { + l["from"] = json!({ "id": r["id"], "start": r["start"], "end": r["end"] }); + l["doc"] = json!(uid); + } + Ok(r) +} + +/// The Find text and the switches of [`SWITCHES`]: what a match is, as params. +fn query(d: &Dialog) -> Value { + query_in(&d.fields) +} + +/// [`query`] of the dialog fields, or of the last search, in `fields`. +fn query_in(fields: &Map) -> Value { + let mut q = json!({ "find": fields.get("find").and_then(Value::as_str).unwrap_or_default() }); + for key in SWITCHES { + q[key] = json!(fields.get(key).and_then(Value::as_bool).unwrap_or(false)); + } + q +} + +/// The place the search reached, `{id, start, end}`, while its document is the active one and +/// the Find text and the switches are those it was reached with. +fn place<'a>(app: &VectorcraftApp, d: &'a Dialog) -> Option<&'a Value> { + let uid = active_uid(app)?; + let same = d.fields.get(DOC).and_then(Value::as_u64) == Some(uid) && d.fields.get(AT_QUERY) == Some(&query(d)); + same.then(|| d.fields.get(AT)).flatten().filter(|at| at.is_object()) +} + +/// Keep `at`, a place in the active document, as the place the search reached. +fn set_place(app: &VectorcraftApp, d: &mut Dialog, at: Value) { + d.fields.insert(AT.into(), at); + d.fields.insert(DOC.into(), json!(active_uid(app))); + d.fields.insert(AT_QUERY.into(), query(d)); +} + +/// The match Replace changes, as `{id, start, end}`: the one Find reached in the active document, +/// while the Find text and the switches are as they were when it was found. +fn current_match<'a>(app: &VectorcraftApp, d: &'a Dialog) -> Option<&'a Value> { + let found = d.fields.get(FOUND)?; + (found.get("query") == Some(&query(d))).then(|| place(app, d)).flatten() +} + +/// Keep what the dialog searched for and the place it reached, for Edit › Find Next and for the +/// next time the dialog opens. +fn remember(app: &mut VectorcraftApp, d: &Dialog) { + let mut last = query(d); + last["replace"] = json!(d.str("replace")); + last["backwards"] = json!(d.bool("backwards")); + if let Some(at) = place(app, d) { + last["from"] = at.clone(); + last["doc"] = json!(active_uid(app)); + } + app.ui.last_find = Some(last); +} + +/// Find: the next match after the place the search reached, kept as that place and as the match +/// Replace changes. With no match, the note says so. +fn find(app: &mut VectorcraftApp, d: &mut Dialog) -> Result { + let mut p = query(d); + p["backwards"] = json!(d.bool("backwards")); + if let Some(at) = place(app, d) { + p["from"] = at.clone(); + } + d.fields.remove(FOUND); + d.fields.remove(NOTE); + let r = app.run(NEXT, p)?; + if r["id"].is_null() { + app.status("No matches found"); + d.fields.insert(NOTE.into(), json!(app.ui.status)); + return Ok(r); + } + set_place(app, d, json!({ "id": r["id"], "start": r["start"], "end": r["end"] })); + d.fields.insert(FOUND.into(), json!({ "index": r["index"], "count": r["count"], "query": query(d) })); + Ok(r) +} + +/// Replace: the match Find reached becomes the Replace With text, and the search goes on from +/// it. With no such match, it finds one. +fn replace(app: &mut VectorcraftApp, d: &mut Dialog) -> Result { + let Some(at) = current_match(app, d).cloned() else { return find(app, d) }; + let mut p = query(d); + for key in ["hiddenLayers", "lockedLayers"] { + if let Some(o) = p.as_object_mut() { + o.remove(key); + } + } + p["replace"] = json!(d.str("replace")); + for key in ["id", "start", "end"] { + p[key] = at[key].clone(); + } + d.fields.remove(FOUND); + d.fields.remove(NOTE); + let r = app.run(REPLACE, p)?; + set_place(app, d, json!({ "id": r["id"], "start": r["start"], "end": r["end"] })); + Ok(r) +} + +/// Replace All: every match becomes the Replace With text, and the note says how many. +fn replace_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result { + let mut p = query(d); + p["replace"] = json!(d.str("replace")); + d.fields.remove(FOUND); + d.fields.remove(NOTE); + let r = app.run(COMMAND, p)?; + // The matches that changed: those that already read as the Replace With text do not count. + match (r["count"].as_u64().unwrap_or(0), r["replaced"].as_u64().unwrap_or(0)) { + (0, _) => app.status("No matches found"), + (_, n) => app.status(format!("Matches replaced: {n}")), + } + d.fields.insert(NOTE.into(), json!(app.ui.status)); + Ok(r) +} + +/// A button or `ui.dialog.confirm`: run the `action` and keep the dialog open, or close it for +/// `done`. What a command refuses is the note, and the dialog stays open. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut d = d.clone(); + let action = d.fields.insert("action".into(), json!("find")).and_then(|a| a.as_str().map(str::to_string)).unwrap_or_default(); + let r = match action.as_str() { + "done" => { + remember(app, &d); + app.ui.dialog = None; + return Ok(Value::Null); + } + "" | "find" => find(app, &mut d), + "replace" => replace(app, &mut d), + "replaceFind" => match current_match(app, &d) { + Some(_) => replace(app, &mut d).and_then(|_| find(app, &mut d)), + None => find(app, &mut d), + }, + "replaceAll" => replace_all(app, &mut d), + _ => Err("no such action".to_string()), + }; + if let Err(e) = &r { + d.fields.insert(NOTE.into(), json!(e)); + } + remember(app, &d); + app.ui.dialog = Some(d); + r +} + +/// The match Find reached as it reads in its text: (the text before it on its line, the match, +/// the text after it), each at most [`CONTEXT`] characters, and its place among the matches. +fn shown_match(app: &VectorcraftApp, d: &Dialog) -> Option<([String; 3], String)> { + let at = current_match(app, d)?; + let found = d.fields.get(FOUND)?; + let whole = |v: &Value| v.as_u64().and_then(|n| usize::try_from(n).ok()); + let (id, start, end) = (at["id"].as_u64()?, whole(&at["start"])?, whole(&at["end"])?); + let NodeKind::Text(t) = &app.session.active()?.doc.node(NodeId(id))?.kind else { return None }; + let text = t.plain_text(); + let (before, hit, after) = (text.get(..start)?, text.get(start..end)?, text.get(end..)?); + let before = before.rsplit(['\n', '\r']).next().unwrap_or_default(); + let after = after.split(['\n', '\r']).next().unwrap_or_default(); + let skip = before.chars().count().saturating_sub(CONTEXT); + let lead = if skip > 0 { "…" } else { "" }; + let tail = if after.chars().count() > CONTEXT { "…" } else { "" }; + let before = format!("{lead}{}", before.chars().skip(skip).collect::()); + let after = format!("{}{tail}", after.chars().take(CONTEXT).collect::()); + Some(([before, hit.to_string(), after], format!("{} / {}", found["index"], found["count"]))) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let can_find = !d.str("find").is_empty(); + let found = current_match(app, d).is_some(); + let mut action = None; + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + widgets::dim_label(ui, tl!("Find:")); + form::text(ui, d, "find", 320.0); + ui.add_space(6.0); + widgets::dim_label(ui, tl!("Replace With:")); + form::text(ui, d, "replace", 320.0); + ui.add_space(10.0); + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + form::check(ui, d, "matchCase", "Match Case"); + form::check(ui, d, "wholeWord", "Find Whole Word"); + form::check(ui, d, "backwards", "Search Backwards"); + }); + ui.add_space(16.0); + ui.vertical(|ui| { + form::check(ui, d, "hiddenLayers", "Check Hidden Layers"); + form::check(ui, d, "lockedLayers", "Check Locked Layers"); + }); + }); + }); + ui.add_space(16.0); + ui.vertical(|ui| { + let mut button = |ui: &mut egui::Ui, label: &str, enabled: bool, name: &'static str| { + if ui.add_enabled_ui(enabled, |ui| widgets::flat_button(ui, label, 130.0).clicked()).inner { + action = Some(name); + } + ui.add_space(6.0); + }; + button(ui, if found { tl!("Find Next") } else { tl!("Find") }, can_find, "find"); + button(ui, tl!("Replace"), can_find && found, "replace"); + button(ui, tl!("Replace & Find"), can_find && found, "replaceFind"); + button(ui, tl!("Replace All"), can_find, "replaceAll"); + button(ui, tl!("Done"), true, "done"); + }); + }); + ui.add_space(8.0); + if let Some(([before, hit, after], place)) = shown_match(app, d) { + let t = crate::theme::Tokens::get(ui.ctx()); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + widgets::dim_name(ui, &format!("{place} {before}")); + ui.colored_label(t.text_strong, egui::RichText::new(hit).strong().underline()); + widgets::dim_name(ui, &after); + }); + } else if let Some(note) = d.fields.get(NOTE).and_then(Value::as_str) { + widgets::dim_name(ui, &crate::i18n::message(crate::i18n::current(), note)); + } + // Enter finds, as the Find button does. + if action.is_none() && can_find && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { + action = Some("find"); + } + match action { + Some(name) => { + d.fields.insert("action".into(), json!(name)); + DialogAction::Confirm + } + None => DialogAction::None, + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs new file mode 100644 index 0000000000..a55e1c0085 --- /dev/null +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -0,0 +1,377 @@ +use egui::{Event, PointerButton, Pos2, Rect, vec2}; +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use crate::VectorcraftApp; + +/// An app on a document holding point type `texts`, bottom first, with nothing selected → the +/// app and the type objects' ids. +fn app_with(texts: &[&str]) -> (VectorcraftApp, Vec) { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let ids = texts.iter().map(|t| s.execute("text.create", &json!({"x": 50, "y": 50, "text": t})).unwrap()["id"].as_u64().unwrap()).collect(); + s.execute("select.none", &json!({})).unwrap(); + (VectorcraftApp::new(s, crate::Services::default()), ids) +} + +/// Choose Edit › Find and Replace…, as a click on the menu item does. +fn choose(app: &mut VectorcraftApp) { + let (id, p) = crate::shortcut_editor::menu_target(super::COMMAND).expect("the menu item gives params"); + crate::menus::invoke(app, &id, p); +} + +/// Choose Edit › Find Next, as a click on the menu item does. +fn choose_find_next(app: &mut VectorcraftApp) { + let e = crate::menus::menu_entries(app).into_iter().find(|e| e.label == "Find Next").expect("in the Edit menu"); + assert_eq!((e.command.as_deref(), e.enabled), (Some(super::NEXT), true)); + crate::menus::invoke(app, super::NEXT, json!({"find": ""})); +} + +fn set(app: &mut VectorcraftApp, k: &str, v: Value) { + app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); +} + +fn field(app: &VectorcraftApp, k: &str) -> Value { + app.ui.dialog.as_ref().expect("the dialog is open").fields.get(k).cloned().unwrap_or(Value::Null) +} + +/// The match Replace would change, as (object, start, end). +fn matched(app: &VectorcraftApp) -> Option<(u64, u64, u64)> { + let at = super::current_match(app, app.ui.dialog.as_ref()?)?; + Some((at["id"].as_u64()?, at["start"].as_u64()?, at["end"].as_u64()?)) +} + +fn plain(app: &VectorcraftApp, id: u64) -> String { + match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not type"), + } +} + +fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +fn selected(app: &VectorcraftApp) -> Vec { + app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect() +} + +/// One frame of the dialog on an 800 × 600 window → the text painted, with its rect. +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, Rect)> { + // A window takes a sizing frame and fades in: each frame is a quarter second on. + let time = ctx.input(|i| i.time) + 0.25; + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, Rect)>) { + match s { + egui::Shape::Text(t) => v.push((t.galley.text().to_string(), Rect::from_min_size(t.pos, t.galley.size()))), + egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut v = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, &mut v)); + v +} + +fn context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx +} + +fn click(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) -> Vec<(String, Rect)> { + frame(app, ctx, vec![]); + let texts = frame(app, ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![Event::PointerMoved(at)]); + frame(app, ctx, vec![press(true)]); + frame(app, ctx, vec![press(false)]); + frame(app, ctx, vec![]) +} + +/// Edit › Find and Replace… opens the dialog of its own, with the fields and options of the +/// public reference's "Find and replace text", instead of the generic parameter dialog. +#[test] +fn the_edit_menu_opens_the_find_and_replace_dialog() { + let (mut app, _) = app_with(&["cat"]); + let e = crate::menus::menu_entries(&app).into_iter().find(|e| e.label == "Find and Replace…").expect("in the Edit menu"); + assert_eq!((e.path.as_slice(), e.command.as_deref(), e.enabled), (&["Edit".to_string()][..], Some(super::COMMAND), true)); + choose(&mut app); + let d = app.ui.dialog.as_ref().expect("Find and Replace opens"); + assert_eq!((d.kind.as_str(), d.fields["__command"].clone()), (super::KIND, json!(super::COMMAND))); + for (key, want) in [("find", json!("")), ("replace", json!("")), ("action", json!("find"))] { + assert_eq!(d.fields[key], want, "{key}"); + } + for key in ["matchCase", "wholeWord", "backwards", "hiddenLayers", "lockedLayers"] { + assert_eq!(d.fields[key], json!(false), "{key}"); + } + let ctx = context(); + frame(&mut app, &ctx, vec![]); + let texts: Vec = frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + for label in [ + "Find and Replace", + "Find:", + "Replace With:", + "Match Case", + "Find Whole Word", + "Search Backwards", + "Check Hidden Layers", + "Check Locked Layers", + "Find", + "Replace", + "Replace & Find", + "Replace All", + "Done", + ] { + assert!(texts.iter().any(|t| t == label), "no `{label}` in {texts:?}"); + } +} + +/// The dialog stays open from match to match: Find goes to the next match and selects its +/// object, Replace changes that match, Replace & Find changes it and goes on, Replace All changes +/// the rest, and Done closes. Each Replace is one undo step, and so is Replace All; finding and a +/// Replace All with nothing to replace record none. +#[test] +fn the_buttons_step_through_the_matches() { + let (mut app, ids) = app_with(&["cat cat", "a cat"]); + let (bottom, top) = (ids[0], ids[1]); + choose(&mut app); + let ctx = context(); + set(&mut app, "find", json!("cat")); + set(&mut app, "replace", json!("dog")); + let steps = undo_steps(&app); + // Find: the first match, in the top object, shown with its place and its line of text. + let texts = click(&mut app, &ctx, "Find"); + assert_eq!((matched(&app), selected(&app), undo_steps(&app)), (Some((top, 2, 5)), vec![top], steps)); + assert!(texts.iter().any(|(t, _)| t.starts_with("1 / 3")) && texts.iter().any(|(t, _)| t == "cat"), "{texts:?}"); + assert!(texts.iter().any(|(t, _)| t == "Find Next"), "Find reads Find Next once a match is found: {texts:?}"); + // Replace: that match only, and the search stays where it was. + click(&mut app, &ctx, "Replace"); + assert_eq!((plain(&app, top), plain(&app, bottom), undo_steps(&app)), ("a dog".to_string(), "cat cat".to_string(), steps + 1)); + assert_eq!((matched(&app), field(&app, "__at")), (None, json!({"id": top, "start": 2, "end": 5}))); + // Find goes on from there, to the bottom object. + click(&mut app, &ctx, "Find"); + assert_eq!((matched(&app), selected(&app), field(&app, "__found")["count"].clone()), (Some((bottom, 0, 3)), vec![bottom], json!(2))); + // Replace & Find: one undo step, and the next match is the one left. + click(&mut app, &ctx, "Replace & Find"); + assert_eq!((plain(&app, bottom), undo_steps(&app), matched(&app)), ("dog cat".to_string(), steps + 2, Some((bottom, 4, 7)))); + // Replace All: the rest as one undo step, with the count under the fields. + let texts = click(&mut app, &ctx, "Replace All"); + assert_eq!((plain(&app, bottom), undo_steps(&app), matched(&app)), ("dog dog".to_string(), steps + 3, None)); + assert!(texts.iter().any(|(t, _)| t == "Matches replaced: 1"), "{texts:?}"); + // Nothing left: no undo step, and the dialog says so, for Replace All and for Find. + for button in ["Replace All", "Find"] { + let texts = click(&mut app, &ctx, button); + assert_eq!((undo_steps(&app), matched(&app)), (steps + 3, None), "{button}"); + assert!(texts.iter().any(|(t, _)| t == "No matches found"), "{button}: {texts:?}"); + } + assert!(app.ui.dialog.is_some(), "the dialog stays open until Done"); + click(&mut app, &ctx, "Done"); + assert!(app.ui.dialog.is_none(), "Done closes it"); + assert_eq!(undo_steps(&app), steps + 3); +} + +/// Replace and Replace & Find wait for a match found with the Find text and the options as they +/// are: before the first Find, and after the Find text changes, a click on them changes nothing. +/// With no Find text, no button but Done acts. Enter runs Find. +#[test] +fn replace_waits_for_a_match_of_the_text_as_it_is() { + let (mut app, ids) = app_with(&["cat cart"]); + choose(&mut app); + let ctx = context(); + let steps = undo_steps(&app); + set(&mut app, "replace", json!("x")); + for button in ["Find", "Replace", "Replace & Find", "Replace All"] { + click(&mut app, &ctx, button); + assert_eq!((plain(&app, ids[0]), undo_steps(&app), matched(&app)), ("cat cart".to_string(), steps, None), "{button} with no Find text"); + } + set(&mut app, "find", json!("cat")); + for button in ["Replace", "Replace & Find"] { + click(&mut app, &ctx, button); + assert_eq!((plain(&app, ids[0]), undo_steps(&app), matched(&app)), ("cat cart".to_string(), steps, None), "{button} before Find"); + } + // Enter finds. + frame(&mut app, &ctx, vec![]); + let enter = |pressed| Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![enter(true)]); + frame(&mut app, &ctx, vec![enter(false)]); + assert_eq!(matched(&app), Some((ids[0], 0, 3))); + // The Find text changes: the match found is no longer the one to replace. + set(&mut app, "find", json!("ca")); + assert_eq!(matched(&app), None); + for button in ["Replace", "Replace & Find"] { + click(&mut app, &ctx, button); + assert_eq!((plain(&app, ids[0]), undo_steps(&app)), ("cat cart".to_string(), steps), "{button} after the Find text changed"); + } + // An option changes: the same. + set(&mut app, "find", json!("cat")); + assert_eq!(matched(&app), Some((ids[0], 0, 3))); + set(&mut app, "matchCase", json!(true)); + assert_eq!(matched(&app), None); + // Search Backwards is a direction, not what a match is. + set(&mut app, "matchCase", json!(false)); + set(&mut app, "backwards", json!(true)); + assert_eq!(matched(&app), Some((ids[0], 0, 3))); + click(&mut app, &ctx, "Replace"); + assert_eq!((plain(&app, ids[0]), undo_steps(&app)), ("x cart".to_string(), steps + 1)); +} + +/// `ui.dialog.confirm` runs the dialog's `action`, keeps it open and puts `action` back to find; +/// done closes it. An action it does not know is refused, and so is an empty Find text. +#[test] +fn confirm_runs_the_action() { + let (mut app, ids) = app_with(&["cat cat cat"]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + set(&mut app, "replace", json!("dog")); + let steps = undo_steps(&app); + let r = crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((r["start"].clone(), r["index"].clone(), r["count"].clone(), matched(&app)), (json!(0), json!(1), json!(3), Some((ids[0], 0, 3)))); + set(&mut app, "action", json!("replaceFind")); + let r = crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((plain(&app, ids[0]), r["start"].clone(), field(&app, "action")), ("dog cat cat".to_string(), json!(4), json!("find"))); + set(&mut app, "action", json!("replace")); + let r = crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((plain(&app, ids[0]), r["replaced"].clone(), matched(&app)), ("dog dog cat".to_string(), json!(true), None)); + // Replace with no match found: it finds one. + set(&mut app, "action", json!("replace")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((plain(&app, ids[0]), matched(&app), undo_steps(&app)), ("dog dog cat".to_string(), Some((ids[0], 8, 11)), steps + 2)); + set(&mut app, "action", json!("replaceAll")); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap(), json!({"count": 1, "replaced": 1})); + assert_eq!((plain(&app, ids[0]), undo_steps(&app)), ("dog dog dog".to_string(), steps + 3)); + // Matches that already read as the Replace With text are found and not counted as replaced. + set(&mut app, "find", json!("DOG")); + set(&mut app, "action", json!("replaceAll")); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap(), json!({"count": 3, "replaced": 0})); + assert_eq!((undo_steps(&app), field(&app, "__note")), (steps + 3, json!("Matches replaced: 0"))); + set(&mut app, "find", json!("dog")); + for (action, find) in [("erase", "dog"), ("find", ""), ("replaceAll", "")] { + set(&mut app, "action", json!(action)); + set(&mut app, "find", json!(find)); + assert!(crate::dialogs::confirm(&mut app).is_err(), "{action} {find:?}"); + assert_eq!((plain(&app, ids[0]), undo_steps(&app), field(&app, "action")), ("dog dog dog".to_string(), steps + 3, json!("find"))); + assert!(field(&app, "__note").is_string(), "{action} {find:?}: the dialog shows why"); + } + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); +} + +/// Edit › Find Next goes on from the dialog's last search while the dialog is closed, with its +/// options, and says when nothing matches. With no search yet, it opens the dialog, and the +/// dialog opens again on the last search. +#[test] +fn find_next_goes_on_from_the_last_search() { + let (mut app, ids) = app_with(&["Cat", "cat", "cat"]); + choose_find_next(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND), "no search yet: the dialog opens"); + set(&mut app, "find", json!("cat")); + set(&mut app, "replace", json!("dog")); + set(&mut app, "matchCase", json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((ids[2], 0, 3))); + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + let steps = undo_steps(&app); + // On from the match the dialog found; Match Case still leaves out "Cat". + for want in [ids[1], ids[2], ids[1]] { + choose_find_next(&mut app); + assert_eq!((selected(&app), app.ui.dialog.is_none(), undo_steps(&app)), (vec![want], true, steps)); + } + // The dialog opens on the last search and the place it reached. + choose(&mut app); + assert_eq!((field(&app, "find"), field(&app, "replace"), field(&app, "matchCase")), (json!("cat"), json!("dog"), json!(true))); + assert_eq!(field(&app, "__at"), json!({"id": ids[1], "start": 0, "end": 3})); + set(&mut app, "find", json!("zebra")); + assert!(crate::dialogs::confirm(&mut app).unwrap()["id"].is_null()); + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + app.ui.status.clear(); + choose_find_next(&mut app); + assert_eq!((app.ui.status.as_str(), selected(&app)), ("No matches found", vec![ids[1]])); +} + +/// The place a search reached goes with the Find text and the switches it was reached with: a +/// search for other text starts again, in the dialog and when `ui.paramDialog` gives other text, +/// and the same search goes on from that place. +#[test] +fn a_changed_search_starts_again() { + let (mut app, ids) = app_with(&["cat dog cat", "dog"]); + let (bottom, top) = (ids[0], ids[1]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((bottom, 0, 3))); + set(&mut app, "find", json!("dog")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((top, 0, 3)), "not the dog after the cat found"); + set(&mut app, "find", json!("cat")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((bottom, 0, 3))); + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + crate::menus::invoke(&mut app, "ui.paramDialog", json!({"command": super::COMMAND, "params": {"find": "dog"}})); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((top, 0, 3))); + app.ui.dialog = None; + choose(&mut app); + assert_eq!(field(&app, "find"), json!("dog")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((bottom, 4, 7)), "the same search goes on"); +} + +/// The place a search reached belongs to its document: in another document, Edit › Find Next and +/// the dialog start at that document's first match, even where an object there has the same id. +/// The params of a `ui.paramDialog` call take the place of the last search's, a switch that is off +/// included, while the menu item's own params leave the last search as it was. +#[test] +fn a_search_place_stays_in_its_document_and_given_params_win() { + let (mut app, ids) = app_with(&["cat cat"]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + set(&mut app, "matchCase", json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((ids[0], 0, 3))); + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + // A second document, whose type object has the id of the first one's. + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + let other = app.run("text.create", json!({"x": 50, "y": 50, "text": "cat cat"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.none", json!({})).unwrap(); + assert_eq!(other, ids[0]); + choose_find_next(&mut app); + assert_eq!( + (selected(&app), app.ui.last_find.as_ref().map(|l| l["from"].clone())), + (vec![other], Some(json!({"id": other, "start": 0, "end": 3}))) + ); + // The dialog opens on the last search; Find goes on in this document. + choose(&mut app); + assert_eq!(field(&app, "matchCase"), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((other, 4, 7))); + // Back in the first document, the dialog's place is not used: Replace finds first and changes + // nothing. + assert!(app.session.set_active(0)); + assert_eq!(matched(&app), None); + set(&mut app, "replace", json!("dog")); + set(&mut app, "action", json!("replace")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((plain(&app, ids[0]), matched(&app)), ("cat cat".to_string(), Some((ids[0], 0, 3)))); + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + // Given params win over the last search; the menu item's own do not. + crate::menus::invoke(&mut app, "ui.paramDialog", json!({"command": super::COMMAND, "params": {"matchCase": false, "replace": "dog"}})); + assert_eq!((field(&app, "find"), field(&app, "matchCase"), field(&app, "replace")), (json!("cat"), json!(false), json!("dog"))); + app.ui.dialog = None; + let empty = json!({"find": "", "replace": "", "matchCase": false, "wholeWord": false}); + crate::menus::invoke(&mut app, "ui.paramDialog", json!({"command": super::COMMAND, "params": empty})); + assert_eq!((field(&app, "find"), field(&app, "matchCase")), (json!(""), json!(false))); + app.ui.dialog = None; + choose(&mut app); + assert_eq!((field(&app, "find"), field(&app, "matchCase")), (json!("cat"), json!(true))); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 28944173dd..ae97c08ddb 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1202,6 +1202,16 @@ font-technology Variable Променливи Fill: click for swatches, Shift-click for the color mixer Запълване: щракнете за образци, Shift-щракване за смесителя на цветове Find Търсене Find and Replace… Търсене и замяна… + Find and Replace Търсене и замяна + Find: Търсене: + Replace With: Замяна с: + Replace & Find Замяна и търсене + Replace All Замяна на всички + Match Case Съвпадение на малки и главни букви + Find Whole Word Търсене на цяла дума + Search Backwards Търсене назад + Check Hidden Layers Проверка на скритите слоеве + Check Locked Layers Проверка на заключените слоеве Find Font Търсене на шрифт Find Font… Търсене на шрифт… Find Next Търсене на следващ diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 01b90e5148..e0f2a7791d 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -85,6 +85,16 @@ Paste without Formatting Zalijepi bez oblikovanja Clear Očisti Find and Replace… Pronađi i zamijeni… + Find and Replace Pronađi i zamijeni + Find: Pronađi: + Replace With: Zamijeni sa: + Replace & Find Zamijeni i pronađi + Replace All Zamijeni sve + Match Case Razlikuj velika i mala slova + Find Whole Word Pronađi cijelu riječ + Search Backwards Pretraži unazad + Check Hidden Layers Provjeri skrivene slojeve + Check Locked Layers Provjeri zaključane slojeve Find Next Pronađi sljedeće Spelling Pravopis Auto Spell Check Automatska provjera pravopisa diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 4ddd1d5605..1110e85c25 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1697,6 +1697,19 @@ digits Malayalam Malaiàlam Filters Filtres Find Cerca Find and Replace… Cerca i reemplaça… + Find and Replace Cerca i reemplaça + Find: Cerca: + Replace With: Reemplaça per: + Replace & Find Reemplaça i cerca + Replace All Reemplaça-ho tot + Match Case Distingeix majúscules i minúscules + Find Whole Word Cerca la paraula sencera + Search Backwards Cerca cap enrere + Check Hidden Layers Comprova les capes ocultes + Check Locked Layers Comprova les capes bloquejades +@msg No matches found No s’ha trobat cap coincidència +@msg Matches replaced: {n} Coincidències reemplaçades: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} no hi ha cap coincidència de `find` als bytes {_1}..{_2} de l’objecte {_3} Find Font Cerca un tipus de lletra Find Font Files Cerca fitxers de tipus de lletra Find Fonts Cerca tipus de lletra diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 211982f086..d8d9ff3c05 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -90,6 +90,19 @@ Paste without Formatting Vložit bez formátování Clear Smazat Find and Replace… Najít a nahradit… + Find and Replace Najít a nahradit + Find: Najít: + Replace With: Nahradit čím: + Replace & Find Nahradit a najít + Replace All Nahradit vše + Match Case Rozlišovat velká a malá písmena + Find Whole Word Najít celé slovo + Search Backwards Hledat zpět + Check Hidden Layers Prohledat skryté vrstvy + Check Locked Layers Prohledat zamknuté vrstvy +@msg No matches found Nenalezeny žádné shody +@msg Matches replaced: {n} Nahrazeno shod: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} na bajtech {_1}..{_2} objektu {_3} není žádná shoda s `find` Find Next Najít další Spelling Pravopis Auto Spell Check Automatická kontrola pravopisu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b3de0ae89a..d2c4bf5afa 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -78,6 +78,16 @@ Paste without Formatting Indsæt uden formatering Clear Fjern Find and Replace… Find og erstat… + Find and Replace Find og erstat + Find: Find: + Replace With: Erstat med: + Replace & Find Erstat og find + Replace All Erstat alle + Match Case Forskel på store og små bogstaver + Find Whole Word Find hele ord + Search Backwards Søg baglæns + Check Hidden Layers Kontrollér skjulte lag + Check Locked Layers Kontrollér låste lag Find Next Find næste Spelling Stavekontrol Auto Spell Check Automatisk stavekontrol diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d0610144ef..4a1eabcece 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1230,6 +1230,19 @@ font-technology Variable Variabel Fill: click for swatches, Shift-click for the color mixer Fläche: Klicken für Farbfelder, Shift-Klick für den Farbmischer Find Suchen Find and Replace… Suchen und ersetzen… + Find and Replace Suchen und ersetzen + Find: Suchen: + Replace With: Ersetzen durch: + Replace & Find Ersetzen und suchen + Replace All Alle ersetzen + Match Case Groß-/Kleinschreibung beachten + Find Whole Word Ganzes Wort suchen + Search Backwards Rückwärts suchen + Check Hidden Layers Ausgeblendete Ebenen durchsuchen + Check Locked Layers Gesperrte Ebenen durchsuchen +@msg No matches found Keine Treffer gefunden +@msg Matches replaced: {n} Ersetzte Treffer: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} kein Treffer für `find` bei Byte {_1}..{_2} von Objekt {_3} Find Font Schrift suchen Find Font… Schrift suchen… Find Next Weitersuchen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index d03f8c6958..5f12f6ff1b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1180,6 +1180,19 @@ font-technology Variable Μεταβλητές Fill: click for swatches, Shift-click for the color mixer Γέμισμα: κλικ για δείγματα, Shift-κλικ για τον μείκτη χρωμάτων Find Εύρεση Find and Replace… Εύρεση και αντικατάσταση… + Find and Replace Εύρεση και αντικατάσταση + Find: Εύρεση: + Replace With: Αντικατάσταση με: + Replace & Find Αντικατάσταση και εύρεση + Replace All Αντικατάσταση όλων + Match Case Ταίριασμα πεζών-κεφαλαίων + Find Whole Word Εύρεση ολόκληρης λέξης + Search Backwards Αναζήτηση προς τα πίσω + Check Hidden Layers Έλεγχος κρυφών επιπέδων + Check Locked Layers Έλεγχος κλειδωμένων επιπέδων +@msg No matches found Δεν βρέθηκαν αντιστοιχίες +@msg Matches replaced: {n} Αντιστοιχίες που αντικαταστάθηκαν: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} καμία αντιστοιχία του `find` στα byte {_1}..{_2} του αντικειμένου {_3} Find Font Εύρεση γραμματοσειράς Find Font… Εύρεση γραμματοσειράς… Find Next Εύρεση επόμενου diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3e8bd23752..654ec57749 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1251,6 +1251,19 @@ font-technology Variable Variables Fill: click for swatches, Shift-click for the color mixer Relleno: clic para muestras, Shift+clic para el mezclador de colores Find Buscar Find and Replace… Buscar y reemplazar… + Find and Replace Buscar y reemplazar + Find: Buscar: + Replace With: Reemplazar por: + Replace & Find Reemplazar y buscar + Replace All Reemplazar todo + Match Case Coincidir mayúsculas y minúsculas + Find Whole Word Buscar palabra completa + Search Backwards Buscar hacia atrás + Check Hidden Layers Comprobar capas ocultas + Check Locked Layers Comprobar capas bloqueadas +@msg No matches found No se encontraron coincidencias +@msg Matches replaced: {n} Coincidencias reemplazadas: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} no hay ninguna coincidencia de `find` en los bytes {_1}..{_2} del objeto {_3} Find Font Buscar fuente Find Font… Buscar fuente… Find Next Buscar siguiente diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d408220f47..fd19f7246c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -98,6 +98,19 @@ Paste without Formatting Liitä ilman muotoilua Clear Tyhjennä Find and Replace… Etsi ja korvaa… + Find and Replace Etsi ja korvaa + Find: Etsi: + Replace With: Korvaa tekstillä: + Replace & Find Korvaa ja etsi + Replace All Korvaa kaikki + Match Case Sama kirjainkoko + Find Whole Word Etsi koko sana + Search Backwards Etsi taaksepäin + Check Hidden Layers Tarkista piilotetut tasot + Check Locked Layers Tarkista lukitut tasot +@msg No matches found Osumia ei löytynyt +@msg Matches replaced: {n} Korvattuja osumia: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} objektin {_3} tavuissa {_1}..{_2} ei ole haun `find` osumaa Find Next Etsi seuraava Spelling Oikeinkirjoitus Auto Spell Check Automaattinen oikeinkirjoituksen tarkistus diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 318bbbeb44..9d79ede0b2 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1245,6 +1245,19 @@ font-technology Variable Variables Fill: click for swatches, Shift-click for the color mixer Fond : cliquez pour le nuancier, Maj+clic pour le mélangeur de couleurs Find Rechercher Find and Replace… Rechercher et remplacer… + Find and Replace Rechercher et remplacer + Find: Rechercher: + Replace With: Remplacer par: + Replace & Find Remplacer et rechercher + Replace All Tout remplacer + Match Case Respecter la casse + Find Whole Word Rechercher le mot entier + Search Backwards Rechercher vers l’arrière + Check Hidden Layers Vérifier les calques masqués + Check Locked Layers Vérifier les calques verrouillés +@msg No matches found Aucune occurrence trouvée +@msg Matches replaced: {n} Occurrences remplacées : {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} aucune occurrence de `find` aux octets {_1}..{_2} de l’objet {_3} Find Font Rechercher une police Find Font… Rechercher une police… Find Next Rechercher le suivant diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 78c0a9a7eb..a68dcbedc3 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1885,6 +1885,19 @@ antiAlias Sharp शार्प Filters फिल्टर Find खोजें Find and Replace… खोजें और बदलें… + Find and Replace खोजें और बदलें + Find: खोजें: + Replace With: इससे रिप्लेस करें: + Replace & Find रिप्लेस करें और खोजें + Replace All सभी रिप्लेस करें + Match Case केस मिलाएँ + Find Whole Word पूरा शब्द खोजें + Search Backwards पीछे की ओर खोजें + Check Hidden Layers छिपी हुई लेयर्स जाँचें + Check Locked Layers लॉक की गई लेयर्स जाँचें +@msg No matches found कोई मिलान नहीं मिला +@msg Matches replaced: {n} रिप्लेस किए गए मिलान: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} ऑब्जेक्ट {_3} के बाइट {_1}..{_2} पर `find` का कोई मिलान नहीं है Find Font फ़ॉन्ट खोजें Find Font Files फ़ॉन्ट फ़ाइल का पता लगाएं Find Font… फ़ॉन्ट खोजें… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index a1f6100b2f..1747ad1712 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1559,6 +1559,19 @@ digits Malayalam Malajálam Film & Video Film és videó Find Keresés Find and Replace… Keresés és csere… + Find and Replace Keresés és csere + Find: Keresés: + Replace With: Csere erre: + Replace & Find Csere és keresés + Replace All Az összes cseréje + Match Case Kis- és nagybetűk megkülönböztetése + Find Whole Word Teljes szó keresése + Search Backwards Keresés visszafelé + Check Hidden Layers Rejtett rétegek ellenőrzése + Check Locked Layers Zárolt rétegek ellenőrzése +@msg No matches found Nincs találat +@msg Matches replaced: {n} Cserélt találatok: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} nincs `find` találat a(z) {_3} objektum {_1}..{_2} bájtjain Find Font Betűtípus keresése Find Font Files Betűtípusfájlok keresése Find Fonts Betűtípusok keresése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c7c6b956db..0312437363 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -78,6 +78,16 @@ Paste without Formatting Tempel tanpa pemformatan Clear Hapus Find and Replace… Cari dan ganti… + Find and Replace Cari dan ganti + Find: Cari: + Replace With: Ganti dengan: + Replace & Find Ganti dan cari + Replace All Ganti semua + Match Case Cocokkan huruf besar/kecil + Find Whole Word Cari seluruh kata + Search Backwards Cari mundur + Check Hidden Layers Periksa lapisan tersembunyi + Check Locked Layers Periksa lapisan terkunci Find Next Cari berikutnya Spelling Ejaan Auto Spell Check Pemeriksaan ejaan otomatis diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6743704785..093544fda9 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1260,6 +1260,19 @@ font-technology Variable Variabili Fill: click for swatches, Shift-click for the color mixer Riempimento: fai clic per i campioni, Shift+clic per il miscelatore colori Find Trova Find and Replace… Trova e sostituisci… + Find and Replace Trova e sostituisci + Find: Trova: + Replace With: Sostituisci con: + Replace & Find Sostituisci e trova + Replace All Sostituisci tutto + Match Case Maiuscole/minuscole + Find Whole Word Trova parola intera + Search Backwards Cerca all'indietro + Check Hidden Layers Controlla livelli nascosti + Check Locked Layers Controlla livelli bloccati +@msg No matches found Nessuna corrispondenza trovata +@msg Matches replaced: {n} Corrispondenze sostituite: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} nessuna corrispondenza di `find` ai byte {_1}..{_2} dell'oggetto {_3} Find Font Trova font Find Font… Trova font… Find Next Trova successivo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c9cdb8fcbe..afa5bb4a68 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -163,6 +163,19 @@ digits Malayalam マラヤーラム数字 Paste without Formatting 書式なしでペースト Clear 消去 Find and Replace… 検索と置換… + Find and Replace 検索と置換 + Find: 検索: + Replace With: 置換文字列: + Replace & Find 置換して検索 + Replace All すべて置換 + Match Case 大文字と小文字を区別 + Find Whole Word 単語単位で検索 + Search Backwards 逆方向に検索 + Check Hidden Layers 非表示レイヤーを検索 + Check Locked Layers ロックされたレイヤーを検索 +@msg No matches found 一致する文字列が見つかりません +@msg Matches replaced: {n} 置換した一致: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} オブジェクト {_3} のバイト {_1}..{_2} に `find` の一致はありません Find Next 次を検索 Find Objects オブジェクトを検索 Compare with Image 画像と比較 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 55f726dc38..5c62e0615b 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -88,6 +88,19 @@ Paste without Formatting ფორმატირების გარეშე ჩასმა Clear გასუფთავება Find and Replace… ძებნა და ჩანაცვლება… + Find and Replace ძებნა და ჩანაცვლება + Find: ძებნა: + Replace With: ჩანაცვლება შემდეგით: + Replace & Find ჩანაცვლება და ძებნა + Replace All ყველას ჩანაცვლება + Match Case რეგისტრის გათვალისწინება + Find Whole Word მთელი სიტყვის ძებნა + Search Backwards უკუმიმართულებით ძებნა + Check Hidden Layers დამალული შრეების შემოწმება + Check Locked Layers ჩაკეტილი შრეების შემოწმება +@msg No matches found დამთხვევები ვერ მოიძებნა +@msg Matches replaced: {n} ჩანაცვლებული დამთხვევები: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} ობიექტ {_3}-ის {_1}..{_2} ბაიტებზე `find`-ის დამთხვევა არ არის Find Next შემდეგის ძებნა Spelling მართლწერა Auto Spell Check მართლწერის ავტომატური შემოწმება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index abe2b4bc28..a5fc870751 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -156,6 +156,19 @@ digits Malayalam 말라얄람어 Paste without Formatting 서식 없이 붙여넣기 Clear 지우기 Find and Replace… 찾기 및 바꾸기… + Find and Replace 찾기 및 바꾸기 + Find: 찾기: + Replace With: 바꿀 내용: + Replace & Find 바꾼 후 찾기 + Replace All 모두 바꾸기 + Match Case 대/소문자 구분 + Find Whole Word 단어 단위로 찾기 + Search Backwards 역방향 검색 + Check Hidden Layers 숨겨진 레이어 확인 + Check Locked Layers 잠긴 레이어 확인 +@msg No matches found 일치하는 항목이 없습니다 +@msg Matches replaced: {n} 바꾼 일치 항목: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} 개체 {_3}의 바이트 {_1}..{_2}에 `find`와 일치하는 항목이 없습니다 Find Next 다음 찾기 Find Objects 개체 찾기 Compare with Image 이미지와 비교 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ed281382a4..3b3d163817 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -582,6 +582,19 @@ Paste without Formatting Plakken zonder opmaak Clear Wissen Find and Replace… Zoeken en vervangen… + Find and Replace Zoeken en vervangen + Find: Zoeken: + Replace With: Vervangen door: + Replace & Find Vervangen en zoeken + Replace All Alles vervangen + Match Case Hoofdlettergevoelig + Find Whole Word Heel woord zoeken + Search Backwards Achterwaarts zoeken + Check Hidden Layers Verborgen lagen controleren + Check Locked Layers Vergrendelde lagen controleren +@msg No matches found Geen overeenkomsten gevonden +@msg Matches replaced: {n} Vervangen overeenkomsten: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} geen overeenkomst van `find` bij bytes {_1}..{_2} van object {_3} Find Next Volgende zoeken Spelling Spelling Auto Spell Check Automatische spellingcontrole diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 08e96e6a35..6f91958d78 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -93,6 +93,19 @@ Paste without Formatting Wklej bez formatowania Clear Wyczyść Find and Replace… Znajdź i zamień… + Find and Replace Znajdź i zamień + Find: Znajdź: + Replace With: Zastąp przez: + Replace & Find Zastąp i znajdź + Replace All Zastąp wszystko + Match Case Uwzględnij wielkość liter + Find Whole Word Znajdź całe słowo + Search Backwards Szukaj wstecz + Check Hidden Layers Sprawdź ukryte warstwy + Check Locked Layers Sprawdź zablokowane warstwy +@msg No matches found Nie znaleziono dopasowań +@msg Matches replaced: {n} Zastąpione dopasowania: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} brak dopasowania `find` w bajtach {_1}..{_2} obiektu {_3} Find Next Znajdź następny Spelling Pisownia Auto Spell Check Automatyczne sprawdzanie pisowni diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 79c4d9dc8e..2e096d6485 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1140,6 +1140,19 @@ antiAlias Sharp Nítido Find Font… Localizar Fonte… Find Next Localizar Próximo Find and Replace… Localizar e Substituir… + Find and Replace Localizar e Substituir + Find: Localizar: + Replace With: Substituir por: + Replace & Find Substituir e Localizar + Replace All Substituir Tudo + Match Case Diferenciar Maiúsculas de Minúsculas + Find Whole Word Localizar Palavra Inteira + Search Backwards Pesquisar para Trás + Check Hidden Layers Verificar Camadas Ocultas + Check Locked Layers Verificar Camadas Bloqueadas +@msg No matches found Nenhuma correspondência encontrada +@msg Matches replaced: {n} Correspondências substituídas: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} nenhuma correspondência de `find` nos bytes {_1}..{_2} do objeto {_3} First Page Primeira Página First-line Left Indent Recuo Esquerdo da Primeira Linha Fisheye… Olho de Peixe… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9f608618e7..b88785cf7a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1249,6 +1249,19 @@ font-technology Variable Вариативные Fill: click for swatches, Shift-click for the color mixer Заливка: щёлкните для образцов, Shift+щелчок — для смесителя цветов Find Найти Find and Replace… Найти и заменить… + Find and Replace Найти и заменить + Find: Найти: + Replace With: Заменить на: + Replace & Find Заменить и найти + Replace All Заменить все + Match Case Учитывать регистр + Find Whole Word Найти слово целиком + Search Backwards Искать назад + Check Hidden Layers Проверять скрытые слои + Check Locked Layers Проверять заблокированные слои +@msg No matches found Совпадений не найдено +@msg Matches replaced: {n} Заменено совпадений: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} в байтах {_1}..{_2} объекта {_3} нет совпадения с `find` Find Font Найти шрифт Find Font… Найти шрифт… Find Next Найти далее diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6156ca23d5..b36244f510 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1215,6 +1215,19 @@ font-technology Variable Variabla Fill: click for swatches, Shift-click for the color mixer Fyllning: klicka för färgrutor, Shift-klicka för färgmixern Find Sök Find and Replace… Sök och ersätt… + Find and Replace Sök och ersätt + Find: Sök: + Replace With: Ersätt med: + Replace & Find Ersätt och sök + Replace All Ersätt alla + Match Case Matcha skiftläge + Find Whole Word Sök hela ord + Search Backwards Sök bakåt + Check Hidden Layers Kontrollera dolda lager + Check Locked Layers Kontrollera låsta lager +@msg No matches found Inga träffar hittades +@msg Matches replaced: {n} Ersatta träffar: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} ingen träff för `find` vid byte {_1}..{_2} i objekt {_3} Find Font Sök typsnitt Find Font… Sök typsnitt… Find Next Sök nästa diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7120d44707..964a66274a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1204,6 +1204,19 @@ font-technology Variable Değişken Fill: click for swatches, Shift-click for the color mixer Doldur: renk örnekleri için tıklayın, renk karıştırıcı için Shift tuşunu basılı tutarak tıklayın Find Bul Find and Replace… Bul ve Değiştir… + Find and Replace Bul ve Değiştir + Find: Bul: + Replace With: Şununla Değiştir: + Replace & Find Değiştir ve Bul + Replace All Tümünü Değiştir + Match Case Büyük/Küçük Harf Eşleştir + Find Whole Word Tam Sözcüğü Bul + Search Backwards Geriye Doğru Ara + Check Hidden Layers Gizli Katmanları Denetle + Check Locked Layers Kilitli Katmanları Denetle +@msg No matches found Eşleşme bulunamadı +@msg Matches replaced: {n} Değiştirilen eşleşmeler: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} {_3} nesnesinin {_1}..{_2} baytlarında `find` eşleşmesi yok Find Font Yazı Tipi Bul Find Font… Yazı Tipi Bul… Find Next Sonrakini Bul diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 84f296b0a6..d23d1f72ca 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1254,6 +1254,19 @@ font-technology Variable Варіативні Fill: click for swatches, Shift-click for the color mixer Заливка: клацніть для зразків, Shift+клацання — для змішувача кольорів Find Знайти Find and Replace… Знайти та замінити… + Find and Replace Знайти та замінити + Find: Знайти: + Replace With: Замінити на: + Replace & Find Замінити та знайти + Replace All Замінити все + Match Case Враховувати регістр + Find Whole Word Знайти слово цілком + Search Backwards Шукати назад + Check Hidden Layers Перевіряти приховані шари + Check Locked Layers Перевіряти заблоковані шари +@msg No matches found Збігів не знайдено +@msg Matches replaced: {n} Замінено збігів: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} у байтах {_1}..{_2} об’єкта {_3} немає збігу з `find` Find Font Знайти шрифт Find Font… Знайти шрифт… Find Next Знайти далі diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e8b9e5758f..5bebf649d9 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1470,6 +1470,19 @@ digits Malayalam Malayalam Posterization Áp phích hóa Find Tìm Find and Replace… Tìm và thay thế… + Find and Replace Tìm và thay thế + Find: Tìm: + Replace With: Thay thế bằng: + Replace & Find Thay thế và tìm + Replace All Thay thế tất cả + Match Case Phân biệt chữ hoa chữ thường + Find Whole Word Tìm toàn bộ từ + Search Backwards Tìm ngược + Check Hidden Layers Kiểm tra lớp ẩn + Check Locked Layers Kiểm tra lớp bị khóa +@msg No matches found Không tìm thấy kết quả khớp +@msg Matches replaced: {n} Số kết quả khớp đã thay thế: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} không có kết quả khớp với `find` tại byte {_1}..{_2} của đối tượng {_3} Find Font Tìm phông Find Font Files Tìm tệp phông chữ Find Fonts Tìm phông chữ diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 719968086f..eb4d47a4dd 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1192,6 +1192,19 @@ antiAlias Sharp 锐利 Fill: click for swatches, Shift-click for the color mixer 填色:单击开启色板,按住 Shift 单击开启混色器 Find 查找 Find and Replace… 查找和替换… + Find and Replace 查找和替换 + Find: 查找: + Replace With: 替换为: + Replace & Find 替换并查找 + Replace All 全部替换 + Match Case 区分大小写 + Find Whole Word 查找全字匹配 + Search Backwards 反向搜索 + Check Hidden Layers 检查隐藏图层 + Check Locked Layers 检查锁定图层 +@msg No matches found 未找到匹配项 +@msg Matches replaced: {n} 已替换的匹配项:{n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} 对象 {_3} 的字节 {_1}..{_2} 处没有 `find` 的匹配项 Find Font 查找字体 Find Font… 查找字体… Find Next 查找下一个 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 121a8b8c02..f054cbeda5 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1226,6 +1226,19 @@ font-technology Variable 可變 Fill: click for swatches, Shift-click for the color mixer 填色:按一下開啟色票,按住 Shift 按一下開啟混色器 Find 尋找 Find and Replace… 尋找與取代… + Find and Replace 尋找與取代 + Find: 尋找: + Replace With: 取代為: + Replace & Find 取代並尋找 + Replace All 全部取代 + Match Case 大小寫須相符 + Find Whole Word 尋找全字 + Search Backwards 反向搜尋 + Check Hidden Layers 檢查隱藏圖層 + Check Locked Layers 檢查鎖定圖層 +@msg No matches found 找不到相符項目 +@msg Matches replaced: {n} 已取代的相符項目:{n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} 物件 {_3} 的位元組 {_1}..{_2} 處沒有 `find` 的相符項目 Find Font 尋找字體 Find Font… 尋找字體… Find Next 尋找下一個 diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 953b5b58f4..ebf5707949 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -146,9 +146,10 @@ const NOT_INSERTED_MENUS: [&str; 4] = ["VectorCraft", "File", "Window", "Help"]; /// Commands whose menu items do more than run the command, which action playback does not do: /// Object › Image Trace › Make and Make and Expand trace off the UI thread with progress and Cancel -/// ([`crate::trace_runs::start`]), and Object › Pattern › Make and Edit Pattern open the Pattern -/// Options panel. -const MENU_ONLY_COMMANDS: [&str; 4] = ["imageTrace.make", "imageTrace.makeAndExpand", "object.pattern.make", "object.pattern.edit"]; +/// ([`crate::trace_runs::start`]), Object › Pattern › Make and Edit Pattern open the Pattern +/// Options panel, and Edit › Find Next goes on from the last Find and Replace search or opens its +/// dialog ([`crate::dialogs::find_replace::find_next`]). +const MENU_ONLY_COMMANDS: [&str; 5] = ["imageTrace.make", "imageTrace.makeAndExpand", "object.pattern.make", "object.pattern.edit", "edit.findNext"]; /// The View menu commands that the app runs itself, not the engine, and that can be steps of an /// action ([`plays_in_app`]): Outline, Pixel Preview, Trim View, Presentation Mode and Screen Mode, diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 3aab5e1e44..475d71ed07 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -298,6 +298,18 @@ fn open_view_dialog(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool { } return true; } + // Find Next with no text to find, as its menu item runs it: the next match of the last Find + // and Replace search, or the dialog when there has been none. + if id == crate::dialogs::find_replace::NEXT + && p.get("find").is_none_or(|f| f.as_str() == Some("")) + && p.as_object().is_none_or(|o| o.len() <= 1) + && app.session.active().is_some() + { + if let Err(e) = crate::dialogs::find_replace::find_next(app) { + app.status(e); + } + return true; + } // Edit Views…: the saved views in a list, to rename or delete. if id == "view.saved.edit" && p.as_object().is_none_or(|o| o.is_empty()) { if let Err(e) = crate::dialogs::edit_views::open(app) { diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 7b7f7a6b21..f2a0b789d1 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -705,6 +705,10 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option { let cmd = s("command").unwrap_or_default(); let mut fields = p.get("params").and_then(Value::as_object).cloned().unwrap_or_default(); + // Find and Replace has a dialog of its own, which stays open from match to match. + if cmd == crate::dialogs::find_replace::COMMAND { + return Some(crate::dialogs::find_replace::open(app, &fields)); + } fields.insert("__command".into(), json!(cmd)); fields.insert("__label".into(), json!(s("label").unwrap_or(cmd.clone()))); app.ui.dialog = Some(crate::state::Dialog { kind: "command".into(), fields }); diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 4b86b4152d..538ffd303b 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -95,7 +95,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Paste without Formatting", "edit.pasteWithoutFormatting"), c("Clear", "edit.clear"), Sep, - cp("Find and Replace…", "edit.findReplace", json!({"find": "", "replace": "", "matchCase": false, "wholeWord": false})), + cp("Find and Replace…", "edit.findReplace", crate::dialogs::find_replace::menu_params()), cp("Find Next", "edit.findNext", json!({"find": ""})), sub("Spelling", vec![c("Auto Spell Check", "edit.autoSpellCheck"), todos("Check Spelling…", "Cmd+I")]), // Edit › Edit Custom Dictionary…, beside Spelling, on the public Check and correct diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 52c8c2e7bf..641268a9ab 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -802,7 +802,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{effect: id, index?: int (edit that applied effect in place, prefilled; OK runs effect.setParams), item?: appearance item index|null (the fill/stroke whose effects, null the object's; default: the Appearance panel's active item), aligned?: bool (index and item are rows of the first selected object's stack, which OK edits in each object where it has them, as effect.setParams does)} open the effect's dialog with live preview; without `index`, an effect already in that list first opens `effectExists` (confirm edits it, discard adds another) → {pending: \"effectExists\"}", ), - ("ui.paramDialog", "Command Dialog", "", "{command, label?, params} open a parameter dialog for any command"), + ( + "ui.paramDialog", + "Command Dialog", + "", + "{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place, and Edit › Find Next goes on from it in the same document while the dialog is closed", + ), ( "ui.recolorDialog", "Recolor Artwork…", diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index ded320a5aa..796e2016db 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -387,7 +387,7 @@ mod tests { ("object.path.cleanUp", "command"), ("object.mesh.create", "command"), ("type.smartPunctuation", "command"), - ("edit.findReplace", "command"), + ("edit.findReplace", crate::dialogs::find_replace::KIND), ("object.path.smooth", crate::dialogs::smooth_slider::KIND), ]; for (id, kind) in expected { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 80a87b4563..bfaabf7db6 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -582,6 +582,11 @@ pub struct UiState { /// The Replace Font request behind the status bar's warning ([`ReplaceFontWarning`]). Not saved. #[serde(skip)] pub replace_font_warning: Option, + /// The last Find and Replace search ([`crate::dialogs::find_replace`]): the dialog's Find and + /// Replace With text, its options and the place the search reached, which Edit › Find Next + /// goes on from while the dialog is closed. Not saved. + #[serde(skip)] + pub last_find: Option, /// The notes of the last open that gave any, or of the last save or export, with the status /// text that names the first of them: hovering that text lists them when there are several. /// Not saved. @@ -1171,6 +1176,7 @@ impl Default for UiState { status: String::new(), status_sets: 0, replace_font_warning: None, + last_find: None, status_notes: None, palette_open: false, palette_query: String::new(), diff --git a/docs/mcp.md b/docs/mcp.md index 2e43c14d0e..7350d2f4c2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8688,6 +8688,52 @@ for it (each a `text.editRange {id, start, end, insert}` item labelled with its All (`text.spelling.ignoreAll {word}`) and Add to Dictionary (`text.spelling.addWord {word}`); the context menu's entries list them with their params. A right-click on type also has Spelling › Auto Spell Check (`edit.autoSpellCheck`). +## Find and Replace + +`edit.findNext {find, matchCase?, wholeWord?, backwards?, hiddenLayers?, lockedLayers?, from?}` finds the next match +of `find` and selects its type object. The result is `{id, start, end, index, count, selected}`: `start` and `end` +are byte offsets in the type object's text, the ones `text.editRange` takes, `index` is the match's place among all +the matches (from 1) and `count` is how many there are. With no match it is `{id: null, count: 0}`. Nothing is +recorded for undo. + +- The search reaches visible, unlocked type on visible, unlocked layers, off locked artboards. `hiddenLayers` adds the + type of hidden layers and sublayers and `lockedLayers` that of locked ones, as Check Hidden Layers and Check Locked + Layers do in [Find and replace text](https://helpx.adobe.com/pdf/illustrator_reference.pdf). A hidden or locked + object or group keeps its type out. +- `backwards` is Search Backwards on that page: the search goes from the bottom of the stacking order to the top. + Without it, the search goes from the top down. +- These rules are VectorCraft's own. Inside a type object the matches come in reading order, or from the last with + `backwards`. `from: {id, start, end}`, a match the command returned or the range `edit.replaceMatch` returned, is + where the search goes on from; past the last match it starts again at the first. Without `from` it goes on after the + first selected type object, and with no type selected it starts at the first match. A match on a hidden or locked + layer comes back with `selected: false` and the selection stays as it is. A match stays inside one style run. + +`edit.replaceMatch {find, replace?, matchCase?, wholeWord?, id, start, end}` replaces that one match with `replace` +as one undo step and returns `{id, start, end, replaced}`, with `start` and `end` the replacement's bytes. Bytes that +are no match of `find` are refused. A match that already reads as `replace` is left as it is, with no undo step and +`replaced: false`. `edit.findReplace {find, replace?, matchCase?, wholeWord?, hiddenLayers?, lockedLayers?, ids?}` +replaces every match in the type the search reaches (or in `ids`) as one undo step and returns `{count, replaced}`, +with `count` the matches and `replaced` those that did not already read as `replace`; when +nothing changes, no undo step is recorded. An empty `find` is an error in all three. + +```json +{"name":"run_command","arguments":{"command":"edit.findNext","params":{"find":"colour","wholeWord":true}}} +{"name":"run_command","arguments":{"command":"edit.replaceMatch","params":{"find":"colour","replace":"color","wholeWord":true,"id":12,"start":4,"end":10}}} +{"name":"run_command","arguments":{"command":"edit.findNext","params":{"find":"colour","wholeWord":true,"from":{"id":12,"start":4,"end":9}}}} +``` + +In the app, Edit › Find and Replace… opens a dialog that stays open (kind `findReplace`), with Find and Replace With +fields, Match Case, Find Whole Word, Search Backwards, Check Hidden Layers and Check Locked Layers, and Find, Replace, +Replace & Find, Replace All and Done. Its fields are `find`, `replace`, `matchCase`, `wholeWord`, `backwards`, +`hiddenLayers`, `lockedLayers` and `action`; `ui.dialog.confirm` runs the `action`: `find` (the default), `replace`, +`replaceFind`, `replaceAll` or `done`, which closes the dialog. The dialog shows the match found in its line of text +with its place among the matches. Replace and Replace & Find change a match that Find reached with the Find text and +the options as they are now, and find one otherwise. Enter runs Find. Edit › Find Next goes on from the dialog's last +search while the dialog is closed, and opens the dialog when there has been none. A place the search reached in one +document is not used in another, nor once the Find text or an option that decides a match changes: the search then +starts again as it does without `from`. `ui.paramDialog` opens +the dialog on the last search, with the fields its `params` give in its place. + ## Justification options diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8f5043993a..315f02eee1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1659,6 +1659,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Layers panel's New Layer (on top), Select Art and Target (Shift-click), Move Rows (the copy), Template, Paste Remembers Layers and Release to Layers (Build) refuse a value other than true, false or null, such as "true", and leave the document, the selection, the highlighted rows and the undo history as they were; New Sublayer refuses such a `top` too. Change Case, Smart Punctuation, Find and Replace, Convert To Area Type, Convert To Point Type, Type on a Path Options, the Type on a Path effects and Fill with Placeholder Text record no undo step when they change nothing. Find and Replace, Find Next, Change Case, Smart Punctuation, Insert Character and Type on a Path Options refuse a text option other than text or null, such as a replacement of 5, and a switch other than true, false or null, such as "true". Smart Punctuation also refuses a scope other than selection or document, Type on a Path Options a spacing given as text, and Find and Replace `ids` that are not a list of existing object ids. Each leaves the text, the selection and the undo history as they were. + Edit › Find and Replace… opens a dialog that stays open, with Find, Replace, Replace & Find, Replace All and Done, and Match Case, Find Whole Word, Search Backwards, Check Hidden Layers and Check Locked Layers. Find Next (`edit.findNext`) returns each match with its bytes, from the top of the stacking order down or, with Search Backwards, from the bottom up; `edit.replaceMatch` replaces one match as one undo step; Edit › Find Next goes on from the dialog's last search. The commands that take `keepModel` (fills and strokes, Appearance rows, Live Paint, Shape Builder fills, gradient stops and freeform points, gradient mesh points, type colors, the Symbol Stainer and the swatch commands) refuse a `keepModel` other than true, false or null, such as "true". Toggle Fill/Stroke Focus (`fill`), Invert, Complement, Apply Last Color and Apply Last Gradient (`stroke`), `paint.setFill` and `paint.setStroke` (`focus`, `none`), and `appearance.setItem`, `livePaint.fill`, `livePaint.strokeEdge`, a `shapeBuilder.merge` `fill`, `swatch.new` and `swatch.edit`'s `paint` (`none`) refuse such a value too. Each leaves the document, its undo history and the defaults for new art as they were. The shape tools' commands (Rectangle, Polygon, Star, Flare, Spiral, Arc, Rectangular Grid and Polar Grid), `path.create` (with `anchors` or `d`), the type commands (new type, type in a path, character formats, the byte range a text command takes, Touch Type, font size steps, `text.getRange`, Optical Margin Alignment, System Layout, Fractional Widths, Ruby and Area Type Options), the symbol commands (Place, Delete, the Symbol Sprayer and the symbolism tools), the swatch commands, the Appearance panel's commands, the gradient and freeform gradient commands, Shape Builder, Live Paint and Image Trace refuse an option other than true, false or null and a number given as text, such as "true" or "40", and leave the document and its undo history as they were. - **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font, and Print and Print Preview warn about the type that prints in it; `textAs: outlines` keeps the PDF's embedded glyphs). Two installed versions of one family and style (a font library keeping an old file beside a new one) both load, the first staying the one the family and style resolve to; PDF and `.ai` import tries each version when the glyphs differ, and type set in a version other than that one names it (`CharStyle::font_version`), which layout, the substituted-glyph highlight, Find Font, Package and Document Info follow. Fonts outside the font folders are listed too: those font services such as Adobe Fonts load on Windows, through DirectWrite and, for those only GDI lists, through GDI (#1258), and those apps and font managers register with CoreText on macOS (#579). When a document opens with fonts that aren't available, fonts used only in symbols included, a Missing Fonts dialog lists them after the linked-file questions, with Find Fonts (Type › Find Font on them) and Close. Its Find in Folder… (in Find Font too) searches a folder on several threads, reads only what the font scan reads of font files and skips app packages, the Program Files and ProgramData folders, the system's folders and the app data folders in a home folder; Add Fonts copies the font files the user chooses, suitcase fonts with their resource fork, into VectorCraft's own Fonts folder, which the desktop app and `vectorcraft-cli` read (`text.missingFonts`, `text.findFontFiles`, `text.addFontFiles`). The font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux). From 21edd7f6d85708b67c333eddcb5606416b35e215 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:42:57 -0800 Subject: [PATCH 2/9] i18n: Danish rows for Find and Replace messages --- crates/ui-egui/src/i18n/da.tsv | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 19171ddcc0..e0b922564b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -697,6 +697,9 @@ Search Backwards Søg baglæns Check Hidden Layers Kontrollér skjulte lag Check Locked Layers Kontrollér låste lag +@msg No matches found Ingen forekomster fundet +@msg Matches replaced: {n} Erstattede forekomster: {n} +@msg no match of `find` at bytes {_1}..{_2} of object {_3} ingen forekomst af `find` ved byte {_1}..{_2} i objekt {_3} Find Next Find næste Spelling Stavekontrol Auto Spell Check Automatisk stavekontrol From 322cc6049f0d83ca2aad213c1d492dd81ddb196e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 13:51:14 -0800 Subject: [PATCH 3/9] i18n: French Find and Replace match count avoids a colon without a no-break space --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 96d05a0ab9..d24a320e5e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1285,7 +1285,7 @@ font-technology Variable Variables Check Hidden Layers Vérifier les calques masqués Check Locked Layers Vérifier les calques verrouillés @msg No matches found Aucune occurrence trouvée -@msg Matches replaced: {n} Occurrences remplacées : {n} +@msg Matches replaced: {n} Occurrences remplacées ({n}) @msg no match of `find` at bytes {_1}..{_2} of object {_3} aucune occurrence de `find` aux octets {_1}..{_2} de l’objet {_3} Find Font Rechercher une police Find Font… Rechercher une police… From d0de7581559f64e0c6a93c7dcdd037c3a64fb33e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 16:30:39 -0800 Subject: [PATCH 4/9] Rerun CI From 1f704f2dc37a89613036763ba18f1df8fe69ad72 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 21:29:50 -0800 Subject: [PATCH 5/9] Palette: Find Next is listed, since a pick runs it as its menu item does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A pick of Edit › Find Next goes on from the last Find and Replace search or opens the dialog, so the palette lists it among the commands a pick still runs. --- crates/ui-egui/src/palette.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index b4e3190ee7..1af89b882a 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -40,8 +40,9 @@ const WRAPPED: &[(&str, &str)] = &[ /// selection's gradient matches, Pixel Snapping Options… /// opens its dialog, the three Asset Export commands open the Asset Export panel (#4864), New /// Symbol makes a symbol of the selection, Gradient Vector gives the selection the default -/// gradient, Define Perspective Grid makes the document's grid, and Select Slice deselects the -/// slices. +/// gradient, Define Perspective Grid makes the document's grid, Select Slice deselects the +/// slices, and Find Next goes on from the last Find and Replace search or opens its dialog, as +/// its menu item does. const PICK_RUNS: &[&str] = &[ "script.stop", "script.console.clear", @@ -65,6 +66,7 @@ const PICK_RUNS: &[&str] = &[ "paint.setGradientGeom", "perspective.grid.set", "object.slice.select", + "edit.findNext", ]; /// The menu path of a panel's result: a pick runs Show Panel (`window.panel`) for the panel. From d4b1ff8f603fbdde4e33ff2bd6c456de777bfb83 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 21:53:34 -0800 Subject: [PATCH 6/9] Find and Replace: a dialog field of the wrong type is an error ui.paramDialog for edit.findReplace used to drop a field of the wrong type, such as a number for find, and open on the last search. It now returns an error and leaves the dialog closed. A null field still gives none, as the menu item's does. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/find_replace.rs | 11 +++++++++-- .../ui-egui/src/dialogs/find_replace/tests.rs | 19 +++++++++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 3 ++- 5 files changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 05116b02ec..25fb02285e 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -847,7 +847,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place, and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs index a43e737e18..458b7a2184 100644 --- a/crates/ui-egui/src/dialogs/find_replace.rs +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -79,8 +79,8 @@ fn active_uid(app: &VectorcraftApp) -> Option { } /// Open Find and Replace on the last search when there has been one, with the fields that -/// `params` gives in its place. A value of another type than the field's, such as the menu item's -/// null `find` ([`menu_params`]), gives none. +/// `params` gives in its place. A null value, such as the menu item's `find` ([`menu_params`]), +/// gives none. A field given a value of another type is an error, and the dialog does not open. pub fn open(app: &mut VectorcraftApp, params: &Map) -> Result { let mut fields = Map::new(); fields.insert("find".into(), json!("")); @@ -88,6 +88,13 @@ pub fn open(app: &mut VectorcraftApp, params: &Map) -> Result return Err(format!("`{k}` must be a string")), + Some(Value::Bool(_)) if !v.is_boolean() => return Err(format!("`{k}` must be true or false")), + _ => {} + } + } let last = app.ui.last_find.as_ref().and_then(Value::as_object).cloned().unwrap_or_default(); for (k, v) in last.iter().chain(params) { // Only the dialog's own fields, each of its own type. diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index a55e1c0085..e0e6031668 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -131,6 +131,25 @@ fn the_edit_menu_opens_the_find_and_replace_dialog() { } } +/// A field given a value of another type than its own is an error and the dialog does not open; a +/// null value gives no field. +#[test] +fn the_dialog_rejects_a_field_of_the_wrong_type() { + let (mut app, _) = app_with(&["cat"]); + let open = |app: &mut VectorcraftApp, params: Value| app.run("ui.paramDialog", json!({"command": super::COMMAND, "params": params})); + for (params, want) in [ + (json!({"find": 17}), "`find` must be a string"), + (json!({"replace": true}), "`replace` must be a string"), + (json!({"matchCase": "yes"}), "`matchCase` must be true or false"), + (json!({"backwards": 1}), "`backwards` must be true or false"), + ] { + assert_eq!(open(&mut app, params.clone()).unwrap_err(), want, "{params}"); + assert!(app.ui.dialog.is_none(), "{params}"); + } + open(&mut app, json!({"find": null, "replace": "dog", "wholeWord": true})).unwrap(); + assert_eq!((field(&app, "find"), field(&app, "replace"), field(&app, "wholeWord")), (json!(""), json!("dog"), json!(true))); +} + /// The dialog stays open from match to match: Find goes to the next match and selects its /// object, Replace changes that match, Replace & Find changes it and goes on, Replace All changes /// the rest, and Done closes. Each Replace is one undo step, and so is Replace All; finding and a diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 013f519f0c..b1db0a7f0e 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -848,7 +848,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place, and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", diff --git a/docs/mcp.md b/docs/mcp.md index e367f19671..1d077aa478 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9996,7 +9996,8 @@ the options as they are now, and find one otherwise. Enter runs Find. Edit › F search while the dialog is closed, and opens the dialog when there has been none. A place the search reached in one document is not used in another, nor once the Find text or an option that decides a match changes: the search then starts again as it does without `from`. `ui.paramDialog` opens -the dialog on the last search, with the fields its `params` give in its place. +the dialog on the last search, with the fields its `params` give in its place. A null field gives none, and a field of +the wrong type is an error that leaves the dialog closed. ## Justification options From 2275ca2fe00c5ec2a50804fa873a4fabb1ddfe7d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 22:36:13 -0800 Subject: [PATCH 7/9] Find and Replace: confirming with a field of the wrong type runs no action ui.dialog.confirm used to read a replace that is not a string as empty text, so Replace All could delete every match, and a switch that is not true or false as off. It now returns the error, which shows under the match found, and runs nothing; the match stays for Replace once the field is set right. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/find_replace.rs | 36 ++++++++++++++----- .../ui-egui/src/dialogs/find_replace/tests.rs | 30 ++++++++++++++-- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 3 +- 5 files changed, 58 insertions(+), 15 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 25fb02285e..43ead3f6c2 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -847,7 +847,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs index 458b7a2184..523586d1a9 100644 --- a/crates/ui-egui/src/dialogs/find_replace.rs +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -88,13 +88,7 @@ pub fn open(app: &mut VectorcraftApp, params: &Map) -> Result return Err(format!("`{k}` must be a string")), - Some(Value::Bool(_)) if !v.is_boolean() => return Err(format!("`{k}` must be true or false")), - _ => {} - } - } + check_types(params, true)?; let last = app.ui.last_find.as_ref().and_then(Value::as_object).cloned().unwrap_or_default(); for (k, v) in last.iter().chain(params) { // Only the dialog's own fields, each of its own type. @@ -115,6 +109,21 @@ pub fn open(app: &mut VectorcraftApp, params: &Map) -> Result, null_gives_none: bool) -> Result<(), String> { + for (k, v) in fields.iter().filter(|(_, v)| !(null_gives_none && v.is_null())) { + if matches!(k.as_str(), "find" | "replace") && !v.is_string() { + return Err(format!("`{k}` must be a string")); + } + if (k == "backwards" || SWITCHES.contains(&k.as_str())) && !v.is_boolean() { + return Err(format!("`{k}` must be true or false")); + } + } + Ok(()) +} + /// Edit › Find Next with no text to find: the next match of the last search, from the place it /// reached, with the options the dialog had. With no search yet, it opens the dialog. pub fn find_next(app: &mut VectorcraftApp) -> Result { @@ -249,10 +258,17 @@ fn replace_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result Result { let mut d = d.clone(); let action = d.fields.insert("action".into(), json!("find")).and_then(|a| a.as_str().map(str::to_string)).unwrap_or_default(); + if let Err(e) = check_types(&d.fields, false) { + d.fields.insert(NOTE.into(), json!(e)); + app.ui.dialog = Some(d); + return Err(e); + } let r = match action.as_str() { "done" => { remember(app, &d); @@ -345,7 +361,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc ui.colored_label(t.text_strong, egui::RichText::new(hit).strong().underline()); widgets::dim_name(ui, &after); }); - } else if let Some(note) = d.fields.get(NOTE).and_then(Value::as_str) { + } + // Find and Replace remove the note, so it shows under a match only when an action was refused. + if let Some(note) = d.fields.get(NOTE).and_then(Value::as_str) { widgets::dim_name(ui, &crate::i18n::message(crate::i18n::current(), note)); } // Enter finds, as the Find button does. diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index e0e6031668..0e38820877 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -132,10 +132,34 @@ fn the_edit_menu_opens_the_find_and_replace_dialog() { } /// A field given a value of another type than its own is an error and the dialog does not open; a -/// null value gives no field. +/// null value gives no field. A field set to such a value once the dialog is open runs no action: +/// the error is the note, shown under the match found, and the text, the match and the last search +/// stay as they were. #[test] fn the_dialog_rejects_a_field_of_the_wrong_type() { - let (mut app, _) = app_with(&["cat"]); + let (mut app, ids) = app_with(&["cat"]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + crate::dialogs::confirm(&mut app).unwrap(); + let last = app.ui.last_find.clone(); + for (k, v, want) in [ + ("replace", json!(5), "`replace` must be a string"), + ("replace", Value::Null, "`replace` must be a string"), + ("matchCase", json!("yes"), "`matchCase` must be true or false"), + ] { + set(&mut app, k, v.clone()); + set(&mut app, "action", json!("replaceAll")); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap_err(), want, "{k}: {v}"); + assert_eq!((plain(&app, ids[0]), field(&app, "__note"), app.ui.last_find.clone()), ("cat".to_string(), json!(want), last.clone())); + assert_eq!(matched(&app), Some((ids[0], 0, 3)), "Replace still changes the match found"); + let ctx = context(); + frame(&mut app, &ctx, vec![]); + let texts: Vec = frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(texts.iter().any(|t| t == want) && texts.iter().any(|t| t == "cat"), "the note shows under the match: {texts:?}"); + set(&mut app, k, if k == "replace" { json!("dog") } else { json!(false) }); + } + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); let open = |app: &mut VectorcraftApp, params: Value| app.run("ui.paramDialog", json!({"command": super::COMMAND, "params": params})); for (params, want) in [ (json!({"find": 17}), "`find` must be a string"), @@ -147,7 +171,7 @@ fn the_dialog_rejects_a_field_of_the_wrong_type() { assert!(app.ui.dialog.is_none(), "{params}"); } open(&mut app, json!({"find": null, "replace": "dog", "wholeWord": true})).unwrap(); - assert_eq!((field(&app, "find"), field(&app, "replace"), field(&app, "wholeWord")), (json!(""), json!("dog"), json!(true))); + assert_eq!((field(&app, "find"), field(&app, "replace"), field(&app, "wholeWord")), (json!("cat"), json!("dog"), json!(true))); } /// The dialog stays open from match to match: Find goes to the next match and selects its diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index b1db0a7f0e..4408654daa 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -848,7 +848,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", diff --git a/docs/mcp.md b/docs/mcp.md index 1d077aa478..accd19856e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9997,7 +9997,8 @@ search while the dialog is closed, and opens the dialog when there has been none document is not used in another, nor once the Find text or an option that decides a match changes: the search then starts again as it does without `from`. `ui.paramDialog` opens the dialog on the last search, with the fields its `params` give in its place. A null field gives none, and a field of -the wrong type is an error that leaves the dialog closed. +the wrong type is an error that leaves the dialog closed. Once it is open, `ui.dialog.confirm` with a field of the +wrong type runs no action and returns the error. ## Justification options From d27a9e94667721c895c2605758a986c7b4c2616a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 01:12:58 -0800 Subject: [PATCH 8/9] Find and Replace: an action that is not a string runs no action Confirming the dialog with a number, null or list as its action used to run Find, which moved the match found, the selection and the last search. It is now an error, shown as the note, like a field of the wrong type. --- crates/ui-egui/src/dialogs/find_replace.rs | 13 ++++++++---- .../ui-egui/src/dialogs/find_replace/tests.rs | 21 +++++++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs index 523586d1a9..f56d07c722 100644 --- a/crates/ui-egui/src/dialogs/find_replace.rs +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -260,16 +260,21 @@ fn replace_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result Result { let mut d = d.clone(); - let action = d.fields.insert("action".into(), json!("find")).and_then(|a| a.as_str().map(str::to_string)).unwrap_or_default(); - if let Err(e) = check_types(&d.fields, false) { + let action = d.fields.insert("action".into(), json!("find")); + let checked = match &action { + Some(a) if !a.is_string() => Err("`action` must be a string".to_string()), + _ => check_types(&d.fields, false), + }; + if let Err(e) = checked { d.fields.insert(NOTE.into(), json!(e)); app.ui.dialog = Some(d); return Err(e); } - let r = match action.as_str() { + let r = match action.as_ref().and_then(Value::as_str).unwrap_or_default() { "done" => { remember(app, &d); app.ui.dialog = None; diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index 0e38820877..59dbe4937b 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -174,6 +174,27 @@ fn the_dialog_rejects_a_field_of_the_wrong_type() { assert_eq!((field(&app, "find"), field(&app, "replace"), field(&app, "wholeWord")), (json!("cat"), json!("dog"), json!(true))); } +/// An `action` that is not a string runs no action, Find included: the error is the note, and the +/// match found, the selection and the last search stay as they were. +#[test] +fn an_action_of_the_wrong_type_runs_no_action() { + let (mut app, _) = app_with(&["cat", "cat"]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + crate::dialogs::confirm(&mut app).unwrap(); + let (at, sel, last) = (matched(&app), selected(&app), app.ui.last_find.clone()); + assert!(at.is_some()); + for v in [json!(5), Value::Null, json!(["find"])] { + set(&mut app, "action", v.clone()); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap_err(), "`action` must be a string", "{v}"); + assert_eq!((matched(&app), selected(&app), app.ui.last_find.clone()), (at, sel.clone(), last.clone()), "{v}"); + assert_eq!(field(&app, "__note"), json!("`action` must be a string"), "{v}"); + } + set(&mut app, "action", json!("find")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_ne!(matched(&app), at, "a string action still runs"); +} + /// The dialog stays open from match to match: Find goes to the next match and selects its /// object, Replace changes that match, Replace & Find changes it and goes on, Replace All changes /// the rest, and Done closes. Each Replace is one undo step, and so is Replace All; finding and a From efc36481b174be967bbbf3d94be5a6c7e5e12c5a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 01:46:57 -0800 Subject: [PATCH 9/9] Find and Replace: Find with other Find text starts at the first match With no place to go on from, the dialog left out edit.findNext's from, so the search went on after the selected type object and passed over its matches: after Find selected a type object, changing the Find text skipped the matches in it. edit.findNext now starts at the first match for a null from, and the dialog sends one. --- crates/engine/src/cmd/typemenu.rs | 12 +++++++----- crates/engine/src/tests/menucmds.rs | 4 ++++ crates/ui-egui/src/dialogs/find_replace.rs | 5 ++--- .../ui-egui/src/dialogs/find_replace/tests.rs | 17 +++++++++++++++++ docs/mcp.md | 6 ++++-- 5 files changed, 34 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index 85bc20926a..f9c6471812 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Find Next", ["Edit"], None, - "{find, matchCase?: false, wholeWord?: false, backwards?: false, hiddenLayers?: false, lockedLayers?: false, from?: {id, start, end} (a match this command returned, or the range edit.replaceMatch returned)} find the next match of `find` in the type edit.findReplace reaches and select its type object → {id, start, end (the match's bytes in the object's plain text), index (its place among all the matches, from 1), count, selected} or {id: null, count: 0}. The search visits type objects from the top of the stacking order down and each object's matches in reading order; backwards visits the objects from the bottom up and each object's matches from the last. It goes on after `from` and, past the last match, starts again at the first. Without `from` it goes on after the first selected type object, and with no type selected it starts at the first match. A match on a hidden or locked layer is returned with selected false and the selection stays as it is. Nothing is recorded for undo.", + "{find, matchCase?: false, wholeWord?: false, backwards?: false, hiddenLayers?: false, lockedLayers?: false, from?: {id, start, end} (a match this command returned, or the range edit.replaceMatch returned)} find the next match of `find` in the type edit.findReplace reaches and select its type object → {id, start, end (the match's bytes in the object's plain text), index (its place among all the matches, from 1), count, selected} or {id: null, count: 0}. The search visits type objects from the top of the stacking order down and each object's matches in reading order; backwards visits the objects from the bottom up and each object's matches from the last. It goes on after `from` and, past the last match, starts again at the first. Without `from` it goes on after the first selected type object, and with no type selected, or with a null `from`, it starts at the first match. A match on a hidden or locked layer is returned with selected false and the selection stays as it is. Nothing is recorded for undo.", has_doc, find_next ), @@ -1856,10 +1856,12 @@ fn find_next(s: &mut Session, p: &Value) -> Result { let q = Query::of(p, C)?; let backwards = switch_or(p, "backwards", false, C)?; let (hidden, locked) = (switch_or(p, "hiddenLayers", false, C)?, switch_or(p, "lockedLayers", false, C)?); - // A `from` that is no object gives no `id`, and is refused as one without it. + // A `from` that is no object gives no `id`, and is refused as one without it. A null `from` + // starts at the first match, whatever is selected. let from = match p.get("from") { - None | Some(Value::Null) => None, - Some(v) => Some(Match::of(v, C)?), + None => None, + Some(Value::Null) => Some(None), + Some(v) => Some(Some(Match::of(v, C)?)), }; let st = s.doc()?; // The objects in the order the search visits them: from the top of the stacking order down, @@ -1885,7 +1887,7 @@ fn find_next(s: &mut Session, p: &Value) -> Result { // The search goes on from `from`, or from the whole of the first selected type object it // visits, so that the same call again reaches the next object. From anywhere else it starts // at the first match. - let from = from.or_else(|| { + let from = from.unwrap_or_else(|| { st.selection.objects.iter().filter(|id| order.contains(id)).find_map(|id| match &st.doc.node(*id)?.kind { NodeKind::Text(t) => Some(Match { id: *id, start: 0, end: t.runs.iter().map(|r| r.text.len()).sum() }), _ => None, diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index dbbf9e803d..9c03205ee7 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -2476,6 +2476,10 @@ fn find_next_steps_through_the_matches_in_both_directions() { // A `from` in an object the search does not visit starts at the first match. let r = s.execute("edit.findNext", &json!({"find": "cat", "from": {"id": 999_999, "start": 0, "end": 0}})).unwrap(); assert_eq!(found(&r), (top.0, 2, 5, 1, 3)); + // So does a null `from`, with a type object selected. + sel(&mut s, &[top]); + let r = s.execute("edit.findNext", &json!({"find": "cat", "from": null})).unwrap(); + assert_eq!(found(&r), (top.0, 2, 5, 1, 3)); // Nothing found: no match, and the selection stays. let r = s.execute("edit.findNext", &json!({"find": "zebra"})).unwrap(); assert_eq!((r, selected(&s)), (json!({"id": null, "count": 0}), vec![top])); diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs index f56d07c722..8e229980e6 100644 --- a/crates/ui-egui/src/dialogs/find_replace.rs +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -204,9 +204,8 @@ fn remember(app: &mut VectorcraftApp, d: &Dialog) { fn find(app: &mut VectorcraftApp, d: &mut Dialog) -> Result { let mut p = query(d); p["backwards"] = json!(d.bool("backwards")); - if let Some(at) = place(app, d) { - p["from"] = at.clone(); - } + // With no place, the search starts at the first match, not after the selected type object. + p["from"] = place(app, d).cloned().unwrap_or(Value::Null); d.fields.remove(FOUND); d.fields.remove(NOTE); let r = app.run(NEXT, p)?; diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index 59dbe4937b..1f2bb756ab 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -195,6 +195,23 @@ fn an_action_of_the_wrong_type_runs_no_action() { assert_ne!(matched(&app), at, "a string action still runs"); } +/// Find with other Find text starts again at the first match, the matches in the type object the +/// last Find selected included. +#[test] +fn find_with_other_text_starts_at_the_first_match() { + let (mut app, ids) = app_with(&["dog", "cat dog"]); + let (bottom, top) = (ids[0], ids[1]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((matched(&app), selected(&app)), (Some((top, 0, 3)), vec![top])); + set(&mut app, "find", json!("dog")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((matched(&app), selected(&app)), (Some((top, 4, 7)), vec![top])); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((bottom, 0, 3))); +} + /// The dialog stays open from match to match: Find goes to the next match and selects its /// object, Replace changes that match, Replace & Find changes it and goes on, Replace All changes /// the rest, and Done closes. Each Replace is one undo step, and so is Replace All; finding and a diff --git a/docs/mcp.md b/docs/mcp.md index accd19856e..1b0bcf1ef0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9969,8 +9969,10 @@ recorded for undo. - These rules are VectorCraft's own. Inside a type object the matches come in reading order, or from the last with `backwards`. `from: {id, start, end}`, a match the command returned or the range `edit.replaceMatch` returned, is where the search goes on from; past the last match it starts again at the first. Without `from` it goes on after the - first selected type object, and with no type selected it starts at the first match. A match on a hidden or locked - layer comes back with `selected: false` and the selection stays as it is. A match stays inside one style run. + first selected type object, and with no type selected, or with `from: null`, it starts at the first match. The Find + and Replace dialog sends `from: null` when it has no place to go on from, as when its Find text or a switch changed + since its last match. A match on a hidden or locked layer comes back with `selected: false` and the selection stays + as it is. A match stays inside one style run. `edit.replaceMatch {find, replace?, matchCase?, wholeWord?, id, start, end}` replaces that one match with `replace` as one undo step and returns `{id, start, end, replaced}`, with `start` and `end` the replacement's bytes. Bytes that