Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

fix(edit): keep a one-row centred title centred when it grows (#2581)

Krzysztof Cieślikad9e5d2ba99d
diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs
index b542142df..dc86c947b 100644
--- a/crates/edit/src/tests.rs
+++ b/crates/edit/src/tests.rs
@@ -2046,6 +2046,43 @@ fn paragraphs_take_new_formatting() {
}
}
+#[test]
+fn a_one_row_title_keeps_its_centre_when_it_grows_and_when_it_wraps() {
+ // A centred one-row title (its centre is at x ≈ 306 on the 600 pt page) above a body
+ // left-aligned at x = 72. Growing it must not drag it to the right.
+ let src = "BT /F1 18 Tf 1 0 0 1 252.477 700 Tm (Centered title) Tj ET\n\
+ BT /F1 12 Tf 1 0 0 1 72 640 Tm (Body text below the heading starts here and runs) Tj ET\n\
+ BT /F1 12 Tf 1 0 0 1 72 625.6 Tm (on for a second row of ordinary words.) Tj ET";
+ let mut doc = text_page(src);
+ let before = text::text_blocks(&doc, 0).unwrap()[0].clone();
+ let centre = (before.rect[0] + before.rect[2]) / 2.0;
+ text::rewrite_block(&mut doc, 0, 0, Some("Centered title with a few more words"), &text::BlockStyle::default()).unwrap();
+ let doc = reopen(&doc);
+ let blocks = text::text_blocks(&doc, 0).unwrap();
+ let lines = text::text_lines(&doc, 0).unwrap();
+ assert_eq!(blocks[0].text, "Centered title with a few more words");
+ let r = lines[blocks[0].lines[0]].rect;
+ assert!(((r[0] + r[2]) / 2.0 - centre).abs() < 1.0, "the grown title stays centred on {centre}, its centre is {}", (r[0] + r[2]) / 2.0);
+ // Long enough to have to wrap: every row stays centred on the same centre too.
+ let mut doc = text_page(src);
+ text::rewrite_block(
+ &mut doc,
+ 0,
+ 0,
+ Some("Centered title with many more words added so that the single row has to become much longer"),
+ &text::BlockStyle::default(),
+ )
+ .unwrap();
+ let doc = reopen(&doc);
+ let blocks = text::text_blocks(&doc, 0).unwrap();
+ let lines = text::text_lines(&doc, 0).unwrap();
+ assert!(blocks[0].lines.len() > 1, "the long title wraps into rows: {:?}", blocks[0].text);
+ for i in &blocks[0].lines {
+ let r = lines[*i].rect;
+ assert!(((r[0] + r[2]) / 2.0 - centre).abs() < 2.0, "row {:?} stays centred on {centre}", lines[*i].text);
+ }
+}
+
#[test]
fn a_new_paragraph_colour_does_not_spill_into_the_text_after_it() {
let mut doc = text_page("BT /F1 10 Tf 72 700 Td (First paragraph) Tj 0 -40 Td (Second paragraph) Tj ET");
diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rs
index 9c83cf9a3..a24a0f477 100644
--- a/crates/edit/src/text.rs
+++ b/crates/edit/src/text.rs
@@ -22,7 +22,7 @@ use crate::EditError;
#[path = "text_regions.rs"]
mod regions;
-use regions::{group_blocks, rewrite_styled_block};
+use regions::{group_blocks, is_centred, rewrite_styled_block};
/// One line of existing text.
#[derive(Clone, Debug, PartialEq)]
@@ -2098,6 +2098,11 @@ fn rewrite_block_from(
} else {
members.iter().map(|l| l.frame_rect()).reduce(|a, f| [a[0].min(f[0]), a[1].min(f[1]), a[2].max(f[2]), a[3].max(f[3])]).unwrap_or(b.rect)
};
+ // A centred title is laid out in the box it already sits in, so it keeps its centre as it
+ // grows or wraps, rather than being grown to the right up to the page's margin (#2581).
+ // Turned text is left alone: its centre lives along its own baseline, not in page space.
+ let crop = p.crop(doc);
+ let centred = upright && !rtl && style.width.is_none() && style.align.is_none() && is_centred(&b, &lines, (crop[0] + crop[2]) / 2.0, first.size);
// A paragraph keeps its width (or takes the one asked for); a single line grows to the right
// (to the left when right-to-left), up to the page's margin.
let width = match style.width {
@@ -2106,14 +2111,15 @@ fn rewrite_block_from(
Some(_) => return Err(EditError::Invalid("the paragraph's width must be a number".into())),
// Turned text: the page's margins are along another axis. A single line grows (below).
None if !upright => (frame[2] - frame[0]).max(size * k),
- None if anchored_right => (b.rect[2] - b.rect[0]).max(size * k).max(b.rect[2] + dx - (p.crop(doc)[0] + 36.0)),
- None if members.len() == 1 => (b.rect[2] - b.rect[0]).max(size * k).max(p.crop(doc)[2] - 36.0 - (b.rect[0] + dx)),
+ None if anchored_right => (b.rect[2] - b.rect[0]).max(size * k).max(b.rect[2] + dx - (crop[0] + 36.0)),
+ // A centred line is not stretched to the margin: its own box is the frame it is centred in.
+ None if members.len() == 1 && !centred => (b.rect[2] - b.rect[0]).max(size * k).max(crop[2] - 36.0 - (b.rect[0] + dx)),
None => (b.rect[2] - b.rect[0]).max(size * k),
};
if !width.is_finite() {
return Err(EditError::Invalid("the paragraph's width must be a number".into()));
}
- let align = style.align.or(rtl.then_some(crate::added::Align::Right));
+ let align = if centred { Some(crate::added::Align::Center) } else { style.align.or(rtl.then_some(crate::added::Align::Right)) };
// Where a right-aligned line ends, from the paragraph's left edge (user space).
let right_edge = if anchored_right { (b.rect[2] - b.rect[0]).max(0.0) } else { width };
// The move and the width are checked here, before the fallback fonts are written: a refused
diff --git a/crates/edit/src/text_regions.rs b/crates/edit/src/text_regions.rs
index 2d7baf519..75e35b723 100644
--- a/crates/edit/src/text_regions.rs
+++ b/crates/edit/src/text_regions.rs
@@ -31,6 +31,43 @@ fn frame_row_rect(row: &[usize], lines: &[TextLine]) -> Option<[f64; 4]> {
row.iter().filter_map(|i| lines.get(*i)).map(TextLine::frame_rect).reduce(union)
}
+/// The left edge the rest of the page's text sits on, ignoring the rows of `block`. A single row
+/// that does not share it is not merely an indented or full-width left-aligned line, so its own
+/// centre is the only remaining explanation for where it sits.
+fn neighbour_left(lines: &[TextLine], block: &TextBlock) -> Option<f64> {
+ let mut edges: HashMap<i64, usize> = HashMap::new();
+ for (i, line) in lines.iter().enumerate() {
+ if block.lines.contains(&i) {
+ continue;
+ }
+ // Quarter-point buckets: equal edges found through different runs still agree.
+ *edges.entry((line.rect[0] * 4.0).round() as i64).or_insert(0) += 1;
+ }
+ let (best, _) = edges.into_iter().max_by_key(|(_, count)| *count)?;
+ Some(best as f64 / 4.0)
+}
+
+/// Whether a block reads as centred, and so must keep its centre when it grows or wraps.
+///
+/// Several ragged rows whose left edges disagree while their centres agree are centred. A one row
+/// block cannot say that: all of its left edges are the same, so the ragged test never fires and a
+/// centred title would be taken for left-aligned and grow to the right (#2581). Fall back to the
+/// page instead — a lone row sitting on the page's own centre, and not on the edge the rest of the
+/// text uses, is a centred title. A full-width left-aligned line still lines up with that edge, so
+/// it is not mistaken for one.
+pub(super) fn is_centred(block: &TextBlock, lines: &[TextLine], page_centre: f64, size: f64) -> bool {
+ let centre = (block.rect[0] + block.rect[2]) / 2.0;
+ let lefts: Vec<_> = block.rows.iter().filter_map(|r| row_rect(r, lines).map(|r| r[0])).collect();
+ if block.rows.len() > 1 {
+ let left_span = lefts.iter().copied().fold(f64::NEG_INFINITY, f64::max) - lefts.iter().copied().fold(f64::INFINITY, f64::min);
+ return left_span > size * 0.5
+ && block.rows.iter().all(|row| row_rect(row, lines).is_some_and(|r| ((r[0] + r[2]) / 2.0 - centre).abs() < size));
+ }
+ lefts
+ .first()
+ .is_some_and(|left| (centre - page_centre).abs() < size && neighbour_left(lines, block).is_none_or(|edge| (*left - edge).abs() > size * 0.5))
+}
+
pub(super) fn group_blocks(lines: &[TextLine]) -> Vec<TextBlock> {
group_layout(lines, true)
}
@@ -674,12 +711,8 @@ pub(super) fn rewrite_styled_block(
.ok_or_else(|| EditError::Invalid("the paragraph is drawn in a space it cannot be edited in".into()))?;
let (tx, ty) = back.apply(dx, dy);
block_ops.push(Op::new("cm", vec![n(1.0), n(0.0), n(0.0), n(1.0), n(tx), n(ty)]));
- let centre = (block.rect[0] + block.rect[2]) / 2.0;
- let lefts: Vec<_> = block.rows.iter().filter_map(|r| row_rect(r, lines).map(|r| r[0])).collect();
- let left_span = lefts.iter().copied().fold(f64::NEG_INFINITY, f64::max) - lefts.iter().copied().fold(f64::INFINITY, f64::min);
- let centered = block.rows.len() > 1
- && left_span > first.size * 0.5
- && block.rows.iter().all(|row| row_rect(row, lines).is_some_and(|r| ((r[0] + r[2]) / 2.0 - centre).abs() < first.size));
+ let crop = p.crop(doc);
+ let centered = is_centred(block, lines, (crop[0] + crop[2]) / 2.0, first.size);
let source_leading = block
.rows
.windows(2)
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 533013b54..e47bd2898 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -1962,8 +1962,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/ui-egui/tests/editing.rs::the_format_panel_restyles_the_paragraph_being_edited"]
-notes = "left, centre, right and justify (word spacing per line, last line left) for existing paragraphs and added text"
+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/editing.rs::the_format_panel_restyles_the_paragraph_being_edited"]
+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)"
[[feature]]
id = "edit.line-paragraph-spacing"