Skip to content

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

refactor(engine): reduce complexity in path join and paragraph style apply (Sonar) (#1729)

Dylan M. Taylor3eeab5aead88
diff --git a/crates/engine/src/cmd/anchors.rs b/crates/engine/src/cmd/anchors.rs
index 72b2f085b..fec81de4b 100644
--- a/crates/engine/src/cmd/anchors.rs
+++ b/crates/engine/src/cmd/anchors.rs
@@ -78,6 +78,70 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
+/// The first open subpath (two anchors or more) of an item.
+fn first_open_subpath(d: &Document, id: ItemId) -> Option<usize> {
+ d.item(id).and_then(|it| it.path.subpaths.iter().position(|sp| !sp.closed && sp.anchors.len() > 1))
+}
+
+/// Close every open subpath of one path.
+fn close_open_subpaths(d: &mut Document, id: ItemId) -> Result<Value> {
+ let it = d.item_mut(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
+ let mut closed = 0;
+ for sp in it.path.subpaths.iter_mut().filter(|sp| !sp.closed && sp.anchors.len() > 1) {
+ sp.closed = true;
+ closed += 1;
+ }
+ if closed == 0 {
+ return Err(bad("path.join", "the path is already closed"));
+ }
+ as_path(&mut it.shape);
+ Ok(json!({"id": id.0, "closed": closed}))
+}
+
+/// Join the open subpaths of two paths at their nearest ends, into the first path.
+fn join_open_pair(d: &mut Document, sel: &mut designcraft_doc::Selection, a: ItemId, b: ItemId) -> Result<Value> {
+ let (Some(sa), Some(sb)) = (first_open_subpath(d, a), first_open_subpath(d, b)) else {
+ return Err(bad("path.join", "select two open paths"));
+ };
+ // b's path in a's space.
+ let inv_a = to_inner(d, a).ok_or(designcraft_doc::DocError::NoItem(a))?;
+ let xf_b = to_inner(d, b).ok_or(designcraft_doc::DocError::NoItem(b))?.inverse();
+ let m = inv_a * xf_b;
+ let mut pb = d.item(b).and_then(|it| it.path.subpaths.get(sb).cloned()).ok_or(designcraft_doc::DocError::NoItem(b))?;
+ for an in &mut pb.anchors {
+ *an = Anchor { p: m * an.p, h_in: m * an.h_in, h_out: m * an.h_out, kind: an.kind };
+ }
+ let ita = d.item_mut(a).ok_or(designcraft_doc::DocError::NoItem(a))?;
+ let pa = ita.path.subpaths.get_mut(sa).ok_or_else(|| bad("path.join", "no such subpath"))?;
+ // The pair of ends nearest each other; then a's end meets b's start.
+ let ends = |sp: &designcraft_geom::SubPath| (sp.anchors.first().map(|x| x.p), sp.anchors.last().map(|x| x.p));
+ let ((Some(a0), Some(a1)), (Some(b0), Some(b1))) = (ends(pa), ends(&pb)) else {
+ return Err(bad("path.join", "select two open paths"));
+ };
+ let pairs = [(a1, b0, false, false), (a1, b1, false, true), (a0, b0, true, false), (a0, b1, true, true)];
+ let Some(&(_, _, rev_a, rev_b)) = pairs.iter().min_by(|x, y| (x.0 - x.1).hypot().total_cmp(&(y.0 - y.1).hypot())) else {
+ return Err(bad("path.join", "select two open paths"));
+ };
+ if rev_a {
+ pa.reverse();
+ }
+ if rev_b {
+ pb.reverse();
+ }
+ let mut rest = pb.anchors.into_iter();
+ if let Some(first) = rest.next() {
+ match pa.anchors.last_mut() {
+ Some(last) if (last.p - first.p).hypot() < 0.01 => *last = Anchor::with_handles(last.p, last.h_in, first.h_out),
+ _ => pa.anchors.push(first),
+ }
+ }
+ pa.anchors.extend(rest);
+ as_path(&mut ita.shape);
+ d.remove_item(b)?;
+ *sel = designcraft_doc::Selection::items(vec![a]);
+ Ok(json!({"id": a.0}))
+}
+
/// Join Path: close one open path, or join two open paths at their nearest ends.
fn join_paths(s: &mut Session, p: &Value) -> Result<Value> {
let ids = super::targets(s, p)?;
@@ -90,63 +154,9 @@ fn join_paths(s: &mut Session, p: &Value) -> Result<Value> {
path_editable(d, *id, "path.join")?;
}
}
- let open = |d: &Document, id: ItemId| d.item(id).and_then(|it| it.path.subpaths.iter().position(|sp| !sp.closed && sp.anchors.len() > 1));
match ids.as_slice() {
- [id] => {
- let it = d.item_mut(*id).ok_or(designcraft_doc::DocError::NoItem(*id))?;
- let mut closed = 0;
- for sp in it.path.subpaths.iter_mut().filter(|sp| !sp.closed && sp.anchors.len() > 1) {
- sp.closed = true;
- closed += 1;
- }
- if closed == 0 {
- return Err(bad("path.join", "the path is already closed"));
- }
- as_path(&mut it.shape);
- Ok(json!({"id": id.0, "closed": closed}))
- }
- [a, b] => {
- let (Some(sa), Some(sb)) = (open(d, *a), open(d, *b)) else {
- return Err(bad("path.join", "select two open paths"));
- };
- // b's path in a's space.
- let inv_a = to_inner(d, *a).ok_or(designcraft_doc::DocError::NoItem(*a))?;
- let xf_b = to_inner(d, *b).ok_or(designcraft_doc::DocError::NoItem(*b))?.inverse();
- let m = inv_a * xf_b;
- let mut pb = d.item(*b).and_then(|it| it.path.subpaths.get(sb).cloned()).ok_or(designcraft_doc::DocError::NoItem(*b))?;
- for an in &mut pb.anchors {
- *an = Anchor { p: m * an.p, h_in: m * an.h_in, h_out: m * an.h_out, kind: an.kind };
- }
- let ita = d.item_mut(*a).ok_or(designcraft_doc::DocError::NoItem(*a))?;
- let pa = ita.path.subpaths.get_mut(sa).ok_or_else(|| bad("path.join", "no such subpath"))?;
- // The pair of ends nearest each other; then a's end meets b's start.
- let ends = |sp: &designcraft_geom::SubPath| (sp.anchors.first().map(|x| x.p), sp.anchors.last().map(|x| x.p));
- let ((Some(a0), Some(a1)), (Some(b0), Some(b1))) = (ends(pa), ends(&pb)) else {
- return Err(bad("path.join", "select two open paths"));
- };
- let pairs = [(a1, b0, false, false), (a1, b1, false, true), (a0, b0, true, false), (a0, b1, true, true)];
- let Some(&(_, _, rev_a, rev_b)) = pairs.iter().min_by(|x, y| (x.0 - x.1).hypot().total_cmp(&(y.0 - y.1).hypot())) else {
- return Err(bad("path.join", "select two open paths"));
- };
- if rev_a {
- pa.reverse();
- }
- if rev_b {
- pb.reverse();
- }
- let mut rest = pb.anchors.into_iter();
- if let Some(first) = rest.next() {
- match pa.anchors.last_mut() {
- Some(last) if (last.p - first.p).hypot() < 0.01 => *last = Anchor::with_handles(last.p, last.h_in, first.h_out),
- _ => pa.anchors.push(first),
- }
- }
- pa.anchors.extend(rest);
- as_path(&mut ita.shape);
- d.remove_item(*b)?;
- *sel = designcraft_doc::Selection::items(vec![*a]);
- Ok(json!({"id": a.0}))
- }
+ [id] => close_open_subpaths(d, *id),
+ [a, b] => join_open_pair(d, sel, *a, *b),
_ => Err(bad("path.join", "select one or two open paths")),
}
})
diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs
index 5d440a5d4..f09a442cc 100644
--- a/crates/engine/src/cmd/style.rs
+++ b/crates/engine/src/cmd/style.rs
@@ -761,6 +761,48 @@ fn redefine(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {
result
}
+/// Apply paragraph style `name` over `r` in one story; `clear` drops overrides instead of keeping
+/// only those that differ from the style (`resolved` is the style's paragraph and character attributes).
+fn apply_para_in_story(
+ st: &mut designcraft_doc::Story,
+ r: &std::ops::Range<usize>,
+ name: &str,
+ clear: bool,
+ resolved: (&designcraft_doc::ParaProps, &designcraft_doc::CharProps),
+ styles: &designcraft_doc::Styles,
+) {
+ let (style_para, style_chars) = resolved;
+ // Text selections are half-open: a selection ending at the next paragraph's
+ // start must not apply a style to that paragraph too.
+ let end = if r.is_empty() { r.start } else { r.end.saturating_sub(1) };
+ let (first, last) = (st.para_at(r.start), st.para_at(end));
+ st.format_paras(r.start..end, |f| {
+ f.style = name.to_string();
+ if clear {
+ f.para = ParaAttrs::default();
+ f.chars = CharAttrs::default();
+ } else {
+ f.para.retain_differences(style_para);
+ f.chars.retain_differences(style_chars);
+ }
+ });
+ for (pi, range) in st.para_ranges().into_iter().enumerate().take(last.saturating_add(1)).skip(first) {
+ let Some(pf) = st.paras.get(pi) else { continue };
+ let (_, base) = styles.resolve_para(pf);
+ let end = range.end.saturating_add(1).min(st.len());
+ let range = if clear && !r.is_empty() { range.start.max(r.start)..end.min(r.end) } else { range.start..end };
+ st.format_chars(range, |f| {
+ if clear {
+ f.over = CharAttrs::default();
+ } else {
+ let mut inherited = base.clone();
+ inherited.apply(&styles.char_style_attrs(&f.style));
+ f.over.retain_differences(&inherited);
+ }
+ });
+ }
+}
+
fn apply_para(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("style.paragraph.apply", "missing name"))?.to_string();
let clear = p.get("clearOverrides").and_then(Value::as_bool).unwrap_or(false);
@@ -772,37 +814,8 @@ fn apply_para(s: &mut Session, p: &Value) -> Result<Value> {
let styles = d.styles.clone();
let (style_para, style_chars) = styles.resolve_para_style(&name);
for t in &targets {
- let r = &t.range;
if let Some(st) = d.text_story_mut(t.story, t.cell) {
- // Text selections are half-open: a selection ending at the next paragraph's
- // start must not apply a style to that paragraph too.
- let end = if r.is_empty() { r.start } else { r.end.saturating_sub(1) };
- let (first, last) = (st.para_at(r.start), st.para_at(end));
- st.format_paras(r.start..end, |f| {
- f.style = name.clone();
- if clear {
- f.para = ParaAttrs::default();
- f.chars = CharAttrs::default();
- } else {
- f.para.retain_differences(&style_para);
- f.chars.retain_differences(&style_chars);
- }
- });
- for (pi, range) in st.para_ranges().into_iter().enumerate().take(last.saturating_add(1)).skip(first) {
- let Some(pf) = st.paras.get(pi) else { continue };
- let (_, base) = styles.resolve_para(pf);
- let end = range.end.saturating_add(1).min(st.len());
- let range = if clear && !r.is_empty() { range.start.max(r.start)..end.min(r.end) } else { range.start..end };
- st.format_chars(range, |f| {
- if clear {
- f.over = CharAttrs::default();
- } else {
- let mut inherited = base.clone();
- inherited.apply(&styles.char_style_attrs(&f.style));
- f.over.retain_differences(&inherited);
- }
- });
- }
+ apply_para_in_story(st, &t.range, &name, clear, (&style_para, &style_chars), &styles);
}
}
ok()