Merge pull request #14896 from jayzed80/fix/find-replace-change-without-match-14669

Find and Replace Text: Change without a current match does nothing (#14669)
This commit is contained in:
David Mann authored and GitHub committed 2026-11-15 15:49:44 +01:00
commit 21a46bbf32
3 files changed
+146 -7

No files matched your search

+20 -2
View File
@@ -53,14 +53,28 @@ pub struct CustomShape {
pub path: Path,
}
/// Remembered Find and Replace Text match (or collapsed cursor after a replacement) and the
/// search query it belongs to.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FindCursor {
pub layer: LayerId,
pub start: usize,
pub end: usize,
pub find: String,
pub case_sensitive: bool,
pub whole_word: bool,
pub forward: bool,
pub all_layers: bool,
}
/// Edit-menu state kept by the session.
#[derive(Clone, Debug, Default)]
pub struct EditState {
pub fade: Option<FadeSource>,
/// Custom shape library (the vector tools read it).
pub custom_shapes: Vec<CustomShape>,
/// Find and Replace Text position: (layer, byte offset after the current match).
pub find_cursor: Option<(LayerId, usize, usize)>,
/// Find and Replace Text position and the query it belongs to.
pub find_cursor: Option<FindCursor>,
}
/// Commands whose result Edit › Fade can blend back against the previous state.
@@ -457,3 +471,7 @@ mod fade_visibility_tests;
#[cfg(test)]
#[path = "edit_menu_cmds/caf_new_layer_name_tests.rs"]
mod caf_new_layer_name_tests;
#[cfg(test)]
#[path = "edit_menu_cmds/find_replace_change_tests.rs"]
mod find_replace_change_tests;
@@ -1,4 +1,4 @@
use super::{Document, EngineError, LayerContent, LayerId, Result, Session, Value, bad, bool_or, json, layer_param, str_or};
use super::{Document, EngineError, FindCursor, LayerContent, LayerId, Result, Session, Value, bad, bool_or, json, layer_param, str_or};
// ------------------------------------------------------------------ Find and Replace Text
@@ -78,6 +78,7 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
layers.iter().filter_map(|id| Some((*id, find_matches(&text_of(&doc, *id)?, &find, case, whole)))).filter(|(_, m)| !m.is_empty()).collect();
let count: usize = plan.iter().map(|(_, m)| m.len()).sum();
if count == 0 {
s.edit_state.find_cursor = None;
return Ok(json!({"count": 0, "layers": 0}));
}
s.edit("Replace All Text", |doc, _| {
@@ -97,7 +98,15 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
}
"find" | "change" | "changeFind" => {
let doc = st.doc.clone();
let cursor = s.edit_state.find_cursor;
let same_query = s
.edit_state
.find_cursor
.as_ref()
.is_some_and(|c| c.find == find && c.case_sensitive == case && c.whole_word == whole && c.forward == forward && c.all_layers == all_layers);
if !same_query {
s.edit_state.find_cursor = None;
}
let cursor = s.edit_state.find_cursor.as_ref().map(|c| (c.layer, c.start, c.end));
let mut changed = None;
if action != "find"
&& let Some((id, a, b)) = cursor
@@ -116,15 +125,19 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
// Collapse the cursor on the side the search moves away from, so the next search
// skips the replaced text even when the replacement still matches.
let c = if forward { end } else { a };
s.edit_state.find_cursor = Some((id, c, c));
s.edit_state.find_cursor =
Some(FindCursor { layer: id, start: c, end: c, find: find.clone(), case_sensitive: case, whole_word: whole, forward, all_layers });
changed = Some((id, a, end));
if action == "change" {
return Ok(json!({"changed": {"layer": id.0, "start": a, "end": end}}));
}
}
if action == "change" {
return Ok(json!({"changed": null}));
}
// Find the next match after the cursor (wrapping through the layers).
let doc = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
let cursor = s.edit_state.find_cursor;
let cursor = s.edit_state.find_cursor.as_ref().map(|c| (c.layer, c.start, c.end));
let start = cursor.and_then(|(id, _, _)| layers.iter().position(|l| *l == id)).unwrap_or(0);
for k in 0..=layers.len() {
// `allLayers: false` with a non-type layer active leaves no layers to search (#703).
@@ -148,7 +161,8 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
}
};
if let Some((a, b)) = hit {
s.edit_state.find_cursor = Some((id, a, b));
s.edit_state.find_cursor =
Some(FindCursor { layer: id, start: a, end: b, find, case_sensitive: case, whole_word: whole, forward, all_layers });
let _ = s.select_layer(id);
return Ok(
json!({"found": {"layer": id.0, "start": a, "end": b, "text": &text[a..b]}, "changed": changed.map(|(l, a, b)| json!({"layer": l.0, "start": a, "end": b}))}),
@@ -0,0 +1,107 @@
use super::*;
use photocraft_doc::LayerId;
fn text_of(s: &Session, id: LayerId) -> String {
match &s.active().unwrap().doc.layer(id).unwrap().content {
LayerContent::Text(t) => t.text.clone(),
_ => String::new(),
}
}
fn new_doc_with_type(text: &str) -> (Session, LayerId) {
let mut s = Session::new();
s.execute("file.new", json!({"width": 64, "height": 64, "depth": 8})).unwrap();
let id = LayerId(s.execute("type.create", json!({"text": text, "x": 2, "y": 12})).unwrap()["layer"].as_u64().unwrap());
(s, id)
}
#[test]
fn change_without_match_changes_nothing_and_does_not_advance() {
let (mut s, id) = new_doc_with_type("cat Cat");
let steps = s.active().unwrap().history.past_len();
let r = s.execute("edit.findAndReplaceText", json!({"find": "cat", "replace": "dog", "action": "change", "allLayers": false})).unwrap();
assert!(r["changed"].is_null(), "{r}");
assert!(r["found"].is_null(), "{r}");
assert_eq!(text_of(&s, id), "cat Cat");
assert_eq!(s.active().unwrap().history.past_len(), steps);
assert!(s.edit_state.find_cursor.is_none());
}
#[test]
fn change_all_with_zero_hits_drops_remembered_match() {
let (mut s, id) = new_doc_with_type("cats");
let f = s.execute("edit.findAndReplaceText", json!({"find": "cats", "action": "find"})).unwrap();
assert_eq!(f["found"]["text"], "cats");
let all = s.execute("edit.findAndReplaceText", json!({"find": "nonexistent", "replace": "dogs", "action": "changeAll"})).unwrap();
assert_eq!(all["count"].as_u64(), Some(0));
let c = s.execute("edit.findAndReplaceText", json!({"find": "cats", "replace": "dogs", "action": "change"})).unwrap();
assert!(c["changed"].is_null(), "{c}");
assert!(c["found"].is_null(), "{c}");
assert_eq!(text_of(&s, id), "cats");
}
#[test]
fn new_find_or_option_change_drops_remembered_match() {
let cases = [
json!({"find": "dog", "replace": "bird", "action": "change"}),
json!({"find": "cat", "replace": "bird", "action": "change", "caseSensitive": true}),
json!({"find": "cat", "replace": "bird", "action": "change", "wholeWord": true}),
json!({"find": "cat", "replace": "bird", "action": "change", "allLayers": false}),
json!({"find": "cat", "replace": "bird", "action": "change", "forward": false}),
];
for params in cases {
let (mut s, id) = new_doc_with_type("cat");
let f = s.execute("edit.findAndReplaceText", json!({"find": "cat", "action": "find"})).unwrap();
assert_eq!(f["found"]["text"], "cat");
let c = s.execute("edit.findAndReplaceText", params.clone()).unwrap();
assert!(c["changed"].is_null(), "{params}: {c}");
assert!(c["found"].is_null(), "{params}: {c}");
assert_eq!(text_of(&s, id), "cat", "{params}");
}
}
#[test]
fn reference_sequence_find_change_change_change_find_x4() {
let (mut s, id) = new_doc_with_type("cat Cat CAT cats");
let p = |action: &str| {
json!({
"find": "cat",
"replace": "dog",
"action": action,
"allLayers": false,
"caseSensitive": false,
"wholeWord": false,
})
};
let mut replacements = 0;
let f = s.execute("edit.findAndReplaceText", p("find")).unwrap();
assert_eq!((f["found"]["start"].as_u64(), f["found"]["end"].as_u64()), (Some(0), Some(3)), "{f}");
let c1 = s.execute("edit.findAndReplaceText", p("change")).unwrap();
assert!(c1["changed"].is_object(), "{c1}");
replacements += 1;
// Second Change in a row replaces nothing and does not move on.
let c2 = s.execute("edit.findAndReplaceText", p("change")).unwrap();
assert!(c2["changed"].is_null(), "{c2}");
assert!(c2["found"].is_null(), "{c2}");
assert_eq!(text_of(&s, id), "dog Cat CAT cats");
let mut found_texts = Vec::new();
for _ in 0..4 {
let cf = s.execute("edit.findAndReplaceText", p("changeFind")).unwrap();
if cf["changed"].is_object() {
replacements += 1;
}
found_texts.push(cf["found"]["text"].as_str().map(str::to_string));
}
assert_eq!(found_texts, vec![Some("Cat".to_string()), Some("CAT".to_string()), Some("cat".to_string()), None]);
assert_eq!(replacements, 4);
assert_eq!(text_of(&s, id), "dog dog dog dogs");
}