mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge #15007 into the merge queue batch
Find and Replace Text: search the layers in the reference order (#14661)
This commit is contained in:
commit
17d0c45b5c
3 files changed
+244
-38
No files matched your search
@@ -75,6 +75,8 @@ pub struct EditState {
|
||||
pub custom_shapes: Vec<CustomShape>,
|
||||
/// Find and Replace Text position and the query it belongs to.
|
||||
pub find_cursor: Option<FindCursor>,
|
||||
/// First layer visited in the current Find Next round (so wrapping stops before it).
|
||||
pub find_start: Option<LayerId>,
|
||||
}
|
||||
|
||||
/// Commands whose result Edit › Fade can blend back against the previous state.
|
||||
@@ -479,3 +481,7 @@ mod caf_new_layer_name_tests;
|
||||
#[cfg(test)]
|
||||
#[path = "edit_menu_cmds/find_replace_change_tests.rs"]
|
||||
mod find_replace_change_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "edit_menu_cmds/find_replace_order_tests.rs"]
|
||||
mod find_replace_order_tests;
|
||||
@@ -37,19 +37,27 @@ pub fn find_matches(text: &str, find: &str, case: bool, whole: bool) -> Vec<(usi
|
||||
out
|
||||
}
|
||||
|
||||
fn type_layers(doc: &Document, forward: bool) -> Vec<LayerId> {
|
||||
// Layers panel order: top first.
|
||||
let mut ids: Vec<LayerId> =
|
||||
doc.walk().into_iter().rev().filter(|(p, _, l)| matches!(l.content, LayerContent::Text(_)) && !doc.locks_at(p).all).map(|(_, _, l)| l.id).collect();
|
||||
if !forward {
|
||||
ids.reverse();
|
||||
fn type_layers(doc: &Document) -> Vec<LayerId> {
|
||||
// Layers panel order: bottom to top (upward), with group contents in stack position.
|
||||
doc.walk().into_iter().filter(|(p, _, l)| matches!(l.content, LayerContent::Text(_)) && !doc.locks_at(p).all).map(|(_, _, l)| l.id).collect()
|
||||
}
|
||||
|
||||
/// Index in `layers` to start a new round from `active` (going upward in `doc.walk()`).
|
||||
fn start_index(doc: &Document, layers: &[LayerId], active: Option<LayerId>) -> usize {
|
||||
let Some(aid) = active else { return 0 };
|
||||
if let Some(pos) = layers.iter().position(|id| *id == aid) {
|
||||
return pos;
|
||||
}
|
||||
ids
|
||||
let walk = doc.walk();
|
||||
let Some(active_walk) = walk.iter().position(|(_, _, l)| l.id == aid) else {
|
||||
return 0;
|
||||
};
|
||||
walk.iter().skip(active_walk + 1).find_map(|(_, _, l)| layers.iter().position(|id| *id == l.id)).unwrap_or(0)
|
||||
}
|
||||
|
||||
pub(super) fn has_type_layer(s: &Session) -> std::result::Result<(), String> {
|
||||
let d = s.active().ok_or("no document open")?;
|
||||
if type_layers(&d.doc, true).is_empty() { Err("the document has no type layers".into()) } else { Ok(()) }
|
||||
if type_layers(&d.doc).is_empty() { Err("the document has no type layers".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -60,7 +68,8 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(bool_or(p, "caseSensitive", false), bool_or(p, "wholeWord", false), bool_or(p, "forward", true), bool_or(p, "allLayers", true));
|
||||
let action = str_or(p, "action", "changeAll").to_string();
|
||||
let st = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let mut layers = type_layers(&st.doc, forward);
|
||||
let active_layer = st.active_layer;
|
||||
let mut layers = type_layers(&st.doc);
|
||||
if !all_layers {
|
||||
let active = layer_param(s, p).ok();
|
||||
layers.retain(|id| Some(*id) == active);
|
||||
@@ -79,6 +88,7 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let count: usize = plan.iter().map(|(_, m)| m.len()).sum();
|
||||
if count == 0 {
|
||||
s.edit_state.find_cursor = None;
|
||||
s.edit_state.find_start = None;
|
||||
return Ok(json!({"count": 0, "layers": 0}));
|
||||
}
|
||||
s.edit("Replace All Text", |doc, _| {
|
||||
@@ -94,6 +104,7 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(())
|
||||
})?;
|
||||
s.edit_state.find_cursor = None;
|
||||
s.edit_state.find_start = None;
|
||||
Ok(json!({"count": count, "layers": plan.len()}))
|
||||
}
|
||||
"find" | "change" | "changeFind" => {
|
||||
@@ -104,7 +115,9 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.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 {
|
||||
// A new query starts a new round: forget both the cursor and the round origin.
|
||||
s.edit_state.find_cursor = None;
|
||||
s.edit_state.find_start = None;
|
||||
}
|
||||
let cursor = s.edit_state.find_cursor.as_ref().map(|c| (c.layer, c.start, c.end));
|
||||
let mut changed = None;
|
||||
@@ -135,41 +148,51 @@ pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if action == "change" {
|
||||
return Ok(json!({"changed": null}));
|
||||
}
|
||||
// Find the next match after the cursor (wrapping through the layers).
|
||||
// Find the next match after the cursor (upward, wrapping once, stopping before the start layer).
|
||||
let doc = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
|
||||
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).
|
||||
let Some(&id) = layers.get((start + k) % layers.len().max(1)) else { break };
|
||||
let Some(text) = text_of(&doc, id) else { continue };
|
||||
let ms = find_matches(&text, &find, case, whole);
|
||||
let hit = match (k, cursor) {
|
||||
(0, Some((cid, a, b))) if cid == id => {
|
||||
if forward {
|
||||
ms.into_iter().find(|m| m.0 >= b)
|
||||
} else {
|
||||
ms.into_iter().rev().find(|m| m.1 <= a)
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if forward {
|
||||
ms.into_iter().next()
|
||||
} else {
|
||||
ms.into_iter().next_back()
|
||||
}
|
||||
}
|
||||
if !layers.is_empty() {
|
||||
let start = cursor.and_then(|(id, _, _)| layers.iter().position(|l| *l == id)).unwrap_or_else(|| start_index(&doc, &layers, active_layer));
|
||||
let origin = match cursor {
|
||||
Some(_) => s.edit_state.find_start.filter(|o| layers.contains(o)).unwrap_or(layers[start]),
|
||||
None => layers[start],
|
||||
};
|
||||
if let Some((a, b)) = hit {
|
||||
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}))}),
|
||||
);
|
||||
for k in 0..layers.len() {
|
||||
let Some(&id) = layers.get((start + k) % layers.len()) else { break };
|
||||
if k > 0 && id == origin {
|
||||
break;
|
||||
}
|
||||
let Some(text) = text_of(&doc, id) else { continue };
|
||||
let ms = find_matches(&text, &find, case, whole);
|
||||
let hit = match (k, cursor) {
|
||||
(0, Some((cid, a, b))) if cid == id => {
|
||||
if forward {
|
||||
ms.into_iter().find(|m| m.0 >= b)
|
||||
} else {
|
||||
ms.into_iter().rev().find(|m| m.1 <= a)
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if forward {
|
||||
ms.into_iter().next()
|
||||
} else {
|
||||
ms.into_iter().next_back()
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some((a, b)) = hit {
|
||||
s.edit_state.find_cursor =
|
||||
Some(FindCursor { layer: id, start: a, end: b, find, case_sensitive: case, whole_word: whole, forward, all_layers });
|
||||
s.edit_state.find_start = Some(origin);
|
||||
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}))}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
s.edit_state.find_cursor = None;
|
||||
s.edit_state.find_start = None;
|
||||
Ok(json!({"found": null, "changed": changed.map(|(l, a, b)| json!({"layer": l.0, "start": a, "end": b}))}))
|
||||
}
|
||||
other => Err(bad(cmd, format!("unknown action `{other}` (find|change|changeFind|changeAll)"))),
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
use super::*;
|
||||
|
||||
fn make_order_doc() -> (Session, [LayerId; 6], LayerId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 800, "height": 500, "depth": 8, "background": "white"})).unwrap();
|
||||
let id_of = |v: Value| LayerId(v["layer"].as_u64().unwrap());
|
||||
|
||||
let t1 = id_of(s.execute("type.create", json!({"text": "cat Cat CAT cats", "x": 10, "y": 40, "size": 12})).unwrap());
|
||||
let t2 = id_of(s.execute("type.create", json!({"text": "the cat sat", "x": 10, "y": 80, "size": 12})).unwrap());
|
||||
let t5 = id_of(s.execute("type.create", json!({"box": [10, 100, 200, 80], "text": "concatenate cat", "size": 12})).unwrap());
|
||||
let t6 = id_of(s.execute("type.create", json!({"text": "café cafe", "x": 10, "y": 200, "size": 12})).unwrap());
|
||||
let t7 = id_of(s.execute("type.create", json!({"text": "dog", "x": 10, "y": 240, "size": 12})).unwrap());
|
||||
|
||||
// Group G1 holding T8, then an empty pixel layer on top.
|
||||
let t8 = id_of(s.execute("type.create", json!({"text": "grouped cat", "x": 10, "y": 280, "size": 12})).unwrap());
|
||||
s.execute("layer.new.groupFromLayers", json!({"name": "G1", "layers": [t8.0]})).unwrap();
|
||||
let top_pixel = id_of(s.execute("layer.new.layer", json!({"name": "empty"})).unwrap());
|
||||
|
||||
// Verify bottom-to-top walk order of type layers is T1, T2, T5, T6, T7, T8.
|
||||
let walked_type_ids: Vec<LayerId> =
|
||||
s.active().unwrap().doc.walk().into_iter().filter_map(|(_, _, l)| matches!(l.content, LayerContent::Text(_)).then_some(l.id)).collect();
|
||||
assert_eq!(walked_type_ids, vec![t1, t2, t5, t6, t7, t8]);
|
||||
|
||||
(s, [t1, t2, t5, t6, t7, t8], top_pixel)
|
||||
}
|
||||
|
||||
fn find_next(s: &mut Session, forward: bool, all_layers: bool) -> Option<(LayerId, usize, usize, String)> {
|
||||
let r = s
|
||||
.execute(
|
||||
"edit.findAndReplaceText",
|
||||
json!({
|
||||
"find": "cat",
|
||||
"action": "find",
|
||||
"forward": forward,
|
||||
"allLayers": all_layers,
|
||||
"caseSensitive": false,
|
||||
"wholeWord": false,
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
let f = r.get("found")?;
|
||||
if f.is_null() {
|
||||
return None;
|
||||
}
|
||||
let layer = LayerId(f["layer"].as_u64().unwrap());
|
||||
let start = f["start"].as_u64().unwrap() as usize;
|
||||
let end = f["end"].as_u64().unwrap() as usize;
|
||||
let text = f["text"].as_str().unwrap().to_string();
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(layer));
|
||||
Some((layer, start, end, text))
|
||||
}
|
||||
|
||||
fn collect_round(s: &mut Session, forward: bool, all_layers: bool) -> Vec<(LayerId, usize, usize, String)> {
|
||||
let mut hits = Vec::new();
|
||||
while let Some(hit) = find_next(s, forward, all_layers) {
|
||||
assert!(hits.len() < 32, "search did not terminate: {hits:?}");
|
||||
hits.push(hit);
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_next_from_t1_forward_visits_upward_and_stops_at_end() {
|
||||
let (mut s, [t1, t2, t5, _t6, _t7, t8], _) = make_order_doc();
|
||||
s.execute("layer.select", json!({"layer": t1.0})).unwrap();
|
||||
let history_before = s.active().unwrap().history.past_len();
|
||||
|
||||
let hits = collect_round(&mut s, true, true);
|
||||
|
||||
assert_eq!(
|
||||
hits,
|
||||
vec![
|
||||
(t1, 0, 3, "cat".into()),
|
||||
(t1, 4, 7, "Cat".into()),
|
||||
(t1, 8, 11, "CAT".into()),
|
||||
(t1, 12, 15, "cat".into()),
|
||||
(t2, 4, 7, "cat".into()),
|
||||
(t5, 3, 6, "cat".into()),
|
||||
(t5, 12, 15, "cat".into()),
|
||||
(t8, 8, 11, "cat".into()),
|
||||
]
|
||||
);
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history_before, "Find Next adds no history state");
|
||||
|
||||
// Next Find Next after the end starts a new round from the active layer (t8).
|
||||
assert_eq!(find_next(&mut s, true, true), Some((t8, 8, 11, "cat".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_next_from_t5_forward_wraps_and_stops_before_t5() {
|
||||
let (mut s, [t1, t2, t5, _t6, _t7, t8], _) = make_order_doc();
|
||||
s.execute("layer.select", json!({"layer": t5.0})).unwrap();
|
||||
|
||||
let hits = collect_round(&mut s, true, true);
|
||||
|
||||
assert_eq!(
|
||||
hits,
|
||||
vec![
|
||||
(t5, 3, 6, "cat".into()),
|
||||
(t5, 12, 15, "cat".into()),
|
||||
(t8, 8, 11, "cat".into()),
|
||||
(t1, 0, 3, "cat".into()),
|
||||
(t1, 4, 7, "Cat".into()),
|
||||
(t1, 8, 11, "CAT".into()),
|
||||
(t1, 12, 15, "cat".into()),
|
||||
(t2, 4, 7, "cat".into()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_next_from_t5_backward_reverses_only_in_layer_matches() {
|
||||
let (mut s, [t1, t2, t5, _t6, _t7, t8], _) = make_order_doc();
|
||||
s.execute("layer.select", json!({"layer": t5.0})).unwrap();
|
||||
|
||||
let hits = collect_round(&mut s, false, true);
|
||||
|
||||
assert_eq!(
|
||||
hits,
|
||||
vec![
|
||||
(t5, 12, 15, "cat".into()),
|
||||
(t5, 3, 6, "cat".into()),
|
||||
(t8, 8, 11, "cat".into()),
|
||||
(t1, 12, 15, "cat".into()),
|
||||
(t1, 8, 11, "CAT".into()),
|
||||
(t1, 4, 7, "Cat".into()),
|
||||
(t1, 0, 3, "cat".into()),
|
||||
(t2, 4, 7, "cat".into()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_next_from_t7_backward_goes_upward_to_t8_first() {
|
||||
let (mut s, [_t1, _t2, _t5, _t6, t7, t8], _) = make_order_doc();
|
||||
s.execute("layer.select", json!({"layer": t7.0})).unwrap();
|
||||
|
||||
assert_eq!(find_next(&mut s, false, true), Some((t8, 8, 11, "cat".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_next_single_layer_and_change_all_preserved() {
|
||||
let (mut s, [_t1, _t2, t5, _t6, _t7, _t8], _) = make_order_doc();
|
||||
s.execute("layer.select", json!({"layer": t5.0})).unwrap();
|
||||
|
||||
let fwd = collect_round(&mut s, true, false);
|
||||
assert_eq!(fwd, vec![(t5, 3, 6, "cat".into()), (t5, 12, 15, "cat".into())]);
|
||||
|
||||
let bwd = collect_round(&mut s, false, false);
|
||||
assert_eq!(bwd, vec![(t5, 12, 15, "cat".into()), (t5, 3, 6, "cat".into())]);
|
||||
|
||||
let r = s.execute("edit.findAndReplaceText", json!({"find": "cat", "replace": "fox", "action": "changeAll"})).unwrap();
|
||||
assert_eq!((r["count"].as_u64(), r["layers"].as_u64()), (Some(8), Some(4)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_query_starts_a_new_round_and_reaches_the_old_origin() {
|
||||
let (mut s, [t1, t2, ..], _) = make_order_doc();
|
||||
s.execute("layer.select", json!({"layer": t1.0})).unwrap();
|
||||
// The round starts at T1: four hits there, then the match in T2.
|
||||
for _ in 0..4 {
|
||||
assert_eq!(find_next(&mut s, true, true).map(|h| h.0), Some(t1));
|
||||
}
|
||||
assert_eq!(find_next(&mut s, true, true), Some((t2, 4, 7, "cat".into())));
|
||||
|
||||
// A query that matches only in the old origin (T1) must be reachable from the cursor in T2.
|
||||
let r = s.execute("edit.findAndReplaceText", json!({"find": "CAT", "action": "find", "forward": true, "allLayers": true, "caseSensitive": true})).unwrap();
|
||||
assert_eq!((r["found"]["layer"].as_u64(), r["found"]["text"].as_str()), (Some(t1.0), Some("CAT")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_next_from_top_pixel_layer_wraps_to_bottom_type_layer() {
|
||||
let (mut s, [t1, ..], top_pixel) = make_order_doc();
|
||||
s.execute("layer.select", json!({"layer": top_pixel.0})).unwrap();
|
||||
|
||||
assert_eq!(find_next(&mut s, true, true), Some((t1, 0, 3, "cat".into())));
|
||||
}
|
||||
Reference in new issue
Block a user