PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
fix: bound backdrop edits and withhold unsafe integration behavior
FredAppsd7f3e67141ef
diff --git a/crates/edit/src/backdrop.rs b/crates/edit/src/backdrop.rsindex cc0092174..43e16b40e 100644--- a/crates/edit/src/backdrop.rs+++ b/crates/edit/src/backdrop.rs@@ -26,7 +26,7 @@//! Anything else is real content and stays.use pdfcraft_content::{Matrix, Op, Pieces};-use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream};+use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object, PdfString, Stream};use sha2::{Digest, Sha256};use crate::{EditError, MarkKind};@@ -174,8 +174,8 @@ pub(crate) fn replace(doc: &mut Document, page: &pdfcraft_model::Page) -> Result}dict.set(TAG.to_vec(), Object::Dict(note));let copy = doc.add(Object::Stream(Stream::flate(dict, bytes)));- // Every slot that draws the original: a page may list the same stream twice, and a second- // copy of the fill would cover the background again.+ // scan accepts only one execution of this stream on the page. Other pages keep the+ // original stream; ambiguous repeated executions are never rewritten.let mut list = crate::place::contents(doc, page)?;let mut replaced = false;for entry in list.iter_mut().filter(|o| matches!(o, Object::Ref(r) if *r == original)) {@@ -208,7 +208,7 @@ pub(crate) fn restore(doc: &mut Document, page: &pdfcraft_model::Page) -> Resultlet same = |w: &ObjRef| match &*doc.get(*w) {Object::Stream(s) => {[TAG, &b"PCMark"[..], b"Subtype"].iter().all(|k| s.dict.get(k).is_none())- && s.decoded().ok().as_deref() == Some(bytes.as_slice())+ && DecodeBudget::new(SCAN_BYTES, 0).decode_strict(s).ok().as_deref() == Some(bytes.as_slice())}_ => false,};@@ -248,7 +248,7 @@ fn restored_copy(doc: &Document, page: &pdfcraft_model::Page, copy: ObjRef) -> Oreturn None;}let hash = note.get(b"Before")?.as_string()?;- let bytes = s.decoded().ok()?;+ let bytes = DecodeBudget::new(SCAN_BYTES, 0).decode_strict(s).ok()?;let parsed = pdfcraft_content::parse(head(&bytes));// The `n` standing in for the fill, after exactly the operators that came before it.let fill = parsed.ops.get(index)?;@@ -354,7 +354,8 @@ fn scan(doc: &Document, p: &pdfcraft_model::Page, swap: Option<(ObjRef, &[u8])>)let crop = p.crop(doc);let c = p.dict.get(b"Contents")?;let list: Vec<Object> = match &*doc.resolve(c) {- Object::Array(a) => a.clone(),+ Object::Array(a) if a.len() <= SCAN_OPS => a.clone(),+ Object::Array(_) => return None,_ => vec![c.clone()],};// The page's own content: untagged streams (marks and the q/Q wrapper carry /PCMark). Read@@ -363,6 +364,7 @@ fn scan(doc: &Document, p: &pdfcraft_model::Page, swap: Option<(ObjRef, &[u8])>)let mut data = Vec::new();let mut starts = Vec::new();let mut total = 0usize;+ let mut budget = DecodeBudget::new(SCAN_BYTES, 0);for (slot, o) in list.iter().enumerate() {if total >= SCAN_BYTES {break;@@ -378,13 +380,21 @@ fn scan(doc: &Document, p: &pdfcraft_model::Page, swap: Option<(ObjRef, &[u8])>)return None;}let bytes = match swap {- Some((with, b)) if with == *r => b.to_vec(),+ Some((with, b)) if with == *r => {+ if b.len() > SCAN_BYTES.saturating_sub(total) {+ return None;+ }+ budget.decode_strict(&Stream::from_raw(Dict::new(), b.to_vec())).ok()?+ }// Tolerant decoding can return an empty or partial stream after corruption.// That cannot prove which paint preceded the candidate backdrop.- _ => s.decoded_strict().ok()?,+ _ => budget.decode_strict(s).ok()?,};+ if bytes.len() > SCAN_BYTES.saturating_sub(total).saturating_sub(1) {+ return None;+ }starts.push(total);- total = total.saturating_add(bytes.len()).saturating_add(1);+ total += bytes.len() + 1;refs.push((slot, *r));data.push(bytes);}@@ -392,6 +402,15 @@ fn scan(doc: &Document, p: &pdfcraft_model::Page, swap: Option<(ObjRef, &[u8])>)let parsed = pdfcraft_content::parse(head(pieces.data()));let res = resources(doc, &p.dict);let found = walk(doc, &res, crop, &parsed.ops);+ // A match proves the graphics state for one execution only. Repeated references may+ // paint real artwork under a different color or transform: leave them untouched.+ if let Some((Backdrop::Fill, Some(op))) = &found {+ let piece = pieces.piece_of(op.start);+ let (_, reference) = refs.get(piece)?;+ if list.iter().filter(|o| matches!(o, Object::Ref(r) if r == reference)).count() != 1 {+ return None;+ }+ }found.map(|(b, op)| match (b, op) {(Backdrop::Fill, Some(op)) => (b, Some(Found { refs, pieces, starts, op })),_ => (b, None),diff --git a/crates/edit/src/backdrop_tests.rs b/crates/edit/src/backdrop_tests.rsindex 98578da57..30bc2ef8b 100644--- a/crates/edit/src/backdrop_tests.rs+++ b/crates/edit/src/backdrop_tests.rs@@ -497,7 +497,7 @@ fn the_backdrop_copy_keeps_the_original_dictionary_less_its_old_encoding() {}#[test]-fn a_stream_listed_twice_is_replaced_in_both_slots_and_restored_in_both() {+fn a_stream_listed_twice_is_left_untouched_as_ambiguous() {let mut doc = build(&["<< /Type /Catalog /Pages 2 0 R >>".to_string(),"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 200] >>".into(),@@ -508,7 +508,7 @@ fn a_stream_listed_twice_is_replaced_in_both_slots_and_restored_in_both() {add_background(&mut doc, &[0], &red(), false).unwrap();let s = streams(&doc);assert_eq!(s.len(), 3, "{s:?}");- assert!(s[1..].iter().all(|c| c.contains("re n") && !c.contains("re f")), "no slot still paints the white fill: {s:?}");+ assert_eq!(s[1..], original[..], "repeated executions are not qualified independently");remove_marks(&mut doc, &[0], MarkKind::Background).unwrap();assert_eq!(streams(&doc), original);}@@ -569,3 +569,39 @@ fn an_undecodable_stream_before_a_white_fill_keeps_the_backdrop_unknown() {let doc = build(&objs);assert_eq!(page_backdrop(&doc, 0).unwrap(), None, "unknown earlier paint must not be treated as an empty stream");}++#[test]+fn shared_fill_used_as_later_artwork_is_not_rewritten() {+ let mut doc = build(&[+ "<< /Type /Catalog /Pages 2 0 R >>".to_string(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 200] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Contents [4 0 R 5 0 R 6 0 R 5 0 R 7 0 R] >>".into(),+ stream("", "1 g"),+ stream("", "0 0 300 200 re f"),+ stream("", "q 0 g 0.25 0 0 0.25 20 20 cm"),+ stream("", "Q"),+ ]);+ assert_eq!(page_backdrop(&doc, 0).unwrap(), None);+ let original = streams(&doc);+ add_background(&mut doc, &[0], &red(), false).unwrap();+ assert_eq!(streams(&doc)[1..], original[..], "the later black artwork keeps its fill");+ let mut saved = reopen(&doc);+ assert_eq!(streams(&saved)[1..], original[..]);+ remove_marks(&mut saved, &[0], MarkKind::Background).unwrap();+ assert_eq!(streams(&saved), original);+ assert_eq!(streams(&reopen(&saved)), original);+}++#[test]+fn compressed_backdrop_content_is_refused_before_expanding_past_the_scan_budget() {+ let mut doc = page(&["1 g 0 0 300 200 re f"]);+ let mut bytes = b"1 g 0 0 300 200 re f\n".to_vec();+ bytes.resize(2 * 1024 * 1024, b' ');+ let source = doc.add(Object::Stream(Stream::flate(Dict::new(), &bytes)));+ let page = pdfcraft_model::pages(&doc)[0].obj;+ doc.update_dict(page, |d| d.set(b"Contents".to_vec(), Object::Ref(source))).unwrap();+ assert_eq!(page_backdrop(&doc, 0).unwrap(), None);+ add_background(&mut doc, &[0], &red(), false).unwrap();+ let Object::Stream(unchanged) = &*doc.get(source) else { panic!("stream") };+ assert_eq!(unchanged.decoded_strict().unwrap(), bytes, "refusal preserves the source");+}diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex 3650ffd0b..d45e983a2 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -7758,62 +7758,49 @@ fn a_flatten_refused_on_a_later_page_changes_nothing() {assert_eq!((*doc.get(first)).clone(), before, "the first page keeps its comment and content");}-/// One row of an edited paragraph aligned on its own (#A: highlighting a line and aligning it):-/// the other rows stay where they were.+/// Existing-row alignment is explicitly refused without mutating the paragraph.#[test]-fn one_row_of_a_paragraph_takes_its_own_alignment() {- let mut doc = text_page("BT /F1 10 Tf 12 TL 100 700 Td (One two three four five six seven) Tj T* (eight nine ten eleven twelve) Tj ET");- let block = text::text_blocks(&doc, 0).unwrap()[0].clone();- assert_eq!(block.editor_text, "One two three four five six seven\neight nine ten eleven twelve");- let style = text::BlockStyle { aligns: vec![None, Some(added::Align::Right)], ..Default::default() };- text::rewrite_block(&mut doc, 0, 0, Some(&block.editor_text), &style).unwrap();- let lines = text::text_lines(&doc, 0).unwrap();- let row = |t: &str| lines.iter().find(|l| l.text.starts_with(t)).unwrap().rect;- assert!((row("One")[0] - block.rect[0]).abs() < 0.5, "the first row stays at the left: {:?}", row("One"));- assert!((row("eight")[2] - block.rect[2]).abs() < 1.0, "the second row ends at the right edge: {:?} vs {}", row("eight"), block.rect[2]);+fn one_row_of_a_paragraph_takes_its_own_alignment_is_refused_without_changing_the_document() {+ for align in [added::Align::Left, added::Align::Center, added::Align::Right, added::Align::Justify] {+ let mut doc = text_page("BT /F1 10 Tf 12 TL 72 700 Td (First row) Tj T* (Second row) Tj ET");+ let before = page_content_bytes(&doc, 0);+ let blocks = text::text_blocks(&doc, 0).unwrap();+ let style = text::BlockStyle { aligns: vec![None, Some(align)], ..Default::default() };+ let error = text::rewrite_block(&mut doc, 0, 0, Some(&blocks[0].editor_text), &style).unwrap_err();+ assert!(error.to_string().contains("selected-row alignment"));+ assert_eq!(page_content_bytes(&doc, 0), before);+ assert_eq!(page_content_bytes(&reopen(&doc), 0), before);+ }}-/// Only a row given an alignment of its own is rewritten. The others keep their source operators,-/// `TJ` word gaps included, so their words stay exactly where they were: rebuilt from the text,-/// the first row's words moved by about a point and a half while its outer width stayed the same.+/// Refusal preserves all existing rows and their saved content stream.#[test]-fn rows_without_their_own_alignment_keep_their_operators() {- let first = "[(One) -250 (two) -250 (three) -250 (four)] TJ";- let mut doc = text_page(&format!("BT /F1 10 Tf 12 TL 72 700 Td {first} T* [(five) -250 (six) -250 (seven) -250 (eight)] TJ T* (nine ten) Tj ET"));- let block = text::text_blocks(&doc, 0).unwrap()[0].clone();- assert_eq!(block.editor_text.matches('\n').count(), 2, "one paragraph of three rows: {:?}", block.editor_text);- let row = |doc: &Document, starts: &str| text::text_lines(doc, 0).unwrap().into_iter().find(|l| l.text.starts_with(starts)).expect("the row");- let ink = row(&doc, "One").ink;- let style = text::BlockStyle { aligns: vec![None, None, Some(added::Align::Right)], ..Default::default() };- text::rewrite_block(&mut doc, 0, 0, Some(&block.editor_text), &style).unwrap();- let doc = reopen(&doc);- assert_eq!(row(&doc, "One").ink, ink, "the first row's words stay where they were");- let content = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned();- assert!(content.contains(first), "the first row keeps its operator: {content}");- assert!((row(&doc, "nine").rect[2] - block.rect[2]).abs() < 1.0, "the last row is right-aligned: {:?}", row(&doc, "nine").rect);+fn rows_without_their_own_alignment_keep_their_operators_is_refused_without_changing_the_document() {+ for align in [added::Align::Left, added::Align::Center, added::Align::Right, added::Align::Justify] {+ let mut doc = text_page("BT /F1 10 Tf 12 TL 72 700 Td (First row) Tj T* (Second row) Tj ET");+ let before = page_content_bytes(&doc, 0);+ let blocks = text::text_blocks(&doc, 0).unwrap();+ let style = text::BlockStyle { aligns: vec![None, Some(align)], ..Default::default() };+ let error = text::rewrite_block(&mut doc, 0, 0, Some(&blocks[0].editor_text), &style).unwrap_err();+ assert!(error.to_string().contains("selected-row alignment"));+ assert_eq!(page_content_bytes(&doc, 0), before);+ assert_eq!(page_content_bytes(&reopen(&doc), 0), before);+ }}-/// The same in a region of several styles: only the short first row is centred.+/// Mixed-style rows also refuse unsupported per-row intent before writing.#[test]-fn one_row_of_a_styled_region_takes_its_own_alignment() {- let mut doc = mixed_region_page();- let block = text::text_blocks(&doc, 0).unwrap()[1].clone();- assert_eq!(- block.editor_text,- "About-Plain bold text.-Italic footer"- );- let row = |lines: &[text::TextLine], t: &str| lines.iter().find(|l| l.text.starts_with(t)).unwrap().rect;- let before = text::text_lines(&doc, 0).unwrap();- let style = text::BlockStyle { aligns: vec![Some(added::Align::Center)], ..Default::default() };- text::rewrite_block(&mut doc, 0, 1, Some(&block.editor_text), &style).unwrap();- let lines = text::text_lines(&doc, 0).unwrap();- assert!((row(&lines, "Italic")[0] - row(&before, "Italic")[0]).abs() < 0.5, "the last row stays put");- assert!((row(&lines, "Plain")[0] - row(&before, "Plain")[0]).abs() < 0.5, "the middle row stays put");- let about = row(&lines, "About");- let (mid, centre) = ((about[0] + about[2]) / 2.0, (block.rect[0] + block.rect[2]) / 2.0);- assert!(about[0] > row(&before, "About")[0] + 5.0 && (mid - centre).abs() < 1.5, "the first row is centred: {mid} vs {centre}");+fn one_row_of_a_styled_region_takes_its_own_alignment_is_refused_without_changing_the_document() {+ for align in [added::Align::Left, added::Align::Center, added::Align::Right, added::Align::Justify] {+ let mut doc = mixed_region_page();+ let before = page_content_bytes(&doc, 0);+ let blocks = text::text_blocks(&doc, 0).unwrap();+ let style = text::BlockStyle { aligns: vec![None, Some(align)], ..Default::default() };+ let error = text::rewrite_block(&mut doc, 0, 1, Some(&blocks[1].editor_text), &style).unwrap_err();+ assert!(error.to_string().contains("selected-row alignment"));+ assert_eq!(page_content_bytes(&doc, 0), before);+ assert_eq!(page_content_bytes(&reopen(&doc), 0), before);+ }}/// Added text: each paragraph is laid out with its own alignment, a justified paragraph's last@@ -7896,7 +7883,7 @@ fn a_lone_row_aligns_across_the_column_it_sits_in() {let blocks = text::text_blocks(doc, 0).unwrap();let (index, block) = blocks.iter().enumerate().find(|(_, b)| b.lines.contains(&line)).unwrap();// The title is the paragraph's first row.- let style = text::BlockStyle { aligns: vec![Some(a)], ..Default::default() };+ let style = text::BlockStyle { align: Some(a), ..Default::default() };text::rewrite_block(doc, 0, index, Some(&block.editor_text), &style).unwrap();};align(&mut doc, added::Align::Center);@@ -7939,7 +7926,7 @@ fn a_title_moves_to_its_column_only_for_an_alignment_of_its_own() {for draft in ["Title", "Title\nSub"] {let mut doc = text_page(page);let style = text::BlockStyle { aligns: vec![None, Some(added::Align::Right)], ..Default::default() };- text::rewrite_block(&mut doc, 0, 0, Some(draft), &style).unwrap();+ assert!(text::rewrite_block(&mut doc, 0, 0, Some(draft), &style).is_err());assert!((title(&doc)[0] - before[0]).abs() < 0.5, "{draft:?}: the title stays put, {:?} vs {before:?}", title(&doc));}}@@ -7958,7 +7945,7 @@ fn a_column_is_measured_by_its_whole_rows_not_its_first_runs() {body.rows.iter().filter_map(|row| row.iter().filter_map(|i| lines.get(*i)).map(|l| l.rect[2]).reduce(f64::max)).fold(f64::MIN, f64::max);let mut doc = text_page(page);let index = blocks.iter().position(|b| b.text == "A longer title").expect("the title is a block of its own");- let style = text::BlockStyle { aligns: vec![Some(added::Align::Right)], ..Default::default() };+ let style = text::BlockStyle { align: Some(added::Align::Right), ..Default::default() };text::rewrite_block(&mut doc, 0, index, Some("A longer title"), &style).unwrap();let title = text::text_lines(&doc, 0).unwrap().into_iter().find(|l| l.text == "A longer title").unwrap().rect;assert!((title[2] - column_right).abs() < 1.0, "right: on the whole row's right edge, {title:?} vs {column_right}");@@ -7972,7 +7959,7 @@ fn an_isolated_row_edited_with_an_alignment_does_not_wrap_at_its_old_width() {for align in [added::Align::Center, added::Align::Right] {let mut doc = text_page("BT /F1 18 Tf 1 0 0 1 100 700 Tm (Title) Tj ET");let longer = "A much longer title for the page";- let style = text::BlockStyle { aligns: vec![Some(align)], ..Default::default() };+ let style = text::BlockStyle { align: Some(align), ..Default::default() };text::rewrite_block(&mut doc, 0, 0, Some(longer), &style).unwrap();let lines = text::text_lines(&doc, 0).unwrap();assert_eq!(lines.iter().map(|l| l.text.as_str()).collect::<Vec<_>>(), [longer], "{align:?}: the title stays on one row");@@ -7996,7 +7983,7 @@ fn a_lone_row_aligns_in_its_own_column_not_a_closer_full_width_heading() {let mut doc = text_page(page);let blocks = text::text_blocks(&doc, 0).unwrap();let index = blocks.iter().position(|b| b.text == "Title").unwrap();- let style = text::BlockStyle { aligns: vec![Some(align)], ..Default::default() };+ let style = text::BlockStyle { align: Some(align), ..Default::default() };text::rewrite_block(&mut doc, 0, index, Some("Title"), &style).unwrap();text::text_lines(&doc, 0).unwrap().into_iter().find(|l| l.text == "Title").unwrap().rect};@@ -8018,7 +8005,7 @@ fn a_lone_row_aligns_across_its_own_column_of_two() {let blocks = text::text_blocks(&doc, 0).unwrap();let column = blocks.iter().find(|b| b.text.starts_with("The first")).unwrap().rect;let index = blocks.iter().position(|b| b.text == "Title").unwrap();- let style = text::BlockStyle { aligns: vec![Some(added::Align::Left)], ..Default::default() };+ let style = text::BlockStyle { align: Some(added::Align::Left), ..Default::default() };text::rewrite_block(&mut doc, 0, index, Some("Title"), &style).unwrap();let title = text::text_lines(&doc, 0).unwrap().into_iter().find(|l| l.text == "Title").unwrap().rect;assert!((title[0] - column[0]).abs() < 0.5, "left: on the first column's edge, {title:?} vs {column:?}");@@ -8043,7 +8030,7 @@ fn a_lone_row_of_two_styles_aligns_across_its_column() {let centre = |doc: &mut Document| {let blocks = text::text_blocks(doc, 0).unwrap();let (index, block) = blocks.iter().enumerate().find(|(_, b)| b.text == "Big Title").unwrap();- let style = text::BlockStyle { aligns: vec![Some(added::Align::Center)], ..Default::default() };+ let style = text::BlockStyle { align: Some(added::Align::Center), ..Default::default() };text::rewrite_block(doc, 0, index, Some(&block.editor_text), &style).unwrap();};centre(&mut doc);@@ -8078,7 +8065,7 @@ fn a_titles_column_ignores_distant_full_width_headers_and_footers() {for align in [added::Align::Center, added::Align::Center, added::Align::Right, added::Align::Left] {let blocks = text::text_blocks(&doc, 0).unwrap();let (index, block) = blocks.iter().enumerate().find(|(_, b)| b.text == name).unwrap();- let style = text::BlockStyle { aligns: vec![Some(align)], ..Default::default() };+ let style = text::BlockStyle { align: Some(align), ..Default::default() };text::rewrite_block(&mut doc, 0, index, Some(&block.editor_text), &style).unwrap();doc = reopen(&doc);let title = rect(&doc, name);@@ -8534,18 +8521,18 @@ fn q_inside_a_text_object_restores_the_text_matrices() {}}-/// Integration of #4180 and #2529: soft wraps retain the source paragraph's alignment,-/// while a typed newline advances to the next alignment and survives a save/reopen.+/// Whole-paragraph alignment retains both soft wraps and typed hard breaks after save/reopen.+/// Selected-row alignment for existing PDF content is withheld until it can persist safely.#[test]-fn wrapped_rows_keep_alignment_separate_from_hard_break_markers() {+fn wrapped_rows_keep_whole_paragraph_alignment_and_hard_break_markers() {let mut doc = text_page("BT /F1 10 Tf 12 TL 72 700 Td (Old) Tj ET");- let style = text::BlockStyle { width: Some(60.0), aligns: vec![Some(added::Align::Left), Some(added::Align::Right)], ..Default::default() };+ let style = text::BlockStyle { width: Some(60.0), align: Some(added::Align::Left), ..Default::default() };text::rewrite_block(&mut doc, 0, 0, Some("One two three four five six\nTail"), &style).unwrap();let doc = reopen(&doc);let lines = text::text_lines(&doc, 0).unwrap();assert!(lines.len() > 2, "the first logical row must wrap");let tail = lines.iter().find(|line| line.text == "Tail").unwrap();- assert!((tail.rect[2] - 132.0).abs() < 1.0, "the second logical row stays right-aligned: {:?}", tail.rect);+ assert!((tail.rect[0] - 72.0).abs() < 1.0, "the second logical row keeps the paragraph alignment: {:?}", tail.rect);for line in lines.iter().filter(|line| line.text != "Tail") {assert!((line.rect[0] - 72.0).abs() < 1.0, "soft-wrapped rows stay left-aligned: {:?}", line.rect);}@@ -8577,3 +8564,15 @@ fn ordinary_soft_wrap_counts_keep_their_spaces() {assert_eq!(blocks[0].reflow_text, format!("First{}Second", " ".repeat(gap)));}}++#[test]+fn styled_existing_justification_is_refused_instead_of_silently_left_aligning() {+ let mut doc = mixed_region_page();+ let before = page_content_bytes(&doc, 0);+ let blocks = text::text_blocks(&doc, 0).unwrap();+ let style = text::BlockStyle { align: Some(added::Align::Justify), ..Default::default() };+ let error = text::rewrite_block(&mut doc, 0, 1, Some(&blocks[1].editor_text), &style).unwrap_err();+ assert!(error.to_string().contains("justification"));+ assert_eq!(page_content_bytes(&doc, 0), before);+ assert_eq!(page_content_bytes(&reopen(&doc), 0), before);+}diff --git a/crates/edit/src/text/rewrite.rs b/crates/edit/src/text/rewrite.rsindex 976f8a1b1..ec2fac984 100644--- a/crates/edit/src/text/rewrite.rs+++ b/crates/edit/src/text/rewrite.rs@@ -791,6 +791,13 @@ pub(crate) fn rewrite_block_from() -> Result<LineEdit, EditError> {let blocks = group_blocks(&lines);let b = blocks.get(block).cloned().ok_or_else(|| EditError::Invalid(format!("page {} has no paragraph {}", page + 1, block + 1)))?;+ // Existing PDF paragraphs do not yet persist selected-row alignment intent. Refuse+ // that operation before writing anything; whole-paragraph `align` remains supported.+ if style.aligns.iter().any(Option::is_some) {+ return Err(EditError::Invalid(+ "selected-row alignment of existing paragraphs is not supported until it can be preserved across editing sessions".into(),+ ));+ }// An alignment for a one-row paragraph is laid out across the column it sits in, as a// paragraph of that width moved to its left edge.let framed;@@ -812,6 +819,9 @@ pub(crate) fn rewrite_block_from(let mut res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();let mut fonts_res = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();let dispatch = choose_rewrite_path(doc, &fonts_res, &b, &members, first, text, style)?;+ if dispatch.use_styled_path && style.align == Some(crate::added::Align::Justify) {+ return Err(EditError::Invalid("justification of mixed-style existing paragraphs is not supported".into()));+ }if dispatch.use_styled_path {return rewrite_styled_block(doc, page, &b, &lines, text, style, max_glyphs);}diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 7147af2d4..692ba47a0 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -9280,3 +9280,54 @@ fn need_appearances_buttons_are_displayed_from_their_captions() {assert!(ink(&shown, inside(x, 100)) > 700, "the file's square at {x}");}}++#[test]+fn repeated_backdrop_artwork_survives_background_undo_redo_and_both_save_modes() {+ let white = "1 g";+ let rectangle = "0 0 100 100 re f";+ let artwork = "q 0 g 0.25 0 0 0.25 20 20 cm";+ let raw = format!(+ "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\+ 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\+ 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents [4 0 R 5 0 R 6 0 R 5 0 R 7 0 R] >> endobj\n\+ 4 0 obj << /Length {} >> stream\n{white}\nendstream endobj\n\+ 5 0 obj << /Length {} >> stream\n{rectangle}\nendstream endobj\n\+ 6 0 obj << /Length {} >> stream\n{artwork}\nendstream endobj\n\+ 7 0 obj << /Length 1 >> stream\nQ\nendstream endobj\ntrailer << /Root 1 0 R >>\n%%EOF",+ white.len(), rectangle.len(), artwork.len()+ );+ // Start with a conventional xref, so the first save can exercise incremental output.+ let source = pdfcraft_cos::Document::open(Arc::new(raw.into_bytes())).unwrap();+ let bytes = pdfcraft_cos::write_full(&source, &pdfcraft_cos::SaveOptions::default()).unwrap();+ let mut s = Session::new();+ let id = s.open("shared-backdrop.pdf", None, Arc::new(bytes), None).unwrap();+ let black = |s: &Session, id| {+ let rgba = pixel(s, id, 0, 30, 70);+ assert!(rgba[0] < 20 && rgba[1] < 20 && rgba[2] < 20, "later artwork survives: {rgba:?}");+ };+ black(&s, id);+ s.apply(+ id,+ Edit::AddBackground {+ pages: vec![0],+ settings: Background { color: [1.0, 0.0, 0.0], ..Background::default() },+ replace: false,+ file: None,+ },+ )+ .unwrap();+ black(&s, id);+ s.undo(id).unwrap();+ black(&s, id);+ s.redo(id).unwrap();+ black(&s, id);+ let saved = s.save_bytes(id).unwrap();+ let reopened = s.open("incremental.pdf", None, saved.clone(), None).unwrap();+ black(&s, reopened);+ let doc = pdfcraft_cos::Document::open(saved).unwrap();+ let full = pdfcraft_cos::write_full(&doc, &pdfcraft_cos::SaveOptions::default()).unwrap();+ let rewritten = s.open("full.pdf", None, Arc::new(full), None).unwrap();+ black(&s, rewritten);+ s.apply(rewritten, Edit::RemoveMarks { kind: MarkKind::Background }).unwrap();+ black(&s, rewritten);+}diff --git a/crates/optimize/src/images.rs b/crates/optimize/src/images.rsindex 65cecfffd..933806197 100644--- a/crates/optimize/src/images.rs+++ b/crates/optimize/src/images.rs@@ -908,27 +908,24 @@ fn packed_rows(samples: &[u8], row_len: usize, w: usize, h: usize, (n, bpc, whitSome(out)}-/// Whether sample 1 is the dark one of the 1-bit image `d` describes, after its decode array-/// (`[0 1]` when it has none of two numbers): the painted part of an image mask and black in grey-/// decode to 0, and full ink in a separation (or a DeviceN of one colourant) to 1. An indexed image-/// says the sample that decodes to entry 0 (its decode array maps samples to entries, ISO 32000-2-/// §8.9.5.2): its palette says which entry is darker, and the palette isn't read yet, so a tie goes-/// to entry 0 whatever its colour.-fn dark_is_one(doc: &Document, d: &Dict) -> bool {- let number = |v: Option<&Object>| v.and_then(|v| doc.resolve(v).as_f64());+/// Resolve polarity only for explicitly understood samples. Indexed palettes and custom+/// colour spaces stay at their original resolution rather than guessing which entry is dark.+fn dark_is_one(doc: &Document, d: &Dict) -> Option<bool> {+ let number = |v: Option<&Object>| v.and_then(|v| doc.resolve(v).as_f64()).filter(|v| v.is_finite());let (d0, d1) = match d.get(b"Decode").map(|v| doc.resolve(v)).as_deref() {- Some(Object::Array(a)) => number(a.first()).zip(number(a.get(1))).unwrap_or((0.0, 1.0)),- _ => (0.0, 1.0),+ Some(Object::Array(a)) if a.len() == 2 => number(a.first()).zip(number(a.get(1)))?,+ None => (0.0, 1.0),+ _ => return None,};+ if d0 == d1 {+ return None;+ }if matches!(d.get(b"ImageMask"), Some(Object::Bool(true))) {- return d1 < d0;+ return Some(d1 < d0);}match d.get(b"ColorSpace").map(|cs| doc.resolve(cs)).as_deref() {- Some(Object::Array(a)) => match a.first().and_then(Object::as_name) {- Some(b"Separation" | b"DeviceN") => d1 > d0,- _ => d1 < d0,- },- _ => d1 < d0,+ Some(Object::Name(n)) if matches!(n.as_slice(), b"DeviceGray" | b"G") => Some(d1 < d0),+ _ => None,}}@@ -937,7 +934,12 @@ fn dark_is_one(doc: &Document, d: &Dict) -> bool {/// (1 if `dark_is_one`, see [`dark_is_one`]), so a dark line half a new pixel wide stays. `None`/// when the rows are short or the new size isn't smaller in both directions or empty. Also says/// how many new pixels cover both samples.+#[cfg(test)]pub(crate) fn downsample_bits(data: &[u8], w: u32, h: u32, nw: u32, nh: u32, dark_is_one: bool) -> Option<(Vec<u8>, u64)> {+ downsample_bits_checked(data, w, h, nw, nh, dark_is_one).map(|(out, mixed, _)| (out, mixed))+}++fn downsample_bits_checked(data: &[u8], w: u32, h: u32, nw: u32, nh: u32, dark_is_one: bool) -> Option<(Vec<u8>, u64, bool)> {if nw == 0 || nh == 0 || nw > w || nh > h {return None;}@@ -951,7 +953,11 @@ pub(crate) fn downsample_bits(data: &[u8], w: u32, h: u32, nw: u32, nh: u32, dar// Per source column, the area its 1 samples cover in the new row.let mut ones = vec![0u64; usize::try_from(w).ok()?];let mut mixed = 0u64;+ let mut previous_mixed = vec![false; usize::try_from(nw).ok()?];+ let mut local_tone = false;for j in 0..nh {+ let mut left_mixed = false;+ let mut above_left_mixed = false;ones.fill(0);let (y0, y1) = (j * h, (j + 1) * h);for y in y0 / nh..y1.div_ceil(nh).min(h) {@@ -972,21 +978,28 @@ pub(crate) fn downsample_bits(data: &[u8], w: u32, h: u32, nw: u32, nh: u32, dar// Against what the 0 samples cover: covered is at most w·h, which can't overflow// (w·h < 2^64 for u32 sizes).let zeros = w * h - covered;- mixed += u64::from(covered > 0 && zeros > 0);+ let is_mixed = covered > 0 && zeros > 0;+ mixed += u64::from(is_mixed);+ let column = usize::try_from(i).ok()?;+ let above = *previous_mixed.get(column)?;+ local_tone |= is_mixed && left_mixed && above && above_left_mixed;+ *previous_mixed.get_mut(column)? = is_mixed;+ left_mixed = is_mixed;+ above_left_mixed = above;if covered > zeros || (dark_is_one && covered == zeros) {let i = usize::try_from(i).ok()?;*out_row.get_mut(i / 8)? |= 0x80 >> (i % 8);}}}- Some((out, mixed))+ Some((out, mixed, local_tone))}/// A black-and-white image (see [`one_bit`]) resampled and stored again per `settings`, if that is/// smaller as stored; `ppi` is its effective resolution, and `defaults` says it is drawn where/// `/DefaultGray` or `/DefaultRGB` is or may be in force. Also says whether it was resampled.///-/// - **Resampled** ([`downsample_bits`]) when its resolution is above `above_ppi`, to `target_ppi`,+/// - **Resampled** ([`downsample_bits_checked`]) when its resolution is above `above_ppi`, to `target_ppi`,/// unless it has a soft mask, whose own size would then have to follow, or is a halftone or a/// dither: most of its new pixels would cover both black and white, and taking the sample that/// covers more would turn its tones solid (a 50% screen black, a 25% one white).@@ -1025,12 +1038,15 @@ fn mono(doc: &Document, s: &Stream, ppi: f64, defaults: bool, settings: &MonoSet} else {(w, h)};- let averaged = if (nw, nh) != (w, h) {+ let polarity = if defaults { None } else { dark_is_one(doc, packed.as_ref().unwrap_or(d)) };+ let averaged = if (nw, nh) != (w, h) && polarity.is_some() {// The dark sample of the image as it ends up: packed RGB is grey, with grey's decode pair.- let (out, mixed) = downsample_bits(&data, w, h, nw, nh, dark_is_one(doc, packed.as_ref().unwrap_or(d)))?;+ let (out, mixed, local_tone) = downsample_bits_checked(&data, w, h, nw, nh, polarity?)?;// A halftone or dither: most new pixels cover both samples. Text covers both only along// its edges.- (mixed.saturating_mul(2) <= u64::from(nw) * u64::from(nh)).then_some(out)+ // A dense 2x2 patch of mixed output samples can encode a local photo even when+ // white margins dominate the page. Conservatively retain the original image.+ (!local_tone && mixed.saturating_mul(2) <= u64::from(nw) * u64::from(nh)).then_some(out)} else {None};@@ -1310,15 +1326,15 @@ mod downsample_tests {("ColorSpace", Object::Array(vec![Object::name("Separation"), Object::name("Spot"), Object::name("DeviceCMYK"), Object::Null]));let indexed = ("ColorSpace", Object::Array(vec![Object::name("Indexed"), Object::name("DeviceGray"), 1.into(), Object::Null]));for (entries, dark_one) in [- (vec![grey.clone()], false),- (vec![grey, inverted.clone()], true),- (vec![mask.clone()], false),- (vec![mask, inverted.clone()], true),- (vec![separation.clone()], true),- (vec![separation, inverted.clone()], false),- (vec![indexed.clone()], false),- (vec![indexed, inverted], true),- (vec![("ColorSpace", Object::name("DeviceGray")), ("Decode", Object::Array(vec![Object::name("x"), 0.into()]))], false),+ (vec![grey.clone()], Some(false)),+ (vec![grey, inverted.clone()], Some(true)),+ (vec![mask.clone()], Some(false)),+ (vec![mask, inverted.clone()], Some(true)),+ (vec![separation.clone()], None),+ (vec![separation, inverted.clone()], None),+ (vec![indexed.clone()], None),+ (vec![indexed, inverted], None),+ (vec![("ColorSpace", Object::name("DeviceGray")), ("Decode", Object::Array(vec![Object::name("x"), 0.into()]))], None),] {assert_eq!(dark_is_one(&doc, &image(&entries)), dark_one, "{entries:?}");}diff --git a/crates/optimize/tests/optimize.rs b/crates/optimize/tests/optimize.rsindex 3e8b5b9b1..a01def069 100644--- a/crates/optimize/tests/optimize.rs+++ b/crates/optimize/tests/optimize.rs@@ -3413,3 +3413,87 @@ fn lzw_streams_that_cannot_be_read_or_are_not_asked_for_stay_unchanged() {assert_eq!(optimize(&mut doc, &Settings::default()).unwrap().lzw_streams, 1);assert_eq!(stream(&doc, c).decoded_strict().unwrap(), ops);}++/// Unknown palette polarity is never guessed. Both palette orders and Decode directions+/// retain the original thin rule and exact samples through a full save and render.+#[test]+fn indexed_thin_rules_keep_their_samples_for_both_palette_orders_and_decodes() {+ let (w, h) = (1200u32, 480u32);+ let stride = (w as usize).div_ceil(8);+ let mut gray_data = vec![0xFF; stride * h as usize];+ for y in 0..h as usize {+ gray_data[y * stride + 101 / 8] &= !(0x80 >> (101 % 8));+ }+ let mut gray = Document::new_empty();+ let gray_image = mono_image(&mut gray, w, h, &gray_data, None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);+ page(&mut gray, &[("Im", gray_image)], "q 144 0 0 57.6 20 600 cm /Im Do Q");+ let gray_render = render(&gray);+ optimize(&mut gray, &Settings::default()).unwrap();+ let gray_stream = stream(&gray, gray_image);+ let gray_samples = gray.decoded_image(&gray_stream).unwrap();+ assert!(gray_samples.iter().any(|b| *b != 0xFF), "the DeviceGray thin rule survives");+ for white_first in [false, true] {+ for inverted in [false, true] {+ let mut data = vec![0xFF; stride * h as usize];+ for y in 0..h as usize {+ data[y * stride + 101 / 8] &= !(0x80 >> (101 % 8));+ }+ if white_first != inverted {+ data.iter_mut().for_each(|b| *b = !*b);+ }+ let palette = if white_first { vec![255, 0] } else { vec![0, 255] };+ let cs = Object::Array(vec![+ Object::name("Indexed"),+ Object::name("DeviceGray"),+ 1.into(),+ Object::String(pdfcraft_cos::PdfString::literal(palette)),+ ]);+ let mut entries = vec![("BitsPerComponent", 1.into()), ("ColorSpace", cs)];+ if inverted {+ entries.push(("Decode", Object::Array(vec![1.into(), 0.into()])));+ }+ let mut doc = Document::new_empty();+ let image = mono_image(&mut doc, w, h, &data, None, &entries);+ page(&mut doc, &[("Im", image)], "q 144 0 0 57.6 20 600 cm /Im Do Q");+ let before = render(&doc);+ assert_eq!(before, gray_render, "the palette image is visually identical to DeviceGray");+ optimize(&mut doc, &Settings::default()).unwrap();+ let s = stream(&doc, image);+ assert_eq!((s.dict.int(b"Width"), s.dict.int(b"Height")), (Some(w.into()), Some(h.into())));+ assert_eq!(doc.decoded_image(&s).unwrap(), data);+ let saved = Document::open(Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap();+ assert_eq!(render(&saved), before, "palette white-first={white_first}, inverted={inverted}");+ }+ }+}++/// White margins must not hide a small screened photograph from the tone guard.+#[test]+fn mixed_text_and_small_halftone_regions_keep_their_tones_with_wide_white_margins() {+ let (w, h) = (1200u32, 480u32);+ let stride = (w as usize).div_ceil(8);+ for side in [8usize, 40, 300] {+ let mut data = vec![0xFF; stride * h as usize];+ for y in 40..40 + side {+ for x in 100..100 + side {+ if (x + y) % 2 == 0 {+ data[y * stride + x / 8] &= !(0x80 >> (x % 8));+ }+ }+ }+ // A separate one-pixel text/rule stroke makes this a mixed-content scan.+ for y in 380..420 {+ data[y * stride + 801 / 8] &= !(0x80 >> (801 % 8));+ }+ let mut doc = Document::new_empty();+ let image = mono_image(&mut doc, w, h, &data, None, &[("BitsPerComponent", 1.into()), ("ColorSpace", Object::name("DeviceGray"))]);+ page(&mut doc, &[("Im", image)], "q 144 0 0 57.6 20 600 cm /Im Do Q");+ let before = render(&doc);+ optimize(&mut doc, &Settings::default()).unwrap();+ let s = stream(&doc, image);+ assert_eq!((s.dict.int(b"Width"), s.dict.int(b"Height")), (Some(w.into()), Some(h.into())));+ assert_eq!(doc.decoded_image(&s).unwrap(), data, "screened samples survive, not a solid patch");+ let saved = Document::open(Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap();+ assert_eq!(render(&saved), before, "local halftone {side}x{side}");+ }+}diff --git a/crates/ui-egui/src/panels/format_text_ui.rs b/crates/ui-egui/src/panels/format_text_ui.rsindex 0a8ac6af8..eccef2aa7 100644--- a/crates/ui-egui/src/panels/format_text_ui.rs+++ b/crates/ui-egui/src/panels/format_text_ui.rs@@ -65,6 +65,9 @@ impl Paragraphs<'_> {/// `align` picked: for the selected paragraphs, or the whole box (dropping theirs).fn choose(&self, look: &mut AddedText, align: TextAlign) {+ if !self.tidy && self.selected().is_some() {+ return;+ }match self.selected() {Some(which) => {let count = pdfcraft_engine::paragraph_align::count(self.text);@@ -192,7 +195,11 @@ pub(crate) fn panel(TextAlign::Right => "align-right",TextAlign::Justify => "align-justify",};- let align = icons::button(ui, current, 30.0, false, tl!("Alignment"));+ let supported = paragraphs.as_ref().is_none_or(|p| p.tidy || p.selected().is_none());+ let align = ui+ .add_enabled_ui(supported, |ui| icons::button(ui, current, 30.0, false, tl!("Alignment")))+ .inner+ .on_disabled_hover_text(format!("{} — {}", tl!("Alignment"), tl!("Planned")));let align = flyout(ui, t, align);egui::Popup::menu(&align).show(|ui| {ui.horizontal(|ui| {diff --git a/crates/ui-egui/tests/it/editing.rs b/crates/ui-egui/tests/it/editing.rsindex 4f4bbf06b..0eb5ccb7f 100644--- a/crates/ui-egui/tests/it/editing.rs+++ b/crates/ui-egui/tests/it/editing.rs@@ -7114,99 +7114,49 @@ fn row_rect(h: &Harness<'static, PdfCraftApp>, starts: &str) -> [f64; 4] {s.session.get(s.views[0].id).unwrap().text_lines(0).into_iter().find(|l| l.text.starts_with(starts)).expect("the row").rect}-/// Bug A: with one row of a paragraph selected, an alignment applies to that row only.-/// Bug C: Undo then puts the paragraph back and closes the editor, instead of leaving it open on-/// a text the page no longer has.+/// Existing-row alignment stays disabled until intent survives reopening; cancellation keeps all rows.#[test]-fn aligning_a_selected_row_aligns_only_that_row_and_undo_puts_it_back() {+fn selected_existing_rows_keep_alignment_disabled_and_the_complete_paragraph() {let mut h = three_row_paragraph();+ let before = h.state().views[0].line_editor.as_ref().unwrap().text.clone();let first = row_rect(&h, "One");- let wide = row_rect(&h, "three");let last = row_rect(&h, "nine");- // Select the last row.h.key_press_modifiers(Modifiers::COMMAND, Key::End);h.key_press_modifiers(Modifiers::SHIFT, Key::Home);h.run_steps(2);- align_by_pointer(&mut h, "Align right");- {- let s = h.state();- assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), Some("Edit text"));- assert!(s.views[0].line_editor.is_some(), "the paragraph stays open");- }- let moved = row_rect(&h, "nine");- assert!((row_rect(&h, "One")[0] - first[0]).abs() < 0.5, "the first row stays put");- assert!((moved[2] - wide[2]).abs() < 1.0 && moved[0] > last[0] + 20.0, "the last row is right-aligned: {moved:?}");- h.key_press_modifiers(Modifiers::COMMAND, Key::Z);- h.run_steps(4);- let s = h.state();- assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), None, "the alignment is undone");- assert!(s.views[0].line_editor.is_none(), "the editor closed with the step it showed");- assert!((row_rect(&h, "nine")[0] - last[0]).abs() < 0.5, "the last row is back");+ assert!(h.get_by_label("Alignment").accesskit_node().is_disabled());+ let button = h.get_by_label("Alignment").rect().center();+ click_at(&mut h, button);+ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, before);+ assert_eq!(row_rect(&h, "One"), first);+ assert_eq!(row_rect(&h, "nine"), last);+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_undo(), None);+ h.key_press(Key::Escape);+ h.run_steps(3);+ assert_eq!(row_rect(&h, "One"), first);+ assert_eq!(row_rect(&h, "nine"), last);}-/// Format text's alignment flyout by keyboard or screen reader: each control is focused, then-/// pressed, with no pointer anywhere.-fn align_by_focus(h: &mut Harness<'static, PdfCraftApp>, choice: &str) {- for label in ["Alignment", choice] {- h.get_by_label(label).focus();- h.run_steps(2);- h.get_by_label(label).click();- h.run_steps(3);- }-}-/// The same as by pointer, with the alignment controls reached by keyboard or a screen reader:-/// the paragraph stays open when the focus leaves it for the Format text panel, the selected row-/// takes the alignment, and a second choice is for that row again.+/// Clearing the selection restores ordinary whole-paragraph alignment and its undo step.#[test]-fn aligning_a_selected_row_by_keyboard_keeps_the_paragraph_open() {+fn whole_paragraph_alignment_stays_available_without_a_row_selection() {let mut h = three_row_paragraph();- let first = row_rect(&h, "One");- let wide = row_rect(&h, "three");h.key_press_modifiers(Modifiers::COMMAND, Key::End);h.key_press_modifiers(Modifiers::SHIFT, Key::Home);h.run_steps(2);- align_by_focus(&mut h, "Align right");- assert!(h.state().views[0].line_editor.is_some(), "the paragraph stays open");- let moved = row_rect(&h, "nine");- assert!((moved[2] - wide[2]).abs() < 1.0, "the last row is right-aligned: {moved:?}");- align_by_focus(&mut h, "Centre");- assert!(h.state().views[0].line_editor.is_some(), "the paragraph is still open");- assert!((row_rect(&h, "One")[0] - first[0]).abs() < 0.5, "the first row stays put: {:?}", row_rect(&h, "One"));- let last = row_rect(&h, "nine");- assert!((((last[0] + last[2]) - (wide[0] + wide[2])) / 2.0).abs() < 1.0, "the last row is centred: {last:?} in {wide:?}");-}--/// A row aligned on its own, deleted by typing, then brought back with Undo from the menu: it-/// comes back with its alignment, and Redo deletes it again. The box's history keeps only text,-/// so the restored row took the alignment of the row before it.-#[test]-fn undo_brings_a_deleted_row_back_with_its_alignment() {- let mut h = three_row_paragraph();- // Right-align the last row on its own.- h.key_press_modifiers(Modifiers::COMMAND, Key::End);- h.key_press_modifiers(Modifiers::SHIFT, Key::Home);+ assert!(h.get_by_label("Alignment").accesskit_node().is_disabled());+ h.key_press(Key::End);h.run_steps(2);+ assert!(!h.get_by_label("Alignment").accesskit_node().is_disabled());align_by_pointer(&mut h, "Align right");- let ed = |h: &Harness<'static, PdfCraftApp>| h.state().views[0].line_editor.clone().expect("the paragraph stays open");- let (three_rows, aligned) = (ed(&h).text, ed(&h).look.aligns);- assert_eq!(aligned.last(), Some(&Some(pdfcraft_engine::TextAlign::Right)), "{aligned:?}");- // Delete the last row with the line break before it.- h.key_press_modifiers(Modifiers::COMMAND, Key::End);- h.key_press_modifiers(Modifiers::SHIFT, Key::Home);- h.key_press_modifiers(Modifiers::SHIFT, Key::ArrowLeft);- h.key_press(Key::Backspace);- h.run_steps(2);- let (two_rows, after_delete) = (ed(&h).text, ed(&h).look.aligns);- assert_eq!(pdfcraft_engine::paragraph_align::count(&two_rows), 2, "{two_rows:?}");- assert!(h.state_mut().execute("edit.undo"));- h.run_steps(3);- assert_eq!((ed(&h).text, ed(&h).look.aligns), (three_rows, aligned), "Undo brings the row back right-aligned");- assert!(h.state_mut().execute("edit.redo"));+ assert!(h.state().views[0].line_editor.is_some());+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);h.run_steps(3);- assert_eq!((ed(&h).text, ed(&h).look.aligns), (two_rows, after_delete), "Redo deletes it again");+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_undo(), None);}+/// Redo after Undo in the box puts the typing back, in the box: it doesn't reach the document,/// whose own Redo (a formatting change waiting here) must stay waiting.#[test]@@ -7239,47 +7189,6 @@ fn redo_after_undoing_typing_puts_the_typing_back() {assert_eq!((doc.can_redo(), doc.text_blocks(0)[0].base_font.as_str()), (Some("Edit text"), "Helvetica"), "the document's Redo still waits");}-/// A row aligned on its own keeps its alignment when the whole paragraph is then made bold: the-/// rewrite for the bold carries the rows' alignments too, as nothing in the page records them.-#[test]-fn a_row_aligned_on_its_own_keeps_it_through_more_formatting() {- let mut h = three_row_paragraph();- let wide = row_rect(&h, "three");- h.key_press_modifiers(Modifiers::COMMAND, Key::End);- h.key_press_modifiers(Modifiers::SHIFT, Key::Home);- h.run_steps(2);- align_by_pointer(&mut h, "Align right");- // Nothing selected: the bold is for the whole paragraph.- h.key_press(Key::End);- h.run_steps(2);- assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().selection, None);- h.get_by_label("Bold").click();- h.run_steps(4);- assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().text_blocks(0)[0].base_font, "Helvetica-Bold");- let last = row_rect(&h, "nine");- assert!(- (last[2] - row_rect(&h, "three")[2].max(wide[2])).abs() < 1.0 && last[0] > wide[0] + 20.0,- "the last row is still right-aligned: {last:?}"- );-}--/// A second alignment picked while the same row is still selected applies to that row again, not-/// the whole paragraph.-#[test]-fn a_second_alignment_for_a_selected_row_stays_on_that_row() {- let mut h = three_row_paragraph();- let first = row_rect(&h, "One");- let wide = row_rect(&h, "three");- h.key_press_modifiers(Modifiers::COMMAND, Key::End);- h.key_press_modifiers(Modifiers::SHIFT, Key::Home);- h.run_steps(2);- align_by_pointer(&mut h, "Align right");- align_by_pointer(&mut h, "Centre");- assert!((row_rect(&h, "One")[0] - first[0]).abs() < 0.5, "the first row stays put: {:?}", row_rect(&h, "One"));- let last = row_rect(&h, "nine");- let (mid, centre) = ((last[0] + last[2]) / 2.0, (wide[0] + wide[2]) / 2.0);- assert!((mid - centre).abs() < 1.0, "the last row is centred: {last:?} in {wide:?}");-}/// Redo from the menu or toolbar with typing in the box the page doesn't have yet. Closing the/// box first applied the typing, a new edit that dropped the document's waiting Redo, and thediff --git a/docs/integration-20261030.md b/docs/integration-20261030.mdindex 92b5e0712..2ee2dac6a 100644--- a/docs/integration-20261030.md+++ b/docs/integration-20261030.md@@ -5,6 +5,16 @@ Base: 1d1cbc4ec92012767f5b48c92b451e15eb401c42Validation: combined GitHub CI passed on bdf56209ce6a22980ef488eec92a55073f5a4e18 (Linux and Windows, run 41038860617). No fresh manual GUI pass has been performed. The subsequent architectural-guard additions require a fresh run.All included source heads are preserved as merge parents, retaining original authorship. No upstream PR was merged. Conflicts were resolved after the user requested inclusion despite merge conflicts.+## Review follow-up and withheld behavior++Review 5712795161 identified combined-behavior gaps after the green baseline at 673178b.+The follow-up is pending fresh hosted validation; earlier results below are historical evidence.++- Backdrop detection uses a shared strict 64 KiB decoding budget, including intermediate filter outputs, and caps content-stream entries. A fill stream executed more than once on the page is treated as ambiguous and is not replaced; source artwork stays untouched.+- Monochrome downsampling no longer guesses Indexed/custom color-space polarity. Those images may be recompressed losslessly but retain their resolution. A local 2-by-2 patch of mixed output samples conservatively retains the entire source image, even when white margins dominate it.+- **Withheld from #4180:** selected-row alignment of existing PDF paragraphs. The UI disables it for a text selection and the editing API explicitly refuses per-row alignment intent before mutation. Whole-paragraph alignment and the independently persisted alignments of added text remain available. Prior immediate-row tests are replaced by safe-refusal tests; no cross-session alignment guarantee is claimed for the withheld feature.+- The custom JBIG2 encoder still needs separate representative independent-decoder qualification. No codec corruption defect has been established by this review. No fresh native manual GUI acceptance pass is claimed.+## Included- [#4304](https://github.com/storytold/pdfcraft/pull/4304): M11: PDF Optimizer stores black-and-white images as CCITT Group 4 (optimize.mono-compression) (1b7164cab1fc187c5385c30f94449542fe284280)- [#4335](https://github.com/storytold/pdfcraft/pull/4335): M11: black-and-white pictures stay one bit: Create PDF, the optimizer, and CCITT image export (210ba20fe69e701286bbfdbd924cfc01d9aaa9f4)@@ -76,7 +86,7 @@ For each source-head diff above, the added `#[test]` function names were matched- #2635: 6/6 added source regression names passed; 0 missing, 0 skipped.- #1952: 6/6 added source regression names passed; 0 missing, 0 skipped.-The conflict-specific tests `wrapped_rows_keep_alignment_separate_from_hard_break_markers` and `black_and_white_images_become_jbig2` (including the CCITT-to-JBIG2 conversion/render assertions) passed in that same run. Source tests for alignment/history, paragraph boundaries, field calculations and button export values remain present and passed.+The conflict-specific tests `wrapped_rows_keep_alignment_separate_from_hard_break_markers` and `black_and_white_images_become_jbig2` (including the CCITT-to-JBIG2 conversion/render assertions) passed in that same run. Those counts describe that baseline. In the review follow-up, unsupported existing-row alignment success tests are replaced by safe-refusal tests; the corresponding feature is withheld. Paragraph-boundary, field-calculation and button-export coverage is retained.## Protect dependency checkdiff --git a/parity/acrobat-features.toml b/parity/acrobat-features.tomlindex 98ebd7e9a..d4a06ba8f 100644--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@ -1974,8 +1974,8 @@ milestone = "M7"status = "shipped"commands = ["edit.edit_text", "edit.text"]tools = ["text_edit", "content_update"]-evidence = ["crates/edit/src/tests.rs::justify_underline_and_spacing", "crates/edit/src/tests.rs::paragraphs_take_new_formatting", "crates/edit/src/tests.rs::a_one_row_title_keeps_its_centre_when_it_grows_and_when_it_wraps", "crates/ui-egui/tests/it/editing.rs::the_format_panel_restyles_the_paragraph_being_edited", "crates/edit/src/tests.rs::one_row_of_a_paragraph_takes_its_own_alignment", "crates/edit/src/tests.rs::one_row_of_a_styled_region_takes_its_own_alignment", "crates/edit/src/tests.rs::added_text_paragraphs_keep_their_own_alignments", "crates/ui-egui/tests/it/editing.rs::aligning_a_selected_row_aligns_only_that_row_and_undo_puts_it_back", "crates/ui-egui/tests/it/content.rs::aligning_a_selected_line_of_added_text_aligns_only_that_line", "crates/automation/tests/it/automation.rs::added_text_lines_take_their_own_alignments"]-notes = "left, centre, right and justify (word spacing per line, last line left) for existing paragraphs and added text. A centred paragraph is found either from its ragged rows or, for a one row title, from its centre sitting on the page's own centre away from the edge the rest of the text uses, so growing or wrapping it keeps that centre (#2581). With text selected, Format text aligns only the lines (rows between line breaks) the selection touches; with only the caret, the whole paragraph or box (aligns in text_edit, page_add_text and content_update). Added text keeps each line's alignment in its /PCAdded parameters, and a justified line's last row is not stretched. Missing: an edited paragraph's per-row alignment is not recorded in the page, so after it is closed and reopened a later rewrite of it can put that row back to the paragraph's alignment (as whole-paragraph justify is lost, #2508/#2515); aligning a row can regroup the paragraph, and the editor then shows only the part it groups first; a row justified on its own in a region of mixed styles is left-aligned, as the styled-region rewrite doesn't justify (a whole paragraph there isn't justified either); the added-text editor stretches justified lines with egui's own spacing, close to but not exactly as written"+evidence = ["crates/edit/src/tests.rs::justify_underline_and_spacing", "crates/edit/src/tests.rs::paragraphs_take_new_formatting", "crates/edit/src/tests.rs::a_one_row_title_keeps_its_centre_when_it_grows_and_when_it_wraps", "crates/ui-egui/tests/it/editing.rs::the_format_panel_restyles_the_paragraph_being_edited", "crates/edit/src/tests.rs::one_row_of_a_paragraph_takes_its_own_alignment_is_refused_without_changing_the_document", "crates/edit/src/tests.rs::one_row_of_a_styled_region_takes_its_own_alignment_is_refused_without_changing_the_document", "crates/edit/src/tests.rs::added_text_paragraphs_keep_their_own_alignments", "crates/ui-egui/tests/it/editing.rs::selected_existing_rows_keep_alignment_disabled_and_the_complete_paragraph", "crates/ui-egui/tests/it/content.rs::aligning_a_selected_line_of_added_text_aligns_only_that_line", "crates/automation/tests/it/automation.rs::added_text_lines_take_their_own_alignments"]+notes = "Whole-paragraph left, centre and right alignment remain available for existing PDF text; the supported single-style path also justifies. Mixed-style existing-paragraph justification is explicitly refused rather than silently applying Left. Selected-row alignment of existing PDF paragraphs is withheld: the UI disables alignment with a text selection, and text_edit refuses per-row intent before mutation until persistence and regrouping can be qualified. Added text retains independently persisted per-line alignment in /PCAdded, including through page_add_text and content_update. Missing: existing whole-paragraph justification intent across reopening (#2508/#2515), mixed-style justification, and existing-row alignment persistence/regrouping. The added-text preview uses egui spacing, close to but not exactly as written. Review 5712795161 follow-up validation is pending."[[feature]]id = "edit.line-paragraph-spacing"