Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

PARITY-FIND-SCOPE: respect search scope and first-match limits

sanyamsingh0014760a000dbcf
diff --git a/crates/engine/src/cmd/find.rs b/crates/engine/src/cmd/find.rs
index 5dc0bc8ad..39f85b0a5 100644
--- a/crates/engine/src/cmd/find.rs
+++ b/crates/engine/src/cmd/find.rs
@@ -1,17 +1,22 @@
//! Edit → Find/Change: plain text and GREP (regular expressions) with InDesign's metacharacters,
//! optional formatting in the change, scoped to the document, a story or the selection.
-use designcraft_doc::{StoryId, TextSel, story};
+use std::ops::Range;
+use std::sync::{Arc, Weak};
+
+use designcraft_doc::story::floor_char_boundary;
+use designcraft_doc::{Document, Selection, StoryId, TextSel};
use serde_json::{Value, json};
use super::{CommandSpec, bad, bool_or, cmd, has_doc, str_param};
-use crate::{Result, Session};
+use crate::{DocState, Result, Session};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(noundo "find.objects", "Find Object", [], None,
"{fill?, stroke?: swatch, strokeWeight?, opacity? (0–1), kind?: text|graphic|shape|line|group, layer?, label?, select?: bool (default true)} → {ids} — Find/Change › Object, through the document",
has_doc, |s, p| {
+ s.reset_find_scope();
let ids = find_objects(&s.doc()?.doc, p);
if p.get("select").and_then(Value::as_bool).unwrap_or(true) && !ids.is_empty() {
let st = s.doc_mut()?;
@@ -28,6 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"{…find.objects criteria, change: {fill?, stroke?, strokeWeight?, opacity?}} → {changed}",
has_doc,
|s, p| {
+ s.reset_find_scope();
let ids = find_objects(&s.doc()?.doc, p);
let ch = p.get("change").cloned().unwrap_or(Value::Null);
if !ch.is_object() {
@@ -65,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
change
),
- cmd!(noundo "find.next", "Find Next", ["Edit"], Some("Cmd+Alt+F"), "{find, grep?, …} — selects the next match after the caret", has_doc, find_next),
+ cmd!(noundo "find.next", "Find Next", ["Edit"], Some("Cmd+Alt+F"), "{find, grep?, caseSensitive?, wholeWord?, scope?: document|story|selection, story?} — Selection starts at its original beginning; later calls advance within the scope", has_doc, find_next),
]
}
@@ -125,34 +131,182 @@ fn build(p: &Value) -> Result<regex::Regex> {
.map_err(|e| bad("find", format!("bad GREP: {e}")))
}
-fn scope(s: &Session, p: &Value) -> Result<Vec<(StoryId, std::ops::Range<usize>)>> {
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum Domain {
+ Document,
+ Story,
+ Selection,
+ Explicit(StoryId),
+}
+
+impl Domain {
+ fn from_params(p: &Value) -> Self {
+ if let Some(id) = p.get("story").and_then(Value::as_u64) {
+ return Self::Explicit(StoryId(id));
+ }
+ match str_param(p, "scope").unwrap_or("document") {
+ "story" => Self::Story,
+ "selection" => Self::Selection,
+ _ => Self::Document,
+ }
+ }
+}
+
+/// Whether two requests use the same search domain, including explicit-story precedence.
+pub fn same_find_domain(a: &Value, b: &Value) -> bool {
+ Domain::from_params(a) == Domain::from_params(b)
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct Matcher {
+ find: String,
+ grep: bool,
+ case_sensitive: bool,
+ whole_word: bool,
+}
+
+impl Matcher {
+ fn from_params(p: &Value) -> Self {
+ Self {
+ find: str_param(p, "find").unwrap_or("").to_string(),
+ grep: bool_or(p, "grep", false),
+ case_sensitive: bool_or(p, "caseSensitive", false),
+ whole_word: bool_or(p, "wholeWord", false),
+ }
+ }
+}
+
+/// A search owns its original domain, not the selection used to paint the latest hit.
+/// Weak identity avoids retaining an old document merely for this transient cache.
+#[derive(Clone)]
+pub(crate) struct FindContext {
+ document: Weak<Document>,
+ uid: u64,
+ revision: u64,
+ selection: Selection,
+ domain: Domain,
+ matcher: Matcher,
+ targets: Vec<(StoryId, Range<usize>)>,
+ order: Vec<usize>,
+ target: usize,
+ offset: usize,
+ last_match_end: Option<usize>,
+}
+
+impl FindContext {
+ pub(crate) fn is_current(&self, st: &DocState) -> bool {
+ self.uid == st.uid && Weak::ptr_eq(&self.document, &Arc::downgrade(&st.doc)) && self.revision == st.revision && self.selection == st.selection
+ }
+
+ fn acknowledge(&mut self, st: &DocState) {
+ self.revision = st.revision;
+ self.selection = st.selection.clone();
+ }
+
+ fn restart(&mut self, st: &DocState) -> Result<()> {
+ self.target = 0;
+ self.last_match_end = None;
+ self.order = (0..self.targets.len()).collect();
+ let caret = st.selection.text.filter(|t| t.cell.is_none() && st.selection.cells.is_none());
+ if self.domain == Domain::Document
+ && let Some(t) = st.selection.text
+ && let Some(i) = self.targets.iter().position(|(sid, _)| *sid == t.story)
+ {
+ self.order.rotate_left(i);
+ }
+ let first = self.order.first().and_then(|i| self.targets.get(*i));
+ self.offset = match first {
+ Some((sid, r)) if self.domain != Domain::Selection => caret.filter(|t| t.story == *sid).map_or(r.start, |t| t.range().end.min(r.end)),
+ Some((_, r)) => r.start,
+ None => 0,
+ };
+ if let Some((sid, r)) = first {
+ let text = target_text(&st.doc, *sid, r)?;
+ if text.get(self.offset.saturating_sub(r.start)..).is_none() {
+ return Err(bad("find", "invalid UTF-8 search cursor"));
+ }
+ }
+ Ok(())
+ }
+
+ fn advance_target(&mut self) {
+ self.target = self.target.saturating_add(1);
+ self.last_match_end = None;
+ self.offset = self.order.get(self.target).and_then(|i| self.targets.get(*i)).map_or(0, |(_, r)| r.start);
+ }
+
+ fn advance_empty(&mut self, text: &str, relative_end: usize, end: usize) {
+ // Move one Unicode scalar, not one byte; an endpoint is returned at most once.
+ if let Some(ch) = text.get(relative_end..).and_then(|rest| rest.chars().next()) {
+ self.offset = end + ch.len_utf8();
+ } else {
+ self.advance_target();
+ }
+ }
+}
+
+fn target_text<'a>(d: &'a Document, sid: StoryId, r: &Range<usize>) -> Result<&'a str> {
+ d.story(sid)
+ .ok_or_else(|| bad("find", "no such story"))?
+ .text
+ .get(r.clone())
+ .ok_or_else(|| bad("find", "invalid selection bounds or UTF-8 boundary"))
+}
+
+fn scope(s: &Session, p: &Value) -> Result<FindContext> {
let st = s.doc()?;
+ let domain = Domain::from_params(p);
+ let matcher = Matcher::from_params(p);
+ if let Some(previous) = s.find_context.as_ref().filter(|c| c.is_current(st) && c.domain == domain) {
+ let mut context = previous.clone();
+ if context.matcher != matcher {
+ context.matcher = matcher;
+ context.restart(st)?;
+ }
+ return Ok(context);
+ }
let d = &st.doc;
- if let Some(sid) = p.get("story").and_then(Value::as_u64) {
- let sid = StoryId(sid);
- let len = d.story(sid).map(|x| x.len()).ok_or_else(|| bad("find", "no such story"))?;
- return Ok(vec![(sid, 0..len)]);
- }
- match str_param(p, "scope").unwrap_or("document") {
- "story" => {
- let t = st.selection.text.ok_or_else(|| bad("find", "no story selected"))?;
- Ok(vec![(t.story, 0..d.story(t.story).map(|x| x.len()).unwrap_or(0))])
+ let targets = match domain {
+ Domain::Explicit(sid) => {
+ let len = d.story(sid).ok_or_else(|| bad("find", "no such story"))?.len();
+ vec![(sid, 0..len)]
}
- "selection" => {
+ Domain::Story | Domain::Selection => {
+ if st.selection.cells.is_some() || st.selection.text.is_some_and(|t| t.cell.is_some()) {
+ return Err(bad("find", "Story/Selection search in table cells or notes is not supported"));
+ }
let t = st.selection.text.ok_or_else(|| bad("find", "no text selected"))?;
- Ok(vec![(t.story, t.range())])
+ let story = d.story(t.story).ok_or_else(|| bad("find", "no such story"))?;
+ let r = if domain == Domain::Selection { t.range() } else { 0..story.len() };
+ target_text(d, t.story, &r)?;
+ vec![(t.story, r)]
}
- _ => Ok(d.stories.values().map(|x| (x.id, 0..x.len())).collect()),
- }
+ Domain::Document => d.stories.values().map(|x| (x.id, 0..x.len())).collect(),
+ };
+ let mut context = FindContext {
+ document: Arc::downgrade(d),
+ uid: st.uid,
+ revision: st.revision,
+ selection: st.selection.clone(),
+ domain,
+ matcher,
+ targets,
+ order: Vec::new(),
+ target: 0,
+ offset: 0,
+ last_match_end: None,
+ };
+ context.restart(st)?;
+ Ok(context)
}
fn find(s: &mut Session, p: &Value) -> Result<Value> {
let re = build(p)?;
+ let context = scope(s, p)?;
let st = s.doc()?;
let mut out = Vec::new();
- for (sid, r) in scope(s, p)? {
- let Some(story) = st.doc.story(sid) else { continue };
- let text = &story.text[r.clone()];
+ for (sid, r) in &context.targets {
+ let text = target_text(&st.doc, *sid, r)?;
for m in re.find_iter(text) {
out.push(json!({"story": sid.0, "start": r.start + m.start(), "end": r.start + m.end(), "text": m.as_str()}));
if out.len() >= 10_000 {
@@ -160,6 +314,7 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
+ s.find_context = Some(context);
Ok(Value::Array(out))
}
@@ -182,13 +337,13 @@ fn change(s: &mut Session, p: &Value) -> Result<Value> {
}
}
super::text::validate_char_fill(&s.doc()?.doc, &over, "find.change")?;
- let targets = scope(s, p)?;
+ let targets = scope(s, p)?.targets;
s.edit(|d, sel| {
let mut count = 0usize;
for (sid, r) in targets {
let Some(story) = d.story(sid) else { continue };
// Collect matches first (positions refer to the original text), apply back to front.
- let text = story.text[r.clone()].to_string();
+ let text = story.text.get(r.clone()).ok_or_else(|| bad("find", "invalid selection bounds or UTF-8 boundary"))?.to_string();
let mut edits: Vec<(std::ops::Range<usize>, String)> = Vec::new();
for caps in re.captures_iter(&text) {
let Some(m) = caps.get(0) else { continue };
@@ -211,10 +366,21 @@ fn change(s: &mut Session, p: &Value) -> Result<Value> {
}
count += 1;
}
- if let Some(t) = sel.text.as_mut().filter(|t| t.story == sid) {
- let len = st.len();
- t.anchor = t.anchor.min(len);
- t.focus = t.focus.min(len);
+ if let Some(t) = sel.text.as_mut().filter(|t| t.story == sid && t.cell.is_none()) {
+ // Repair byte validity once against the final story, without remapping valid offsets.
+ let range = t.range();
+ let start = floor_char_boundary(&st.text, range.start);
+ let mut end = range.end.min(st.len());
+ if t.is_caret() {
+ end = start;
+ } else if !st.text.is_char_boundary(end) {
+ let floor = floor_char_boundary(&st.text, end);
+ end = st.text.get(floor..).and_then(|rest| rest.chars().next()).map_or(floor, |ch| floor + ch.len_utf8());
+ }
+ (t.anchor, t.focus) = if t.anchor <= t.focus { (start, end) } else { (end, start) };
+ }
+ if first_only && count > 0 {
+ break;
}
}
Ok(json!({"count": count}))
@@ -223,29 +389,44 @@ fn change(s: &mut Session, p: &Value) -> Result<Value> {
fn find_next(s: &mut Session, p: &Value) -> Result<Value> {
let re = build(p)?;
+ let mut context = scope(s, p)?;
let st = s.doc()?;
- let (start_story, start_pos) = st.selection.text.map(|t| (Some(t.story), t.range().end)).unwrap_or((None, 0));
- let mut order: Vec<StoryId> = st.doc.stories.keys().copied().collect();
- if let Some(ss) = start_story
- && let Some(i) = order.iter().position(|x| *x == ss)
- {
- order.rotate_left(i);
- }
let mut hit = None;
- for (k, sid) in order.iter().enumerate() {
- let Some(story) = st.doc.story(*sid) else { continue };
- let from = if k == 0 && start_story == Some(*sid) { start_pos.min(story.len()) } else { 0 };
- if let Some(m) = re.find_at(&story.text, from) {
- hit = Some((*sid, m.start(), m.end()));
+ while let Some((sid, r)) = context.order.get(context.target).and_then(|i| context.targets.get(*i)).cloned() {
+ let text = target_text(&st.doc, sid, &r)?;
+ let from = context.offset.checked_sub(r.start).ok_or_else(|| bad("find", "invalid search cursor"))?;
+ if text.get(from..).is_none() {
+ return Err(bad("find", "invalid UTF-8 search cursor"));
+ }
+ if let Some(m) = re.find_at(text, from) {
+ let (a, b) = (r.start + m.start(), r.start + m.end());
+ // Match find_iter/captures_iter: suppress an empty match adjacent to the
+ // previous match's end, but keep adjacent nonempty matches.
+ if m.is_empty() && context.last_match_end == Some(b) {
+ context.advance_empty(text, m.end(), b);
+ continue;
+ }
+ hit = Some((sid, a, b));
+ context.last_match_end = Some(b);
+ if m.is_empty() {
+ context.advance_empty(text, m.end(), b);
+ } else {
+ context.offset = b;
+ }
break;
}
+ context.advance_target();
}
- let Some((sid, a, b)) = hit else { return Ok(Value::Null) };
+ let Some((sid, a, b)) = hit else {
+ s.find_context = Some(context);
+ return Ok(Value::Null);
+ };
let frame = st.doc.story(sid).and_then(|x| x.frames.first().copied());
let stm = s.doc_mut()?;
- stm.selection = designcraft_doc::Selection::text(TextSel { story: sid, anchor: a, focus: b, frame, cell: None });
+ stm.selection = Selection::text(TextSel { story: sid, anchor: a, focus: b, frame, cell: None });
stm.revision += 1;
- let _ = story::PAGE_NUMBER;
+ context.acknowledge(stm);
+ s.find_context = Some(context);
Ok(json!({"story": sid.0, "start": a, "end": b}))
}
@@ -278,6 +459,664 @@ mod tests {
s.execute("find.next", &json!({"find": "or"})).unwrap();
assert!(s.doc().unwrap().selection.text.is_some());
}
+ fn scope_session(text: &str) -> (Session, designcraft_doc::StoryId) {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let frame = s.execute("frame.create", &json!({"rect": [36, 36, 100, 100], "content": "text", "text": text})).unwrap();
+ (s, designcraft_doc::StoryId(frame["story"].as_u64().unwrap()))
+ }
+
+ fn scope_select(s: &mut Session, sid: designcraft_doc::StoryId, a: usize, b: usize) {
+ s.execute("text.select", &json!({"story": sid.0, "anchor": a, "focus": b})).unwrap();
+ }
+
+ fn scope_hit(s: &mut Session, p: &serde_json::Value, sid: designcraft_doc::StoryId, a: usize, b: usize) {
+ assert_eq!(s.execute("find.next", p).unwrap(), json!({"story": sid.0, "start": a, "end": b}));
+ let selected = s.doc().unwrap().selection.text.unwrap();
+ assert_eq!((selected.story, selected.range(), selected.cell), (sid, a..b, None));
+ }
+
+ #[test]
+ fn find_scope_first_change_stops_after_first_matching_story_and_repairs_selection() {
+ for (texts, first, explicit, grep, expected, count) in [
+ (vec!["red red", "red"], Some(true), false, false, vec!["blue red", "red"], 1),
+ (vec!["keep", "red red", "red"], Some(true), false, false, vec!["keep", "blue red", "red"], 1),
+ (vec!["keep", "other"], Some(true), false, false, vec!["keep", "other"], 0),
+ (vec!["red red", "red"], Some(false), false, false, vec!["blue blue", "blue"], 3),
+ (vec!["red red", "red"], None, false, false, vec!["blue blue", "blue"], 3),
+ (vec!["red red", "red"], Some(true), true, false, vec!["blue red", "red"], 1),
+ (vec!["red red", "red"], Some(false), true, false, vec!["blue blue", "red"], 2),
+ (vec!["", "é🙂"], Some(true), false, true, vec!["X", "é🙂"], 1),
+ (vec!["é", "🙂"], Some(false), false, true, vec!["XéX", "X🙂X"], 4),
+ ] {
+ let (mut s, sid) = scope_session(texts[0]);
+ let mut sids = vec![sid];
+ for text in texts.iter().skip(1) {
+ let frame = s.execute("frame.create", &json!({"rect": [120, 36, 200, 100], "content": "text", "text": text})).unwrap();
+ sids.push(designcraft_doc::StoryId(frame["story"].as_u64().unwrap()));
+ }
+ assert_eq!(s.doc().unwrap().doc.stories.keys().copied().collect::<Vec<_>>(), sids);
+ // Document Change keeps canonical target order even with a later story current.
+ scope_select(&mut s, *sids.last().unwrap(), 0, 0);
+ let before = s.doc().unwrap().doc.clone();
+ let mut p = json!({
+ "find": if grep { "(?:)" } else { "red" },
+ "change": if grep { "X" } else { "blue" },
+ "scope": "document", "grep": grep
+ });
+ if let Some(first) = first {
+ p["first"] = json!(first);
+ }
+ if explicit {
+ p["story"] = json!(sid.0);
+ p["scope"] = json!("selection");
+ }
+ if first == Some(true) && !explicit && !grep && texts.last() == Some(&"red") {
+ let last = *sids.last().unwrap();
+ scope_hit(&mut s, &p, last, 0, 3);
+ let first_hit = sids[if texts.len() == 2 { 0 } else { 1 }];
+ assert_eq!(
+ s.execute("find.find", &p).unwrap(),
+ json!([
+ {"story": first_hit.0, "start": 0, "end": 3, "text": "red"},
+ {"story": first_hit.0, "start": 4, "end": 7, "text": "red"},
+ {"story": last.0, "start": 0, "end": 3, "text": "red"}
+ ]),
+ "Count remains canonical after Next paints the later story"
+ );
+ }
+ let selection = s.doc().unwrap().selection.clone();
+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": count}));
+ let st = s.doc().unwrap();
+ assert_eq!(st.selection, selection);
+ for (i, sid) in sids.iter().enumerate() {
+ assert_eq!(st.doc.story(*sid).unwrap().text, expected[i]);
+ if texts[i] == expected[i] {
+ assert_eq!(st.doc.story(*sid), before.story(*sid), "untouched story {i} stays entirely unchanged");
+ }
+ }
+ st.doc.check().unwrap();
+ }
+
+ // Identical replacement is still one counted match, not a reason to visit another story.
+ let (mut s, sid) = scope_session("red red");
+ let other = s.execute("frame.create", &json!({"rect": [120, 36, 200, 100], "content": "text", "text": "red"})).unwrap();
+ let other_sid = designcraft_doc::StoryId(other["story"].as_u64().unwrap());
+ scope_select(&mut s, other_sid, 0, 3);
+ let before = s.doc().unwrap().doc.clone();
+ let selection = s.doc().unwrap().selection.clone();
+ assert_eq!(
+ s.execute("find.change", &json!({"find": "red", "change": "red", "scope": "document", "first": true})).unwrap(),
+ json!({"count": 1})
+ );
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red");
+ assert_eq!(s.doc().unwrap().doc.story(other_sid), before.story(other_sid));
+ assert_eq!(s.doc().unwrap().selection, selection);
+ s.doc().unwrap().doc.check().unwrap();
+
+ for reverse in [false, true] {
+ let (mut s, sid) = scope_session("éX X");
+ let other = s.execute("frame.create", &json!({"rect": [120, 36, 200, 100], "content": "text", "text": "X"})).unwrap();
+ let other_sid = designcraft_doc::StoryId(other["story"].as_u64().unwrap());
+ scope_select(&mut s, sid, if reverse { 3 } else { 2 }, if reverse { 2 } else { 3 });
+ let before = s.doc().unwrap().doc.clone();
+ let mut selection = s.doc().unwrap().selection.clone();
+ let t = selection.text.as_mut().unwrap();
+ (t.anchor, t.focus) = if reverse { (6, 2) } else { (2, 6) };
+ let p = json!({"find": "X", "change": "🙂", "scope": "document", "first": true});
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 3);
+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 1}));
+ let st = s.doc().unwrap();
+ assert_eq!(st.doc.story(sid).unwrap().text, "é🙂 X");
+ assert_eq!(st.doc.story(other_sid), before.story(other_sid));
+ assert_eq!(st.selection, selection, "first-match exit must follow final UTF-8 repair");
+ st.doc.check().unwrap();
+ assert_eq!(
+ s.execute("find.find", &json!({"find": "🙂", "scope": "selection"})).unwrap(),
+ json!([{"story": sid.0, "start": 2, "end": 6, "text": "🙂"}])
+ );
+ }
+ }
+
+ #[test]
+ fn find_scope_exact_baseline_count_next_change() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let frame = s
+ .execute(
+ "frame.create",
+ &json!({
+ "rect": [36, 36, 300, 200], "content": "text", "text": "red red"
+ }),
+ )
+ .unwrap();
+ let sid = frame["story"].as_u64().unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 3})).unwrap();
+ assert_eq!(
+ s.execute("find.find", &json!({"find": "red", "scope": "selection"})).unwrap(),
+ json!([{"story": sid, "start": 0, "end": 3, "text": "red"}])
+ );
+ assert_eq!(s.execute("find.next", &json!({"find": "red", "scope": "selection"})).unwrap(), json!({"story": sid, "start": 0, "end": 3}));
+ assert_eq!(s.execute("find.change", &json!({"find": "red", "change": "blue", "scope": "selection"})).unwrap(), json!({"count": 1}));
+ assert_eq!(s.execute("story.get", &json!({"story": sid})).unwrap()["text"], "blue red");
+ }
+
+ #[test]
+ fn find_scope_change_growth_preserves_direction_and_full_scalar_hits() {
+ for (text, find, change, changed, start, old_end, new_end) in [("a", "a", "é", "é", 0, 1, 2), ("éX", "X", "🙂", "é🙂", 2, 3, 6)] {
+ for reverse in [false, true] {
+ let (mut s, sid) = scope_session(text);
+ // Real caret movement keeps the frame identity, unlike text.select.
+ s.execute("text.move", &json!({"dir": "left", "extend": reverse})).unwrap();
+ if !reverse {
+ s.execute("text.move", &json!({"dir": "right", "extend": true})).unwrap();
+ }
+ let selected = s.doc().unwrap().selection.text.unwrap();
+ assert_eq!((selected.anchor, selected.focus), if reverse { (old_end, start) } else { (start, old_end) });
+ assert!(selected.frame.is_some());
+ let mut expected = s.doc().unwrap().selection.clone();
+ let t = expected.text.as_mut().unwrap();
+ (t.anchor, t.focus) = if reverse { (new_end, start) } else { (start, new_end) };
+ let p = json!({"find": find, "change": change, "scope": "selection"});
+ assert_eq!(s.execute("find.find", &p).unwrap(), json!([{"story": sid.0, "start": start, "end": old_end, "text": find}]));
+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 1}));
+ let st = s.doc().unwrap();
+ assert_eq!(st.doc.story(sid).unwrap().text, changed);
+ assert_eq!(st.selection, expected);
+ let t = st.selection.text.unwrap();
+ assert!(changed.is_char_boundary(t.anchor) && changed.is_char_boundary(t.focus));
+ assert!(s.find_context.is_none());
+ let p = json!({"find": change, "scope": "selection"});
+ assert_eq!(s.execute("find.find", &p).unwrap(), json!([{"story": sid.0, "start": start, "end": new_end, "text": change}]));
+ scope_hit(&mut s, &p, sid, start, new_end);
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);
+ }
+ }
+ }
+
+ #[test]
+ fn find_scope_change_repairs_final_boundaries_without_remapping_valid_offsets() {
+ for (text, (a, b), find, change, changed, (after_a, after_b), count) in [
+ ("aX", (1, 1), "a", "é", "éX", (0, 0), 1), // A caret stays collapsed and floors.
+ ("aX", (2, 2), "a", "é", "éX", (2, 2), 1), // A valid caret stays at its byte offset.
+ ("abc", (1, 2), "abc", "🙂", "🙂", (0, 4), 1), // Both endpoints need repair.
+ ("abc", (2, 1), "abc", "🙂", "🙂", (4, 0), 1),
+ ("é🙂", (2, 6), "🙂", "X", "éX", (2, 3), 1), // Existing shortening behavior.
+ ("é🙂", (6, 2), "🙂", "X", "éX", (3, 2), 1),
+ ("red", (0, 3), "red", "blue", "blue", (0, 3), 1), // Do not extend a valid upper bound.
+ ("aX", (1, 2), "a", "zz", "zzX", (1, 2), 1), // Do not track the original X.
+ ("aaX", (1, 2), "a", "é", "ééX", (0, 2), 2), // Per-edit repair would wrongly yield 0..4.
+ ("aaX", (2, 3), "a", "é", "ééX", (2, 4), 2),
+ ("abc", (1, 3), "abc", "", "", (0, 0), 1),
+ ("abc", (2, 3), "abc", "é", "é", (2, 2), 1), // EOF clamp may collapse a nonempty range.
+ ] {
+ let (mut s, sid) = scope_session(text);
+ scope_select(&mut s, sid, a, b);
+ let mut expected = s.doc().unwrap().selection.clone();
+ let t = expected.text.as_mut().unwrap();
+ (t.anchor, t.focus) = (after_a, after_b);
+ assert_eq!(s.execute("find.change", &json!({"find": find, "change": change, "scope": "document"})).unwrap(), json!({"count": count}));
+ let st = s.doc().unwrap();
+ assert_eq!(st.doc.story(sid).unwrap().text, changed, "{text} {a}->{b}");
+ assert_eq!(st.selection, expected, "{text} {a}->{b}");
+ assert!(changed.is_char_boundary(after_a) && changed.is_char_boundary(after_b));
+ if after_a == after_b {
+ assert_eq!(
+ s.execute("find.find", &json!({"find": "(?:)", "grep": true, "scope": "selection"})).unwrap(),
+ json!([{"story": sid.0, "start": after_a, "end": after_a, "text": ""}])
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn find_scope_change_other_story_and_no_hits_preserve_selection() {
+ for explicit in [false, true] {
+ let (mut s, sid) = scope_session("éX");
+ let frame = s.doc().unwrap().selection.text.unwrap().frame.unwrap();
+ let other = s.execute("frame.create", &json!({"rect": [120, 36, 200, 100], "content": "text", "text": "a"})).unwrap();
+ let other_sid = designcraft_doc::StoryId(other["story"].as_u64().unwrap());
+ scope_select(&mut s, sid, 3, 2);
+ let before = s.doc().unwrap().selection.clone();
+ let mut p = json!({"find": "a", "change": "🙂", "scope": "document"});
+ if explicit {
+ p["story"] = json!(other_sid.0);
+ }
+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 1}));
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "éX");
+ assert_eq!(s.doc().unwrap().doc.story(other_sid).unwrap().text, "🙂");
+ assert_eq!(s.doc().unwrap().selection, before);
+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 0}));
+ assert_eq!(s.doc().unwrap().selection, before);
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "éX");
+ assert_eq!(s.doc().unwrap().doc.story(other_sid).unwrap().text, "🙂");
+
+ s.execute("selection.set", &json!({"ids": [frame.0]})).unwrap();
+ let before = s.doc().unwrap().selection.clone();
+ assert!(before.text.is_none());
+ p["find"] = json!("🙂");
+ p["change"] = json!("é");
+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 1}));
+ assert_eq!(s.doc().unwrap().selection, before);
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "éX");
+ assert_eq!(s.doc().unwrap().doc.story(other_sid).unwrap().text, "é");
+ }
+ }
+
+ #[test]
+ fn find_scope_mixed_grep_matches_count_next_and_change() {
+ for (text, pattern, expected, changed) in [
+ ("a", "a*", vec![(0, 1)], "X"),
+ ("aa", "a|(?:)", vec![(0, 1), (1, 2)], "XX"),
+ ("ab", "a*", vec![(0, 1), (2, 2)], "XbX"),
+ ("éa", "é|(?:)", vec![(0, 2), (3, 3)], "XaX"),
+ ] {
+ let (mut s, sid) = scope_session(text);
+ scope_select(&mut s, sid, 0, text.len());
+ let p = json!({"find": pattern, "grep": true, "scope": "selection", "change": "X"});
+ let counted = s.execute("find.find", &p).unwrap();
+ let ranges: Vec<_> =
+ counted.as_array().unwrap().iter().map(|m| (m["start"].as_u64().unwrap() as usize, m["end"].as_u64().unwrap() as usize)).collect();
+ assert_eq!(ranges, expected, "{pattern} on {text}");
+ for (a, b) in &expected {
+ scope_hit(&mut s, &p, sid, *a, *b);
+ }
+ for _ in 0..2 {
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null, "{pattern} on {text}");
+ }
+ assert_eq!(s.execute("find.find", &p).unwrap(), counted);
+ assert_eq!(s.execute("find.change", &p).unwrap()["count"], expected.len());
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, changed);
+ }
+ }
+
+ #[test]
+ fn find_scope_capture_replacement_and_first_keep_original_domain() {
+ let (mut s, sid) = scope_session("a1 a2 | a3");
+ scope_select(&mut s, sid, 0, 5);
+ let p = json!({"find": r"a(\d)", "grep": true, "scope": "selection", "change": "b$1", "first": true});
+ scope_hit(&mut s, &p, sid, 0, 2);
+ scope_hit(&mut s, &p, sid, 3, 5);
+ assert_eq!(s.execute("find.change", &p).unwrap()["count"], 1);
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "b1 a2 | a3");
+ }
+
+ #[test]
+ fn find_scope_selection_retains_nonempty_hits_count_change_and_native_text() {
+ for (a, b) in [(0, 7), (7, 0)] {
+ let (mut s, sid) = scope_session("red red | red");
+ scope_select(&mut s, sid, a, b);
+ let p = json!({"find": "red", "change": "blue", "scope": "selection", "attrs": {"fontStyle": "Italic"}});
+ let before = s.doc().unwrap().doc.clone();
+ let selection = s.doc().unwrap().selection.clone();
+ let revision = s.doc().unwrap().revision;
+ let history = s.doc().unwrap().history.undo.len();
+ let strong = std::sync::Arc::strong_count(&before);
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 2);
+ assert_eq!(s.doc().unwrap().selection, selection);
+ assert_eq!(s.doc().unwrap().revision, revision);
+ assert_eq!(std::sync::Arc::strong_count(&before), strong, "search stores weak document identity");
+ scope_hit(&mut s, &p, sid, 0, 3);
+ scope_hit(&mut s, &p, sid, 4, 7);
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 2);
+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
+ assert_eq!(s.doc().unwrap().history.undo.len(), history);
+ assert_eq!(s.execute("find.change", &p).unwrap()["count"], 2);
+ let changed = s.doc().unwrap().doc.story(sid).unwrap().clone();
+ assert_eq!(changed.text, "blue blue | red");
+ assert_eq!(changed.char_format_at(0).over.font_style.as_deref(), Some("Italic"));
+ assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);
+ assert!(s.find_context.is_none());
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");
+ assert!(s.find_context.is_none());
+ s.execute("edit.redo", &json!({})).unwrap();
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap(), &changed);
+ let native = s.execute("file.serialize", &json!({})).unwrap();
+ s.execute("file.openBytes", &json!({"name": "scope.designcraft", "base64": native["base64"]})).unwrap();
+ assert_eq!(serde_json::to_value(s.doc().unwrap().doc.story(sid).unwrap()).unwrap(), serde_json::to_value(&changed).unwrap());
+ assert!(s.find_context.is_none());
+ }
+ }
+
+ #[test]
+ fn find_scope_matcher_restart_replacement_continuation_and_external_reselection() {
+ let (mut s, sid) = scope_session("red blue red | blue red");
+ scope_select(&mut s, sid, 0, 12);
+ let mut p = json!({"find": "red", "scope": "selection", "change": "one"});
+ scope_hit(&mut s, &p, sid, 0, 3);
+ p["change"] = json!("two");
+ p["attrs"] = json!({"fontStyle": "Italic"});
+ scope_hit(&mut s, &p, sid, 9, 12);
+ p["find"] = json!("blue");
+ scope_hit(&mut s, &p, sid, 4, 8);
+ p["find"] = json!("red");
+ scope_hit(&mut s, &p, sid, 0, 3);
+ p["caseSensitive"] = json!(true);
+ scope_hit(&mut s, &p, sid, 0, 3);
+ p["grep"] = json!(true);
+ scope_hit(&mut s, &p, sid, 0, 3); // GREP alone changes matcher identity.
+ p["find"] = json!("r.d");
+ scope_hit(&mut s, &p, sid, 0, 3);
+ p["wholeWord"] = json!(true);
+ scope_hit(&mut s, &p, sid, 0, 3);
+ let hit = s.doc().unwrap().selection.text.unwrap();
+ scope_select(&mut s, sid, hit.anchor, hit.focus);
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 1, "same-range external reselection starts a new domain");
+ scope_hit(&mut s, &p, sid, 0, 3);
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);
+ scope_select(&mut s, sid, 20, 23);
+ p["find"] = json!("red");
+ scope_hit(&mut s, &p, sid, 20, 23);
+ }
+
+ #[test]
+ fn find_scope_word_reselection_at_same_hit_recaptures_bounds() {
+ let (mut s, sid) = scope_session("red red | red");
+ scope_select(&mut s, sid, 0, 7);
+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 2);
+ scope_hit(&mut s, &p, sid, 0, 3);
+ let selected = s.doc().unwrap().selection.clone();
+ let frame = selected.text.unwrap().frame.unwrap();
+ let point = {
+ let st = s.doc().unwrap();
+ let cs = s.cache.get(&st.doc, sid, None);
+ let (fi, x, baseline, ascent, _) = designcraft_compose::caret(&cs, 1).unwrap();
+ let inner = designcraft_geom::Point::new(x, baseline - ascent * 0.5);
+ assert_eq!(cs.frames[fi].frame, frame);
+ assert_eq!(designcraft_compose::hit(&cs, fi, inner), Some(1), "real point lies inside the current hit");
+ let loc = st.doc.find(frame).unwrap();
+ st.doc.parent_xf(&loc) * st.doc.text_xf(st.doc.item(frame).unwrap()) * inner
+ };
+ let before = s.doc().unwrap().doc.clone();
+ let revision = s.doc().unwrap().revision;
+ let history = s.doc().unwrap().history.undo.len();
+ s.execute("text.selectWord", &json!({"frame": frame.0, "point": [point.x, point.y]})).unwrap();
+ assert!(s.text_drag, "exercise place's in-selection early return");
+ assert_eq!(s.doc().unwrap().selection, selected, "same full selection, including frame");
+ assert_eq!(s.doc().unwrap().revision, revision + 1);
+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
+ assert_eq!(s.doc().unwrap().history.undo.len(), history);
+ assert!(s.find_context.is_none());
+ assert_eq!(s.execute("find.find", &p).unwrap(), json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));
+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 1}));
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");
+ assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");
+ s.execute("edit.redo", &json!({})).unwrap();
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");
+ }
+
+ #[test]
+ fn find_scope_story_explicit_story_document_order_and_scope_changes() {
+ let (mut s, a) = scope_session("black red");
+ let other = s.execute("frame.create", &json!({"rect": [150, 36, 100, 100], "content": "text", "text": "red"})).unwrap();
+ let b = designcraft_doc::StoryId(other["story"].as_u64().unwrap());
+ scope_select(&mut s, a, 0, 9);
+ let story = json!({"find": "red", "scope": "story"});
+ assert_eq!(s.execute("find.next", &story).unwrap(), serde_json::Value::Null, "Story does not enter B or wrap to its prefix");
+ scope_select(&mut s, b, 0, 0);
+ let explicit = json!({"find": "black", "story": a.0, "scope": "selection"});
+ scope_hit(&mut s, &explicit, a, 0, 5);
+ let selection = s.doc().unwrap().selection.clone();
+ assert!(s.execute("find.next", &json!({"find": "red", "story": u64::MAX})).is_err());
+ assert_eq!(s.doc().unwrap().selection, selection);
+ scope_select(&mut s, a, 0, 9);
+ scope_hit(&mut s, &json!({"find": "red"}), b, 0, 3);
+ let counted = s.execute("find.find", &json!({"find": "red"})).unwrap();
+ assert_eq!(counted[0]["story"], a.0, "Count retains canonical story order");
+ assert_eq!(counted[1]["story"], b.0);
+ scope_select(&mut s, a, 0, 9);
+ scope_hit(&mut s, &json!({"find": "red", "scope": "selection"}), a, 6, 9);
+ assert_eq!(s.execute("find.next", &story).unwrap(), serde_json::Value::Null, "scope change uses the current caret");
+ s.execute("selection.set", &json!({"ids": []})).unwrap();
+ for command in ["find.find", "find.next", "find.change"] {
+ assert!(s.execute(command, &json!({"find": "red", "change": "blue", "scope": "selection"})).is_err());
+ }
+ }
+
+ #[test]
+ fn find_scope_substring_context_utf8_zero_width_and_invalid_ranges() {
+ let (mut s, sid) = scope_session("scat é🙂 red");
+ scope_select(&mut s, sid, 1, 4);
+ let p = json!({"find": "cat", "wholeWord": true, "scope": "selection"});
+ scope_hit(&mut s, &p, sid, 1, 4);
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 1);
+ scope_select(&mut s, sid, 1, 4);
+ let p = json!({"find": "^c|^a", "grep": true, "scope": "selection"});
+ scope_hit(&mut s, &p, sid, 1, 2);
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null, "cursor does not redefine ^");
+ scope_select(&mut s, sid, 5, 11);
+ let empty = json!({"find": "(?:)", "grep": true, "scope": "selection"});
+ for pos in [5, 7, 11] {
+ scope_hit(&mut s, &empty, sid, pos, pos);
+ }
+ for _ in 0..2 {
+ assert_eq!(s.execute("find.next", &empty).unwrap(), serde_json::Value::Null);
+ }
+ assert_eq!(s.execute("find.find", &empty).unwrap().as_array().unwrap().len(), 3);
+ scope_select(&mut s, sid, 7, 7);
+ scope_hit(&mut s, &empty, sid, 7, 7);
+ assert_eq!(s.execute("find.next", &empty).unwrap(), serde_json::Value::Null);
+ scope_select(&mut s, sid, 12, 15);
+ let nonempty = json!({"find": "red", "change": "blue", "scope": "selection"});
+ scope_hit(&mut s, &nonempty, sid, 12, 15);
+ assert_eq!(s.execute("find.change", &nonempty).unwrap()["count"], 1);
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "scat é🙂 blue");
+ for range in [6..7, 0..usize::MAX] {
+ let st = s.doc_mut().unwrap();
+ st.selection = designcraft_doc::Selection::text(designcraft_doc::TextSel {
+ story: sid,
+ anchor: range.start,
+ focus: range.end,
+ frame: None,
+ cell: None,
+ });
+ st.revision += 1;
+ for command in ["find.find", "find.next", "find.change"] {
+ let before = s.doc().unwrap().doc.clone();
+ let err = s.execute(command, &json!({"find": "x", "change": "y", "scope": "selection"})).unwrap_err();
+ assert!(matches!(err, crate::EngineError::BadParams { .. }), "{err}");
+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
+ }
+ }
+ }
+
+ #[test]
+ fn find_scope_invalid_query_keeps_continuation_and_cross_boundary_nonmatches() {
+ let (mut s, sid) = scope_session("red red | red");
+ scope_select(&mut s, sid, 0, 7);
+ let p = json!({"find": "red", "scope": "selection"});
+ scope_hit(&mut s, &p, sid, 0, 3);
+ let selected = s.doc().unwrap().selection.clone();
+ assert!(s.execute("find.next", &json!({"find": "[", "grep": true, "scope": "selection"})).is_err());
+ assert_eq!(s.doc().unwrap().selection, selected);
+ scope_hit(&mut s, &p, sid, 4, 7);
+ assert_eq!(s.execute("find.find", &json!({"find": "red |", "scope": "selection"})).unwrap(), json!([]));
+ }
+
+ #[test]
+ fn find_scope_document_switch_edit_and_reset() {
+ let (mut s, sid) = scope_session("red red | red");
+ scope_select(&mut s, sid, 0, 7);
+ let p = json!({"find": "red", "scope": "selection"});
+ scope_hit(&mut s, &p, sid, 0, 3);
+ s.execute("file.new", &json!({})).unwrap();
+ s.set_active(0);
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 1);
+ scope_select(&mut s, sid, 0, 7);
+ scope_hit(&mut s, &p, sid, 0, 3);
+ s.execute("story.setText", &json!({"story": sid.0, "text": "red"})).unwrap();
+ assert!(s.find_context.is_none());
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 1);
+ s.reset_find_scope();
+ assert!(s.find_context.is_none());
+ }
+
+ #[test]
+ fn find_scope_real_preview_restores_before_resolving_bounds() {
+ let (mut s, sid) = scope_session("");
+ s.execute(
+ "data.source.select",
+ &json!({
+ "bytes": crate::cmd::base64_encode(b"x\nred red | red\n"), "name": "scope.csv"
+ }),
+ )
+ .unwrap();
+ s.execute("data.placeholder.add", &json!({"field": "x", "story": sid.0, "at": 0})).unwrap();
+ let template = s.doc().unwrap().doc.clone();
+ assert_eq!(template.story(sid).unwrap().text, "<<x>>");
+ s.execute("data.preview", &json!({"record": 1})).unwrap();
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");
+ // Install a viewport selection in the real preview. text.select is journaled
+ // and would itself restore the template before selecting.
+ let st = s.doc_mut().unwrap();
+ st.selection = designcraft_doc::Selection::text(designcraft_doc::TextSel { story: sid, anchor: 0, focus: 7, frame: None, cell: None });
+ st.revision += 1;
+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 2);
+ let history = s.doc().unwrap().history.undo.len();
+ let err = s.execute("find.change", &p).unwrap_err();
+ assert!(matches!(err, crate::EngineError::BadParams { .. }), "{err}");
+ assert!(std::sync::Arc::ptr_eq(&template, &s.doc().unwrap().doc));
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "<<x>>");
+ assert_eq!(s.doc().unwrap().history.undo.len(), history);
+ assert!(s.doc().unwrap().preview_stash.is_none());
+ assert!(s.find_context.is_none());
+ // Valid fresh bounds are allowed after restoration; no cached preview range
+ // survives. A document query can see the preview, but Next sees the template.
+ s.execute("data.preview", &json!({"record": 1})).unwrap();
+ let document = json!({"find": "red"});
+ assert_eq!(s.execute("find.find", &document).unwrap().as_array().unwrap().len(), 3);
+ assert_eq!(s.execute("find.next", &document).unwrap(), serde_json::Value::Null);
+ assert!(std::sync::Arc::ptr_eq(&template, &s.doc().unwrap().doc));
+ assert_eq!(s.execute("find.find", &document).unwrap(), json!([]));
+ assert_eq!(s.doc().unwrap().history.undo.len(), history);
+ }
+
+ fn child_scope_session(note: bool, child: &str) -> (Session, designcraft_doc::StoryId, designcraft_doc::TextSel) {
+ let (mut s, sid) = scope_session("red");
+ scope_select(&mut s, sid, 3, 3);
+ if note {
+ s.execute("footnote.insert", &json!({"text": child})).unwrap();
+ } else {
+ s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap();
+ s.execute("text.insert", &json!({"text": child, "raw": true})).unwrap();
+ }
+ let selected = s.doc().unwrap().selection.text.unwrap();
+ (s, sid, selected)
+ }
+
+ #[test]
+ fn find_scope_children_error_atomically_and_parent_requests_stay_top_level() {
+ for note in [false, true] {
+ for child in ["red", "red x", "é red red red red red"] {
+ let (mut s, sid, mut selected) = child_scope_session(note, child);
+ selected.anchor = 0;
+ selected.focus = child.len();
+ s.doc_mut().unwrap().selection = designcraft_doc::Selection::text(selected);
+ let before = s.doc().unwrap().doc.clone();
+ let selection = s.doc().unwrap().selection.clone();
+ let history = s.doc().unwrap().history.undo.len();
+ let revision = s.doc().unwrap().revision;
+ let journal = s.journal.clone();
+ for scope in ["story", "selection"] {
+ for command in ["find.find", "find.next", "find.change"] {
+ let err = s.execute(command, &json!({"find": "red", "change": "blue", "scope": scope})).unwrap_err();
+ assert!(matches!(err, crate::EngineError::BadParams { .. }), "{err}");
+ assert!(err.to_string().contains("not supported"));
+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
+ assert_eq!(s.doc().unwrap().selection, selection);
+ assert_eq!(s.doc().unwrap().history.undo.len(), history);
+ assert_eq!(s.doc().unwrap().revision, revision);
+ assert_eq!(s.journal, journal);
+ }
+ }
+ for explicit in [false, true] {
+ let mut p = json!({"find": "red", "change": "blue"});
+ if explicit {
+ p["story"] = json!(sid.0);
+ p["scope"] = json!("selection");
+ }
+ s.doc_mut().unwrap().selection = selection.clone();
+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 1);
+ scope_hit(&mut s, &p, sid, 0, 3);
+ s.doc_mut().unwrap().selection = selection.clone();
+ assert_eq!(s.execute("find.change", &p).unwrap()["count"], 1);
+ assert_eq!(s.doc().unwrap().doc.text_story(sid, selected.cell).unwrap().text, child);
+ assert_eq!(s.doc().unwrap().selection, selection, "parent replacement does not clamp child offsets");
+ p["find"] = json!("blue");
+ p["change"] = json!("red");
+ s.execute("find.change", &p).unwrap();
+ }
+ }
+ }
+ let (mut s, _, _) = child_scope_session(false, "red");
+ s.execute("table.selectTable", &json!({})).unwrap();
+ for scope in ["story", "selection"] {
+ for command in ["find.find", "find.next", "find.change"] {
+ assert!(
+ s.execute(command, &json!({"find": "red", "change": "blue", "scope": scope})).unwrap_err().to_string().contains("not supported")
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn find_scope_threaded_overset_story_uses_logical_offsets() {
+ let text = format!("{}red", "word ".repeat(100));
+ let (mut s, sid) = scope_session(&text);
+ let a = s.doc().unwrap().doc.story(sid).unwrap().frames[0];
+ let next = s.execute("frame.create", &json!({"rect": [150, 36, 20, 1], "content": "text"})).unwrap();
+ let b = designcraft_doc::ItemId(next["id"].as_u64().unwrap());
+ s.edit(|d, _| Ok(d.thread(a, b)?)).unwrap();
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().frames.len(), 2);
+ scope_select(&mut s, sid, 0, 0);
+ scope_hit(&mut s, &json!({"find": "red", "scope": "story"}), sid, 500, 503);
+ assert_eq!(s.execute("find.next", &json!({"find": "red", "scope": "story"})).unwrap(), serde_json::Value::Null);
+ }
+
+ #[test]
+ fn find_scope_zero_width_story_explicit_and_document_endpoints_terminate() {
+ for scope in ["story", "explicit", "document"] {
+ let (mut s, sid) = scope_session("é🙂");
+ scope_select(&mut s, sid, 0, 0);
+ let mut p = json!({"find": "(?:)", "grep": true, "scope": scope});
+ if scope == "explicit" {
+ p["story"] = json!(sid.0);
+ }
+ for pos in [0, 2, 6] {
+ scope_hit(&mut s, &p, sid, pos, pos);
+ }
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);
+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);
+ }
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn find_scope_revert_releases_context_with_same_document_uid() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("scope.designcraft");
+ let (mut s, sid) = scope_session("red red | red");
+ s.execute("file.save", &json!({"path": path.to_string_lossy()})).unwrap();
+ scope_select(&mut s, sid, 0, 7);
+ let p = json!({"find": "red", "scope": "selection"});
+ scope_hit(&mut s, &p, sid, 0, 3);
+ let uid = s.doc().unwrap().uid;
+ s.execute("story.setText", &json!({"story": sid.0, "text": "red red"})).unwrap();
+ scope_select(&mut s, sid, 0, 7);
+ scope_hit(&mut s, &p, sid, 0, 3);
+ s.execute("file.revert", &json!({})).unwrap();
+ assert_eq!(s.doc().unwrap().uid, uid);
+ assert!(s.find_context.is_none());
+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");
+ assert!(s.execute("find.find", &p).is_err(), "revert's empty selection cannot inherit a previous range");
+ }
}
/// Objects matching Find/Change › Object criteria, in document order (nested ones included).
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index 31e4544f4..a0a6ac32c 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -15,7 +15,8 @@ mod editorial;
mod endnotes;
mod export;
mod file;
-mod find;
+pub(crate) mod find;
+pub use find::same_find_domain;
mod fonts;
mod guides;
mod index;
diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs
index b57e9e88a..9c05ecfae 100644
--- a/crates/engine/src/cmd/text.rs
+++ b/crates/engine/src/cmd/text.rs
@@ -29,6 +29,8 @@ pub fn specs() -> Vec<CommandSpec> {
let text = &st.doc.text_story(t.story, t.cell).map(|x| x.text.clone()).unwrap_or_default();
let (a, b) = word_bounds(text, t.focus);
st.selection.text = Some(TextSel { anchor: a, focus: b, ..t });
+ // A word reselection is external even when place kept the same range for dragging.
+ st.revision = st.revision.wrapping_add(1);
ok()
}),
cmd!(noundo "text.selectSentence", "Select Sentence", [], None, "{frame, point} — the sentence under the point (triple click)", has_doc, |s, p| {
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index caeeb80ba..3064592f0 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -260,6 +260,7 @@ pub struct Session {
pub cache: Arc<Cache>,
pub(crate) tool: Box<dyn designcraft_tools::Tool>,
pub journal: Vec<(String, Value)>,
+ pub(crate) find_context: Option<cmd::find::FindContext>,
pub clipboard: Option<Arc<Document>>,
/// Crash-recovery folder (the app sets it; saving or closing a document removes its entry).
pub recovery_dir: Option<std::path::PathBuf>,
@@ -300,6 +301,7 @@ impl Session {
cache: Arc::new(Cache::new()),
tool: designcraft_tools::create("selection"),
journal: vec![],
+ find_context: None,
clipboard: None,
recovery_dir: None,
text_clipboard: None,
@@ -358,13 +360,26 @@ impl Session {
pub fn doc_mut(&mut self) -> Result<&mut DocState> {
self.active_mut().ok_or(EngineError::NoDocument)
}
+ /// Release the transient Find/Change domain when its caller starts or closes a search.
+ pub fn reset_find_scope(&mut self) {
+ self.find_context = None;
+ }
+
+ fn discard_stale_find_scope(&mut self) {
+ if self.find_context.as_ref().is_some_and(|c| self.active().is_none_or(|st| !c.is_current(st))) {
+ self.reset_find_scope();
+ }
+ }
+
pub fn set_active(&mut self, i: usize) {
if i < self.docs.len() && self.active != Some(i) {
+ self.reset_find_scope();
self.stop_data_preview();
self.active = Some(i);
}
}
pub fn add_document(&mut self, d: DocState) -> usize {
+ self.reset_find_scope();
self.stop_data_preview();
self.docs.push(d);
self.active = Some(self.docs.len() - 1);
@@ -388,6 +403,7 @@ impl Session {
recovery::discard_document(self, i, recovery_dir.as_deref());
}
if i < self.docs.len() {
+ self.reset_find_scope();
self.docs.remove(i);
self.active = if self.docs.is_empty() { None } else { Some(i.min(self.docs.len() - 1)) };
}
@@ -418,6 +434,8 @@ impl Session {
if id != "data.preview" && (spec.undoable || spec.journal) {
self.stop_data_preview();
}
+ // Preview restoration can replace the document before a Find handler resolves bounds.
+ self.discard_stale_find_scope();
let before = self.active().map(|d| (d.uid, d.doc.clone()));
let r = (spec.run)(self, params)?;
// Undo, redo or deleting layers can take the active layer away: new objects would land on
@@ -455,6 +473,7 @@ impl Session {
if spec.journal {
self.journal.push((id.to_string(), params.clone()));
}
+ self.discard_stale_find_scope();
Ok(r)
}
@@ -542,6 +561,7 @@ impl Session {
st.doc = Arc::new(doc);
st.selection = sel;
st.revision += 1;
+ self.reset_find_scope();
Ok(r)
}
}
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 5a4de0058..c66bc9272 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -288,13 +288,19 @@ pub fn handle(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest) ->
"ui.dialog.set" => match app.ui.dialog.as_mut() {
Some(d) => {
let Some(f) = s("field") else { return err("missing `field`") };
- d.fields.insert(f.to_string(), p.get("value").cloned().unwrap_or(Value::Null));
+ let value = p.get("value").cloned().unwrap_or(Value::Null);
+ if d.set_field(f, value) {
+ app.session.reset_find_scope();
+ }
ok(serde_json::to_value(&*d).unwrap_or_default())
}
None => err("no dialog open"),
},
"ui.dialog.open" => {
let Some(id) = s("id") else { return err("missing `id`") };
+ if id == "findChange" || app.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange") {
+ app.session.reset_find_scope();
+ }
let d = crate::dialogs::Dialog::new(id, p.get("fields").cloned().unwrap_or(Value::Null));
let v = serde_json::to_value(&d).unwrap_or_default();
app.ui.dialog = Some(d);
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 695a66af1..396cd2500 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -77,6 +77,16 @@ impl Dialog {
}
Dialog { id: id.into(), fields }
}
+ /// Set a field and report a genuine Find domain/mode transition to the caller.
+ pub(crate) fn set_field(&mut self, key: &str, value: Value) -> bool {
+ let before =
+ (self.id == "findChange" && matches!(key, "scope" | "story" | "objectMode")).then(|| (self.b("objectMode"), find_change_params(self)));
+ self.fields.insert(key.into(), value);
+ before.is_some_and(|(object_mode, params)| {
+ object_mode != self.b("objectMode") || !designcraft_engine::cmd::same_find_domain(&params, &find_change_params(self))
+ })
+ }
+
fn s(&self, k: &str) -> String {
match self.fields.get(k) {
Some(Value::String(s)) => s.clone(),
@@ -1181,536 +1191,640 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
// forms remain reachable at large UI scales, without shrinking their text.
let footer_height = ui.spacing().interact_size.y.max(ui.text_style_height(&egui::TextStyle::Button) + 2.0 * ui.spacing().button_padding.y);
let body_height = (available.y - ui.min_size().y - footer_height - 12.0 - 2.0 * ui.spacing().item_spacing.y).max(1.0);
- egui::ScrollArea::both().id_salt(("dialog_body", &d.id)).min_scrolled_width(1.0).min_scrolled_height(1.0).max_width(width).max_height(body_height).show(ui, |ui| {
- match d.id.as_str() {
- "newDocument" => {
- ui.horizontal(|ui| {
- ui.with_layout(if crate::i18n::is_rtl(&app.ui.language) { egui::Layout::right_to_left(egui::Align::Center) } else { egui::Layout::left_to_right(egui::Align::Center) }, |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Preset"));
- let cur = d.s("preset");
- egui::ComboBox::from_id_salt("preset").selected_text(&cur).width(180.0).show_ui(ui, |ui| {
- for p in designcraft_doc::build::PRESETS {
- if ui.selectable_label(cur == p.name, p.name).clicked() {
- d.fields.insert("preset".into(), json!(p.name));
- d.fields.insert("width".into(), json!(format_measure(p.width, p.units)));
- d.fields.insert("height".into(), json!(format_measure(p.height, p.units)));
- d.fields.insert("facingPages".into(), json!(p.intent == designcraft_doc::Intent::Print));
- }
+ egui::ScrollArea::both()
+ .id_salt(("dialog_body", &d.id))
+ .min_scrolled_width(1.0)
+ .min_scrolled_height(1.0)
+ .max_width(width)
+ .max_height(body_height)
+ .show(ui, |ui| match d.id.as_str() {
+ "newDocument" => {
+ ui.horizontal(|ui| {
+ ui.with_layout(
+ if crate::i18n::is_rtl(&app.ui.language) {
+ egui::Layout::right_to_left(egui::Align::Center)
+ } else {
+ egui::Layout::left_to_right(egui::Align::Center)
+ },
+ |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Preset"));
+ let cur = d.s("preset");
+ egui::ComboBox::from_id_salt("preset").selected_text(&cur).width(180.0).show_ui(ui, |ui| {
+ for p in designcraft_doc::build::PRESETS {
+ if ui.selectable_label(cur == p.name, p.name).clicked() {
+ d.fields.insert("preset".into(), json!(p.name));
+ d.fields.insert("width".into(), json!(format_measure(p.width, p.units)));
+ d.fields.insert("height".into(), json!(format_measure(p.height, p.units)));
+ d.fields.insert("facingPages".into(), json!(p.intent == designcraft_doc::Intent::Print));
+ }
+ }
+ });
+ },
+ );
+ });
+ if crate::i18n::is_rtl(&app.ui.language) {
+ // egui Grid currently supports LTR only. Use explicit RTL rows;
+ // the numeric editors retain LTR alignment and logical values.
+ for (first, key, second, other, toggle) in [
+ ("Width", "width", "Height", "height", false),
+ ("Pages", "pages", "Facing Pages", "facingPages", true),
+ ("Columns", "columns", "Gutter", "gutter", false),
+ ("Top", "marginTop", "Bottom", "marginBottom", false),
+ ("Inside", "marginInside", "Outside", "marginOutside", false),
+ ("Bleed", "bleed", "Primary Text Frame", "primaryTextFrame", true),
+ ] {
+ ui.horizontal(|ui| {
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, first));
+ text_field(ui, &mut d, key, 80.0);
+ if toggle {
+ check(ui, &mut d, other, crate::i18n::tr(&app.ui.language, second));
+ } else {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, second));
+ text_field(ui, &mut d, other, 80.0);
+ }
+ });
+ });
}
+ } else {
+ egui::Grid::new("nd").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Width"));
+ text_field(ui, &mut d, "width", 80.0);
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Height"));
+ text_field(ui, &mut d, "height", 80.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Pages"));
+ text_field(ui, &mut d, "pages", 80.0);
+ ui.label("");
+ check(ui, &mut d, "facingPages", crate::i18n::tr(&app.ui.language, "Facing Pages"));
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Columns"));
+ text_field(ui, &mut d, "columns", 80.0);
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Gutter"));
+ text_field(ui, &mut d, "gutter", 80.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Top"));
+ text_field(ui, &mut d, "marginTop", 80.0);
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Bottom"));
+ text_field(ui, &mut d, "marginBottom", 80.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Inside"));
+ text_field(ui, &mut d, "marginInside", 80.0);
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Outside"));
+ text_field(ui, &mut d, "marginOutside", 80.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Bleed"));
+ text_field(ui, &mut d, "bleed", 80.0);
+ ui.label("");
+ check(ui, &mut d, "primaryTextFrame", crate::i18n::tr(&app.ui.language, "Primary Text Frame"));
+ ui.end_row();
+ });
+ }
+ }
+ "frameSize" => {
+ egui::Grid::new("fs").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Width"));
+ text_field(ui, &mut d, "width", 90.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Height"));
+ text_field(ui, &mut d, "height", 90.0);
+ ui.end_row();
});
+ }
+ "findChange" => {
+ ui.horizontal(|ui| {
+ for (label, grep) in [("Text", false), ("GREP", true)] {
+ if ui
+ .selectable_label(
+ !d.b("objectMode") && d.b("grep") == grep,
+ crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label)),
+ )
+ .clicked()
+ {
+ if d.set_field("objectMode", json!(false)) {
+ app.session.reset_find_scope();
+ }
+ d.fields.insert("grep".into(), json!(grep));
+ }
+ }
+ if ui.selectable_label(d.b("objectMode"), crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Object"))).clicked()
+ && d.set_field("objectMode", json!(true))
+ {
+ app.session.reset_find_scope();
+ }
});
- });
- if crate::i18n::is_rtl(&app.ui.language) {
- // egui Grid currently supports LTR only. Use explicit RTL rows;
- // the numeric editors retain LTR alignment and logical values.
- for (first, key, second, other, toggle) in [
- ("Width", "width", "Height", "height", false),
- ("Pages", "pages", "Facing Pages", "facingPages", true),
- ("Columns", "columns", "Gutter", "gutter", false),
- ("Top", "marginTop", "Bottom", "marginBottom", false),
- ("Inside", "marginInside", "Outside", "marginOutside", false),
- ("Bleed", "bleed", "Primary Text Frame", "primaryTextFrame", true),
- ] {
+ if d.b("objectMode") {
+ // Find/Change › Object: objects by fill and kind; change their fill or opacity.
+ let swatches: Vec<String> = app
+ .session
+ .active()
+ .map(|st| st.doc.swatches.iter().filter(|w| !w.hidden).map(|w| w.name.clone()).collect())
+ .unwrap_or_default();
+ egui::Grid::new("fco").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ for (key, label, any) in [("objFill", "Find fill:", "(any)"), ("objChangeFill", "Change fill to:", "(unchanged)")] {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, label));
+ let cur = d.s(key);
+ egui::ComboBox::from_id_salt(key)
+ .selected_text(if cur.is_empty() { any } else { cur.as_str() })
+ .width(180.0)
+ .show_ui(ui, |ui| {
+ if ui
+ .selectable_label(cur.is_empty(), crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, any)))
+ .clicked()
+ {
+ d.fields.insert(key.into(), json!(""));
+ }
+ for w in &swatches {
+ if ui.selectable_label(*w == cur, w).clicked() {
+ d.fields.insert(key.into(), json!(w));
+ }
+ }
+ });
+ ui.end_row();
+ }
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Kind:"));
+ let cur = d.s("objKind");
+ egui::ComboBox::from_id_salt("objKind").selected_text(if cur.is_empty() { "(any)" } else { cur.as_str() }).show_ui(
+ ui,
+ |ui| {
+ for v in ["", "text", "graphic", "shape", "line", "group"] {
+ if ui
+ .selectable_label(
+ cur == v,
+ crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, if v.is_empty() { "(any)" } else { v })),
+ )
+ .clicked()
+ {
+ d.fields.insert("objKind".into(), json!(v));
+ }
+ }
+ },
+ );
+ ui.end_row();
+ });
+ let mut crit = json!({});
+ if !d.s("objFill").is_empty() {
+ crit["fill"] = json!(d.s("objFill"));
+ }
+ if !d.s("objKind").is_empty() {
+ crit["kind"] = json!(d.s("objKind"));
+ }
ui.horizontal(|ui| {
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, first));
- text_field(ui, &mut d, key, 80.0);
- if toggle {
- check(ui, &mut d, other, crate::i18n::tr(&app.ui.language, second));
- } else {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, second));
- text_field(ui, &mut d, other, 80.0);
- }
- });
+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Find All"))).clicked() {
+ let n = app.run("find.objects", crit.clone()).ok().and_then(|r| r["ids"].as_array().map(Vec::len)).unwrap_or(0);
+ d.fields.insert("status".into(), json!(format!("{n} found")));
+ }
+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Change All"))).clicked()
+ && !d.s("objChangeFill").is_empty()
+ {
+ let mut p = crit.clone();
+ p["change"] = json!({"fill": d.s("objChangeFill")});
+ let n = app.run("find.changeObjects", p).ok().and_then(|r| r["changed"].as_u64()).unwrap_or(0);
+ d.fields.insert("status".into(), json!(format!("{n} changed")));
+ }
});
+ ui.label(d.s("status"));
+ } else {
+ egui::Grid::new("fc").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Find what:"));
+ text_field(ui, &mut d, "find", 260.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Change to:"));
+ text_field(ui, &mut d, "change", 260.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Search:"));
+ let cur = d.s("scope");
+ egui::ComboBox::from_id_salt("fcscope")
+ .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, &cur)))
+ .show_ui(ui, |ui| {
+ for v in ["document", "story", "selection"] {
+ if ui.selectable_label(cur == v, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, v))).clicked()
+ && d.set_field("scope", json!(v))
+ {
+ app.session.reset_find_scope();
+ }
+ }
+ });
+ ui.end_row();
+ });
+ ui.horizontal(|ui| {
+ check(ui, &mut d, "caseSensitive", crate::i18n::tr(&app.ui.language, "Case sensitive"));
+ check(ui, &mut d, "wholeWord", crate::i18n::tr(&app.ui.language, "Whole word"));
+ });
+ ui.horizontal(|ui| {
+ let params0 = find_change_params(&d);
+ let params = || params0.clone();
+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Find Next"))).clicked() {
+ let r = app.run("find.next", params());
+ let msg = match r {
+ Ok(Value::Null) => "No matches".to_string(),
+ Ok(_) => "Found".to_string(),
+ Err(e) => e,
+ };
+ d.fields.insert("status".into(), json!(msg));
+ }
+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Change All"))).clicked() {
+ let msg = match app.run("find.change", params()) {
+ Ok(v) => format!("{} replacement(s) made", v["count"]),
+ Err(e) => e,
+ };
+ d.fields.insert("status".into(), json!(msg));
+ }
+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Count"))).clicked() {
+ let msg = match app.run("find.find", params()) {
+ Ok(v) => format!("{} match(es)", v.as_array().map(|a| a.len()).unwrap_or(0)),
+ Err(e) => e,
+ };
+ d.fields.insert("status".into(), json!(msg));
+ }
+ });
+ if let Some(st) = d.fields.get("status").and_then(Value::as_str) {
+ ui.label(egui::RichText::new(st).color(crate::theme::Tokens::get(ui.ctx()).text_dim));
+ }
}
- } else {
- egui::Grid::new("nd").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Width"));
- text_field(ui, &mut d, "width", 80.0);
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Height"));
- text_field(ui, &mut d, "height", 80.0);
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Pages"));
- text_field(ui, &mut d, "pages", 80.0);
- ui.label("");
- check(ui, &mut d, "facingPages", crate::i18n::tr(&app.ui.language, "Facing Pages"));
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Columns"));
- text_field(ui, &mut d, "columns", 80.0);
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Gutter"));
- text_field(ui, &mut d, "gutter", 80.0);
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Top"));
- text_field(ui, &mut d, "marginTop", 80.0);
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Bottom"));
- text_field(ui, &mut d, "marginBottom", 80.0);
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Inside"));
- text_field(ui, &mut d, "marginInside", 80.0);
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Outside"));
- text_field(ui, &mut d, "marginOutside", 80.0);
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Bleed"));
- text_field(ui, &mut d, "bleed", 80.0);
- ui.label("");
- check(ui, &mut d, "primaryTextFrame", crate::i18n::tr(&app.ui.language, "Primary Text Frame"));
- ui.end_row();
- });
}
- }
- "frameSize" => {
- egui::Grid::new("fs").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Width"));
- text_field(ui, &mut d, "width", 90.0);
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Height"));
- text_field(ui, &mut d, "height", 90.0);
- ui.end_row();
- });
- }
- "findChange" => {
- ui.horizontal(|ui| {
- for (label, grep) in [("Text", false), ("GREP", true)] {
- if ui.selectable_label(!d.b("objectMode") && d.b("grep") == grep, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).clicked() {
- d.fields.insert("grep".into(), json!(grep));
- d.fields.insert("objectMode".into(), json!(false));
- }
+ "paragraphStyleOptions" => paragraph_style_options(app, ui, &mut d),
+ "characterStyleOptions" => character_style_options(app, ui, &mut d),
+ "footnoteOptions" => footnote_options(app, ui, &mut d),
+ "paragraphRules" => {
+ let current = d.fields.get("current").cloned().unwrap_or_default();
+ paragraph_rules(app, ui, &mut d, "", &current);
+ }
+ "insertXref" => insert_xref(app, ui, &mut d),
+ "findFont" => find_font(app, ui, &mut d),
+ "colorPicker" => color_picker(ui, &mut d),
+ "preferences" => preferences(app, ui, &mut d, body_height),
+ "print" => print_dialog(app, ui, &mut d),
+ "pdfImport" => {
+ ui.label(egui::RichText::new(if d.b("async") { d.s("name") } else { d.s("path") }).size(11.0));
+ ui.horizontal(|ui| {
+ crate::rtl::label(
+ ui,
+ crate::i18n::tr(&app.ui.language, "Page (1–{count}):").replace("{count}", &d.n("pages").unwrap_or(1.0).to_string()),
+ );
+ text_field(ui, &mut d, "page", 60.0);
+ });
+ ui.horizontal(|ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Crop to:"));
+ let cur = d.s("crop");
+ let label = |v: &str| match v {
+ "trim" => crate::i18n::tr(&app.ui.language, "Trim"),
+ "bleed" => crate::i18n::tr(&app.ui.language, "Bleed"),
+ "art" => crate::i18n::tr(&app.ui.language, "Art"),
+ "media" => crate::i18n::tr(&app.ui.language, "Media"),
+ _ => crate::i18n::tr(&app.ui.language, "Crop"),
+ };
+ egui::ComboBox::from_id_salt("pdf_crop").selected_text(crate::rtl::widget(ui, label(&cur))).show_ui(ui, |ui| {
+ for v in ["crop", "trim", "bleed", "art", "media"] {
+ if ui.selectable_label(label(&cur) == label(v), label(v)).clicked() {
+ d.fields.insert("crop".into(), json!(v));
+ }
+ }
+ });
+ });
+ }
+ "layerOptions" => {
+ let mut layers = d.fields.get("layers").and_then(Value::as_array).cloned().unwrap_or_default();
+ if layers.is_empty() {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "This PDF has no layers."));
}
- if ui.selectable_label(d.b("objectMode"),crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Object"))).clicked() {
- d.fields.insert("objectMode".into(), json!(true));
+ for l in &mut layers {
+ let mut on = l["visible"].as_bool().unwrap_or(true);
+ if ui.checkbox(&mut on, l["name"].as_str().unwrap_or("")).changed() {
+ l["visible"] = json!(on);
+ }
}
- });
- if d.b("objectMode") {
- // Find/Change › Object: objects by fill and kind; change their fill or opacity.
- let swatches: Vec<String> = app.session.active().map(|st| st.doc.swatches.iter().filter(|w| !w.hidden).map(|w| w.name.clone()).collect()).unwrap_or_default();
- egui::Grid::new("fco").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
- for (key, label, any) in [("objFill", "Find fill:", "(any)"), ("objChangeFill", "Change fill to:", "(unchanged)")] {
+ d.fields.insert("layers".into(), json!(layers));
+ }
+ "colorSettings" => {
+ let profiles = d.fields.get("profiles").and_then(Value::as_array).cloned().unwrap_or_default();
+ egui::Grid::new("color_settings").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ for (key, label, kind) in [("rgb", "RGB:", "rgb"), ("cmyk", "CMYK:", "cmyk")] {
crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, label));
let cur = d.s(key);
- egui::ComboBox::from_id_salt(key).selected_text(if cur.is_empty() { any } else { cur.as_str() }).width(180.0).show_ui(ui, |ui| {
- if ui.selectable_label(cur.is_empty(), crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, any))).clicked() {
- d.fields.insert(key.into(), json!(""));
- }
- for w in &swatches {
- if ui.selectable_label(*w == cur, w).clicked() {
- d.fields.insert(key.into(), json!(w));
+ egui::ComboBox::from_id_salt(("ws", key)).selected_text(&cur).width(260.0).show_ui(ui, |ui| {
+ for pr in profiles.iter().filter(|p| p["kind"] == kind) {
+ let name = pr["name"].as_str().unwrap_or("");
+ if ui.selectable_label(name == cur, name).clicked() {
+ d.fields.insert(key.into(), json!(name));
}
}
});
ui.end_row();
}
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Kind:"));
- let cur = d.s("objKind");
- egui::ComboBox::from_id_salt("objKind").selected_text(if cur.is_empty() { "(any)" } else { cur.as_str() }).show_ui(ui, |ui| {
- for v in ["", "text", "graphic", "shape", "line", "group"] {
- if ui.selectable_label(cur == v, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, if v.is_empty() { "(any)" } else { v }))).clicked() {
- d.fields.insert("objKind".into(), json!(v));
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Intent:"));
+ let cur = d.s("intent");
+ egui::ComboBox::from_id_salt("ws_intent")
+ .selected_text(crate::rtl::widget(
+ ui,
+ crate::i18n::tr(&app.ui.language, designcraft_color::cms::Intent::parse(&cur).map_or("", |i| i.label())),
+ ))
+ .show_ui(ui, |ui| {
+ for i in designcraft_color::cms::Intent::ALL {
+ if ui
+ .selectable_label(i.id() == cur, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, i.label())))
+ .clicked()
+ {
+ d.fields.insert("intent".into(), json!(i.id()));
+ }
}
- }
- });
+ });
ui.end_row();
});
- let mut crit = json!({});
- if !d.s("objFill").is_empty() {
- crit["fill"] = json!(d.s("objFill"));
- }
- if !d.s("objKind").is_empty() {
- crit["kind"] = json!(d.s("objKind"));
- }
- ui.horizontal(|ui| {
- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Find All"))).clicked() {
- let n = app.run("find.objects", crit.clone()).ok().and_then(|r| r["ids"].as_array().map(Vec::len)).unwrap_or(0);
- d.fields.insert("status".into(), json!(format!("{n} found")));
- }
- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Change All"))).clicked() && !d.s("objChangeFill").is_empty() {
- let mut p = crit.clone();
- p["change"] = json!({"fill": d.s("objChangeFill")});
- let n = app.run("find.changeObjects", p).ok().and_then(|r| r["changed"].as_u64()).unwrap_or(0);
- d.fields.insert("status".into(), json!(format!("{n} changed")));
- }
- });
- ui.label(d.s("status"));
- } else {
- egui::Grid::new("fc").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Find what:"));
- text_field(ui, &mut d, "find", 260.0);
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Change to:"));
- text_field(ui, &mut d, "change", 260.0);
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Search:"));
- let cur = d.s("scope");
- egui::ComboBox::from_id_salt("fcscope").selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, &cur))).show_ui(ui, |ui| {
- for v in ["document", "story", "selection"] {
- if ui.selectable_label(cur == v, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, v))).clicked() {
- d.fields.insert("scope".into(), json!(v));
+ check(ui, &mut d, "bpc", crate::i18n::tr(&app.ui.language, "Use Black Point Compensation"));
+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Load Profile…"))).clicked()
+ && let Some(path) = app.services.pick_open.as_mut().and_then(|f| f("icc"))
+ {
+ match app.session.execute("color.loadProfile", &json!({"path": path})) {
+ Ok(_) => {
+ let f = app.session.execute("color.settings", &json!({})).unwrap_or_default();
+ d.fields.insert("profiles".into(), f["profiles"].clone());
}
+ Err(e) => app.status(format!("Color Settings: {e}")),
}
- });
- ui.end_row();
- });
- ui.horizontal(|ui| {
- check(ui, &mut d, "caseSensitive", crate::i18n::tr(&app.ui.language, "Case sensitive"));
- check(ui, &mut d, "wholeWord", crate::i18n::tr(&app.ui.language, "Whole word"));
- });
- ui.horizontal(|ui| {
- let params0 = json!({"find": d.s("find"), "change": d.s("change"), "grep": d.b("grep"), "caseSensitive": d.b("caseSensitive"), "wholeWord": d.b("wholeWord"), "scope": d.s("scope")});
- let params = || params0.clone();
- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Find Next"))).clicked() {
- let r = app.run("find.next", params());
- let msg = match r {
- Ok(Value::Null) => "No matches".to_string(),
- Ok(_) => "Found".to_string(),
- Err(e) => e,
- };
- d.fields.insert("status".into(), json!(msg));
- }
- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Change All"))).clicked() {
- let msg = match app.run("find.change", params()) {
- Ok(v) => format!("{} replacement(s) made", v["count"]),
- Err(e) => e,
- };
- d.fields.insert("status".into(), json!(msg));
- }
- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Count"))).clicked() {
- let msg = match app.run("find.find", params()) {
- Ok(v) => format!("{} match(es)", v.as_array().map(|a| a.len()).unwrap_or(0)),
- Err(e) => e,
- };
- d.fields.insert("status".into(), json!(msg));
}
- });
- if let Some(st) = d.fields.get("status").and_then(Value::as_str) {
- ui.label(egui::RichText::new(st).color(crate::theme::Tokens::get(ui.ctx()).text_dim));
}
- }
- }
- "paragraphStyleOptions" => paragraph_style_options(app, ui, &mut d),
- "characterStyleOptions" => character_style_options(app, ui, &mut d),
- "footnoteOptions" => footnote_options(app, ui, &mut d),
- "paragraphRules" => {
- let current = d.fields.get("current").cloned().unwrap_or_default();
- paragraph_rules(app, ui, &mut d, "", &current);
- }
- "insertXref" => insert_xref(app, ui, &mut d),
- "findFont" => find_font(app, ui, &mut d),
- "colorPicker" => color_picker(ui, &mut d),
- "preferences" => preferences(app, ui, &mut d, body_height),
- "print" => print_dialog(app, ui, &mut d),
- "pdfImport" => {
- ui.label(egui::RichText::new(if d.b("async") { d.s("name") } else { d.s("path") }).size(11.0));
- ui.horizontal(|ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Page (1–{count}):").replace("{count}", &d.n("pages").unwrap_or(1.0).to_string()));
- text_field(ui, &mut d, "page", 60.0);
- });
- ui.horizontal(|ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Crop to:"));
- let cur = d.s("crop");
- let label = |v: &str| match v {
- "trim" => crate::i18n::tr(&app.ui.language, "Trim"),
- "bleed" => crate::i18n::tr(&app.ui.language, "Bleed"),
- "art" => crate::i18n::tr(&app.ui.language, "Art"),
- "media" => crate::i18n::tr(&app.ui.language, "Media"),
- _ => crate::i18n::tr(&app.ui.language, "Crop"),
- };
- egui::ComboBox::from_id_salt("pdf_crop").selected_text(crate::rtl::widget(ui, label(&cur))).show_ui(ui, |ui| {
- for v in ["crop", "trim", "bleed", "art", "media"] {
- if ui.selectable_label(label(&cur) == label(v), label(v)).clicked() {
- d.fields.insert("crop".into(), json!(v));
+ "keyboardShortcuts" => keyboard_shortcuts(app, ui, &mut d),
+ "userDictionary" => user_dictionary(app, ui, &mut d),
+ "menus" => {
+ text_field(ui, &mut d, "query", 260.0);
+ let q = d.s("query").to_lowercase();
+ egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {
+ for (menu, label) in crate::menus::all_menu_items()
+ .into_iter()
+ .filter(|(m, l)| q.is_empty() || m.to_lowercase().contains(&q) || l.to_lowercase().contains(&q))
+ {
+ let key = crate::menus::menu_key(&menu, &label);
+ let mut visible = !app.ui.hidden_menu_items.contains(&key);
+ if ui
+ .checkbox(
+ &mut visible,
+ crate::rtl::widget(
+ ui,
+ format!("{} › {}", crate::i18n::tr(&app.ui.language, &menu), crate::i18n::tr(&app.ui.language, &label)),
+ ),
+ )
+ .changed()
+ {
+ let _ = app.run("window.hideMenuItem", json!({"item": key, "hidden": !visible}));
}
}
});
- });
- }
- "layerOptions" => {
- let mut layers = d.fields.get("layers").and_then(Value::as_array).cloned().unwrap_or_default();
- if layers.is_empty() {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "This PDF has no layers."));
- }
- for l in &mut layers {
- let mut on = l["visible"].as_bool().unwrap_or(true);
- if ui.checkbox(&mut on, l["name"].as_str().unwrap_or("")).changed() {
- l["visible"] = json!(on);
- }
}
- d.fields.insert("layers".into(), json!(layers));
- }
- "colorSettings" => {
- let profiles = d.fields.get("profiles").and_then(Value::as_array).cloned().unwrap_or_default();
- egui::Grid::new("color_settings").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
- for (key, label, kind) in [("rgb", "RGB:", "rgb"), ("cmyk", "CMYK:", "cmyk")] {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, label));
- let cur = d.s(key);
- egui::ComboBox::from_id_salt(("ws", key)).selected_text(&cur).width(260.0).show_ui(ui, |ui| {
- for pr in profiles.iter().filter(|p| p["kind"] == kind) {
- let name = pr["name"].as_str().unwrap_or("");
- if ui.selectable_label(name == cur, name).clicked() {
- d.fields.insert(key.into(), json!(name));
+ "importOptions" => {
+ ui.label(egui::RichText::new(d.s("path")).size(10.5));
+ check(ui, &mut d, "removeStyles", crate::i18n::tr(&app.ui.language, "Remove Styles and Formatting from Text and Tables"));
+ if !d.b("removeStyles") {
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Style Name Conflicts")).font(semibold(12.0)));
+ let conflicts: Vec<String> = d
+ .fields
+ .get("conflicts")
+ .and_then(Value::as_array)
+ .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
+ .unwrap_or_default();
+ ui.label(if conflicts.is_empty() {
+ crate::i18n::tr(&app.ui.language, "No conflicts").to_string()
+ } else {
+ format!("{} conflict(s): {}", conflicts.len(), conflicts.join(", "))
+ });
+ let cur = d.s("styleConflicts");
+ ui.horizontal(|ui| {
+ for (v, l) in [
+ ("useExisting", "Use Document Style Definition"),
+ ("redefine", "Redefine Document Style"),
+ ("autoRename", "Auto Rename"),
+ ] {
+ if ui.radio(cur == v, l).clicked() {
+ d.fields.insert("styleConflicts".into(), json!(v));
}
}
});
- ui.end_row();
- }
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Intent:"));
- let cur = d.s("intent");
- egui::ComboBox::from_id_salt("ws_intent")
- .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, designcraft_color::cms::Intent::parse(&cur).map_or("", |i| i.label()))))
- .show_ui(ui, |ui| {
- for i in designcraft_color::cms::Intent::ALL {
- if ui.selectable_label(i.id() == cur, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, i.label()))).clicked() {
- d.fields.insert("intent".into(), json!(i.id()));
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Style Mapping")).font(semibold(12.0)));
+ let names: Vec<String> =
+ app.session.active().map(|s| s.doc.styles.paragraph.iter().map(|p| p.name.clone()).collect()).unwrap_or_default();
+ let imported: Vec<String> = d
+ .fields
+ .get("styles")
+ .and_then(Value::as_array)
+ .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
+ .unwrap_or_default();
+ egui::ScrollArea::vertical().max_height(180.0).show(ui, |ui| {
+ egui::Grid::new("imp_map").num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| {
+ for w in &imported {
+ ui.label(w);
+ let mapped = d.fields.get("map").and_then(|m| m.get(w)).and_then(Value::as_str).unwrap_or("").to_string();
+ let shown = if mapped.is_empty() { "(import)".to_string() } else { mapped.clone() };
+ egui::ComboBox::from_id_salt(("imp_map", w)).selected_text(crate::rtl::widget(ui, &shown)).width(170.0).show_ui(
+ ui,
+ |ui| {
+ if ui
+ .selectable_label(
+ mapped.is_empty(),
+ crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "(import)")),
+ )
+ .clicked()
+ && let Some(m) = d.fields.get_mut("map").and_then(Value::as_object_mut)
+ {
+ m.remove(w);
+ }
+ for n in &names {
+ if ui.selectable_label(*n == mapped, n).clicked()
+ && let Some(m) = d.fields.get_mut("map").and_then(Value::as_object_mut)
+ {
+ m.insert(w.clone(), json!(n));
+ }
+ }
+ },
+ );
+ ui.end_row();
}
- }
+ });
});
- ui.end_row();
- });
- check(ui, &mut d, "bpc", crate::i18n::tr(&app.ui.language, "Use Black Point Compensation"));
- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Load Profile…"))).clicked()
- && let Some(path) = app.services.pick_open.as_mut().and_then(|f| f("icc"))
- {
- match app.session.execute("color.loadProfile", &json!({"path": path})) {
- Ok(_) => {
- let f = app.session.execute("color.settings", &json!({})).unwrap_or_default();
- d.fields.insert("profiles".into(), f["profiles"].clone());
- }
- Err(e) => app.status(format!("Color Settings: {e}")),
}
}
- }
- "keyboardShortcuts" => keyboard_shortcuts(app, ui, &mut d),
- "userDictionary" => user_dictionary(app, ui, &mut d),
- "menus" => {
- text_field(ui, &mut d, "query", 260.0);
- let q = d.s("query").to_lowercase();
- egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {
- for (menu, label) in crate::menus::all_menu_items().into_iter().filter(|(m, l)| q.is_empty() || m.to_lowercase().contains(&q) || l.to_lowercase().contains(&q)) {
- let key = crate::menus::menu_key(&menu, &label);
- let mut visible = !app.ui.hidden_menu_items.contains(&key);
- if ui.checkbox(&mut visible, crate::rtl::widget(ui, format!("{} › {}", crate::i18n::tr(&app.ui.language, &menu), crate::i18n::tr(&app.ui.language, &label)))).changed() {
- let _ = app.run("window.hideMenuItem", json!({"item": key, "hidden": !visible}));
- }
- }
- });
- }
- "importOptions" => {
- ui.label(egui::RichText::new(d.s("path")).size(10.5));
- check(ui, &mut d, "removeStyles", crate::i18n::tr(&app.ui.language, "Remove Styles and Formatting from Text and Tables"));
- if !d.b("removeStyles") {
- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Style Name Conflicts")).font(semibold(12.0)));
- let conflicts: Vec<String> = d.fields.get("conflicts").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();
- ui.label(if conflicts.is_empty() { crate::i18n::tr(&app.ui.language, "No conflicts").to_string() } else { format!("{} conflict(s): {}", conflicts.len(), conflicts.join(", ")) });
- let cur = d.s("styleConflicts");
+ "closeDocument" => {
+ let text = crate::i18n::tr(&app.ui.language, "“{}” has changes that are not saved. Save them before closing?")
+ .replace("{}", &d.s("title"));
+ crate::rtl::label(ui, text);
+ }
+ "newWorkspace" => {
ui.horizontal(|ui| {
- for (v, l) in [("useExisting", "Use Document Style Definition"), ("redefine", "Redefine Document Style"), ("autoRename", "Auto Rename")] {
- if ui.radio(cur == v, l).clicked() {
- d.fields.insert("styleConflicts".into(), json!(v));
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Name:"));
+ text_field(ui, &mut d, "name", 220.0);
+ });
+ crate::rtl::label(
+ ui,
+ egui::RichText::new(crate::i18n::tr(&app.ui.language, "Saves which bars show and where the panels are.")).size(10.5),
+ );
+ }
+ "fittingOptions" => {
+ check(ui, &mut d, "autoFit", crate::i18n::tr(&app.ui.language, "Auto-Fit"));
+ ui.add_space(4.0);
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Content Fitting")).font(semibold(12.0)));
+ let cur = d.s("fitting");
+ let label = |v: &str| match v {
+ "fillProportionally" => crate::i18n::tr(&app.ui.language, "Fill Frame Proportionally"),
+ "fitProportionally" => crate::i18n::tr(&app.ui.language, "Fit Content Proportionally"),
+ "fitContentToFrame" => crate::i18n::tr(&app.ui.language, "Fit Content to Frame"),
+ "centerContent" => crate::i18n::tr(&app.ui.language, "Center Content"),
+ _ => crate::i18n::tr(&app.ui.language, "None"),
+ };
+ ui.horizontal(|ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Fitting:"));
+ egui::ComboBox::from_id_salt("ff_fit").selected_text(crate::rtl::widget(ui, label(&cur))).width(200.0).show_ui(ui, |ui| {
+ for v in ["none", "fillProportionally", "fitProportionally", "fitContentToFrame", "centerContent"] {
+ if ui.selectable_label(cur == v, crate::rtl::widget(ui, label(v))).clicked() {
+ d.fields.insert("fitting".into(), json!(v));
+ }
}
- }
+ });
});
- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Style Mapping")).font(semibold(12.0)));
- let names: Vec<String> = app.session.active().map(|s| s.doc.styles.paragraph.iter().map(|p| p.name.clone()).collect()).unwrap_or_default();
- let imported: Vec<String> = d.fields.get("styles").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();
- egui::ScrollArea::vertical().max_height(180.0).show(ui, |ui| {
- egui::Grid::new("imp_map").num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| {
- for w in &imported {
- ui.label(w);
- let mapped = d.fields.get("map").and_then(|m| m.get(w)).and_then(Value::as_str).unwrap_or("").to_string();
- let shown = if mapped.is_empty() { "(import)".to_string() } else { mapped.clone() };
- egui::ComboBox::from_id_salt(("imp_map", w)).selected_text(crate::rtl::widget(ui, &shown)).width(170.0).show_ui(ui, |ui| {
- if ui.selectable_label(mapped.is_empty(),crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "(import)"))).clicked()
- && let Some(m) = d.fields.get_mut("map").and_then(Value::as_object_mut)
- {
- m.remove(w);
+ ui.horizontal(|ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Align From:"));
+ let a = d.n("align").unwrap_or(4.0) as u8;
+ egui::Grid::new("ff_align").spacing([2.0, 2.0]).show(ui, |ui| {
+ for row in 0..3u8 {
+ for col in 0..3u8 {
+ let i = row * 3 + col;
+ let (r, resp) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::click());
+ let c = ui.visuals().text_color();
+ if a == i {
+ ui.painter().rect_filled(r.shrink(2.0), 1.0, c);
+ } else {
+ ui.painter().rect_stroke(r.shrink(3.0), 1.0, egui::Stroke::new(1.0, c), egui::StrokeKind::Inside);
}
- for n in &names {
- if ui.selectable_label(*n == mapped, n).clicked()
- && let Some(m) = d.fields.get_mut("map").and_then(Value::as_object_mut)
- {
- m.insert(w.clone(), json!(n));
- }
+ if resp.clicked() {
+ d.fields.insert("align".into(), json!(i));
}
- });
+ }
ui.end_row();
}
});
});
- }
- }
- "closeDocument" => {
- let text = crate::i18n::tr(&app.ui.language, "“{}” has changes that are not saved. Save them before closing?").replace("{}", &d.s("title"));
- crate::rtl::label(ui, text);
- }
- "newWorkspace" => {
- ui.horizontal(|ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Name:"));
- text_field(ui, &mut d, "name", 220.0);
- });
- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Saves which bars show and where the panels are.")).size(10.5));
- }
- "fittingOptions" => {
- check(ui, &mut d, "autoFit", crate::i18n::tr(&app.ui.language, "Auto-Fit"));
- ui.add_space(4.0);
- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Content Fitting")).font(semibold(12.0)));
- let cur = d.s("fitting");
- let label = |v: &str| match v {
- "fillProportionally" => crate::i18n::tr(&app.ui.language, "Fill Frame Proportionally"),
- "fitProportionally" => crate::i18n::tr(&app.ui.language, "Fit Content Proportionally"),
- "fitContentToFrame" => crate::i18n::tr(&app.ui.language, "Fit Content to Frame"),
- "centerContent" => crate::i18n::tr(&app.ui.language, "Center Content"),
- _ => crate::i18n::tr(&app.ui.language, "None"),
- };
- ui.horizontal(|ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Fitting:"));
- egui::ComboBox::from_id_salt("ff_fit").selected_text(crate::rtl::widget(ui, label(&cur))).width(200.0).show_ui(ui, |ui| {
- for v in ["none", "fillProportionally", "fitProportionally", "fitContentToFrame", "centerContent"] {
- if ui.selectable_label(cur == v, crate::rtl::widget(ui, label(v))).clicked() {
- d.fields.insert("fitting".into(), json!(v));
- }
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Crop Amount")).font(semibold(12.0)));
+ egui::Grid::new("ff_crop").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {
+ for (k, l) in [("cropTop", "Top:"), ("cropLeft", "Left:")] {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));
+ text_field(ui, &mut d, k, 70.0);
+ }
+ ui.end_row();
+ for (k, l) in [("cropBottom", "Bottom:"), ("cropRight", "Right:")] {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));
+ text_field(ui, &mut d, k, 70.0);
}
+ ui.end_row();
});
- });
- ui.horizontal(|ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Align From:"));
- let a = d.n("align").unwrap_or(4.0) as u8;
- egui::Grid::new("ff_align").spacing([2.0, 2.0]).show(ui, |ui| {
- for row in 0..3u8 {
- for col in 0..3u8 {
- let i = row * 3 + col;
- let (r, resp) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::click());
- let c = ui.visuals().text_color();
- if a == i {
- ui.painter().rect_filled(r.shrink(2.0), 1.0, c);
- } else {
- ui.painter().rect_stroke(r.shrink(3.0), 1.0, egui::Stroke::new(1.0, c), egui::StrokeKind::Inside);
- }
- if resp.clicked() {
- d.fields.insert("align".into(), json!(i));
+ }
+ "qrCode" => {
+ let cur = d.s("type");
+ ui.horizontal(|ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Type:"));
+ let label = |v: &str| match v {
+ "text" => crate::i18n::tr(&app.ui.language, "Plain Text"),
+ "sms" => crate::i18n::tr(&app.ui.language, "Text Message"),
+ "email" => crate::i18n::tr(&app.ui.language, "Email"),
+ "vcard" => crate::i18n::tr(&app.ui.language, "Business Card"),
+ _ => crate::i18n::tr(&app.ui.language, "Web Hyperlink"),
+ };
+ egui::ComboBox::from_id_salt("qr_type").selected_text(crate::rtl::widget(ui, label(&cur))).width(160.0).show_ui(ui, |ui| {
+ for v in ["url", "text", "sms", "email", "vcard"] {
+ if ui.selectable_label(cur == v, crate::rtl::widget(ui, label(v))).clicked() {
+ d.fields.insert("type".into(), json!(v));
}
}
- ui.end_row();
- }
+ });
});
- });
- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Crop Amount")).font(semibold(12.0)));
- egui::Grid::new("ff_crop").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {
- for (k, l) in [("cropTop", "Top:"), ("cropLeft", "Left:")] {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));
- text_field(ui, &mut d, k, 70.0);
- }
- ui.end_row();
- for (k, l) in [("cropBottom", "Bottom:"), ("cropRight", "Right:")] {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));
- text_field(ui, &mut d, k, 70.0);
- }
- ui.end_row();
- });
- }
- "qrCode" => {
- let cur = d.s("type");
- ui.horizontal(|ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Type:"));
- let label = |v: &str| match v {
- "text" => crate::i18n::tr(&app.ui.language, "Plain Text"),
- "sms" => crate::i18n::tr(&app.ui.language, "Text Message"),
- "email" => crate::i18n::tr(&app.ui.language, "Email"),
- "vcard" => crate::i18n::tr(&app.ui.language, "Business Card"),
- _ => crate::i18n::tr(&app.ui.language, "Web Hyperlink"),
+ let fields: &[(&str, &str)] = match cur.as_str() {
+ "sms" => &[("number", "Cell Number:"), ("message", "Message:")],
+ "email" => &[("to", "Email Address:"), ("subject", "Subject:"), ("body", "Message:")],
+ "vcard" => &[("name", "Name:"), ("org", "Organization:"), ("phone", "Phone:"), ("email", "Email:"), ("url", "URL:")],
+ "text" => &[("content", "Text:")],
+ _ => &[("content", "URL:")],
};
- egui::ComboBox::from_id_salt("qr_type").selected_text(crate::rtl::widget(ui, label(&cur))).width(160.0).show_ui(ui, |ui| {
- for v in ["url", "text", "sms", "email", "vcard"] {
- if ui.selectable_label(cur == v, crate::rtl::widget(ui, label(v))).clicked() {
- d.fields.insert("type".into(), json!(v));
- }
+ egui::Grid::new("qr_fields").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ for (k, l) in fields {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));
+ text_field(ui, &mut d, k, 260.0);
+ ui.end_row();
}
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Color:"));
+ text_field(ui, &mut d, "color", 160.0);
+ ui.end_row();
});
- });
- let fields: &[(&str, &str)] = match cur.as_str() {
- "sms" => &[("number", "Cell Number:"), ("message", "Message:")],
- "email" => &[("to", "Email Address:"), ("subject", "Subject:"), ("body", "Message:")],
- "vcard" => &[("name", "Name:"), ("org", "Organization:"), ("phone", "Phone:"), ("email", "Email:"), ("url", "URL:")],
- "text" => &[("content", "Text:")],
- _ => &[("content", "URL:")],
- };
- egui::Grid::new("qr_fields").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
- for (k, l) in fields {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));
- text_field(ui, &mut d, k, 260.0);
+ }
+ "polygonSettings" => {
+ egui::Grid::new("poly").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Number of Sides:"));
+ text_field(ui, &mut d, "sides", 60.0);
ui.end_row();
- }
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Color:"));
- text_field(ui, &mut d, "color", 160.0);
- ui.end_row();
- });
- }
- "polygonSettings" => {
- egui::Grid::new("poly").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Number of Sides:"));
- text_field(ui, &mut d, "sides", 60.0);
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Star Inset:"));
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Star Inset:"));
+ ui.horizontal(|ui| {
+ text_field(ui, &mut d, "starInset", 60.0);
+ ui.label("%");
+ });
+ ui.end_row();
+ });
+ }
+ STEP_AND_REPEAT => step_and_repeat_dialog(app, ui, &mut d),
+ id if id.starts_with("cmd:") => command_form(app, ui, &mut d),
+ "goToPage" => {
ui.horizontal(|ui| {
- text_field(ui, &mut d, "starInset", 60.0);
- ui.label("%");
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Page"));
+ text_field(ui, &mut d, "page", 80.0);
});
- ui.end_row();
- });
- }
- STEP_AND_REPEAT => step_and_repeat_dialog(app, ui, &mut d),
- id if id.starts_with("cmd:") => command_form(app, ui, &mut d),
- "goToPage" => {
- ui.horizontal(|ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Page"));
- text_field(ui, &mut d, "page", 80.0);
- });
- }
- "ruby" => {
- ui.horizontal(|ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Ruby:"));
- text_field(ui, &mut d, "text", 200.0);
- });
- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Set over the selected text; empty removes it.")).size(11.0));
- }
- "insertTable" => {
- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Table Dimensions")).font(semibold(12.0)));
- egui::Grid::new("ins_table").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Body Rows"));
- text_field(ui, &mut d, "bodyRows", 60.0);
- crate::rtl::label(ui, crate::i18n::tr_context(&app.ui.language, "Columns", "table"));
- text_field(ui, &mut d, "columns", 60.0);
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Header Rows"));
- text_field(ui, &mut d, "headerRows", 60.0);
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Footer Rows"));
- text_field(ui, &mut d, "footerRows", 60.0);
- ui.end_row();
- });
- }
- "textFrameOptions" => {
- seed_text_frame_options(app, &mut d);
- text_frame_options_dialog(app, ui, &mut d);
- }
- "documentSetup" => document_setup(app, ui, &mut d),
- "pdfExport" => pdf_export(app, ui, &mut d),
- "alert" => {
- let file = d.s("file");
- if !file.is_empty() {
- crate::rtl::label(ui, egui::RichText::new(crate::rtl::isolate(&file)).font(semibold(13.0)));
- ui.add_space(4.0);
}
- crate::rtl::label(ui, d.s("message"));
- }
- _ => {}
- }
- });
+ "ruby" => {
+ ui.horizontal(|ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Ruby:"));
+ text_field(ui, &mut d, "text", 200.0);
+ });
+ crate::rtl::label(
+ ui,
+ egui::RichText::new(crate::i18n::tr(&app.ui.language, "Set over the selected text; empty removes it.")).size(11.0),
+ );
+ }
+ "insertTable" => {
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Table Dimensions")).font(semibold(12.0)));
+ egui::Grid::new("ins_table").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Body Rows"));
+ text_field(ui, &mut d, "bodyRows", 60.0);
+ crate::rtl::label(ui, crate::i18n::tr_context(&app.ui.language, "Columns", "table"));
+ text_field(ui, &mut d, "columns", 60.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Header Rows"));
+ text_field(ui, &mut d, "headerRows", 60.0);
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Footer Rows"));
+ text_field(ui, &mut d, "footerRows", 60.0);
+ ui.end_row();
+ });
+ }
+ "textFrameOptions" => {
+ seed_text_frame_options(app, &mut d);
+ text_frame_options_dialog(app, ui, &mut d);
+ }
+ "documentSetup" => document_setup(app, ui, &mut d),
+ "pdfExport" => pdf_export(app, ui, &mut d),
+ "alert" => {
+ let file = d.s("file");
+ if !file.is_empty() {
+ crate::rtl::label(ui, egui::RichText::new(crate::rtl::isolate(&file)).font(semibold(13.0)));
+ ui.add_space(4.0);
+ }
+ crate::rtl::label(ui, d.s("message"));
+ }
+ _ => {}
+ });
ui.add_space(12.0);
let ok_label = if d.id == "closeDocument" { " Save " } else { " OK " };
ui.horizontal(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui
.add(
- egui::Button::new(crate::rtl::widget(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, ok_label)).color(egui::Color32::WHITE)))
- .fill(crate::theme::Tokens::get(ui.ctx()).accent_strong),
+ egui::Button::new(crate::rtl::widget(
+ ui,
+ egui::RichText::new(crate::i18n::tr(&app.ui.language, ok_label)).color(egui::Color32::WHITE),
+ ))
+ .fill(crate::theme::Tokens::get(ui.ctx()).accent_strong),
)
.clicked()
|| ui.input(|i| i.key_pressed(egui::Key::Enter))
@@ -1742,12 +1856,26 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
/// Close the open dialog without applying it (Cancel, Esc, the control channel): a previewing
/// dialog puts the document back as it was.
pub fn cancel(app: &mut DesignApp) {
+ if app.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange") {
+ app.session.reset_find_scope();
+ }
if app.ui.dialog.take().is_some_and(|d| d.fields.contains_key(PREVIEWED)) {
app.session.cancel_interaction();
}
app.cancel_pdf_import();
}
+fn find_change_params(d: &Dialog) -> Value {
+ let mut p = json!({
+ "find": d.s("find"), "change": d.s("change"), "grep": d.b("grep"),
+ "caseSensitive": d.b("caseSensitive"), "wholeWord": d.b("wholeWord"), "scope": d.s("scope"),
+ });
+ if let Some(story) = d.fields.get("story") {
+ p["story"] = story.clone();
+ }
+ p
+}
+
/// Apply the open dialog.
pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
let Some(d) = app.ui.dialog.take() else { return Err("no dialog open".into()) };
@@ -2172,8 +2300,12 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
app.run("footnote.options", p)
}
"alert" => Ok(Value::Null),
- "findChange" if d.b("objectMode") => Ok(Value::Null),
- "findChange" => app.run("find.change", json!({"find": d.s("find"), "change": d.s("change"), "grep": d.b("grep"), "caseSensitive": d.b("caseSensitive"), "wholeWord": d.b("wholeWord"), "scope": d.s("scope")})),
+ "findChange" => {
+ let result = if d.b("objectMode") { Ok(Value::Null) } else { app.run("find.change", find_change_params(&d)) };
+ // Confirmation consumes retained bounds before closing, even on an error.
+ app.session.reset_find_scope();
+ result
+ }
STEP_AND_REPEAT => {
// The preview goes; the copies are made once, as one undo step.
if d.fields.contains_key(PREVIEWED) {
@@ -4022,6 +4154,721 @@ mod tests {
}
}
+ fn scope_control(app: &mut DesignApp, ctx: &egui::Context, method: &str, params: Value) -> Value {
+ let (request, _reply) = crate::control::ControlRequest::new(method, params);
+ let crate::control::Outcome::Done(value) = crate::control::handle(app, ctx, &request) else { panic!("ordinary control response") };
+ assert_eq!(value["ok"], true, "{value}");
+ value["result"].clone()
+ }
+
+ fn scope_click(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, label: &str) {
+ let labels = dialog_frame(app, ctx, screen, vec![]);
+ let pos = visible_label(&labels, screen, label).center();
+ click_dialog(app, ctx, screen, pos);
+ }
+
+ fn scope_dialog() -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) {
+ scope_dialog_with_selection("red red | red", 7)
+ }
+
+ fn scope_dialog_with_selection(text: &str, end: usize) -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) {
+ scope_dialog_with_tool(text, end, None)
+ }
+
+ fn scope_dialog_with_tool(
+ text: &str,
+ end: usize,
+ tool: Option<&str>,
+ ) -> (DesignApp, egui::Context, egui::Rect, designcraft_engine::doc::StoryId) {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.ui.language = "en".into();
+ app.run("file.new", json!({})).unwrap();
+ let frame = app.run("frame.create", json!({"rect": [36, 36, 100, 100], "content": "text", "text": text})).unwrap();
+ let sid = designcraft_engine::doc::StoryId(frame["story"].as_u64().unwrap());
+ let ctx = dialog_context("en");
+ if let Some(tool) = tool {
+ scope_control(&mut app, &ctx, "ui.tool.select", json!({"tool": tool}));
+ }
+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": end})).unwrap();
+ app.run("app.findChange", json!({})).unwrap();
+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1178.0, 814.0));
+ for (field, value) in [("find", "red"), ("change", "unused")] {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));
+ }
+ for _ in 0..3 {
+ dialog_frame(&mut app, &ctx, screen, vec![]);
+ }
+ scope_click(&mut app, &ctx, screen, "document");
+ scope_click(&mut app, &ctx, screen, "selection");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("scope"), "selection");
+ (app, ctx, screen, sid)
+ }
+
+ fn scope_selected(app: &DesignApp, sid: designcraft_engine::doc::StoryId, a: usize, b: usize) {
+ let t = app.session.doc().unwrap().selection.text.unwrap();
+ assert_eq!((t.story, t.range(), t.cell), (sid, a..b, None));
+ }
+
+ fn scope_state_unchanged(app: &DesignApp, before: &designcraft_engine::DocState) {
+ let after = app.session.doc().unwrap();
+ assert!(std::sync::Arc::ptr_eq(&before.doc, &after.doc));
+ assert_eq!(after.uid, before.uid);
+ assert_eq!(after.revision, before.revision);
+ assert_eq!(after.selection, before.selection);
+ assert_eq!(after.history.limit, before.history.limit);
+ for (actual, expected) in [(&after.history.undo, &before.history.undo), (&after.history.redo, &before.history.redo)] {
+ assert_eq!(actual.len(), expected.len());
+ for (a, b) in actual.iter().zip(expected) {
+ assert_eq!(a.label, b.label);
+ assert_eq!(a.selection, b.selection);
+ assert!(std::sync::Arc::ptr_eq(&a.doc, &b.doc));
+ }
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_control_effective_noops_retain_bounds() {
+ for (field, value) in [("objectMode", json!(false)), ("story", Value::Null)] {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key(field));
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ let before = app.session.doc().unwrap().clone();
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));
+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields[field], value);
+ scope_state_unchanged(&app, &before);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 4, 7);
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_explicit_story_ignored_scope_preserves_grep_cursor() {
+ for physical in [false, true] {
+ for (text, pattern, hits, changed) in [
+ ("é", "é|(?:)", vec![(0, 2)], "X"),
+ ("é🙂", "é|(?:)", vec![(0, 2), (6, 6)], "X🙂X"),
+ ("é🙂", "(?:)", vec![(0, 0), (2, 2), (6, 6)], "XéX🙂X"),
+ ] {
+ let (mut app, ctx, screen, sid) = scope_dialog_with_selection(text, 0);
+ for (field, value) in [("find", json!(pattern)), ("change", json!("X")), ("story", json!(sid.0))] {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));
+ }
+ scope_click(&mut app, &ctx, screen, "GREP");
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} match(es)", hits.len()));
+ for &(a, b) in &hits {
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "Found");
+ scope_selected(&app, sid, a, b);
+ let before = app.session.doc().unwrap().clone();
+ let cur = app.ui.dialog.as_ref().unwrap().s("scope");
+ let next = if cur == "selection" { "document" } else { "selection" };
+ if physical {
+ scope_click(&mut app, &ctx, screen, &cur);
+ scope_click(&mut app, &ctx, screen, next);
+ } else {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": next}));
+ }
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("scope"), next);
+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields["story"], json!(sid.0));
+ scope_state_unchanged(&app, &before);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} match(es)", hits.len()));
+ }
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches");
+ // An ignored scope change must not revive an exhausted endpoint either.
+ let before = app.session.doc().unwrap().clone();
+ let cur = app.ui.dialog.as_ref().unwrap().s("scope");
+ let next = if cur == "selection" { "document" } else { "selection" };
+ if physical {
+ scope_click(&mut app, &ctx, screen, &cur);
+ scope_click(&mut app, &ctx, screen, next);
+ } else {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": next}));
+ }
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches");
+ scope_state_unchanged(&app, &before);
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), format!("{} replacement(s) made", hits.len()));
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, changed);
+ }
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_explicit_story_transitions_reset_cursor() {
+ for remove_override in [false, true] {
+ let (mut app, ctx, screen, sid) = scope_dialog_with_selection("é🙂", 0);
+ let other = app.run("frame.create", json!({"rect": [180, 36, 100, 100], "content": "text", "text": "other"})).unwrap();
+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap();
+ for (field, value) in [("find", json!("(?:)")), ("story", json!(sid.0))] {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));
+ }
+ scope_click(&mut app, &ctx, screen, "GREP");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 0);
+ let before = app.session.doc().unwrap().clone();
+ let value = if remove_override { Value::Null } else { other["story"].clone() };
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": value}));
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": sid.0}));
+ scope_state_unchanged(&app, &before);
+ // Away and back still releases continuation even if no Find command intervenes.
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 0);
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 2, 2);
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "é🙂");
+ let other_sid = designcraft_engine::doc::StoryId(other["story"].as_u64().unwrap());
+ assert_eq!(app.session.doc().unwrap().doc.story(other_sid).unwrap().text, "other");
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_control_mode_changes_release_bounds() {
+ for object_mode in [false, true] {
+ let (mut app, ctx, _, sid) = scope_dialog();
+ if object_mode {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "objectMode", "value": true}));
+ }
+ // Direct Session consumers share the retained domain even while Object is shown.
+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});
+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));
+ assert_eq!(count.as_array().unwrap().len(), 2);
+ scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.next", "params": p}));
+ scope_selected(&app, sid, 0, 3);
+ let before = app.session.doc().unwrap().clone();
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "objectMode", "value": !object_mode}));
+ assert_eq!(app.ui.dialog.as_ref().unwrap().b("objectMode"), !object_mode);
+ scope_state_unchanged(&app, &before);
+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));
+ assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));
+ let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p}));
+ assert_eq!(changed, json!({"count": 1}));
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_tool_replacement_releases_bounds() {
+ for (tool, replacement) in [("page", "cmd:layout.pageSize"), ("rectangleFrame", "frameSize")] {
+ let (mut app, ctx, screen, sid) = scope_dialog_with_tool("red red | red", 7, Some(tool));
+ assert_eq!(app.session.tool_id(), tool);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ let before = app.session.doc().unwrap().clone();
+ let active = (app.session.active_index(), app.session.documents().len());
+ let off = app.session.layout().xf(designcraft_engine::doc::SpreadRef::Doc(0)).translation();
+ let x = off.x + before.doc.spreads[0].pages[0].x + 200.0;
+ let y = off.y + 200.0;
+ let events = if tool == "page" {
+ json!([{"kind": "up", "x": x, "y": y}])
+ } else {
+ json!([{"kind": "down", "x": x, "y": y}, {"kind": "up", "x": x, "y": y}])
+ };
+ // Real tool -> Action::Dialog -> after_engine; no injected UI request.
+ scope_control(&mut app, &ctx, "ui.pointer", json!({"events": events}));
+ assert_eq!(app.ui.dialog.as_ref().unwrap().id, replacement);
+ assert!(app.session.ui_requests.is_empty());
+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);
+ scope_state_unchanged(&app, &before);
+ scope_click(&mut app, &ctx, screen, "Cancel");
+ assert!(app.ui.dialog.is_none());
+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);
+ scope_state_unchanged(&app, &before);
+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});
+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));
+ assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));
+ scope_state_unchanged(&app, &before);
+ let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p}));
+ assert_eq!(changed, json!({"count": 1}));
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_tool_without_replacement_retains_bounds() {
+ for tool in ["page", "rectangleFrame"] {
+ let (mut app, ctx, screen, sid) = scope_dialog_with_tool("red red | red", 7, Some(tool));
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ let before = app.session.doc().unwrap().clone();
+ let fields = app.ui.dialog.as_ref().unwrap().fields.clone();
+ scope_control(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "move", "x": 200, "y": 200}]}));
+ assert_eq!(app.ui.dialog.as_ref().unwrap().id, "findChange");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields, fields);
+ scope_state_unchanged(&app, &before);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 4, 7);
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");
+ }
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn find_scope_dialog_native_pdf_replacement_releases_bounds() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("three.pdf");
+ std::fs::write(&path, crate::browser_import_tests::pdf()).unwrap();
+ for dismissal in ["Cancel", "Escape", "control"] {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ let picked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let read = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let seen_pick = picked.clone();
+ let seen_read = read.clone();
+ let pick_path = path.to_string_lossy().to_string();
+ let read_path = pick_path.clone();
+ app.services.pick_open = Some(Box::new(move |purpose| {
+ assert_eq!(purpose, "place");
+ seen_pick.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Some(pick_path.clone())
+ }));
+ app.services.read = Some(Box::new(move |path| {
+ assert_eq!(path, read_path);
+ seen_read.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ std::fs::read(path).map_err(|e| e.to_string())
+ }));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ let before = app.session.doc().unwrap().clone();
+ let active = (app.session.active_index(), app.session.documents().len());
+ // Exercise engine.execute -> UiRequest::Pick -> native host PDF replacement.
+ scope_control(&mut app, &ctx, "engine.execute", json!({"command": "file.place", "params": {}}));
+ assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 1);
+ let dialog = app.ui.dialog.as_ref().unwrap();
+ assert_eq!(dialog.id, "pdfImport");
+ assert_eq!(dialog.s("path"), path.to_string_lossy());
+ assert_eq!(dialog.fields["pages"], 3);
+ assert_eq!(dialog.s("page"), "1");
+ assert!(!dialog.b("async"));
+ assert_eq!(dialog.fields["target"], json!(before.uid));
+ assert!(app.session.ui_requests.is_empty());
+ assert!(app.pending_pdf.is_none());
+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);
+ scope_state_unchanged(&app, &before);
+ match dismissal {
+ "Cancel" => scope_click(&mut app, &ctx, screen, "Cancel"),
+ "Escape" => {
+ dialog_frame(
+ &mut app,
+ &ctx,
+ screen,
+ vec![egui::Event::Key {
+ key: egui::Key::Escape,
+ physical_key: None,
+ pressed: true,
+ repeat: false,
+ modifiers: egui::Modifiers::NONE,
+ }],
+ );
+ }
+ "control" => {
+ scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({}));
+ }
+ _ => panic!("known dismissal"),
+ }
+ assert!(app.ui.dialog.is_none());
+ assert!(app.pending_pdf.is_none());
+ assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);
+ scope_state_unchanged(&app, &before);
+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});
+ let count = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.find", "params": p}));
+ assert_eq!(count, json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));
+ scope_state_unchanged(&app, &before);
+ let changed = scope_control(&mut app, &ctx, "engine.execute", json!({"command": "find.change", "params": p}));
+ assert_eq!(changed, json!({"count": 1}));
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);
+ }
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn find_scope_dialog_native_picker_cancel_retains_bounds() {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ let picked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let seen = picked.clone();
+ app.services.pick_open = Some(Box::new(move |purpose| {
+ assert_eq!(purpose, "place");
+ seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ None
+ }));
+ let read = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let seen_read = read.clone();
+ app.services.read = Some(Box::new(move |_| {
+ seen_read.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Err("canceled picker must not read".into())
+ }));
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ let before = app.session.doc().unwrap().clone();
+ let active = (app.session.active_index(), app.session.documents().len());
+ let fields = app.ui.dialog.as_ref().unwrap().fields.clone();
+ scope_control(&mut app, &ctx, "engine.execute", json!({"command": "file.place", "params": {}}));
+ assert_eq!(picked.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert_eq!(read.load(std::sync::atomic::Ordering::SeqCst), 0);
+ assert_eq!(app.ui.dialog.as_ref().unwrap().id, "findChange");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().fields, fields);
+ assert_eq!((app.session.active_index(), app.session.documents().len()), active);
+ scope_state_unchanged(&app, &before);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 4, 7);
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), before.history.undo.len() + 1);
+ }
+
+ #[test]
+ fn find_scope_dialog_exact_baseline_buttons() {
+ let (mut app, ctx, screen, sid) = scope_dialog_with_selection("red red", 3);
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 replacement(s) made");
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red");
+ }
+
+ #[test]
+ fn find_scope_dialog_grep_tab_alone_restarts_original_selection() {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_click(&mut app, &ctx, screen, "GREP");
+ assert!(app.ui.dialog.as_ref().unwrap().b("grep"));
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("find"), "red");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 4, 7);
+ scope_click(&mut app, &ctx, screen, "Text");
+ assert!(!app.ui.dialog.as_ref().unwrap().b("grep"));
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ }
+
+ #[test]
+ fn find_scope_dialog_buttons_retain_nonempty_hits_and_change_all() {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ let history = app.session.doc().unwrap().history.undo.len();
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 4, 7);
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "No matches");
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history);
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 replacement(s) made");
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1);
+ scope_click(&mut app, &ctx, screen, "Cancel");
+ assert!(app.ui.dialog.is_none());
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");
+ app.run("edit.redo", json!({})).unwrap();
+ let native = app.run("file.serialize", json!({})).unwrap();
+ app.run("file.openBytes", json!({"name": "scope.designcraft", "base64": native["base64"]})).unwrap();
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");
+ }
+
+ fn scope_confirm_case(action: &str) {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ scope_click(&mut app, &ctx, screen, "Count");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ match action {
+ "OK" => scope_click(&mut app, &ctx, screen, "OK"),
+ "Enter" => {
+ dialog_frame(
+ &mut app,
+ &ctx,
+ screen,
+ vec![egui::Event::Key {
+ key: egui::Key::Enter,
+ physical_key: None,
+ pressed: true,
+ repeat: false,
+ modifiers: egui::Modifiers::NONE,
+ }],
+ );
+ }
+ "control" => {
+ assert_eq!(scope_control(&mut app, &ctx, "ui.dialog.confirm", json!({}))["count"], 2);
+ }
+ _ => panic!("known confirmation route"),
+ }
+ assert!(app.ui.dialog.is_none());
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue blue | red");
+ // The closed dialog cannot leave its old seven-byte range for a later direct query.
+ let matches = app.run("find.find", json!({"find": "blue", "scope": "selection"})).unwrap();
+ assert_eq!(matches.as_array().unwrap().len(), 0);
+ }
+
+ #[test]
+ fn find_scope_dialog_ok_consumes_retained_bounds() {
+ scope_confirm_case("OK");
+ }
+
+ #[test]
+ fn find_scope_dialog_enter_consumes_retained_bounds() {
+ scope_confirm_case("Enter");
+ }
+
+ #[test]
+ fn find_scope_dialog_control_confirm_consumes_retained_bounds() {
+ scope_confirm_case("control");
+ }
+
+ #[test]
+ fn find_scope_dialog_query_reselection_cancel_and_reopen() {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "grep", "value": true}));
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "find", "value": "r.d"}));
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({}));
+ assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1);
+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 7})).unwrap();
+ app.run("find.next", json!({"find": "red", "scope": "selection"})).unwrap();
+ scope_control(&mut app, &ctx, "ui.dialog.open", json!({"id": "findChange", "fields": {"find": "red", "scope": "selection"}}));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");
+ app.run("text.select", json!({"story": sid.0, "anchor": 4, "focus": 7})).unwrap();
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 4, 7);
+ app.run("app.findChange", json!({})).unwrap();
+ for (field, value) in [("find", "red"), ("scope", "selection")] {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": field, "value": value}));
+ }
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");
+ }
+
+ #[test]
+ fn find_scope_dialog_word_reselection_limits_count_and_change_buttons() {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ let selected = app.session.doc().unwrap().selection.clone();
+ let frame = selected.text.unwrap().frame.unwrap();
+ let point = {
+ let st = app.session.doc().unwrap();
+ let cs = app.session.cache.get(&st.doc, sid, None);
+ let (fi, x, baseline, ascent, _) = designcraft_compose::caret(&cs, 1).unwrap();
+ let inner = designcraft_geom::Point::new(x, baseline - ascent * 0.5);
+ assert_eq!(cs.frames[fi].frame, frame);
+ assert_eq!(designcraft_compose::hit(&cs, fi, inner), Some(1));
+ let loc = st.doc.find(frame).unwrap();
+ st.doc.parent_xf(&loc) * st.doc.text_xf(st.doc.item(frame).unwrap()) * inner
+ };
+ let before = app.session.doc().unwrap().doc.clone();
+ let revision = app.session.doc().unwrap().revision;
+ app.run("text.selectWord", json!({"frame": frame.0, "point": [point.x, point.y]})).unwrap();
+ assert_eq!(app.session.doc().unwrap().selection, selected);
+ assert_eq!(app.session.doc().unwrap().revision, revision + 1);
+ assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 match(es)");
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "1 replacement(s) made");
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn find_scope_dialog_failed_native_drop_alert_releases_bounds() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("broken.designcraft");
+ std::fs::write(&path, b"not a native document").unwrap();
+ for dismissal in ["OK", "Escape", "control"] {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "2 match(es)");
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ let before = app.session.doc().unwrap().doc.clone();
+ let selected = app.session.doc().unwrap().selection.clone();
+ let revision = app.session.doc().unwrap().revision;
+ let history = app.session.doc().unwrap().history.undo.len();
+ let uid = app.session.doc().unwrap().uid;
+ let error = app.open_dropped(&path.to_string_lossy()).unwrap_err();
+ let alert = app.ui.dialog.as_ref().unwrap();
+ assert_eq!(alert.id, "alert");
+ assert_eq!(alert.s("title"), "Can't Open the File");
+ assert_eq!(alert.s("message"), error);
+ assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc));
+ assert_eq!(app.session.doc().unwrap().selection, selected);
+ assert_eq!(app.session.doc().unwrap().revision, revision);
+ assert_eq!(app.session.doc().unwrap().uid, uid);
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history);
+ match dismissal {
+ "OK" => scope_click(&mut app, &ctx, screen, "OK"),
+ "Escape" => {
+ dialog_frame(
+ &mut app,
+ &ctx,
+ screen,
+ vec![egui::Event::Key {
+ key: egui::Key::Escape,
+ physical_key: None,
+ pressed: true,
+ repeat: false,
+ modifiers: egui::Modifiers::NONE,
+ }],
+ );
+ }
+ "control" => {
+ scope_control(&mut app, &ctx, "ui.dialog.cancel", json!({}));
+ }
+ _ => panic!("known dismissal"),
+ }
+ assert!(app.ui.dialog.is_none());
+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});
+ assert_eq!(app.run("find.find", p.clone()).unwrap(), json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));
+ assert_eq!(app.run("find.change", p).unwrap(), json!({"count": 1}));
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1);
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_child_errors_and_explicit_parent() {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ app.run("text.select", json!({"story": sid.0, "anchor": 13, "focus": 13})).unwrap();
+ app.run("table.insert", json!({"rows": 1, "cols": 1})).unwrap();
+ app.run("text.insert", json!({"text": "red child", "raw": true})).unwrap();
+ let child = app.session.doc().unwrap().selection.text.unwrap();
+ let before = app.session.doc().unwrap().doc.clone();
+ let selection = app.session.doc().unwrap().selection.clone();
+ let history = app.session.doc().unwrap().history.undo.len();
+ for label in ["Count", "Find Next", "Change All"] {
+ scope_click(&mut app, &ctx, screen, label);
+ assert!(app.ui.dialog.as_ref().unwrap().s("status").contains("not supported"));
+ assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc));
+ assert_eq!(app.session.doc().unwrap().selection, selection);
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), history);
+ }
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "change", "value": "blue"}));
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "story", "value": sid.0}));
+ scope_click(&mut app, &ctx, screen, "Count");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "3 match(es)");
+ scope_click(&mut app, &ctx, screen, "Change All");
+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("status"), "3 replacement(s) made");
+ assert_eq!(app.session.doc().unwrap().doc.text_story(sid, child.cell).unwrap().text, "red child");
+ assert!(app.session.doc().unwrap().doc.story(sid).unwrap().text.starts_with("blue blue | blue"));
+ }
+
+ #[test]
+ fn find_scope_dialog_error_confirmation_and_escape_release_context() {
+ for escape in [false, true] {
+ let (mut app, ctx, screen, sid) = scope_dialog();
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ scope_selected(&app, sid, 0, 3);
+ if escape {
+ dialog_frame(
+ &mut app,
+ &ctx,
+ screen,
+ vec![egui::Event::Key {
+ key: egui::Key::Escape,
+ physical_key: None,
+ pressed: true,
+ repeat: false,
+ modifiers: egui::Modifiers::NONE,
+ }],
+ );
+ } else {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "find", "value": "["}));
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "grep", "value": true}));
+ scope_click(&mut app, &ctx, screen, "OK");
+ }
+ assert!(app.ui.dialog.is_none());
+ assert_eq!(app.session.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");
+ assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1);
+ }
+ }
+
+ #[test]
+ fn find_scope_dialog_domain_and_object_changes_release_original_range() {
+ for route in ["scope", "object", "menu", "command"] {
+ let (mut app, ctx, screen, _) = scope_dialog();
+ scope_click(&mut app, &ctx, screen, "Find Next");
+ match route {
+ "scope" => {
+ for scope in ["story", "selection"] {
+ scope_control(&mut app, &ctx, "ui.dialog.set", json!({"field": "scope", "value": scope}));
+ }
+ }
+ "object" => {
+ scope_click(&mut app, &ctx, screen, "Object");
+ scope_click(&mut app, &ctx, screen, "Text");
+ }
+ "menu" => crate::menus::activate(&mut app, "app.newDocumentDialog", &Value::Null),
+ "command" => {
+ app.run("app.newDocumentDialog", json!({})).unwrap();
+ }
+ _ => panic!("known reset route"),
+ }
+ assert_eq!(app.run("find.find", json!({"find": "red", "scope": "selection"})).unwrap().as_array().unwrap().len(), 1);
+ }
+ }
+
#[test]
fn dialog_title_and_actions_fit_scaled_viewports() {
for language in ["en", "ar"] {
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index fc7a3e634..1082dd160 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -622,6 +622,7 @@ impl DesignApp {
pub fn after_engine(&mut self) {
let reqs = std::mem::take(&mut self.session.ui_requests);
for r in reqs {
+ let was_find = self.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange");
match r {
UiRequest::Dialog { id, params } => self.ui.dialog = Some(dialogs::Dialog::new(&id, params)),
UiRequest::View { params } => canvas::apply_view_request(self, &params),
@@ -630,6 +631,10 @@ impl DesignApp {
let _ = self.pick_and_open(&purpose);
}
}
+ // Release only when the request actually replaces Find, including a native PDF picker.
+ if was_find && !self.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange") {
+ self.session.reset_find_scope();
+ }
}
// New documents get a fitted view.
if let Some(st) = self.session.active() {
@@ -986,6 +991,9 @@ impl DesignApp {
let r = self.run(cmd, params);
if let Err(e) = &r {
let title = if cmd == "file.place" { "Can't Place the File" } else { "Can't Open the File" };
+ if self.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange") {
+ self.session.reset_find_scope();
+ }
self.ui.dialog = Some(dialogs::Dialog::new("alert", json!({"title": title, "file": file, "message": e})));
} else if let Ok(result) = &r {
let warnings: Vec<&str> = result
@@ -2108,7 +2116,7 @@ mod browser_import_tests {
result.push_str(&format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1));
result.into_bytes()
}
- fn pdf() -> Vec<u8> {
+ pub(super) fn pdf() -> Vec<u8> {
pdf_pages(3)
}
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 872cb81d0..13d3a54d9 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -752,6 +752,15 @@ pub fn ui_label(id: &str) -> Option<(&'static str, Option<&'static str>)> {
/// Run a UI command; `None` if `id` isn't one.
pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {
+ let was_find = app.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange");
+ let result = run_ui_inner(app, id, p);
+ if was_find && app.ui.dialog.as_ref().is_none_or(|d| d.id != "findChange") {
+ app.session.reset_find_scope();
+ }
+ result
+}
+
+fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {
if let Some(result) = crate::panel_docking::command(app, id, p) {
return Some(result);
}
@@ -957,6 +966,7 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,
}
}
"app.findChange" => {
+ app.session.reset_find_scope();
app.ui.dialog = Some(crate::dialogs::Dialog::new("findChange", json!({})));
Ok(Value::Null)
}
@@ -1880,6 +1890,14 @@ pub fn close_document(app: &mut DesignApp, index: Option<usize>) {
/// A menu item was chosen. An engine command whose label ends in "…" and that takes parameters
/// opens a dialog built from its parameter documentation (see [`crate::dialogs::command_fields`]).
pub fn activate(app: &mut DesignApp, id: &str, params: &Value) {
+ let was_find = app.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange");
+ activate_inner(app, id, params);
+ if was_find && app.ui.dialog.as_ref().is_none_or(|d| d.id != "findChange") {
+ app.session.reset_find_scope();
+ }
+}
+
+fn activate_inner(app: &mut DesignApp, id: &str, params: &Value) {
if params.is_null() && id == "file.close" {
close_document(app, None);
return;