diff --git a/Cargo.lock b/Cargo.lock index 3fe79eb4c..fb17b1406 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1597,6 +1597,7 @@ dependencies = [ name = "rdocx-py" version = "0.17.0" dependencies = [ + "oxml-core", "oxml-layout", "oxml-pdf", "oxml-py-support", diff --git a/README.md b/README.md index 0f39a02a2..5c2df2ae2 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ The archive row uses `cargo package --locked --allow-dirty --no-verify` with all | Measurement | Value | Version | Platform | Build mode | Input | Command | Statistic | Measured on | |---|---|---|---|---|---|---|---|---| -| Crates.io archive: rdocx | 4,501,789 compressed bytes, 56,396,845 member bytes, 37 members | 0.17.0 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo package --locked --allow-dirty --no-verify` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-11-09 | +| Crates.io archive: rdocx | 4,504,780 compressed bytes, 56,407,541 member bytes, 37 members | 0.17.0 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo package --locked --allow-dirty --no-verify` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-11-16 | | Large-document layout throughput | minimum 250 pages/s, observed 31,019.1 pages/s | rdocx 0.14.0 | macOS 26.6.2, Apple M5 Max, arm64 | release, one test thread | 1,000 one-page paragraphs with deterministic fonts | `cargo test -p rdocx --test regression_test --release a_thousand_page_document_paginates_and_renders_within_the_declared_limits -- --ignored --exact --nocapture --test-threads=1` | pages per wall-clock second | 2026-09-19 | | Large-document layout peak allocation | maximum 64 MiB, observed 29.03 MiB | rdocx 0.14.0 | macOS 26.6.2, Apple M5 Max, arm64 | release, one test thread | 1,000 one-page paragraphs with deterministic fonts | `cargo test -p rdocx --test regression_test --release a_thousand_page_document_paginates_and_renders_within_the_declared_limits -- --ignored --exact --nocapture --test-threads=1` | peak live allocation | 2026-09-19 | | Large-document PDF throughput | minimum 1,000 pages/s, observed 60,058.0 pages/s | rdocx 0.14.0 | macOS 26.6.2, Apple M5 Max, arm64 | release, one test thread | 1,000 deterministic layout pages | `cargo test -p rdocx --test regression_test --release a_thousand_page_document_paginates_and_renders_within_the_declared_limits -- --ignored --exact --nocapture --test-threads=1` | pages per wall-clock second | 2026-09-19 | diff --git a/crates/rdocx-py/Cargo.toml b/crates/rdocx-py/Cargo.toml index 0bb338862..aaeb2abd4 100644 --- a/crates/rdocx-py/Cargo.toml +++ b/crates/rdocx-py/Cargo.toml @@ -27,6 +27,7 @@ default = [] extension-module = ["pyo3/extension-module"] [dependencies] +oxml-core = { workspace = true } oxml-pdf = { workspace = true } oxml-layout = { workspace = true } oxml-py-support = { workspace = true } diff --git a/crates/rdocx-py/src/document.rs b/crates/rdocx-py/src/document.rs index 3047f7d94..1356d19d3 100644 --- a/crates/rdocx-py/src/document.rs +++ b/crates/rdocx-py/src/document.rs @@ -64,12 +64,108 @@ fn guarded(work: impl FnOnce() -> T) -> T { impl Drop for Restore { fn drop(&mut self) { WORD_GUARDING.with(|cell| cell.set(self.0)); + if !self.0 { + // The guard's own document clones are not the call's. + let _ = rdocx::take_staging_clones(); + } } } - let _restore = Restore(WORD_GUARDING.with(|cell| cell.replace(true))); + let outer = WORD_GUARDING.with(|cell| cell.replace(true)); + if !outer { + WORD_DOCUMENT_CLONES.fetch_add( + rdocx::take_staging_clones(), + std::sync::atomic::Ordering::Relaxed, + ); + } + let _restore = Restore(outer); work() } +// Debug builds also count the whole-document passes a publication can +// make besides the inventory rebuild: staging clones of the document, story +// walks that resolve a route, save comparisons and full owner inventory +// publications, outside the guards that check a direct route against them. +// A test of the extension module then states which of them a call makes. +#[cfg(debug_assertions)] +static WORD_DOCUMENT_CLONES: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); +#[cfg(debug_assertions)] +static WORD_STORY_WALKS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +#[cfg(debug_assertions)] +static WORD_SAVE_COMPARES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +#[cfg(debug_assertions)] +static WORD_FULL_PUBLICATIONS: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); +#[cfg(debug_assertions)] +thread_local! { + static WORD_CHECKED_ROUTE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Count one walk of a whole story that resolves a route. +pub(crate) fn note_word_story_walk() { + #[cfg(debug_assertions)] + if !WORD_GUARDING.with(std::cell::Cell::get) { + WORD_STORY_WALKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Count one comparison of two staged saves. +fn note_word_save_compare() { + #[cfg(debug_assertions)] + if !WORD_GUARDING.with(std::cell::Cell::get) { + WORD_SAVE_COMPARES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Count one publication that matches the whole owner inventory again. +fn note_word_full_publication() { + #[cfg(debug_assertions)] + if !WORD_GUARDING.with(std::cell::Cell::get) { + WORD_FULL_PUBLICATIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Whether a test asked every publication for its checked whole-document +/// route, in place of the routes that read the owner inventory or one +/// block. Always false in a release build. +fn checked_route_forced() -> bool { + #[cfg(debug_assertions)] + { + WORD_CHECKED_ROUTE.with(std::cell::Cell::get) + } + #[cfg(not(debug_assertions))] + { + false + } +} + +/// Document staging clones, story walks that resolve a route, save +/// comparisons and full owner inventory publications since the last read. +/// Debug builds only. Reading resets all four. +#[cfg(debug_assertions)] +#[pyfunction] +#[pyo3(name = "_word_publication_work")] +pub(crate) fn word_publication_work() -> (usize, usize, usize, usize) { + use std::sync::atomic::Ordering::Relaxed; + ( + WORD_DOCUMENT_CLONES.swap(0, Relaxed) + rdocx::take_staging_clones(), + WORD_STORY_WALKS.swap(0, Relaxed), + WORD_SAVE_COMPARES.swap(0, Relaxed), + WORD_FULL_PUBLICATIONS.swap(0, Relaxed), + ) +} + +/// Take the checked whole-document route for every publication and stage the +/// document for every properties edit, the references the direct routes are +/// compared with. Debug builds only. Returns the previous choice. +#[cfg(debug_assertions)] +#[pyfunction] +#[pyo3(name = "_word_force_checked_route")] +pub(crate) fn word_force_checked_route(force: bool) -> bool { + rdocx::force_staged_properties(force); + WORD_CHECKED_ROUTE.with(|cell| cell.replace(force)) +} + /// The whole-body work counted so far: owner inventory rebuilds and /// whole-source element reads. Debug builds only. Reading resets both. #[cfg(debug_assertions)] @@ -120,6 +216,29 @@ fn note_word_piece_read() { } } +#[cfg(debug_assertions)] +static WORD_PIECE_BYTES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Count the standalone XML bytes of a body block whose owners the checked +/// reader reads, so that a count of reads also tells how much was read. +fn note_word_piece_bytes(bytes: usize) { + #[cfg(debug_assertions)] + if !WORD_GUARDING.with(std::cell::Cell::get) { + WORD_PIECE_BYTES.fetch_add(bytes, std::sync::atomic::Ordering::Relaxed); + } + #[cfg(not(debug_assertions))] + let _ = bytes; +} + +/// Standalone XML bytes of the body blocks whose owners the checked reader +/// read again. Debug builds only. Reading resets the count. +#[cfg(debug_assertions)] +#[pyfunction] +#[pyo3(name = "_word_piece_bytes")] +pub(crate) fn word_piece_bytes() -> usize { + WORD_PIECE_BYTES.swap(0, std::sync::atomic::Ordering::Relaxed) +} + /// Parsed, namespace-scanned, canonicalized and ZIP bytes, then serialized /// children and children read. Debug builds only. Reading resets all six. /// Child staging is not implemented. @@ -1875,6 +1994,7 @@ impl PySectionHandle { .ok_or_else(|| PyIndexError::new_err("section index out of range"))? .set_page_border(edge, style, width, space, color) .map_err(|error| rdocx_to_pyerr(py, error))?; + note_word_save_compare(); candidate .saves_as(&candidate) .map_err(|error| rdocx_to_pyerr(py, error))?; @@ -5389,6 +5509,14 @@ fn word_block_owners( let body = |snapshot: &&rdocx::StoryItemSnapshot| { snapshot.location().story().kind() == rdocx::StoryKind::Body }; + note_word_piece_bytes( + snapshots + .iter() + .filter(body) + .filter(|snapshot| snapshot.is_direct_child()) + .map(|snapshot| snapshot.xml().len()) + .sum(), + ); let direct = snapshots .iter() .filter(body) @@ -10486,7 +10614,12 @@ impl PyDocument { prepared: Option<(&PreparedWordRevision, &rdocx::Document)>, ) -> rdocx::Result { let document = prepared.map_or(&self.inner, |(_, candidate)| candidate); - match self.indexed_paragraph_location(location, prepared.map(|(prepared, _)| prepared)) { + let indexed = (!checked_route_forced()) + .then(|| { + self.indexed_paragraph_location(location, prepared.map(|(prepared, _)| prepared)) + }) + .flatten(); + match indexed { Some(indexed) => { #[cfg(debug_assertions)] assert_indexed_route(&indexed, || location.native(document), "paragraph"); @@ -10496,6 +10629,85 @@ impl PyDocument { } } + /// The route of the physical owner of a table handle's location in the + /// current document: from the inventory, which holds the route the + /// document resolves, or as the document resolves it. + pub(crate) fn table_route( + &self, + index: usize, + related: &Option, + ) -> rdocx::Result { + let native = || crate::table::TableLocation::new(index, related).native(&self.inner); + let indexed = (!checked_route_forced()) + .then(|| self.indexed_table_location(index, related, None)) + .flatten(); + match indexed { + Some(indexed) => { + // The walk of a related table only reads its story again, + // so the walk checks a body table alone. + #[cfg(debug_assertions)] + if related.is_none() { + assert_indexed_route(&indexed, native, "table"); + } + Ok(indexed) + } + None => native(), + } + } + + /// The route and run path of a run handle's physical owner: from the + /// inventory record of that owner, or as the document resolves it. + pub(crate) fn run_route( + &self, + state: &RevisionState, + ) -> PyResult<(rdocx::ContentLocation, rdocx_oxml::text::AcceptedRunPath)> { + if !checked_route_forced() + && let Some((_, owner)) = self.indexed_owner(state) + && let WordOwnerLocation::Run(location, path) = &owner.location + { + // The story walk of a recorded route only reads its story again, + // so the check is that the paragraph there holds this run path. + #[cfg(debug_assertions)] + assert!( + guarded(|| { + let current = + ParagraphLocation::Related(location.clone()).native(&self.inner)?; + self.inner.read_story_paragraph(¤t, |paragraph| { + (0..paragraph.run_count()) + .any(|index| paragraph.run_path(index).as_ref() == Some(path)) + }) + }) + .expect("an indexed run route resolves in the document"), + "indexed run route holds its run path" + ); + return Ok((location.clone(), path.clone())); + } + self.current_run_owner(state) + } + + /// The direct body slot of the paragraph that a body `location` and the + /// run owner `state` both name, from the inventory. A typed edit made + /// through `location` then changes that block and no other. + pub(crate) fn typed_run_edit_slot( + &self, + location: &ParagraphLocation, + state: &RevisionState, + ) -> Option { + if !matches!(location, ParagraphLocation::Body(_)) { + return None; + } + let (_, run) = self.indexed_owner(state)?; + let paragraph = self.owners.get(run.parent?)?; + let WordOwnerLocation::Paragraph(route) = ¶graph.location else { + return None; + }; + let indexed = self.indexed_paragraph_location(location, None)?; + (route.story().kind() == rdocx::StoryKind::Body + && route.index_path().len() == 1 + && same_content_owner(route, &indexed)) + .then_some(paragraph.body_slot?) + } + pub(crate) fn indexed_table_location( &self, index: usize, @@ -11256,6 +11468,7 @@ impl PyDocument { operation: &'static str, publication: WordPublication, ) -> PyResult { + note_word_full_publication(); self.ensure_word_authority(py)?; let forms = matches!( publication, @@ -11594,6 +11807,7 @@ impl PyDocument { operation: &'static str, publication: WordPublication, ) -> PyResult<()> { + note_word_save_compare(); if self .inner .saves_as(&candidate) @@ -11607,10 +11821,83 @@ impl PyDocument { Ok(()) } + /// Publish `candidate`, this document after one typed edit of the + /// direct body paragraph at `slot`, unless the edit changed nothing. The + /// answer is read from that block when it tells, and from the staged + /// save comparison of [`Self::publish_owner_candidate`] when it does + /// not. + pub(crate) fn publish_block_candidate( + &mut self, + py: Python<'_>, + candidate: rdocx::Document, + operation: &'static str, + publication: WordPublication, + slot: usize, + ) -> PyResult<()> { + let Some(same) = self.direct_paragraph_saves_as(&candidate, slot) else { + return self.publish_owner_candidate(py, candidate, operation, publication); + }; + // The staged comparison saves the whole candidate and refuses when + // content outside this block cannot be saved. It checks the block + // answer whenever it gives one. + #[cfg(debug_assertions)] + if let Ok(saved) = guarded(|| self.inner.saves_as(&candidate)) { + assert_eq!(saved, same, "direct body paragraph save comparison"); + } + if same { + return Ok(()); + } + let prepared = self.prepare_word_revision(py, &candidate, operation, publication)?; + self.commit_word_revision(prepared)?; + self.install_inner(candidate); + Ok(()) + } + + /// Whether `candidate`, this document after one typed edit of the + /// direct body paragraph at `slot`, saves as this document, read from + /// that block alone. Equal paragraph models save the same bytes. Two + /// plain paragraphs whose checked reader facts differ, the text and the + /// run paths of [`rdocx::Document::direct_body_paragraph_facts`], save + /// different bytes, as a plain paragraph holds nothing a save + /// renumbers. `None` leaves the answer to the staged save: another + /// paragraph shape, a body whose save is known to fail, text a save + /// refuses, or facts that do not tell. The block answer does not save + /// the rest of the document, so content elsewhere that no save accepts + /// is reported by the save itself, as after `Paragraph.text`. + fn direct_paragraph_saves_as(&self, candidate: &rdocx::Document, slot: usize) -> Option { + if checked_route_forced() || self.inner.unsavable_body_edit().is_some() { + return None; + } + let ( + rdocx_oxml::BodyContent::Paragraph(current), + rdocx_oxml::BodyContent::Paragraph(edited), + ) = ( + self.inner.body_children().get(slot)?, + candidate.body_children().get(slot)?, + ) + else { + return None; + }; + if current == edited { + return Some(true); + } + let before = self.inner.direct_body_paragraph_facts(current).ok()??; + let after = candidate.direct_body_paragraph_facts(edited).ok()??; + // A save refuses a character XML 1.0 cannot carry, with its place in + // the part. The block reader does not, so the staged save answers. + if !after.0.chars().all(oxml_core::xml::is_xml_1_0_character) { + return None; + } + (before != after).then_some(false) + } + pub(crate) fn local_cell_route( &self, state: &RevisionState, ) -> Option<(usize, usize, usize, usize)> { + if checked_route_forced() { + return None; + } let (slot, row, cell) = self.direct_body_cell_slot(state)?; let (_, owner) = self.indexed_owner(state)?; let parent = self.owners.get(owner.parent?)?; @@ -11675,7 +11962,12 @@ impl PyDocument { ) } - /// Publish one prepared direct-body cell edit, touching only its table inventory. + /// Publish one prepared direct-body cell edit, touching only the owners of + /// that cell. `candidate` is the edited cell alone in its table frame, as + /// `direct_body_table_cell_candidate` prepares it, and the checked reader + /// reads that frame for the facts of the cell. The other cells keep the + /// facts the checked reader gave the aligned piece, as their models are + /// the ones it read. #[allow(clippy::too_many_arguments)] pub(crate) fn apply_local_cell_edit( &mut self, @@ -11699,6 +11991,10 @@ impl PyDocument { let Some(piece) = pieces.blocks.get(body_slot) else { return Ok(false); }; + // The piece is spliced in place after the revision commit. + if std::sync::Arc::strong_count(piece) != 1 || std::sync::Arc::weak_count(piece) != 0 { + return Ok(false); + } if !aligned_block(piece, &self.inner.body_children()[body_slot]) { return Ok(false); } @@ -11708,9 +12004,25 @@ impl PyDocument { // Every physical cell must belong to this indexed table subtree, with // its standalone physical ordinal intact. Otherwise use the checked // publisher before preparing any revision or owner/index delta. - if !before.local_table_membership { + if !before.local_table_membership + || before.body_items != 1 + || !matches!(before.cell_paragraphs, Some((_, true))) + { return Ok(false); } + // A text-box count needs its own first-story base. Keep its checked fallback. + if before.text_boxes != 0 || !before.facts.links.is_empty() { + return Ok(false); + } + // Complete membership lists the cells in story order, so the cell's + // story ordinal in the table alone is its position there. + let Ok(local) = before + .facts + .cells + .binary_search_by_key(&(row, cell), |(_, row, cell, _)| (*row, *cell)) + else { + return Ok(false); + }; let Some(table_location) = self .indexes .body_tables @@ -11728,6 +12040,8 @@ impl PyDocument { }; if self.owners[table_index].body_slot != Some(body_slot) || table_location.index_path().len() != 1 + || !matches!(&self.owners[table_index].read_facts, WordReadFacts::Table(rows) + if rows.get(row).and_then(|cells| cells.get(cell)).is_some()) { return Ok(false); } @@ -11740,6 +12054,20 @@ impl PyDocument { }) else { return Ok(false); }; + let WordOwnerLocation::Cell { + story: cell_story, .. + } = &self.owners[selected].location + else { + return Ok(false); + }; + if self + .indexes + .tables_by_parent + .get(&selected) + .is_some_and(|tables| !tables.is_empty()) + { + return Ok(false); + } let retire = publication.is_some(); let paragraph_text = matches!(publication, Some(WordPublication::ParagraphText(_))); let text_selected = match &publication { @@ -11773,20 +12101,8 @@ impl PyDocument { } _ => return Ok(false), }; - let Some(first_cell) = cell_indices.first() else { - return Ok(false); - }; - let WordOwnerLocation::Cell { - story: first_story, .. - } = &self.owners[*first_cell].location - else { - return Ok(false); - }; - // A text-box count needs its own first-story base. Keep its checked fallback. - if before.text_boxes != 0 || !before.facts.links.is_empty() { - return Ok(false); - } - let stories = (first_story.owner_index(), 0); + // The document's ordinal of the cell story, from the cell's own record. + let stories = (cell_story.owner_index(), 0); let block = rdocx_oxml::BodyContent::Table(Box::new(candidate)); note_word_piece_read(); let Some(after) = @@ -11794,21 +12110,28 @@ impl PyDocument { else { return Ok(false); }; - if !after.local_table_membership - || before.body_items != after.body_items - || before.cell_stories != after.cell_stories - || before.text_boxes != after.text_boxes - || before.tables != after.tables - || !after.facts.links.is_empty() - { + let Some((frame_routes, true)) = &after.cell_paragraphs else { return Ok(false); - } - let Some((routes, complete)) = &after.cell_paragraphs else { + }; + let (Some(routes), Some((_, _, WordReadFacts::Table(frame_rows)))) = + (frame_routes.get(&(0, 0, 0)), after.facts.items.first()) + else { return Ok(false); }; - if !complete { + // The frame holds this cell alone, with no nested table, text box or link. + if !after.local_table_membership + || after.facts.cells.len() != 1 + || after.body_items != 1 + || after.cell_stories != 1 + || after.text_boxes != 0 + || after.tables != 1 + || !after.facts.links.is_empty() + || frame_rows.len() != 1 + || frame_rows[0].len() != 1 + { return Ok(false); } + let paragraph_count = frame_rows[0][0]; let item_base = table_location.index_path()[0]; let body = table_location.story(); let place = @@ -11818,20 +12141,40 @@ impl PyDocument { *location = place(location); *slot = slot.map(|_| body_slot); } - for (table, _, _, story) in &mut facts.cells { + for (table, r, c, story) in &mut facts.cells { *table = place(table); + (*r, *c) = (row, cell); *story = placed_story(story, stories); } for (location, _, _) in &mut facts.paragraphs { *location = place(location); } - for location in &mut facts.links { - *location = place(location); - } let mut addresses = word_piece_owner_addresses(facts, 0); - // Walk indexed children, never the document's owner vector. + // The frame's table owner is the table's own record. Keep the cell and + // what it holds, with the cell first and parents among them. + if !matches!( + addresses.first().map(|address| &address.location), + Some(WordOwnerLocation::Table(_)) + ) || !matches!( + addresses.get(1), + Some(WordOwnerAddress { + location: WordOwnerLocation::Cell { .. }, + parent: Some(0), + .. + }) + ) || addresses[2..] + .iter() + .any(|address| !matches!(address.parent, Some(parent) if parent >= 1)) + { + return Ok(false); + } + addresses.remove(0); + for address in &mut addresses { + address.parent = address.parent.and_then(|parent| parent.checked_sub(1)); + } + // Walk indexed children of the cell, never the table's or the document's. let mut previous = Vec::new(); - let mut pending = vec![table_index]; + let mut pending = vec![selected]; while let Some(index) = pending.pop() { note_visited_owner_record(); previous.push(index); @@ -11889,6 +12232,7 @@ impl PyDocument { let mut targets = Vec::with_capacity(addresses.len()); let mut newborn = 0; for index in 0..addresses.len() { + note_visited_owner_record(); let key = key(&addresses, index); let cursor = cursors.entry(key.clone()).or_default(); let old = buckets @@ -11903,9 +12247,10 @@ impl PyDocument { target })); } - if buckets - .iter() - .any(|(key, old)| cursors.get(key).copied().unwrap_or(0) < old.len()) + if targets.first() != Some(&selected) + || buckets + .iter() + .any(|(key, old)| cursors.get(key).copied().unwrap_or(0) < old.len()) { return Ok(false); } @@ -11925,10 +12270,8 @@ impl PyDocument { }); } for (index, address) in addresses.iter_mut().enumerate() { - if matches!(address.location, WordOwnerLocation::Table(_)) && address.parent.is_none() { - address.projection_ordinal = Some(table_ordinal); - } - address.parent = address.parent.map(|parent| targets[parent]); + // The cell's parent is the table, outside the replaced owners. + address.parent = Some(address.parent.map_or(table_index, |parent| targets[parent])); let hash = address.location.route_hash(); route_buckets.entry(hash).or_insert_with(|| { self.indexes @@ -11954,7 +12297,8 @@ impl PyDocument { HashMap::new(), HashMap::new(), ]; - for (index, address) in addresses.iter().enumerate() { + // The table keeps its list of cells, and the cell keeps its record. + for (index, address) in addresses.iter().enumerate().skip(1) { if let Some(parent) = address.parent { let family = match address.location { WordOwnerLocation::Cell { .. } => 0, @@ -11969,15 +12313,7 @@ impl PyDocument { .push(targets[index]); } } - let cell_routes = routes - .iter() - .map(|((table, row, cell), locations)| { - ( - (table_ordinal + table, *row, *cell), - locations.iter().map(&place).collect::>(), - ) - }) - .collect::>(); + let cell_routes = routes.iter().map(&place).collect::>(); let mut births = Vec::new(); let mut retained = Vec::new(); let mut retired = Vec::new(); @@ -12025,6 +12361,29 @@ impl PyDocument { ); births.push(RevisionScope::Text); } + // The piece facts of the cell, in the numbering of the table alone. + let piece_place = |location: &rdocx::ContentLocation| { + placed_route(location, location.story(), (0, (local, 0))) + }; + let piece_paragraphs = after + .facts + .paragraphs + .iter() + .map(|(location, text, runs)| (piece_place(location), text.clone(), runs.clone())) + .collect::>(); + let piece_story = placed_story(&after.facts.cells[0].3, (local, 0)); + let piece_routes = routes.iter().map(piece_place).collect::>(); + // The paragraphs are those of the cell stories, in story order. + let ordinal = |location: &rdocx::ContentLocation| location.story().owner_index(); + let paragraphs = &before.facts.paragraphs; + let paragraph_range = paragraphs + .partition_point(|(location, _, _)| ordinal(location) < local) + ..paragraphs.partition_point(|(location, _, _)| ordinal(location) <= local); + let holds_field = after.holds_field; + let rdocx_oxml::BodyContent::Table(frame) = block else { + unreachable!() + }; + let piece_cell = frame.rows[0].cells[0].clone(); let fail = |_| { pyo3::exceptions::PyMemoryError::new_err("local cell publication allocation failed") }; @@ -12037,14 +12396,6 @@ impl PyDocument { .by_route .try_reserve(route_buckets.len()) .map_err(fail)?; - self.indexes - .cell_paragraphs - .try_reserve(cell_routes.len()) - .map_err(fail)?; - self.indexes - .cells_by_parent - .try_reserve(parent_buckets[0].len()) - .map_err(fail)?; self.indexes .paragraphs_by_parent .try_reserve(parent_buckets[1].len()) @@ -12053,10 +12404,18 @@ impl PyDocument { .runs_by_parent .try_reserve(parent_buckets[2].len()) .map_err(fail)?; - self.indexes - .tables_by_parent - .try_reserve(parent_buckets[3].len()) - .map_err(fail)?; + { + let piece = std::sync::Arc::get_mut( + &mut self.pieces.as_mut().expect("active pieces").blocks[body_slot], + ) + .expect("a piece checked unique"); + let owners = piece.owners.as_mut().expect("aligned piece owners"); + owners + .facts + .paragraphs + .try_reserve(piece_paragraphs.len()) + .map_err(fail)?; + } let revision = if retire { Some( self.revisions @@ -12085,15 +12444,7 @@ impl PyDocument { let snapshot = revision .as_ref() .map(|revision| revision.born(born).expect("prepared snapshot")); - let replacement = std::sync::Arc::new(WordBlockPiece { - block: std::sync::Arc::new(block), - owners: Some(after), - }); let owners = word_owners_with_states(addresses, &states); - let rdocx_oxml::BodyContent::Table(table) = replacement.block.as_ref() else { - unreachable!() - }; - let native_table = (**table).clone(); if let Some(revision) = revision { #[cfg(test)] let revision = if FX283_REFUSE_LOCAL_COMMIT.get() { @@ -12108,7 +12459,8 @@ impl PyDocument { .map_err(revision_to_pyerr)?; } // No recoverably fallible operation follows the revision commit. - self.inner.commit_direct_body_table(body_slot, native_table); + self.inner + .commit_direct_body_table_cell(body_slot, row, cell, *frame); for index in &previous { self.indexes .by_generation @@ -12124,6 +12476,9 @@ impl PyDocument { self.owners[target] = owner; } } + if let WordReadFacts::Table(rows) = &mut self.owners[table_index].read_facts { + rows[row][cell] = paragraph_count; + } for (hash, bucket) in route_buckets { if bucket.is_empty() { self.indexes.by_route.remove(&hash); @@ -12145,16 +12500,216 @@ impl PyDocument { } map.extend(prepared); } - for (key, routes) in cell_routes { - self.indexes.cell_paragraphs.insert(key, routes); - } + self.indexes + .cell_paragraphs + .insert((table_ordinal, row, cell), cell_routes); if let Some(snapshot) = snapshot { self.snapshot_scope = Some(snapshot); } - self.pieces.as_mut().expect("active pieces").blocks[body_slot] = replacement; + let piece = std::sync::Arc::get_mut( + &mut self.pieces.as_mut().expect("active pieces").blocks[body_slot], + ) + .expect("a piece checked unique"); + if let rdocx_oxml::BodyContent::Table(table) = std::sync::Arc::make_mut(&mut piece.block) { + table.rows[row].cells[cell] = piece_cell; + } + let owners = piece.owners.as_mut().expect("aligned piece owners"); + // The inventory reads the table and body items of a piece, here the + // table's own item. A full read also lists the paragraphs of the cell + // stories, which a body splice leaves out. Keep no stale ones. + owners.facts.items.truncate(1); + owners + .facts + .paragraphs + .splice(paragraph_range, piece_paragraphs); + owners.facts.cells[local].3 = piece_story; + if let Some((_, _, WordReadFacts::Table(rows))) = owners.facts.items.first_mut() { + rows[row][cell] = paragraph_count; + } + if let Some((routes, _)) = &mut owners.cell_paragraphs { + routes.insert((0, row, cell), piece_routes); + } + // A field elsewhere in the table may remain. The flag may stay set + // until the next full read of the table, which a set flag asks for. + owners.holds_field |= holds_field; + #[cfg(debug_assertions)] + self.assert_local_cell_publication(body_slot, table_index, table_ordinal); Ok(true) } + /// Debug proof that a local cell publication leaves what a full read of + /// the table gives: the piece facts the inventory reads, body story + /// fingerprints aside, and the inventory records and cell paragraph + /// routes of its owners. + #[cfg(debug_assertions)] + fn assert_local_cell_publication( + &self, + body_slot: usize, + table_index: usize, + table_ordinal: usize, + ) { + guarded(|| { + let fresh = word_block_owners(&self.inner, &self.inner.body_children()[body_slot]) + .expect("a published table reads") + .expect("a published table has owner facts"); + let piece = self.pieces.as_ref().expect("active pieces").blocks[body_slot] + .owners + .as_ref() + .expect("piece owners"); + let content = |location: &rdocx::ContentLocation| { + if location.story().kind() == rdocx::StoryKind::Body { + unfingerprinted_location(location) + } else { + location.clone() + } + }; + let facts = |facts: &WordOwnerFacts| { + ( + facts + .items + .iter() + .filter(|(location, _, _)| { + location.story().kind() == rdocx::StoryKind::Body + || location.item_kind() == rdocx::StoryItemKind::Table + }) + .map(|(location, slot, read)| (content(location), *slot, read.clone())) + .collect::>(), + facts + .cells + .iter() + .map(|(table, row, cell, story)| { + (content(table), *row, *cell, story.clone()) + }) + .collect::>(), + facts.paragraphs.clone(), + facts.links.clone(), + ) + }; + assert_eq!( + facts(&piece.facts), + facts(&fresh.facts), + "local cell piece facts" + ); + assert_eq!( + ( + &piece.relationships, + piece.body_items, + piece.cell_stories, + piece.text_boxes, + &piece.paragraphs, + piece.tables, + piece.local_table_membership, + &piece.cell_paragraphs, + ), + ( + &fresh.relationships, + fresh.body_items, + fresh.cell_stories, + fresh.text_boxes, + &fresh.paragraphs, + fresh.tables, + fresh.local_table_membership, + &fresh.cell_paragraphs, + ), + "local cell piece counts" + ); + assert!(piece.holds_field || !fresh.holds_field); + let WordOwnerLocation::Table(location) = &self.owners[table_index].location else { + panic!("a local cell table owner") + }; + let cells = &self.indexes.cells_by_parent[&table_index]; + let base = cells + .iter() + .filter_map(|index| match &self.owners[*index].location { + WordOwnerLocation::Cell { story, .. } => Some(story.owner_index()), + _ => None, + }) + .min() + .expect("table cells"); + let stories = (base, 0); + let place = |route: &rdocx::ContentLocation| { + placed_route(route, location.story(), (location.index_path()[0], stories)) + }; + let mut placed = fresh.facts.clone(); + for (route, slot, _) in &mut placed.items { + *route = place(route); + *slot = slot.map(|_| body_slot); + } + for (table, _, _, story) in &mut placed.cells { + *table = place(table); + *story = placed_story(story, stories); + } + for (route, _, _) in &mut placed.paragraphs { + *route = place(route); + } + let expected = word_piece_owner_addresses(placed, 0); + let record = |address: &WordOwnerAddress, parent: Option<&WordOwnerLocation>| { + format!( + "{:?}", + ( + owner_location_without_body(&address.location), + parent.map(owner_location_without_body), + address.body_slot, + address.projection_ordinal, + &address.read_facts, + ) + ) + }; + let mut wanted = expected + .iter() + .map(|address| { + let mut address = body_unfingerprinted_address(address); + if address.parent.is_none() { + address.projection_ordinal = Some(table_ordinal); + } + record( + &address, + address.parent.map(|parent| &expected[parent].location), + ) + }) + .collect::>(); + let mut actual = Vec::new(); + let mut pending = vec![table_index]; + while let Some(index) = pending.pop() { + let owner = &self.owners[index]; + let address = WordOwnerAddress { + location: owner.location.clone(), + parent: owner.parent, + body_slot: owner.body_slot, + projection_ordinal: owner.projection_ordinal, + read_facts: owner.read_facts.clone(), + }; + let parent = owner.parent.map(|parent| &self.owners[parent].location); + actual.push(record(&address, parent)); + for children in [ + self.indexes.cells_by_parent.get(&index), + self.indexes.paragraphs_by_parent.get(&index), + self.indexes.runs_by_parent.get(&index), + self.indexes.tables_by_parent.get(&index), + ] + .into_iter() + .flatten() + { + pending.extend(children); + } + } + wanted.sort(); + actual.sort(); + assert_eq!(actual, wanted, "local cell owner records"); + if let Some((routes, _)) = &fresh.cell_paragraphs { + for ((_, row, cell), routes) in routes { + assert_eq!( + self.indexes + .cell_paragraphs + .get(&(table_ordinal, *row, *cell)), + Some(&routes.iter().map(place).collect::>()), + "local cell paragraph routes" + ); + } + } + }); + } + /// Keep live handles when a property edit only moves existing physical /// addresses. A real insert, removal or replacement keeps the conservative /// publication. @@ -12233,6 +12788,7 @@ impl PyDocument { candidate: rdocx::Document, operation: &'static str, ) -> PyResult<()> { + note_word_save_compare(); if self .inner .saves_as(&candidate) @@ -12257,6 +12813,7 @@ impl PyDocument { operation: &'static str, publication: WordPublication, ) -> PyResult<()> { + note_word_save_compare(); if self .inner .saves_as(&candidate) @@ -16024,10 +16581,10 @@ impl PyDocument { "chart legend requires a direct body paragraph", )); }; - let location = ParagraphLocation::Body(index) - .native(&slf.borrow(py).inner) - .map_err(|e| rdocx_to_pyerr(py, e))?; let mut document = slf.borrow_mut(py); + let location = document + .paragraph_route(&ParagraphLocation::Body(index), None) + .map_err(|e| rdocx_to_pyerr(py, e))?; let mut candidate = document.inner.clone_for_staging(); candidate .set_chart_legend(index, visible, position, overlay) diff --git a/crates/rdocx-py/src/formatting.rs b/crates/rdocx-py/src/formatting.rs index 1b1209f9a..f6151c77d 100644 --- a/crates/rdocx-py/src/formatting.rs +++ b/crates/rdocx-py/src/formatting.rs @@ -1266,8 +1266,8 @@ pub(crate) fn apply_paragraph_update( ParagraphLocation::Related(related.clone()) .edit(&mut candidate, |paragraph| update.apply(paragraph)) .map_err(|error| crate::rdocx_to_pyerr(py, error))?; - let native = location - .native(&document.inner) + let native = document + .paragraph_route(&location, None) .map_err(|error| crate::rdocx_to_pyerr(py, error))?; return document.publish_owner_candidate( py, diff --git a/crates/rdocx-py/src/lib.rs b/crates/rdocx-py/src/lib.rs index 75f49ce75..47a35dc86 100644 --- a/crates/rdocx-py/src/lib.rs +++ b/crates/rdocx-py/src/lib.rs @@ -139,6 +139,13 @@ fn _rdocx(module: &Bound<'_, PyModule>) -> PyResult<()> { #[cfg(debug_assertions)] module.add_function(wrap_pyfunction!(document::word_whole_body_work, module)?)?; #[cfg(debug_assertions)] + module.add_function(wrap_pyfunction!(document::word_publication_work, module)?)?; + #[cfg(debug_assertions)] + module.add_function(wrap_pyfunction!( + document::word_force_checked_route, + module + )?)?; + #[cfg(debug_assertions)] module.add_function(wrap_pyfunction!(document::word_splice_work, module)?)?; #[cfg(debug_assertions)] module.add_function(wrap_pyfunction!(document::word_transaction_work, module)?)?; @@ -157,6 +164,8 @@ fn _rdocx(module: &Bound<'_, PyModule>) -> PyResult<()> { #[cfg(debug_assertions)] module.add_function(wrap_pyfunction!(document::word_piece_alignments, module)?)?; #[cfg(debug_assertions)] + module.add_function(wrap_pyfunction!(document::word_piece_bytes, module)?)?; + #[cfg(debug_assertions)] module.add_function(wrap_pyfunction!(document::staging_work, module)?)?; #[cfg(debug_assertions)] module.add_function(wrap_pyfunction!(document::reopen_work, module)?)?; diff --git a/crates/rdocx-py/src/paragraph.rs b/crates/rdocx-py/src/paragraph.rs index 4b6b5e837..d15ee70b7 100644 --- a/crates/rdocx-py/src/paragraph.rs +++ b/crates/rdocx-py/src/paragraph.rs @@ -177,6 +177,7 @@ impl ParagraphLocation { location: &rdocx::ContentLocation, ) -> rdocx::Result { crate::document::note_fx260_word(document.content_count().max(1)); + crate::document::note_word_story_walk(); let owner = location.story(); let story = document .stories()? @@ -199,6 +200,9 @@ impl ParagraphLocation { document: &rdocx::Document, ) -> rdocx::Result { crate::document::note_fx260_word(document.content_count().max(1)); + if !matches!(self, Self::Related(_)) { + crate::document::note_word_story_walk(); + } match self { Self::Body(index) => document.paragraph_story_location(*index)?.ok_or_else(|| { rdocx::Error::Other("paragraph has no checked physical owner".to_owned()) @@ -546,8 +550,8 @@ impl PyParagraph { .map_err(|error| crate::rdocx_to_pyerr(py, error))? .ok_or_else(|| PyIndexError::new_err("inserted link run was not found"))?; let publication = crate::document::WordPublication::ParagraphAppend( - location - .native(&document.inner) + document + .paragraph_route(&location, None) .map_err(|error| crate::rdocx_to_pyerr(py, error))?, ); let prepared = document.prepare_word_revision( @@ -640,8 +644,8 @@ impl PyParagraph { "Paragraph.add_run" }; let publication = crate::document::WordPublication::ParagraphAppend( - location - .native(&document.inner) + document + .paragraph_route(&location, None) .map_err(|error| crate::rdocx_to_pyerr(py, error))?, ); let prepared = @@ -875,8 +879,8 @@ impl PyParagraph { .edit(&mut candidate, |p| p.add_equation(equation)) .map_err(|e| crate::rdocx_to_pyerr(py, e))?; let publication = crate::document::WordPublication::ParagraphAppend( - location - .native(&document.inner) + document + .paragraph_route(&location, None) .map_err(|error| crate::rdocx_to_pyerr(py, error))?, ); let prepared = document.prepare_word_revision( diff --git a/crates/rdocx-py/src/run.rs b/crates/rdocx-py/src/run.rs index f8f8029f6..3b466b8a8 100644 --- a/crates/rdocx-py/src/run.rs +++ b/crates/rdocx-py/src/run.rs @@ -296,20 +296,31 @@ impl PyRun { let mut document = self.document.borrow_mut(py); let publication = match &self.owner { Some(owner) => { - let (location, path) = document.current_run_owner(owner)?; + let (location, path) = document.run_route(owner)?; crate::document::WordPublication::RunText(crate::document::WordOwnerLocation::Run( location, path, )) } None => crate::document::WordPublication::Conservative, }; + // The typed edit below changes the paragraph of this run and nothing + // else, so a run of a direct body paragraph compares that block. + let slot = self + .owner + .as_ref() + .and_then(|owner| document.typed_run_edit_slot(&location, owner)); let mut candidate = document.inner.clone_for_staging(); location .edit(&mut candidate, |paragraph| { paragraph.edit_run(&self.run_path, |run| run.set_text(text)) }) .map_err(|error| crate::rdocx_to_pyerr(py, error))?; - document.publish_owner_candidate(py, candidate, "Run.text", publication) + match slot { + Some(slot) => { + document.publish_block_candidate(py, candidate, "Run.text", publication, slot) + } + None => document.publish_owner_candidate(py, candidate, "Run.text", publication), + } } #[pyo3(signature = (data, filename=None, width=None, height=None, *, options=None))] diff --git a/crates/rdocx-py/src/table.rs b/crates/rdocx-py/src/table.rs index b57d64f0d..89359d968 100644 --- a/crates/rdocx-py/src/table.rs +++ b/crates/rdocx-py/src/table.rs @@ -61,7 +61,7 @@ pub(crate) enum TableLocation { Related(rdocx::ContentLocation), } impl TableLocation { - fn new(index: usize, related: &Option) -> Self { + pub(crate) fn new(index: usize, related: &Option) -> Self { related.as_ref().map_or(Self::Body(index), |location| { Self::Related(location.clone()) }) @@ -74,6 +74,7 @@ impl TableLocation { match self { Self::Related(location) => Self::refreshed(document, location), Self::Body(index) => { + crate::document::note_word_story_walk(); let slot = document.content_index_of_table(*index).ok_or_else(|| { rdocx::Error::Other("table has no checked direct physical owner".into()) })?; @@ -91,6 +92,7 @@ impl TableLocation { location: &rdocx::ContentLocation, ) -> rdocx::Result { crate::document::note_fx260_word(document.content_count().max(1)); + crate::document::note_word_story_walk(); let owner = location.story(); let story = document .stories()? @@ -1202,8 +1204,8 @@ impl PyTable { } .map_err(|error| rdocx_to_pyerr(py, error))?; let publication = crate::document::WordPublication::TableGrid( - TableLocation::new(index, ¤t_related) - .native(&document.inner) + document + .table_route(index, ¤t_related) .map_err(|error| rdocx_to_pyerr(py, error))?, ); let prepared = @@ -1359,8 +1361,8 @@ impl PyTable { } .map_err(|error| rdocx_to_pyerr(py, error))?; let publication = crate::document::WordPublication::TableGrid( - TableLocation::new(table_index, ¤t_related) - .native(&document.inner) + document + .table_route(table_index, ¤t_related) .map_err(|error| rdocx_to_pyerr(py, error))?, ); let prepared = @@ -2585,8 +2587,8 @@ impl PyCell { None => candidate.try_set_cell_text(table, row, cell, value), } .map_err(|error| rdocx_to_pyerr(py, error))?; - let publication = TableLocation::new(table, ¤t_related) - .native(&document.inner) + let publication = document + .table_route(table, ¤t_related) .map(|location| crate::document::WordPublication::CellText(location, row, cell)) .unwrap_or(crate::document::WordPublication::Conservative); let prepared = document.prepare_word_revision(py, &candidate, "Cell.text", publication)?; diff --git a/crates/rdocx-py/tests/test_edit_publication_cost.py b/crates/rdocx-py/tests/test_edit_publication_cost.py new file mode 100644 index 000000000..f1fdae7ca --- /dev/null +++ b/crates/rdocx-py/tests/test_edit_publication_cost.py @@ -0,0 +1,537 @@ +"""Which whole-document passes a mutating call makes when it publishes, and that the direct routes agree with the +checked ones. + +A whole-document pass is work in proportion to the document whatever the edit: a staging clone of the document, a +walk of a story to resolve a route, a comparison of two staged saves, a publication that matches the whole owner +inventory, a rebuild of that inventory, a reopen of the package. The debug build of the extension counts them +(`_word_publication_work`, `_word_whole_body_work`, `_reopen_work`) outside the guards that check a direct route, so +the counts are those of the call. No timing is read. + +FLAT names the calls that make no such pass and do the same counted work in a body four times larger. A cell edit +also does the same counted work in a table twenty times larger and beside a cell of a hundred thousand characters. +The counted work includes the bytes of the blocks whose owners the checked reader reads again +(`_word_piece_bytes`), so a cell edit that read its whole table would show. GROWING names the others with the passes +each one still makes. The flat test is a strict expected failure for a GROWING call, and its passes are asserted +exactly, so a change that makes a call flat or removes one of its passes fails until the entry +moves or shrinks, and a change that adds a pass fails as well. + +`_word_force_checked_route` makes every publication resolve its route by a story walk and compare staged saves, and +every properties edit stage the document: the checked whole-document routes the direct ones replace. Each call must +give the same result, the same saved parts and the same held handles on both. +""" +import datetime +import re +from io import BytesIO +from types import SimpleNamespace +from zipfile import ZipFile + +import pytest + +import rdocx +from rdocx import _rdocx + +pytestmark = pytest.mark.skipif( + not hasattr(_rdocx, "_word_publication_work"), + reason="the publication counters and the route switch exist in debug builds only", +) + +BODY = 8 +STAMP = datetime.datetime(2026, 10, 1, 12, tzinfo=datetime.timezone.utc) + + +def build(paragraphs, rows=2, columns=2, last_cell=""): + """A body of `paragraphs` paragraphs, then a table whose first cell holds "gamma" and whose last cell holds + `last_cell`, and a paragraph of the runs "alpha " and "beta".""" + document = rdocx.Document() + for index in range(paragraphs): + document.add_paragraph(f"Body paragraph {index}") + table = document.add_table(rows, columns) + table.cell(0, 0).text = "gamma" + if last_cell: + table.cell(rows - 1, columns - 1).text = last_cell + document.add_paragraph("alpha ").add_run("beta") + return document + + +def targets(document): + paragraph = document.paragraphs[-1] + return SimpleNamespace(document=document, paragraph=paragraph, run=paragraph.runs[1], table=document.tables[0]) + + +def setter(owner, name, value): + """Set `name` on the object `owner` gives, taken before the call is counted.""" + return lambda t: (lambda target=owner(t): setattr(target, name, value)) + + +def method(owner, name, *arguments): + return lambda t: (lambda target=owner(t): getattr(target, name)(*arguments)) + + +def core(t): + return t.document.core_properties + + +def app(t): + return t.document.app_properties + + +def custom(t): + return t.document.custom_properties + + +def with_client(t): + properties = t.document.custom_properties + properties.set("Client", "ACME") + return properties + + +def cell(t): + return t.table.cell(0, 0) + + +def cell_with_properties(t): + """A cell that already writes its properties, so a property edit moves none of its items.""" + t.table.cell(0, 0).width = rdocx.Inches(1) + return t.document.tables[0].cell(0, 0) + + +def cell_with_table(t): + """A cell that holds a table, which the selected-table candidate of a cell edit declines.""" + t.table.cell(0, 0).add_table(1, 1) + return t.document.tables[0].cell(0, 0) + + +def bookmarked(t): + start, end = rdocx.RunPosition(body_index=0, run_index=0), rdocx.RunPosition(body_index=0, run_index=1) + t.document.add_bookmark("mark", rdocx.RunRange(start=start, end=end)) + return t.document.paragraphs[-1] + + +def with_chart(t): + data = rdocx.CategoryChartData() + data.categories = ["a", "b"] + data.add_series("series", (1.0, 2.0)) + chart = t.document.add_chart(rdocx.XL_CHART_TYPE.COLUMN_CLUSTERED, data, rdocx.Inches(3), rdocx.Inches(2)) + return lambda: t.document.set_chart_legend(chart, visible=True, position="b") + + +CALLS = { + "AppProperties.application": setter(app, "application", "An application"), + "AppProperties.application_version": setter(app, "application_version", "16.0000"), + "AppProperties.company": setter(app, "company", "A company"), + "AppProperties.manager": setter(app, "manager", "A manager"), + "AppProperties.presentation_format": setter(app, "presentation_format", "A format"), + "AppProperties.template": setter(app, "template", "A template"), + "CustomProperties.set": method(custom, "set", "Client", "ACME"), + "CustomProperties.__setitem__": method(custom, "__setitem__", "Client", "ACME"), + "CustomProperties.delete": method(with_client, "delete", "Client"), + "CustomProperties.__delitem__": method(with_client, "__delitem__", "Client"), + "Font.bold": setter(lambda t: t.run.font, "bold", True), + "Paragraph.alignment": setter(lambda t: t.paragraph, "alignment", rdocx.WD_ALIGN_PARAGRAPH.CENTER), + "ParagraphFormat.left_indent": setter(lambda t: t.paragraph.paragraph_format, "left_indent", rdocx.Inches(1)), + "Cell.text": setter(cell, "text", "12.50"), + "Cell.shading": setter(cell, "shading", "D9E2F3"), + "Cell.vertical_alignment": setter(cell, "vertical_alignment", rdocx.WD_CELL_VERTICAL_ALIGNMENT.CENTER), + "Cell.width": setter(cell, "width", rdocx.Inches(1)), + "Cell.set_border": lambda t: (lambda target=cell(t): target.set_border("top", "single", size=4, color="000000")), + "Cell.set_margins": lambda t: (lambda target=cell(t): target.set_margins(top=10, right=10, bottom=10, left=10)), + "Paragraph.text of a cell paragraph": setter(lambda t: t.table.cell(0, 0).paragraphs[0], "text", "12.50"), + "Paragraph.add_run": method(lambda t: t.paragraph, "add_run", " gamma"), + "Paragraph.add_hyperlink": method(lambda t: t.paragraph, "add_hyperlink", "link", "https://example.com/a"), + "Paragraph.add_internal_hyperlink": method(bookmarked, "add_internal_hyperlink", "link", "mark"), + "Paragraph.add_equation": lambda t: (lambda target=t.paragraph: target.add_equation("x^2", format="latex")), + "Cell.text of a cell that holds a table": setter(cell_with_table, "text", "12.50"), + "Document.set_chart_legend": with_chart, + "Paragraph.text": setter(lambda t: t.paragraph, "text", "changed"), + "Run.text": setter(lambda t: t.run, "text", "changed"), + "Run.add_break": method(lambda t: t.run, "add_break"), + "Run.add_tab": method(lambda t: t.run, "add_tab"), + "Table.style": setter(lambda t: t.table, "style", "Table Grid"), + "Table.add_row": method(lambda t: t.table, "add_row"), + "Table.remove_row": method(lambda t: t.table, "remove_row", 1), + "Settings.track_revisions": setter(lambda t: t.document.settings, "track_revisions", True), + "Document.add_paragraph": method(lambda t: t.document, "add_paragraph", "new"), + "Document.add_table": method(lambda t: t.document, "add_table", 1, 1), +} +for name in ("author", "category", "comments", "content_status", "identifier", "keywords", "language", + "last_modified_by", "subject", "title", "version"): + CALLS[f"CoreProperties.{name}"] = setter(core, name, f"A {name}") +for name in ("created", "modified", "last_printed"): + CALLS[f"CoreProperties.{name}"] = setter(core, name, STAMP) +CALLS["CoreProperties.revision"] = setter(core, "revision", 7) + +# Cell edits that read the facts of their cell alone, whatever the body and the table. +CELL_CALLS = ("Cell.text", "Cell.shading", "Cell.vertical_alignment", "Cell.width", "Cell.set_border", + "Cell.set_margins", "Paragraph.text of a cell paragraph") + +# Calls that make no whole-document pass and do the same counted work whatever the body. +FLAT = ( + "AppProperties.application", "AppProperties.application_version", "AppProperties.company", + "AppProperties.manager", "AppProperties.presentation_format", "AppProperties.template", + "CoreProperties.author", "CoreProperties.category", "CoreProperties.comments", "CoreProperties.content_status", + "CoreProperties.created", "CoreProperties.identifier", "CoreProperties.keywords", "CoreProperties.language", + "CoreProperties.last_modified_by", "CoreProperties.last_printed", "CoreProperties.modified", + "CoreProperties.revision", "CoreProperties.subject", "CoreProperties.title", "CoreProperties.version", + "CustomProperties.__delitem__", "CustomProperties.__setitem__", "CustomProperties.delete", + "CustomProperties.set", + "Font.bold", "Paragraph.alignment", "ParagraphFormat.left_indent", +) + CELL_CALLS + +# Calls whose work grows with the body, with the whole-document passes each one makes. A walk in an entry resolves +# the story address its native edit takes, not the route of its publication. An empty entry makes no pass but visits +# every owner record. +GROWING = { + "Paragraph.add_run": {"clones": 1, "publications": 1}, + "Paragraph.add_hyperlink": {"clones": 2, "publications": 1}, + "Paragraph.add_internal_hyperlink": {"clones": 6, "walks": 1, "publications": 1, "rebuilds": 1, "reopens": 1}, + "Paragraph.add_equation": {"clones": 1, "publications": 1}, + "Cell.text of a cell that holds a table": {"clones": 4, "publications": 1, "rebuilds": 1, "reopens": 1}, + "Document.set_chart_legend": {"clones": 5, "compares": 1, "publications": 1, "rebuilds": 1, "reopens": 1}, + "Paragraph.text": {"clones": 1, "publications": 1}, + "Run.text": {"clones": 1, "publications": 1}, + "Run.add_break": {"clones": 1}, + "Run.add_tab": {"clones": 1}, + "Table.style": {"clones": 1}, + "Table.add_row": {"clones": 3, "publications": 1, "rebuilds": 1, "reopens": 1}, + "Table.remove_row": {"clones": 4, "publications": 1, "rebuilds": 1, "reopens": 1}, + "Settings.track_revisions": {"clones": 1}, + "Document.add_paragraph": {}, + "Document.add_table": {}, +} + + +def work(): + """The whole-document passes and the other counted work since the last read. Reading resets every counter.""" + clones, walks, compares, publications = _rdocx._word_publication_work() + rebuilds, source_reads = _rdocx._word_whole_body_work() + passes = {"clones": clones, "walks": walks, "compares": compares, "publications": publications, + "rebuilds": rebuilds, "reopens": _rdocx._reopen_work()[0]} + rest = {"source_reads": source_reads, "piece_reads": _rdocx._word_piece_work(), + "piece_bytes": _rdocx._word_piece_bytes(), "alignments": _rdocx._word_piece_alignments(), + "owner_visits": _rdocx._word_splice_work()[0], "staging": list(_rdocx._staging_work())} + return {name: count for name, count in passes.items() if count}, rest + + +def measure(name, paragraphs, rows=2, columns=2, last_cell=""): + act = CALLS[name](targets(build(paragraphs, rows, columns, last_cell))) + work() + act() + return work() + + +@pytest.mark.parametrize("name", [ + pytest.param(name, marks=pytest.mark.xfail(strict=True, reason="its work still grows with the body")) + if name in GROWING else name + for name in sorted(CALLS) +]) +def test_call_makes_no_whole_document_pass_and_the_same_work_in_a_larger_body(name): + small, large = measure(name, BODY), measure(name, 4 * BODY) + assert small[0] == {} and large[0] == {} + assert small[1] == large[1] + + +@pytest.mark.parametrize("name", CELL_CALLS) +def test_cell_call_makes_no_whole_document_pass_and_the_same_work_in_a_larger_table(name): + small, large = measure(name, BODY, 2, 5), measure(name, BODY, 40, 5) + assert small[0] == {} and large[0] == {} + assert small[1] == large[1] + assert small[1]["piece_bytes"] > 0 + + +@pytest.mark.parametrize("name", CELL_CALLS) +def test_cell_call_does_the_same_work_beside_a_large_cell(name): + small, large = measure(name, BODY, 2, 5, "x"), measure(name, BODY, 2, 5, "x" * 100_000) + assert small[0] == {} and large[0] == {} + assert small[1] == large[1] + + +@pytest.mark.parametrize("name", sorted(GROWING)) +def test_growing_call_makes_only_its_declared_whole_document_passes(name): + for paragraphs in (BODY, 4 * BODY): + assert measure(name, paragraphs)[0] == GROWING[name] + + +def test_every_call_is_flat_or_growing(): + assert not set(FLAT) & set(GROWING) + assert sorted(set(FLAT) | set(GROWING)) == sorted(CALLS) + + +def test_run_text_that_changes_nothing_publishes_nothing_and_saves_nothing(): + document = build(BODY) + run = document.paragraphs[-1].runs[1] + held = document.paragraphs[-1].runs[0] + work() + run.text = "beta" + assert work()[0] == {"clones": 1} + assert (run.text, held.text) == ("beta", "alpha ") + + +def test_run_text_of_a_paragraph_that_is_not_plain_keeps_the_staged_save_comparison(): + document = build(BODY) + paragraph = document.paragraphs[-1] + paragraph.add_hyperlink("link", "https://example.com/a") + run = document.paragraphs[-1].runs[1] + work() + run.text = "changed" + passes = work()[0] + assert passes["compares"] == 1 and passes["publications"] == 1 + assert document.paragraphs[-1].text == "alpha changedlink" + + +def test_run_text_publishes_beside_content_that_no_save_accepts_and_save_reports_it(): + def document(): + result = rdocx.Document() + result.add_paragraph("first") + result.add_paragraph("alpha ").add_run("beta") + result.paragraphs[0].text = "a\x00b" + return result + + for text, expected in (("changed", "alpha changed"), ("beta", "alpha beta")): + direct = document() + direct.paragraphs[1].runs[1].text = text + assert direct.paragraphs[1].text == expected + with pytest.raises(rdocx.PackageError, match="U\\+0000"): + direct.save(BytesIO()) + checked = document() + run = checked.paragraphs[1].runs[1] + previous = _rdocx._word_force_checked_route(True) + try: + with pytest.raises(rdocx.PackageError, match="U\\+0000"): + run.text = text + finally: + _rdocx._word_force_checked_route(previous) + assert checked.paragraphs[1].text == "alpha beta" + + +TEXT_BOX = "box" +TEXT_BOX_BODY = ( + "anchor ' + '' + '' + '' + f"{TEXT_BOX}" + f'{TEXT_BOX}' + "" +) + + +def with_body(body): + """A document opened from a package whose main part holds `body`.""" + result = BytesIO() + with ZipFile(BytesIO(rdocx.Document().to_bytes())) as package, ZipFile(result, "w") as output: + for member in package.infolist(): + data = package.read(member.filename) + if member.filename == "word/document.xml": + data = re.sub(rb".*", body.encode(), data, flags=re.S) + output.writestr(member, data) + return rdocx.Document.from_bytes(result.getvalue()) + + +def text_box_format(): + """The document and the format of the paragraph in the text box of TEXT_BOX_BODY.""" + document = with_body(TEXT_BOX_BODY) + paragraph = next(item.paragraph for item in document.story_items + if item.kind == "paragraph" and item.story.kind == "text_box") + return document, paragraph.paragraph_format + + +def test_text_box_paragraph_format_walks_for_its_edit_address_alone(): + saved = {} + for forced, walks in ((False, 2), (True, 3)): + document, paragraph_format = text_box_format() + work() + previous = _rdocx._word_force_checked_route(forced) + try: + paragraph_format.left_indent = rdocx.Inches(1) + finally: + _rdocx._word_force_checked_route(previous) + passes = work()[0] + assert (passes["walks"], passes["compares"], passes["publications"]) == (walks, 1, 1) + saved[forced] = parts(document) + assert saved[False] == saved[True] + + +def cell_xml(content, properties=""): + return f"{properties}{content}" + + +def text(value): + return f"{value}" + + +def table_xml(columns, *rows): + grid = "".join('' for _ in range(columns)) + return (f"{grid}" + "".join(f"{row}" for row in rows) + + "") + + +# Opened tables whose cells a lone cell might read differently from the whole table, with the cells edited. +CELL_TABLES = { + "merged cells": (table_xml( + 3, + cell_xml(text("a"), '') + + cell_xml(text("b"), ''), + cell_xml("", "") + cell_xml(text("c")) + cell_xml(text("d")), + ), ((0, 1), (1, 0))), + "a bookmark across two cells": (table_xml( + 2, + cell_xml('left') + + cell_xml('right'), + ), ((0, 0), (0, 1))), + "a field in one cell": (table_xml( + 2, + cell_xml(text("left")) + + cell_xml('1'), + ), ((0, 0), (0, 1))), + "row attributes and properties, and markers between cells and rows": ( + '' + '' + cell_xml(text("a")) + + '' + cell_xml(text("b")) + "" + + '' + cell_xml(text("c")) + cell_xml(text("d")) + "" + "", + ((0, 0), (0, 1), (1, 0)), + ), + "an empty cell property element": (table_xml( + 2, cell_xml(text("left"), "") + cell_xml(text("right")), + ), ((0, 0),)), +} + +CELL_EDITS = { + "Cell.shading": lambda cell: setattr(cell, "shading", "D9E2F3"), + "Cell.text": lambda cell: setattr(cell, "text", "12.50"), + "Paragraph.text of a cell paragraph": lambda cell: setattr(cell.paragraphs[0], "text", "12.50"), +} + + +@pytest.mark.parametrize("table", sorted(CELL_TABLES)) +@pytest.mark.parametrize("edit", sorted(CELL_EDITS)) +def test_cell_edit_of_an_opened_table_gives_the_result_handles_and_saved_parts_of_the_checked_route(table, edit): + body, coordinates = CELL_TABLES[table] + for row, column in coordinates: + results = {} + for forced in (False, True): + document = with_body(body) + held = {} + for r, cells in enumerate(document.tables[0].rows): + for c, current in enumerate(cells.cells): + held[f"cell {r} {c}"] = current + held[f"cell {r} {c} paragraph"] = current.paragraphs[0] + held.update({f"cell {r} {c} run": run for run in current.paragraphs[0].runs[:1]}) + target = document.tables[0].rows[row].cells[column] + work() + previous = _rdocx._word_force_checked_route(forced) + try: + CELL_EDITS[edit](target) + finally: + _rdocx._word_force_checked_route(previous) + # Each shape stays on the local route, which makes no whole-document pass. + assert (work()[0] == {}) is not forced + results[forced] = ({name: probe(handle) for name, handle in held.items()}, parts(document)) + assert results[False] == results[True], (row, column) + + +def parts(document): + stream = BytesIO() + document.save(stream) + with ZipFile(BytesIO(stream.getvalue())) as package: + return {name: package.read(name) for name in package.namelist()} + + +def probe(handle): + """What a held handle reads after the call, or the error that says it is stale.""" + try: + for name in ("text", "bold", "left_indent", "page_width"): + if hasattr(type(handle), name): + return "read", repr(getattr(handle, name)) + return "read", len(handle.rows) + except Exception as error: # noqa: BLE001 - the error is the result compared + return type(error).__name__, str(error) + + +def held_handles(document): + first, last = document.paragraphs[0], document.paragraphs[-1] + table = document.tables[0] + return { + "another paragraph": first, "its run": first.runs[0], "the paragraph": last, "its first run": last.runs[0], + "its second run": last.runs[1], "its font": last.runs[1].font, "its format": last.paragraph_format, + "the table": table, "a cell": table.cell(0, 0), "a cell paragraph": table.cell(1, 1).paragraphs[0], + "the first cell's paragraph": table.cell(0, 0).paragraphs[0], + "its cell run": table.cell(0, 0).paragraphs[0].runs[0], "a cell of the same row": table.cell(0, 1), + "the paragraph of that cell": table.cell(0, 1).paragraphs[0], + "the section": document.section(0), + } + + +def outcome(prepare, forced): + document = build(BODY) + held = held_handles(document) + act = prepare(targets(document)) + previous = _rdocx._word_force_checked_route(forced) + try: + try: + value = act() + result = ("returned", type(value).__name__, getattr(value, "text", value if value is None else None)) + except Exception as error: # noqa: BLE001 - the error is the result compared + result = (type(error).__name__, str(error)) + finally: + _rdocx._word_force_checked_route(previous) + return result, {name: probe(handle) for name, handle in held.items()}, parts(document) + + +DIFFERENTIAL = dict(CALLS) +DIFFERENTIAL.update({ + "Run.text unchanged": setter(lambda t: t.run, "text", "beta"), + "Run.text with a character no save accepts": setter(lambda t: t.run, "text", "a\x00b"), + "Run.text with a tab and a line break": setter(lambda t: t.run, "text", "a\tb\nc"), + "Run.text emptied": setter(lambda t: t.run, "text", ""), + "AppProperties.application_version refused": setter(app, "application_version", "sixteen"), + "CustomProperties.delete of a missing name": method(custom, "__delitem__", "Missing"), + "Cell.shading of a cell that writes its properties": setter(cell_with_properties, "shading", "D9E2F3"), + "Cell.text with a tab and a line break": setter(cell, "text", "a\tb\nc"), + "Cell.text with a character no save accepts": setter(cell, "text", "a\x00b"), + "Cell.set_margins refused": lambda t: ( + lambda target=cell(t): target.set_margins(top=-1, right=0, bottom=0, left=0)), +}) + + +@pytest.mark.parametrize("name", sorted(DIFFERENTIAL)) +def test_direct_route_gives_the_result_handles_and_saved_parts_of_the_checked_route(name): + direct, checked = outcome(DIFFERENTIAL[name], False), outcome(DIFFERENTIAL[name], True) + assert direct[0] == checked[0] + assert direct[1] == checked[1] + assert direct[2] == checked[2] + + +@pytest.mark.parametrize("name", [ + "Run.text with a character no save accepts", "AppProperties.application_version refused", + "CustomProperties.delete of a missing name", "Cell.text with a character no save accepts", + "Cell.set_margins refused", +]) +def test_refused_edit_changes_nothing(name): + untouched = build(BODY) + result, held, saved = outcome(DIFFERENTIAL[name], False) + assert result[0] != "returned" + assert saved == parts(untouched) + assert all(kind == "read" for kind, _ in held.values()) + + +def test_forced_checked_route_makes_the_passes_the_direct_routes_replace(): + forced = {} + previous = _rdocx._word_force_checked_route(True) + try: + for name in ("CoreProperties.title", "Paragraph.add_run", "Run.text", "Table.add_row", "Cell.shading", + "Cell.text"): + forced[name] = measure(name, BODY)[0] + finally: + _rdocx._word_force_checked_route(previous) + assert forced["CoreProperties.title"] == {"clones": 1} + assert forced["Paragraph.add_run"]["walks"] == 2 + assert (forced["Run.text"]["walks"], forced["Run.text"]["compares"]) == (1, 1) + assert forced["Table.add_row"]["walks"] == 1 + assert forced["Cell.shading"] == {"clones": 1} + assert (forced["Cell.text"]["walks"], forced["Cell.text"]["publications"]) == (1, 1) diff --git a/crates/rdocx/src/document.rs b/crates/rdocx/src/document.rs index 7f024a7ac..efcfed9a5 100644 --- a/crates/rdocx/src/document.rs +++ b/crates/rdocx/src/document.rs @@ -7436,6 +7436,40 @@ impl Drop for TransactionReadPhase { } } +#[cfg(debug_assertions)] +thread_local! { + static STAGING_CLONES: Cell = const { Cell::new(0) }; + static STAGED_PROPERTIES_FORCED: Cell = const { Cell::new(false) }; +} + +/// Whole-document staging clones made on this thread since the last read. +/// Debug builds only. Reading resets the count. +#[cfg(debug_assertions)] +#[doc(hidden)] +pub fn take_staging_clones() -> usize { + STAGING_CLONES.with(|count| count.replace(0)) +} + +/// Make the properties setters stage a whole document, the reference their +/// direct route is compared with. Debug builds only. Returns the previous +/// choice. +#[cfg(debug_assertions)] +#[doc(hidden)] +pub fn force_staged_properties(force: bool) -> bool { + STAGED_PROPERTIES_FORCED.with(|forced| forced.replace(force)) +} + +fn staged_properties_forced() -> bool { + #[cfg(debug_assertions)] + { + STAGED_PROPERTIES_FORCED.with(Cell::get) + } + #[cfg(not(debug_assertions))] + { + false + } +} + fn note_transaction_clone() { #[cfg(debug_assertions)] TRANSACTION_WORK.with(|work| { @@ -8735,10 +8769,13 @@ fn assert_kept_main_document_without_initializing( #[allow(dead_code)] fn without_staging_work(run: impl FnOnce() -> T) -> T { let paused = STAGING_WORK_PAUSED.with(|cell| cell.replace(true)); + // A debug reference stages clones of its own, which are not the call's. + let clones = STAGING_CLONES.with(Cell::get); #[cfg(test)] let result = a9_without_lookup_work(run); #[cfg(not(test))] let result = run(); + STAGING_CLONES.with(|count| count.set(clones)); STAGING_WORK_PAUSED.with(|cell| cell.set(paused)); result } @@ -25128,6 +25165,8 @@ impl Document { /// Clone all package and typed state while discarding derived layout caches. pub fn clone_for_staging(&self) -> Self { + #[cfg(debug_assertions)] + STAGING_CLONES.with(|count| count.set(count.get() + 1)); Self { package: self.package.clone(), document: self.document.clone(), @@ -25201,7 +25240,7 @@ impl Document { /// Independent cold reference state for debug agreement oracles only. #[cfg(debug_assertions)] fn clone_for_debug_reference(&self) -> Self { - let mut copy = self.clone_for_staging(); + let mut copy = without_staging_work(|| self.clone_for_staging()); copy.parsed = None; copy.main_part_blocks = None; copy.main_body_scans = Arc::new(Mutex::new(MainBodyScans::default())); @@ -27125,6 +27164,106 @@ impl Document { candidate } + /// Apply `edit`, a properties edit, without staging the whole document. + /// + /// `edit` first reserves the properties part in the package graph and the + /// identifier registry, which can fail, then writes the properties model + /// and its part name, which cannot. The package graph, whose part bytes + /// are shared, and the registry are saved first and put back on refusal, + /// so a refused edit leaves no reserved name or relationship id. A + /// success leaves what [`Self::commit_staged_mutation`] leaves for a + /// staged clone: the derived layout is dropped and a signed package + /// records a package mutation. Debug builds run the staged edit on a + /// clone and compare. `edit` is `Fn` for that second run. + fn edit_properties(&mut self, edit: impl Fn(&mut Self) -> Result<()>) -> Result<()> { + if staged_properties_forced() { + let mut candidate = self.clone_for_staging(); + edit(&mut candidate)?; + self.commit_staged_mutation(candidate); + return Ok(()); + } + #[cfg(debug_assertions)] + let staged = without_staging_work(|| self.clone_for_staging()); + let package = self.package.clone(); + let identifiers = self.identifiers.clone(); + let result = edit(self); + match &result { + Ok(()) => { + self.package_signatures_invalidated |= + self.package.package_rels.items.iter().any(|relationship| { + relationship.rel_type == rel_types::DIGITAL_SIGNATURE_ORIGIN + }) && (self.package_signatures_invalidated + || crate::embedded::synchronized_package_mutation_invalidates_signature( + &package, + &self.package, + )); + self.layout_cache + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + self.deterministic_layout_cache + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + } + Err(_) => { + self.package = package; + self.identifiers = identifiers; + } + } + #[cfg(debug_assertions)] + self.assert_properties_edit_matches_staged(staged, &edit, &result); + result + } + + /// Debug proof that a direct properties edit left the package graph, the + /// properties models and their part names of the staged edit, or + /// refused with its error. + #[cfg(debug_assertions)] + fn assert_properties_edit_matches_staged( + &self, + mut staged: Self, + edit: &impl Fn(&mut Self) -> Result<()>, + result: &Result<()>, + ) { + match (result, edit(&mut staged)) { + (Ok(()), Ok(())) => { + assert!( + staged.package.same_package_as(&self.package), + "direct properties edit changed another package graph" + ); + assert_eq!( + staged.identifiers, self.identifiers, + "direct properties edit left another identifier registry" + ); + assert_eq!(staged.core_properties, self.core_properties); + assert_eq!( + format!("{:?}", staged.application_properties), + format!("{:?}", self.application_properties) + ); + assert_eq!(staged.custom_properties, self.custom_properties); + assert_eq!( + ( + &staged.core_properties_part_name, + &staged.application_properties_part_name, + &staged.custom_properties_part_name, + staged.custom_properties_owned, + ), + ( + &self.core_properties_part_name, + &self.application_properties_part_name, + &self.custom_properties_part_name, + self.custom_properties_owned, + ), + "direct properties edit named another part" + ); + } + (Err(direct), Err(staged)) => assert_eq!(direct.to_string(), staged.to_string()), + (Ok(()), Err(staged)) => panic!("direct properties edit hid the staged error {staged}"), + (Err(direct), Ok(())) => panic!("direct properties edit refused with {direct}"), + } + } + pub(crate) fn commit_staged_mutation(&mut self, candidate: Self) { *self = Self::finish_staged_candidate( &self.package, @@ -39867,6 +40006,12 @@ impl Document { } /// Prepare one owner-free direct-body cell edit without changing this document. + /// + /// Returns the edited cell alone in a frame of its table: the table's + /// properties and grid, and one row with the row's properties and this + /// cell. The frame is validated as a body holding it alone. The model + /// limits bound the nesting along each path, and the paths through this + /// cell are the same in the frame and in the table. #[doc(hidden)] pub fn direct_body_table_cell_candidate( &self, @@ -39892,18 +40037,38 @@ impl Document { { return Ok(None); } - let Some(selected) = source.rows.get(row).and_then(|row| row.cells.get(cell)) else { + let Some(source_row) = source.rows.get(row) else { + return Ok(None); + }; + let Some(selected) = source_row.cells.get(cell) else { return Ok(None); }; if selected.content.iter().any(|item| !matches!(item, rdocx_oxml::table::CellContent::Paragraph(paragraph) if paragraph.content_controls.is_empty())) { return Ok(None); } - let mut table = (**source).clone(); - edit(&mut crate::table::Cell { - inner: &mut table.rows[row].cells[cell], - })?; + let mut edited = selected.clone(); + edit(&mut crate::table::Cell { inner: &mut edited })?; + let frame = CT_Tbl { + properties: source.properties.clone(), + grid: source.grid.clone(), + rows: vec![rdocx_oxml::table::CT_Row { + table_property_exception: source_row.table_property_exception.clone(), + properties: source_row.properties.clone(), + cells: vec![edited], + // The start tag attributes, not the raw children between cells. + extra_xml: source_row + .extra_xml + .iter() + .filter(|(at, _)| *at == usize::MAX) + .cloned() + .collect(), + content_controls: Vec::new(), + }], + extra_xml: Vec::new(), + content_controls: Vec::new(), + }; let mut body = CT_Body { - content: vec![BodyContent::Table(Box::new(table))], + content: vec![BodyContent::Table(Box::new(frame))], sect_pr: None, }; body.validate_resource_limits()?; @@ -39913,9 +40078,16 @@ impl Document { Ok(Some(*table)) } - /// Install the prepared table under the same exclusive source qualification. + /// Install the cell of a prepared frame at `row` and `cell` of the table, + /// under the same exclusive source qualification. #[doc(hidden)] - pub fn commit_direct_body_table(&mut self, body_slot: usize, table: CT_Tbl) { + pub fn commit_direct_body_table_cell( + &mut self, + body_slot: usize, + row: usize, + cell: usize, + frame: CT_Tbl, + ) { assert!( self.local_cell_source .as_ref() @@ -39924,7 +40096,13 @@ impl Document { let BodyContent::Table(existing) = &mut self.document.body.content[body_slot] else { panic!("qualified direct table changed kind") }; - **existing = table; + let edited = frame + .rows + .into_iter() + .next() + .and_then(|row| row.cells.into_iter().next()) + .expect("a prepared cell frame"); + existing.rows[row].cells[cell] = edited; self.invalidate_layout(); self.unsavable_body_edit_cache = OnceLock::from(None); } @@ -47904,11 +48082,11 @@ impl Document { /// Replace the complete core-properties model. pub fn set_core_properties(&mut self, properties: CoreProperties) -> Result<()> { - let mut candidate = self.clone_for_staging(); - candidate.reserve_core_properties_bundle()?; - candidate.core_properties = Some(Box::new(properties)); - self.commit_staged_mutation(candidate); - Ok(()) + self.edit_properties(|document| { + document.reserve_core_properties_bundle()?; + document.core_properties = Some(Box::new(properties.clone())); + Ok(()) + }) } /// Remove the complete core-properties part and its package relationship. @@ -47943,11 +48121,11 @@ impl Document { (two digits, a dot, four digits), which Word requires to open the file" ))); } - let mut candidate = self.clone_for_staging(); - candidate.reserve_application_properties_bundle()?; - candidate.application_properties = Some(properties); - self.commit_staged_mutation(candidate); - Ok(()) + self.edit_properties(|document| { + document.reserve_application_properties_bundle()?; + document.application_properties = Some(properties.clone()); + Ok(()) + }) } /// Remove the complete application-properties part and package relationship. @@ -48002,27 +48180,27 @@ impl Document { ))); } - let mut candidate = self.clone_for_staging(); - let created = candidate.custom_properties_part_name.is_none(); - candidate.reserve_custom_properties_bundle()?; - let properties = candidate - .custom_properties - .get_or_insert_with(CustomProperties::default); - if let Some(index) = properties - .properties - .iter() - .position(|existing| existing.name.as_deref() == Some(name)) - { - properties + self.edit_properties(|document| { + let created = document.custom_properties_part_name.is_none(); + document.reserve_custom_properties_bundle()?; + let properties = document + .custom_properties + .get_or_insert_with(CustomProperties::default); + if let Some(index) = properties .properties - .retain(|existing| existing.name.as_deref() != Some(name)); - properties.properties.insert(index, property); - } else { - properties.properties.push(property); - } - candidate.custom_properties_owned |= created; - self.commit_staged_mutation(candidate); - Ok(()) + .iter() + .position(|existing| existing.name.as_deref() == Some(name)) + { + properties + .properties + .retain(|existing| existing.name.as_deref() != Some(name)); + properties.properties.insert(index, property.clone()); + } else { + properties.properties.push(property.clone()); + } + document.custom_properties_owned |= created; + Ok(()) + }) } /// Remove one named custom property. @@ -48035,23 +48213,24 @@ impl Document { else { return Ok(None); }; - let mut candidate = self.clone_for_staging(); - let properties = candidate - .custom_properties - .as_mut() - .expect("custom property lookup proved the model exists"); - properties - .properties - .retain(|property| property.name.as_deref() != Some(name)); - if properties.properties.is_empty() && candidate.custom_properties_owned { - if let Some(part_name) = candidate.custom_properties_part_name.take() { - candidate - .remove_package_properties_bundle(&part_name, rel_types::CUSTOM_PROPERTIES); + self.edit_properties(|document| { + let properties = document + .custom_properties + .as_mut() + .expect("custom property lookup proved the model exists"); + properties + .properties + .retain(|property| property.name.as_deref() != Some(name)); + if properties.properties.is_empty() && document.custom_properties_owned { + if let Some(part_name) = document.custom_properties_part_name.take() { + document + .remove_package_properties_bundle(&part_name, rel_types::CUSTOM_PROPERTIES); + } + document.custom_properties = None; + document.custom_properties_owned = false; } - candidate.custom_properties = None; - candidate.custom_properties_owned = false; - } - self.commit_staged_mutation(candidate); + Ok(()) + })?; Ok(Some(removed)) } @@ -92926,7 +93105,7 @@ fn fx283_local_cell_width_keeps_signed_truncation_and_wrap() { }) .unwrap() .unwrap(); - local.commit_direct_body_table(0, candidate); + local.commit_direct_body_table_cell(0, 0, 0, candidate); let expected = reference .table(0) .unwrap() @@ -93027,7 +93206,7 @@ fn fx283_local_text_matches_checked_fallback_for_anchors_and_opaque_xml() { .direct_body_table_cell_candidate(0, 0, 0, |cell| cell.try_set_text("after\tline\nend")) .unwrap() .unwrap(); - local.commit_direct_body_table(0, table); + local.commit_direct_body_table_cell(0, 0, 0, table); assert_eq!(local.to_bytes().unwrap(), fallback.to_bytes().unwrap()); assert_eq!( local.table(0).unwrap().cell(0, 0).unwrap().text(), @@ -94632,3 +94811,84 @@ fn issue434_insert_document_keeps_effective_font() { ); } } + +#[cfg(test)] +#[test] +fn issue445_properties_edits_stage_no_document_and_refuse_without_a_trace() { + let custom = |value: &str| CustomProperty { + fmtid: "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}".to_owned(), + pid: 2, + name: Some("Client".to_owned()), + value: crate::CustomPropertyValue::Lpwstr(value.to_owned()), + }; + let titled = |title: &str| CoreProperties { + title: Some(title.to_owned()), + ..CoreProperties::default() + }; + let mut document = Document::new(); + document.add_paragraph("body"); + #[cfg(debug_assertions)] + let _ = take_staging_clones(); + document.set_core_properties(titled("kept")).unwrap(); + let mut application = AppProperties::default(); + application.company = Some("kept".to_owned()); + document.set_application_properties(application).unwrap(); + document.set_custom_property(custom("first")).unwrap(); + assert_eq!( + document.remove_custom_property("Client").unwrap(), + Some(custom("first")) + ); + document.set_custom_property(custom("kept")).unwrap(); + #[cfg(debug_assertions)] + assert_eq!(take_staging_clones(), 0); + + // A relationship id range without a free id refuses after the part name + // of a new bundle is reserved. + let mut exhausted = Document::new(); + exhausted.package.package_rels.items[0].id = "rId4294967295".to_owned(); + let before = exhausted.clone_for_staging(); + let refusal = exhausted + .set_custom_property(custom("refused")) + .unwrap_err(); + assert!( + refusal + .to_string() + .contains("relationship id range is exhausted"), + "{refusal}" + ); + assert_eq!(exhausted.identifiers, before.identifiers); + assert!(before.package.same_package_as(&exhausted.package)); + assert_eq!(exhausted.custom_properties, None); + assert_eq!(exhausted.custom_properties_part_name, None); + + // A repeated package relationship id makes every reservation refuse + // before it reserves anything. + let repeated = document.package.package_rels.items[0].clone(); + document.package.package_rels.items.push(repeated); + let before = document.clone_for_staging(); + let refusals = [ + document.set_core_properties(titled("refused")).unwrap_err(), + document + .set_application_properties(AppProperties::default()) + .unwrap_err(), + document.set_custom_property(custom("refused")).unwrap_err(), + ]; + for refusal in refusals { + assert!( + refusal.to_string().contains("duplicate relationship id"), + "{refusal}" + ); + } + assert!(before.package.same_package_as(&document.package)); + assert_eq!(document.identifiers, before.identifiers); + assert_eq!(document.core_properties, before.core_properties); + assert_eq!(document.custom_properties, before.custom_properties); + assert_eq!( + document + .application_properties + .as_ref() + .and_then(|properties| properties.company.as_deref()), + Some("kept") + ); + assert!(before.saves_as(&document).is_err()); +} diff --git a/crates/rdocx/src/lib.rs b/crates/rdocx/src/lib.rs index 1d4531b13..19615f752 100644 --- a/crates/rdocx/src/lib.rs +++ b/crates/rdocx/src/lib.rs @@ -67,8 +67,12 @@ pub use content_control::{ FormFieldTarget, FormFieldValue, FormResetValue, FormValidationIssue, }; #[cfg(debug_assertions)] +pub use document::force_staged_properties; +#[cfg(debug_assertions)] pub use document::take_reopen_work; #[cfg(debug_assertions)] +pub use document::take_staging_clones; +#[cfg(debug_assertions)] pub use document::take_staging_work; pub use document::{ AccessibilityIssue, BodyContentRef, BodyItemContext, BodyItemOwners, BodyItemRef, diff --git a/docs/hld/10-bindings-spec.md b/docs/hld/10-bindings-spec.md index c5493ba53..be670fb8c 100644 --- a/docs/hld/10-bindings-spec.md +++ b/docs/hld/10-bindings-spec.md @@ -5033,22 +5033,81 @@ and serialization retain their existing native errors and binding serial without keeping dormant facts. External stream failure does not reverse native normalization already performed by serialization. -Whole-cell text and the five cell property setters use selected-table candidates -when their physical owner is a qualified direct-body cell. Cell paragraph text -resolves through paragraph_route and joins direct paragraph ordinals rather than -raw story-item positions. First serialized tcPr relocates held paragraph and run -routes for both absent and empty properties. Properties retain scopes. Text -keeps the cell owner, advances its content and retires the existing CellText -descendant scopes, including retained later paragraphs. Paragraph text retains -its own existing policy: selected owner/properties and other cell paragraph -scopes survive while selected content and descendants receive successors. Every fallible candidate, -index, scope and piece preparation precedes revision commit. Exactly one aligned -active piece is replaced after commit. Unsupported or disappearing-owner cases -use the established checked fallback. Cached facts must contain only the root -physical table for local publication. Nested neighboring cells use checked -publication so equal row/cell ordinals cannot exchange held authority. Signed width truncation and wrap, border +Whole-cell text, cell paragraph text and the five cell property setters use a +selected-cell candidate when their physical owner is a qualified direct-body +cell. The candidate is the edited cell alone in a frame of its table: the table +properties and grid, and one row with the row properties and that cell. It is +validated as a body holding the frame alone. The model limits bound nesting +along each path, and the paths through the cell are the same in the frame and in +the table. The checked reader reads the frame for the facts of the cell. The +other cells keep the facts it read for the aligned piece, as the edit reaches no +other cell model. The publication replaces the owner records of that cell, its +paragraphs and their runs, the paragraph count of the cell in the table read +facts and the cell paragraph routes of the cell, so its cost does not depend on +the body, and depends on the table only through the comparison that aligns the +piece with the table and the search of the cell owner among the table's cells. +Cell paragraph text resolves through paragraph_route and joins direct paragraph +ordinals rather than raw story-item positions. First serialized tcPr relocates +held paragraph and run routes for both absent and empty properties. Properties +retain scopes. Text keeps the cell owner, advances its content and retires the +existing CellText descendant scopes, including retained later paragraphs. +Paragraph text retains its own existing policy: selected owner/properties and +other cell paragraph scopes survive while selected content and descendants +receive successors. Every fallible candidate, index, scope and piece preparation +precedes revision commit. Exactly one aligned active piece is updated in place +after commit: the cell of its block, the paragraph facts and story of the cell, +and the table read facts. Its items keep the table's own item, which is what the +inventory reads there. A field flag already set stays set until the next full +read of the table. Debug builds read the whole table again after each such +publication and assert that the piece facts the inventory reads, body story +fingerprints aside, the owner records of the table and its cell paragraph routes +are those of that read. They also count the bytes of each block whose owners the +checked reader reads again, which for these setters is the frame. The debug +checked route switch sends these setters to the whole-document route. +Unsupported or disappearing-owner cases use the established checked fallback. +Cached facts must contain only the root physical table for local publication. +Nested neighboring cells use checked publication so equal row/cell ordinals +cannot exchange held authority. Signed width truncation and wrap, border validation and atomic nonnegative margin validation remain field-specific. +These publications take their selected route from the current owner inventory, +the record the checked reader prepared, without a story walk: Paragraph.add_run, +add_hyperlink and add_equation, Run.text, Table.add_row and remove_row, the +checked fallback of Cell.text, Document.set_chart_legend and a text box +ParagraphFormat. They read it through paragraph_route, table_route and +run_route. Debug builds also resolve a body paragraph or body table route by +the checked story walk and assert that both agree, story fingerprints aside. +For a run they assert that the paragraph at the route holds the run path. A +handle with no inventory record keeps the story walk. A call whose native edit +takes a checked story address still walks for that address: +Paragraph.add_internal_hyperlink, Run.add_picture, Run.replace_xml, +Table.replace_xml, Cell.merge, the note calls and a text box paragraph edit. + +Run.text of a run in a direct body paragraph decides whether its typed edit +changed anything from that block alone. Equal paragraph models publish +nothing. Two plain paragraphs whose checked reader text or run paths differ +publish without a staged save comparison. Text holding a character XML 1.0 +cannot carry, a paragraph that is not plain, a body with a known save failure +and facts that do not tell keep the staged comparison and its error. Every +other publisher keeps the staged comparison. The block answer does not save +the rest of the document. Content elsewhere that no save accepts therefore +does not refuse Run.text, and save reports it, as after Paragraph.text. Debug +builds assert the block answer against the staged comparison whenever that +comparison answers. + +Core, application and custom property setters do not stage the document. Their +only fallible step reserves the properties part in the package graph and the +identifier registry, so those two are saved first and put back on refusal. +Success drops the derived layout and records a signed package mutation, as the +staged commit does. Debug builds compare the package graph, the property models +and their part names with the staged edit. + +Debug builds count document staging clones, story walks that resolve a route, +staged save comparisons and full owner inventory publications in +_word_publication_work, outside the guards. _word_force_checked_route restores +the story walk, the staged comparison and the staged properties edit, so a +test can compare both routes of one call. + Current paragraph, table and cell capture uses derived exact-route indexes. Direct body paragraph slot lookup borrows its existing complete ContentLocation key, including fingerprint and end marker. Control-contained lookup retains its constructed key. This changes no retained owner, map insertion or publication policy. Body and cell-paragraph aliases are prepared from the native batch location projections when the owner inventory is prepared, including before candidate diff --git a/scripts/readme_doctests.py b/scripts/readme_doctests.py index bf17a18d9..f2a2a74b5 100644 --- a/scripts/readme_doctests.py +++ b/scripts/readme_doctests.py @@ -376,7 +376,7 @@ class ReadmeCase: "oxml-opc": "2026-11-06", "oxml-pdf": "2026-11-06", "oxml-sml": "2026-11-06", - "rdocx": "2026-11-09", + "rdocx": "2026-11-16", "rdocx-cli": "2026-11-07", "rdocx-html": "2026-11-06", "rdocx-layout": "2026-11-09", @@ -402,7 +402,7 @@ class ReadmeCase: "oxml-opc": (119_252, 486_417, 12), "oxml-pdf": (102_219, 478_926, 14), "oxml-sml": (24_956, 115_575, 6), - "rdocx": (4_501_789, 56_396_845, 37), + "rdocx": (4_504_780, 56_407_541, 37), "rdocx-cli": (126_182, 593_817, 8), "rdocx-html": (29_407, 118_370, 11), "rdocx-layout": (463_844, 2_543_127, 15),