PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
make xfa som index lookup linear (#2047)
Omar Saidahmed8c4e633a6e45
diff --git a/crates/xfa/src/layout.rs b/crates/xfa/src/layout.rsindex fb9ac5518..a491d3f49 100644--- a/crates/xfa/src/layout.rs+++ b/crates/xfa/src/layout.rs@@ -221,12 +221,6 @@ pub fn instance_count(occur: &Occur, from_data: usize) -> usize {n.min(occur.max.unwrap_or(usize::MAX)).clamp(1, MAX_INSTANCES)}-/// Index of child `i` among the earlier siblings with the same name (the SOM index).-fn sib_index(children: &[Node], i: usize) -> usize {- let name = children.get(i).and_then(|c| c.common().name.as_deref());- children.iter().take(i).filter(|c| c.common().name.as_deref() == name && name.is_some()).count()-}-/// Lay a template out, with the values and repeat counts of `data` (the `xfa:data` element).pub fn layout(tpl: &Template, data: Option<&DataNode>) -> Result<Form, XfaError> {let areas = match &tpl.root.page_set {@@ -521,8 +515,9 @@ impl Layouter<'_> {// Master page content: positioned draws and fields.let ctx = Ctx { font: Font::default(), para: Para::default(), som: area.name.clone().map(|n| format!("{n}[0]")).unwrap_or_default() };let page_rect = Rect::new(0.0, 0.0, area.width, area.height);+ let sibs = SomIndices::of(&area.items);for (i, item) in area.items.iter().enumerate() {- self.draw_positioned_child(item, page_rect, &ctx, 1, sib_index(&area.items, i))?;+ self.draw_positioned_child(item, page_rect, &ctx, 1, sibs.at(i))?;}Ok(())}@@ -748,11 +743,12 @@ impl Layouter<'_> {match sf.layout {Layout::Table => self.flow_table(sf, inner_x, inner_w, &ctx, depth)?,_ => {+ let sibs = SomIndices::of(&sf.children);for (ci, child) in sf.children.iter().enumerate() {if !child.common().presence.occupies() {continue;}- let csib = sib_index(&sf.children, ci);+ let csib = sibs.at(ci);if let Node::Subform(_) = child&& splittable(child){@@ -784,11 +780,12 @@ impl Layouter<'_> {let cols = self.columns(sf, inner_w);let leader =sf.overflow_leader.as_ref().and_then(|name| sf.children.iter().position(|c| c.common().name.as_deref() == Some(name) && is_row(c)));+ let sibs = SomIndices::of(&sf.children);for (ci, child) in sf.children.iter().enumerate() {if !child.common().presence.occupies() {continue;}- let csib = sib_index(&sf.children, ci);+ let csib = sibs.at(ci);if let Node::Subform(row) = child&& row.layout == Layout::Row{@@ -804,7 +801,7 @@ impl Layouter<'_> {{let lh = self.row_height(l, &cols, inner_w, ctx, depth + 1);let (_, y, _) = self.cursor();- self.draw_row(l, &cols, Rect::new(x, y, inner_w, lh), ctx, depth + 1, sib_index(&sf.children, li))?;+ self.draw_row(l, &cols, Rect::new(x, y, inner_w, lh), ctx, depth + 1, sibs.at(li))?;self.place(lh);}let (_, y, _) = self.cursor();@@ -1163,10 +1160,11 @@ impl Layouter<'_> {let ctx = ctx.with_som(&row.common, sib);let inner = rect.inset(&row.common.margin);let (cells, _) = self.cells(row, cols, inner.w, &ctx, depth);+ let sibs = SomIndices::of(&row.children);for (i, r) in cells {if let Some(k) = row.children.get(i) {// Cells stretch to the row height.- self.draw_node(k, Rect::new(inner.x + r.x, inner.y, r.w, inner.h), &ctx, depth + 1, sib_index(&row.children, i))?;+ self.draw_node(k, Rect::new(inner.x + r.x, inner.y, r.w, inner.h), &ctx, depth + 1, sibs.at(i))?;}}Ok(())@@ -1209,8 +1207,9 @@ impl Layouter<'_> {Node::ExclGroup(g) => self.draw_group(g, rect, ctx, depth, sib),Node::Area(a) => {let ctx = ctx.with_som(&a.common, sib);+ let sibs = SomIndices::of(&a.children);for (i, k) in a.children.iter().enumerate() {- self.draw_positioned_child(k, rect, &ctx, depth + 1, sib_index(&a.children, i))?;+ self.draw_positioned_child(k, rect, &ctx, depth + 1, sibs.at(i))?;}Ok(())}@@ -1221,10 +1220,11 @@ impl Layouter<'_> {let parent_ctx = ctx;let ctx = ctx.with_som(&s.common, sib);let inner = rect.inset(&s.common.margin);+ let sibs = SomIndices::of(&s.children);match s.layout {Layout::Positioned => {for (i, k) in s.children.iter().enumerate() {- self.draw_positioned_child(k, inner, &ctx, depth + 1, sib_index(&s.children, i))?;+ self.draw_positioned_child(k, inner, &ctx, depth + 1, sibs.at(i))?;}}Layout::Tb => {@@ -1237,7 +1237,7 @@ impl Layouter<'_> {// A repeating subform here (a table in an area of a positioned page,// say) gets its instances, as in a flowed one, one under another.for instance in 0..self.instances(k, &ctx.som) {- self.draw_node(k, Rect::new(inner.x, y, w, h), &ctx, depth + 1, sib_index(&s.children, i) + instance)?;+ self.draw_node(k, Rect::new(inner.x, y, w, h), &ctx, depth + 1, sibs.at(i) + instance)?;y += h;}}@@ -1249,7 +1249,7 @@ impl Layouter<'_> {for (i, instance, r) in placed {if let Some(k) = s.children.get(i) {let x = if s.layout == Layout::RlTb { inner.right() - r.x - r.w } else { inner.x + r.x };- self.draw_node(k, Rect::new(x, inner.y + r.y, r.w, r.h), &ctx, depth + 1, sib_index(&s.children, i) + instance)?;+ self.draw_node(k, Rect::new(x, inner.y + r.y, r.w, r.h), &ctx, depth + 1, sibs.at(i) + instance)?;}}}@@ -1260,7 +1260,7 @@ impl Layouter<'_> {if !k.common().presence.occupies() {continue;}- let csib = sib_index(&s.children, i);+ let csib = sibs.at(i);if let Node::Subform(r) = k&& r.layout == Layout::Row{@@ -1402,12 +1402,13 @@ impl Layouter<'_> {.collect(),_ => self.pack(&nodes, inner.w, &ctx, depth).0,};+ let sibs = SomIndices::of(&nodes);for (i, r) in placed {if let Some(f) = g.fields.get(i) {let on = f.items.first().cloned().filter(|s| !s.trim().is_empty()).unwrap_or_else(|| (i + 1).to_string());let tip = f.tooltip.clone().or_else(|| g.tooltip.clone());let chosen = selected.as_deref() == Some(on.as_str());- self.draw_field(f, Rect::new(inner.x + r.x, inner.y + r.y, r.w, r.h), &ctx, Some((&group, &on, tip, chosen)), sib_index(&nodes, i))?;+ self.draw_field(f, Rect::new(inner.x + r.x, inner.y + r.y, r.w, r.h), &ctx, Some((&group, &on, tip, chosen)), sibs.at(i))?;}}Ok(())diff --git a/crates/xfa/src/model.rs b/crates/xfa/src/model.rsindex 01a4b9bcf..f4ef3fabc 100644--- a/crates/xfa/src/model.rs+++ b/crates/xfa/src/model.rs@@ -350,6 +350,30 @@ impl Node {}}+pub(crate) struct SomIndices(Vec<usize>);++impl SomIndices {+ pub(crate) fn of(children: &[Node]) -> Self {+ let mut seen = std::collections::HashMap::new();+ SomIndices(+ children+ .iter()+ .map(|c| {+ c.common().name.as_deref().map_or(0, |name| {+ let n = seen.entry(name).or_insert(0);+ *n += 1;+ *n - 1+ })+ })+ .collect(),+ )+ }++ pub(crate) fn at(&self, i: usize) -> usize {+ self.0.get(i).copied().unwrap_or(0)+ }+}+/// How often a subform occurs when no data drives it.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub struct Occur {diff --git a/crates/xfa/src/script.rs b/crates/xfa/src/script.rsindex ddc52af81..17a037664 100644--- a/crates/xfa/src/script.rs+++ b/crates/xfa/src/script.rs@@ -156,12 +156,6 @@ pub fn set_overrides(doc: &mut Document, ov: &Overrides) -> Result<(), XfaError>Ok(())}-/// Index of child `i` among the earlier siblings with the same name.-fn sib_index(children: &[Node], i: usize) -> usize {- let name = children.get(i).and_then(|c| c.common().name.as_deref());- children.iter().take(i).filter(|c| c.common().name.as_deref() == name && name.is_some()).count()-}-fn child_som(parent: &str, name: Option<&str>, index: usize) -> String {match name {Some(n) if !parent.is_empty() => format!("{parent}.{n}[{index}]"),@@ -285,11 +279,12 @@ impl Walker<'_> {if depth > MAX_DEPTH {return out;}+ let sibs = SomIndices::of(nodes);for (i, n) in nodes.iter().enumerate() {if !self.take() {break;}- let sib = sib_index(nodes, i);+ let sib = sibs.at(i);match n {Node::Subform(sf) => {let from_data = match (&sf.common.name, self.data) {@@ -360,12 +355,13 @@ impl Walker<'_> {self.data.and_then(|d| d.text_at(&data_path(self.tpl, &som))).map(|t| t.trim().to_string()).filter(|t| !t.is_empty());self.push_events(&som, &g.scripts, None, None, None);let fields: Vec<Node> = g.fields.iter().map(|f| Node::Field(Box::new(f.clone()))).collect();+ let fsibs = SomIndices::of(&fields);let mut children = Vec::new();for (fi, f) in g.fields.iter().enumerate() {if !self.take() {break;}- children.push(self.field(f, &som, sib_index(&fields, fi), Some(selected.as_deref().unwrap_or(""))));+ children.push(self.field(f, &som, fsibs.at(fi), Some(selected.as_deref().unwrap_or(""))));}out.push(FormNode {name: g.common.name.clone().unwrap_or_else(|| "group".into()),@@ -451,9 +447,9 @@ pub fn apply_overrides(tpl: &Template, ov: &Overrides) -> Template {if depth > MAX_DEPTH {return;}- let sibs: Vec<usize> = (0..nodes.len()).map(|i| sib_index(nodes, i)).collect();+ let sibs = SomIndices::of(nodes);for (i, n) in nodes.iter_mut().enumerate() {- let sib = sibs.get(i).copied().unwrap_or(0);+ let sib = sibs.at(i);let name_default = match n {Node::Field(_) => Some("field"),Node::ExclGroup(_) => Some("group"),@@ -498,8 +494,9 @@ pub fn apply_overrides(tpl: &Template, ov: &Overrides) -> Template {g.common.presence = p;}let fields: Vec<Node> = g.fields.iter().map(|f| Node::Field(Box::new(f.clone()))).collect();+ let fsibs = SomIndices::of(&fields);for (fi, f) in g.fields.iter_mut().enumerate() {- let fsom = child_som(&som, f.common.name.as_deref().or(Some("field")), sib_index(&fields, fi));+ let fsom = child_som(&som, f.common.name.as_deref().or(Some("field")), fsibs.at(fi));if let Some(p) = ov.presence.get(&fsom) {f.common.presence = Presence::parse(Some(p));}diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rsindex a2be0ac2a..da68027d7 100644--- a/crates/xfa/src/tests.rs+++ b/crates/xfa/src/tests.rs@@ -1933,3 +1933,13 @@ fn stripping_takes_the_xfa_out_and_leaves_an_ordinary_document() {assert_eq!(r.field_keys, 2000);assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());}++#[test]+fn som_indices_count_earlier_same_named_siblings() {+ let draw = |name: Option<&str>| {+ Node::Draw(Box::new(Draw { common: Common { name: name.map(str::to_string), ..Default::default() }, ..Default::default() }))+ };+ let children = [draw(Some("a")), draw(Some("b")), draw(Some("a")), draw(None), draw(Some("a")), draw(Some("b"))];+ let sibs = SomIndices::of(&children);+ assert_eq!((0..=children.len()).map(|i| sibs.at(i)).collect::<Vec<_>>(), [0, 0, 1, 0, 2, 1, 0]);+}