Skip to content

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

refactor(engine): split data merge fill and record selection (Sonar S3776, S107)

Dylan M. Taylor681493f458d7
diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs
index d4b2235e9..1c964bae5 100644
--- a/crates/engine/src/cmd/datamerge/fill.rs
+++ b/crates/engine/src/cmd/datamerge/fill.rs
@@ -128,21 +128,33 @@ struct Rep {
text: String,
}
+/// Where `fill_row` looks for linked images: the merge options and the two search folders.
+#[derive(Clone, Copy)]
+pub struct Sources<'a> {
+ pub options: &'a MergeOptions,
+ pub data_dir: Option<&'a Path>,
+ pub doc_dir: Option<&'a Path>,
+}
+
+/// Replacements and hyperlinks collected while walking the placeholders of one record.
+#[derive(Default)]
+struct Pending {
+ reps: Vec<Rep>,
+ links: Vec<(PlaceholderAnchor, HyperlinkDest, String)>,
+ parent: bool,
+ report: FillReport,
+}
+
/// Fill `row` (0-based) into the items `maps` points at. `record` is the 1-based source row.
pub fn fill_row(
doc: &mut designcraft_doc::Document,
fields: &[DataField],
row: &[String],
record: u32,
- options: &MergeOptions,
maps: &Maps,
- data_dir: Option<&Path>,
- doc_dir: Option<&Path>,
+ sources: &Sources,
) -> FillReport {
- let mut report = FillReport::default();
- let mut parent = false;
- let mut reps: Vec<Rep> = Vec::new();
- let mut links: Vec<(PlaceholderAnchor, HyperlinkDest, String)> = Vec::new();
+ let mut pending = Pending::default();
let placeholders = doc.data_merge.placeholders.clone();
for ph in &placeholders {
if !fields.iter().any(|f| f.name == ph.field) {
@@ -150,43 +162,11 @@ pub fn fill_row(
}
let cell = cell_of(fields, row, &ph.field).to_string();
match &ph.anchor {
- PlaceholderAnchor::Text { story, start, end } => {
- let Some(&mapped) = maps.stories.get(story) else {
- if anchor_is_parent(doc, &ph.anchor) {
- parent = true;
- }
- continue;
- };
- match ph.role {
- PlaceholderRole::Text => reps.push(Rep { story: mapped, start: *start, end: *end, text: cell }),
- PlaceholderRole::Hyperlink => {
- if let Some(dest) = classify_link(&cell) {
- links.push((PlaceholderAnchor::Text { story: mapped, start: *start, end: *end }, dest, ph.field.clone()));
- }
- }
- PlaceholderRole::Image | PlaceholderRole::Qr => {}
- }
- }
- PlaceholderAnchor::Item { id } => {
- let Some(&mapped) = maps.items.get(id) else {
- if anchor_is_parent(doc, &ph.anchor) {
- parent = true;
- }
- continue;
- };
- match ph.role {
- PlaceholderRole::Image => place_image(doc, mapped, &ph.field, &cell, record, options, data_dir, doc_dir, &mut report),
- PlaceholderRole::Qr => place_qr(doc, mapped, &ph.field, &cell, record, &mut report),
- PlaceholderRole::Hyperlink => {
- if let Some(dest) = classify_link(&cell) {
- links.push((PlaceholderAnchor::Item { id: mapped }, dest, ph.field.clone()));
- }
- }
- PlaceholderRole::Text => {}
- }
- }
+ PlaceholderAnchor::Text { story, start, end } => plan_text(doc, maps, ph, (*story, *start, *end), cell, &mut pending),
+ PlaceholderAnchor::Item { .. } => plan_item(doc, maps, ph, &cell, record, sources, &mut pending),
}
}
+ let Pending { mut reps, links, parent, mut report } = pending;
typed_reps(doc, fields, row, maps, &placeholders, &mut reps);
apply_reps(doc, &reps);
for (anchor, dest, field) in links {
@@ -207,6 +187,59 @@ pub fn fill_row(
report
}
+fn plan_text(
+ doc: &designcraft_doc::Document,
+ maps: &Maps,
+ ph: &designcraft_doc::Placeholder,
+ (story, start, end): (StoryId, usize, usize),
+ cell: String,
+ pending: &mut Pending,
+) {
+ let Some(&mapped) = maps.stories.get(&story) else {
+ if anchor_is_parent(doc, &ph.anchor) {
+ pending.parent = true;
+ }
+ return;
+ };
+ match ph.role {
+ PlaceholderRole::Text => pending.reps.push(Rep { story: mapped, start, end, text: cell }),
+ PlaceholderRole::Hyperlink => {
+ if let Some(dest) = classify_link(&cell) {
+ pending.links.push((PlaceholderAnchor::Text { story: mapped, start, end }, dest, ph.field.clone()));
+ }
+ }
+ PlaceholderRole::Image | PlaceholderRole::Qr => {}
+ }
+}
+
+fn plan_item(
+ doc: &mut designcraft_doc::Document,
+ maps: &Maps,
+ ph: &designcraft_doc::Placeholder,
+ cell: &str,
+ record: u32,
+ sources: &Sources,
+ pending: &mut Pending,
+) {
+ let PlaceholderAnchor::Item { id } = &ph.anchor else { return };
+ let Some(&mapped) = maps.items.get(id) else {
+ if anchor_is_parent(doc, &ph.anchor) {
+ pending.parent = true;
+ }
+ return;
+ };
+ match ph.role {
+ PlaceholderRole::Image => place_image(doc, mapped, &ph.field, cell, record, sources, &mut pending.report),
+ PlaceholderRole::Qr => place_qr(doc, mapped, &ph.field, cell, record, &mut pending.report),
+ PlaceholderRole::Hyperlink => {
+ if let Some(dest) = classify_link(cell) {
+ pending.links.push((PlaceholderAnchor::Item { id: mapped }, dest, ph.field.clone()));
+ }
+ }
+ PlaceholderRole::Text => {}
+ }
+}
+
fn typed_reps(
doc: &designcraft_doc::Document,
fields: &[DataField],
@@ -326,17 +359,8 @@ fn create_link(doc: &mut designcraft_doc::Document, anchor: PlaceholderAnchor, d
true
}
-fn place_image(
- doc: &mut designcraft_doc::Document,
- item: ItemId,
- field: &str,
- cell: &str,
- record: u32,
- options: &MergeOptions,
- data_dir: Option<&Path>,
- doc_dir: Option<&Path>,
- report: &mut FillReport,
-) {
+fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, cell: &str, record: u32, sources: &Sources, report: &mut FillReport) {
+ let Sources { options, data_dir, doc_dir } = *sources;
let cands = image_candidates(cell, data_dir, doc_dir);
let found = cands.iter().find_map(|p| {
// Refuse huge files before reading them; a too-large image counts as missing.
diff --git a/crates/engine/src/cmd/datamerge/mod.rs b/crates/engine/src/cmd/datamerge/mod.rs
index c07e2fff4..e96feb9fb 100644
--- a/crates/engine/src/cmd/datamerge/mod.rs
+++ b/crates/engine/src/cmd/datamerge/mod.rs
@@ -18,7 +18,7 @@ use serde_json::{Value, json};
use super::{CommandSpec, bad, cmd, has_doc, id_param, ok, str_param};
use crate::{DocState, Result, Session};
-use fill::{FillReport, Maps, MissingImage, copy_item, fill_row, identity_map};
+use fill::{FillReport, Maps, MissingImage, Sources, copy_item, fill_row, identity_map};
use parse::{
Table, TileInput, extension, fingerprint_of, relative_between, select_records, status_of, table_from_bytes, table_from_grid, table_from_objects,
tile,
@@ -210,7 +210,8 @@ fn preview_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let row = source.rows.get((record as usize).saturating_sub(1)).cloned().unwrap_or_default();
let data_dir = source_file(&source, st.path.as_deref().map(Path::new)).as_deref().and_then(Path::parent).map(Path::to_path_buf);
let doc_dir = st.path.as_deref().and_then(parent_dir);
- fill_row(&mut doc, &source.fields, &row, record as u32, &options, &maps, data_dir.as_deref(), doc_dir.as_deref());
+ let sources = Sources { options: &options, data_dir: data_dir.as_deref(), doc_dir: doc_dir.as_deref() };
+ fill_row(&mut doc, &source.fields, &row, record as u32, &maps, &sources);
st.doc = Arc::new(doc);
st.preview_record = Some(record as u32);
st.bump_revision();
@@ -245,10 +246,12 @@ fn merge_cmd(s: &mut Session, p: &Value) -> Result<Value> {
warnings.extend(table.warnings.iter().cloned());
let mut merged = src.clone();
let mut missing = Vec::new();
+ let sources = Sources { options: &options, data_dir: data_dir.as_deref(), doc_dir: doc_dir.as_deref() };
+ let mut sink = Sink { warnings: &mut warnings, missing: &mut missing, parent: false };
if options.per_page == "multiple" {
- tile_records(&mut merged, &src, &table, &selected, &options, data_dir.as_deref(), doc_dir.as_deref(), &mut warnings, &mut missing)?;
+ tile_records(&mut merged, &src, &table, &selected, &sources, &mut sink)?;
} else {
- copy_records(&mut merged, &src, &table, &selected, &options, data_dir.as_deref(), doc_dir.as_deref(), &mut warnings, &mut missing)?;
+ copy_records(&mut merged, &src, &table, &selected, &sources, &mut sink)?;
}
// Status is written only after every error return. The new document then becomes active,
// so this template edit does not push an undo step. The fingerprint stays the last read.
@@ -272,25 +275,14 @@ fn merge_cmd(s: &mut Session, p: &Value) -> Result<Value> {
}))
}
-fn copy_records(
- dst: &mut Document,
- src: &Document,
- table: &Table,
- selected: &[usize],
- options: &MergeOptions,
- data_dir: Option<&Path>,
- doc_dir: Option<&Path>,
- warnings: &mut Vec<String>,
- missing: &mut Vec<MissingImage>,
-) -> Result<()> {
- let mut parent = false;
+fn copy_records(dst: &mut Document, src: &Document, table: &Table, selected: &[usize], sources: &Sources, sink: &mut Sink) -> Result<()> {
if let Some(&idx) = selected.first() {
let maps = identity_map(dst);
- fill_at(dst, table, idx, options, &maps, data_dir, doc_dir, warnings, missing, &mut parent);
+ fill_at(dst, table, idx, sources, &maps, sink);
}
for &idx in selected.iter().skip(1) {
let maps = append_copy(dst, src)?;
- fill_at(dst, table, idx, options, &maps, data_dir, doc_dir, warnings, missing, &mut parent);
+ fill_at(dst, table, idx, sources, &maps, sink);
}
Ok(())
}
@@ -320,17 +312,8 @@ fn append_copy(dst: &mut Document, src: &Document) -> Result<Maps> {
Ok(maps)
}
-fn tile_records(
- dst: &mut Document,
- src: &Document,
- table: &Table,
- selected: &[usize],
- options: &MergeOptions,
- data_dir: Option<&Path>,
- doc_dir: Option<&Path>,
- warnings: &mut Vec<String>,
- missing: &mut Vec<MissingImage>,
-) -> Result<()> {
+fn tile_records(dst: &mut Document, src: &Document, table: &Table, selected: &[usize], sources: &Sources, sink: &mut Sink) -> Result<()> {
+ let options = sources.options;
let (block, ids) = block_of(src);
let (width, height) = src.page(0).map(|p| (p.width, p.height)).unwrap_or((612.0, 792.0));
let plan = tile(&TileInput {
@@ -344,7 +327,7 @@ fn tile_records(
count: selected.len(),
});
if plan.one_per_page {
- warnings.push("Only one record fits on the page, so each record has its own page.".into());
+ sink.warnings.push("Only one record fits on the page, so each record has its own page.".into());
}
if plan.pages > 1 {
let parent = src.page(0).and_then(|p| p.parent);
@@ -356,12 +339,11 @@ fn tile_records(
}
}
}
- let mut parent = false;
for hit in plan.hits {
let Some(&idx) = selected.get(hit.index) else { continue };
if hit.index == 0 && hit.page == 0 && hit.col == 0 && hit.row == 0 {
let maps = identity_map(dst);
- fill_at(dst, table, idx, options, &maps, data_dir, doc_dir, warnings, missing, &mut parent);
+ fill_at(dst, table, idx, sources, &maps, sink);
continue;
}
let Some((dsi, _)) = dst.page_loc(hit.page) else { continue };
@@ -370,39 +352,37 @@ fn tile_records(
let Some(it) = src.item(*id) else { continue };
copy_item(dst, src, it, SpreadRef::Doc(dsi), Vec2::new(hit.dx, hit.dy), &mut maps)?;
}
- fill_at(dst, table, idx, options, &maps, data_dir, doc_dir, warnings, missing, &mut parent);
+ fill_at(dst, table, idx, sources, &maps, sink);
}
Ok(())
}
-fn fill_at(
- doc: &mut Document,
- table: &Table,
- idx: usize,
- options: &MergeOptions,
- maps: &Maps,
- data_dir: Option<&Path>,
- doc_dir: Option<&Path>,
- warnings: &mut Vec<String>,
- missing: &mut Vec<MissingImage>,
- parent: &mut bool,
-) {
+fn fill_at(doc: &mut Document, table: &Table, idx: usize, sources: &Sources, maps: &Maps, sink: &mut Sink) {
let Some(row) = table.rows.get(idx) else { return };
- let report = fill_row(doc, &table.fields, row, (idx as u32).saturating_add(1), options, maps, data_dir, doc_dir);
- absorb(report, warnings, missing, parent);
+ let report = fill_row(doc, &table.fields, row, (idx as u32).saturating_add(1), maps, sources);
+ sink.absorb(report);
}
-fn absorb(report: FillReport, warnings: &mut Vec<String>, missing: &mut Vec<MissingImage>, parent: &mut bool) {
- for w in report.warnings {
- if w == PARENT_WARNING {
- if *parent {
- continue;
+/// Warnings and missing images collected across every record, with the parent-page warning kept to one.
+struct Sink<'a> {
+ warnings: &'a mut Vec<String>,
+ missing: &'a mut Vec<MissingImage>,
+ parent: bool,
+}
+
+impl Sink<'_> {
+ fn absorb(&mut self, report: FillReport) {
+ for w in report.warnings {
+ if w == PARENT_WARNING {
+ if self.parent {
+ continue;
+ }
+ self.parent = true;
}
- *parent = true;
+ self.warnings.push(w);
}
- warnings.push(w);
+ self.missing.extend(report.missing);
}
- missing.extend(report.missing);
}
fn block_of(doc: &Document) -> (Rect, Vec<ItemId>) {
diff --git a/crates/engine/src/cmd/datamerge/parse.rs b/crates/engine/src/cmd/datamerge/parse.rs
index c76c37f1e..36774733e 100644
--- a/crates/engine/src/cmd/datamerge/parse.rs
+++ b/crates/engine/src/cmd/datamerge/parse.rs
@@ -159,38 +159,7 @@ pub fn select_records(count: usize, records: &str, one: u32, range: &str, limit:
let i = record_index(one, count)?;
idx.push(i);
}
- "range" => {
- if range.trim().is_empty() {
- return Err("no records".into());
- }
- for token in range.split(',') {
- let token = token.trim();
- if token.is_empty() {
- continue;
- }
- if let Some((a, b)) = token.split_once('-') {
- let a = parse_record_no(a.trim())?;
- let b = parse_record_no(b.trim())?;
- if a > b {
- return Err(format!("range {a}-{b} is reversed"));
- }
- let mut n = a;
- while n <= b {
- let i = record_index(n, count)?;
- if seen.insert(i) {
- idx.push(i);
- }
- n = n.saturating_add(1);
- }
- } else {
- let n = parse_record_no(token)?;
- let i = record_index(n, count)?;
- if seen.insert(i) {
- idx.push(i);
- }
- }
- }
- }
+ "range" => select_range(range, count, &mut idx, &mut seen)?,
other => return Err(format!("unknown records value \"{other}\"")),
}
if let Some(limit) = limit {
@@ -205,6 +174,38 @@ pub fn select_records(count: usize, records: &str, one: u32, range: &str, limit:
Ok(idx)
}
+/// Expand a comma-separated list of record numbers and `a-b` ranges into `idx`, skipping repeats.
+fn select_range(range: &str, count: usize, idx: &mut Vec<usize>, seen: &mut std::collections::HashSet<usize>) -> Result<(), String> {
+ if range.trim().is_empty() {
+ return Err("no records".into());
+ }
+ for token in range.split(',') {
+ let token = token.trim();
+ if token.is_empty() {
+ continue;
+ }
+ let (a, b) = match token.split_once('-') {
+ Some((a, b)) => (parse_record_no(a.trim())?, parse_record_no(b.trim())?),
+ None => {
+ let n = parse_record_no(token)?;
+ (n, n)
+ }
+ };
+ if a > b {
+ return Err(format!("range {a}-{b} is reversed"));
+ }
+ let mut n = a;
+ while n <= b {
+ let i = record_index(n, count)?;
+ if seen.insert(i) {
+ idx.push(i);
+ }
+ n = n.saturating_add(1);
+ }
+ }
+ Ok(())
+}
+
fn parse_record_no(s: &str) -> Result<u32, String> {
s.parse::<u32>().map_err(|_| format!("bad record \"{s}\""))
}