Skip to content

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

Merge main into feat/align-selected-lines

RiceDeea8ea7d06cdf3
diff --cc crates/automation/src/content.rs
index c162e739d,d0b0b69fd..23f4c4bf0
--- a/crates/automation/src/content.rs
+++ b/crates/automation/src/content.rs
@@@ -53,14 -53,20 +53,20 @@@ fn style(a: &Args, t: &mut AddedText) -
t.color = parse_color(c)?;
}
if let Some(al) = a.opt_str("align")? {
- t.align = match al {
- "left" => TextAlign::Left,
- "center" | "centre" => TextAlign::Center,
- "right" => TextAlign::Right,
- "justify" => TextAlign::Justify,
- other => return Err(bad(format!("unknown align {other:?}"))),
- };
+ t.align = parse_align(al)?;
+ // The whole box: no paragraph keeps an alignment of its own unless `aligns` gives it one.
+ t.aligns.clear();
+ }
+ if let Some(aligns) = opt_aligns(a)? {
+ let count = pdfcraft_engine::paragraph_align::count(&t.text);
+ t.aligns = pdfcraft_engine::paragraph_align::tidy(aligns.into_iter().take(count).collect(), t.align);
}
+ if let Some(c) = a.opt_num("char_spacing")? {
+ if !(-ADDED_CHAR_SPACING_LIMIT..=ADDED_CHAR_SPACING_LIMIT).contains(&c) {
+ return Err(bad(format!("char_spacing must be between -{ADDED_CHAR_SPACING_LIMIT} and {ADDED_CHAR_SPACING_LIMIT} points")));
+ }
+ t.char_spacing = c;
+ }
Ok(())
}
@@@ -197,8 -171,8 +204,8 @@@ impl Automation
if a.get("text").is_some() {
return Err(bad("images have no text"));
}
- if ["font", "size", "bold", "italic", "color", "align", "aligns"].iter().any(|k| a.get(k).is_some()) {
- return Err(bad("font, size, bold, italic, color, align and aligns apply to text"));
- if ["font", "size", "bold", "italic", "color", "align", "char_spacing"].iter().any(|k| a.get(k).is_some()) {
- return Err(bad("font, size, bold, italic, color, align and char_spacing apply to text"));
++ if ["font", "size", "bold", "italic", "color", "align", "aligns", "char_spacing"].iter().any(|k| a.get(k).is_some()) {
++ return Err(bad("font, size, bold, italic, color, align, aligns and char_spacing apply to text"));
}
if let Some(deg) = a.opt_int("rotate")? {
if deg.rem_euclid(90) != 0 {
diff --cc crates/automation/src/tools.rs
index db521074d,9441d7e0c..137acbbfc
--- a/crates/automation/src/tools.rs
+++ b/crates/automation/src/tools.rs
@@@ -594,7 -600,7 +600,8 @@@ pub fn tools() -> Vec<ToolDef>
"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },
"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
+ "aligns": { "type": "array", "maxItems": 4096, "items": { "enum": ["left", "center", "right", "justify", null] }, "description": "Each paragraph's (line's) own alignment, by index; null follows align." },
+ "char_spacing": { "type": "number", "minimum": -500, "maximum": 500, "description": "Points after each character." },
}),
&["doc", "page", "text"],
)),
@@@ -616,7 -622,7 +623,8 @@@
"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },
"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
+ "aligns": { "type": "array", "maxItems": 4096, "items": { "enum": ["left", "center", "right", "justify", null] }, "description": "Each paragraph's (line's) own alignment, by index; null follows align." },
+ "char_spacing": { "type": "number", "minimum": -500, "maximum": 500, "description": "Points after each character." },
"rotate": { "type": "integer" }, "flip_h": { "type": "boolean" }, "flip_v": { "type": "boolean" },
"crop": { "type": "array", "items": { "type": "number", "minimum": 0, "maximum": 0.49 }, "minItems": 4, "maxItems": 4 },
"image": { "type": "string", "description": "Replace the picture with this file." },
diff --cc crates/automation/tests/it/automation.rs
index 46f4bf391,c2eb4b71c..42cf17618
--- a/crates/automation/tests/it/automation.rs
+++ b/crates/automation/tests/it/automation.rs
@@@ -8425,45 -8868,52 +8868,95 @@@ fn bookmark_list_reports_colour_and_sty
assert_eq!(style(&ok(&mut b, "bookmark_list", json!({ "doc": re }))["bookmarks"]), style(&set), "saved");
}
+/// `aligns` gives each line of added text an alignment of its own; `align` alone is the whole box
+/// again. Text edits take `aligns` for a paragraph's rows the same way.
+#[test]
+fn added_text_lines_take_their_own_alignments() {
+ let dir = workdir("paragraph-aligns");
+ let mut a = auto(&dir);
+ let id = ok(&mut a, "doc_create", json!({"from":"blank","width":600,"height":400}))["doc"].as_u64().unwrap();
+ ok(&mut a, "page_add_text", json!({"doc":id,"page":1,"text":"Left line\nRight line","at":[40,50],"width":500,"size":12,"aligns":[null,"right"]}));
+ let rect = |a: &mut Automation, text: &str| -> Vec<f64> {
+ let lines = ok(a, "text_lines", json!({"doc":id,"page":1}));
+ let line = lines["lines"].as_array().unwrap().iter().find(|l| l["text"] == text).cloned().unwrap();
+ line["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect()
+ };
+ assert!((rect(&mut a, "Left line")[0] - 40.0).abs() < 1.0);
+ assert!((rect(&mut a, "Right line")[2] - 540.0).abs() < 1.0, "{:?}", rect(&mut a, "Right line"));
+ // The whole box centred: the right-aligned line goes with it.
+ ok(&mut a, "content_update", json!({"doc":id,"page":1,"index":1,"align":"center"}));
+ let right = rect(&mut a, "Right line");
+ assert!(((right[0] + right[2]) / 2.0 - 290.0).abs() < 1.0, "{right:?}");
+ assert!(a.call("content_update", &json!({"doc":id,"page":1,"index":1,"aligns":["sideways"]})).is_err());
+ assert!(a.call("content_update", &json!({"doc":id,"page":1,"index":1,"aligns":"right"})).is_err());
+}
+
+/// `aligns` alone on an existing paragraph aligns its rows by index, as the app does: the rows
+/// stay rows instead of being rewrapped into one, where only the first entry would count.
+#[test]
+fn text_edit_aligns_alone_aligns_the_paragraphs_rows() {
+ let dir = workdir("paragraph-row-aligns");
+ let body = "BT /F1 12 Tf 14.4 TL 1 0 0 1 72 700 Tm (The quick brown fox jumps over the lazy dog) Tj T* (and keeps running.) Tj ET";
+ std::fs::write(dir.join("rows.pdf"), win_ansi_paragraph_pdf(body)).unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "rows.pdf" }))["doc"].as_u64().unwrap();
+ ok(&mut a, "text_edit", json!({ "doc": doc, "page": 1, "paragraph": 1, "aligns": [null, "right"] }));
+ let lines = ok(&mut a, "text_lines", json!({ "doc": doc, "page": 1 }));
+ let rect = |t: &str| -> Vec<f64> {
+ let line = lines["lines"].as_array().unwrap().iter().find(|l| l["text"] == t).unwrap_or_else(|| panic!("{t:?} is a row: {lines}"));
+ line["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect()
+ };
+ let (first, second) = (rect("The quick brown fox jumps over the lazy dog"), rect("and keeps running."));
+ assert!((first[0] - 72.0).abs() < 0.5, "the first row stays at the left: {first:?}");
+ assert!((second[2] - first[2]).abs() < 1.0 && second[0] > 100.0, "the second row is right-aligned: {second:?} vs {first:?}");
+}
++
+ /// `page_render`'s pixels show a rubber stamp written without an appearance as the stamp its
+ /// `/Name` names (ISO 32000-2 Table 184), and one with an unknown name as a grey placeholder.
+ #[test]
+ fn page_render_draws_stamps_without_an_appearance() {
+ let dir = workdir("stamps-without-appearance");
+ let objects: Vec<&[u8]> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>",
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 100] >>",
+ b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R] >>",
+ b"<< /Type /Annot /Subtype /Stamp /Rect [10 20 130 80] /Name /Approved >>",
+ b"<< /Type /Annot /Subtype /Stamp /Rect [170 20 290 80] /Name /MyCustomStamp >>",
+ ];
+ let mut bytes = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, object) in objects.iter().enumerate() {
+ offsets.push(bytes.len());
+ bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
+ bytes.extend_from_slice(object);
+ bytes.extend_from_slice(b"\nendobj\n");
+ }
+ let xref = bytes.len();
+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
+ for o in offsets {
+ bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
+ std::fs::write(dir.join("stamps.pdf"), bytes).unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "stamps.pdf" }))["doc"].as_u64().unwrap();
+ let (width, _, pixels) = a.render_pixels(doc, 1, 1.0).unwrap();
+ let pixels = pixels.as_ref();
+ // Ink in columns `x0..x1` of rows 20..80, which are the stamps' rows whether counted from the top or the bottom.
+ let ink = |x0: u32, x1: u32| -> Vec<[u8; 3]> {
+ (20..80u32)
+ .flat_map(|y| (x0..x1).map(move |x| (y, x)))
+ .map(|(y, x)| {
+ let i = ((y * width + x) * 4) as usize;
+ [pixels[i], pixels[i + 1], pixels[i + 2]]
+ })
+ .filter(|p| p.iter().any(|v| *v < 200))
+ .collect()
+ };
+ let approved = ink(10, 130);
+ let green = approved.iter().filter(|p| p[1] > p[0] && p[1] > p[2]).count();
+ assert!(green > 300 && green * 10 > approved.len() * 9, "Approved is drawn green: {green} of {}", approved.len());
+ let custom = ink(170, 290);
+ let grey = custom.iter().filter(|p| p[0].abs_diff(p[1]) < 24 && p[1].abs_diff(p[2]) < 24).count();
+ assert!(grey > 100 && grey == custom.len(), "an unknown name is a grey placeholder: {grey} of {}", custom.len());
+ }
diff --cc crates/edit/src/added.rs
index 29ccc4e8c,4157c57e4..a2a6edb11
--- a/crates/edit/src/added.rs
+++ b/crates/edit/src/added.rs
@@@ -116,16 -119,8 +119,18 @@@ pub struct AddedText
pub size: f64,
pub color: [f64; 3],
pub align: Align,
+ /// Extra space after every character, in points: the PDF's character spacing (`Tc`).
+ pub char_spacing: f64,
+ /// Paragraphs (lines typed with Enter) aligned other than [`AddedText::align`], by index;
+ /// `None` and paragraphs past the end follow `align` ([`crate::paragraph_align`]).
+ pub aligns: Vec<Option<Align>>,
+}
+
+impl AddedText {
+ /// Paragraph `i`'s alignment.
+ pub fn paragraph_align(&self, i: usize) -> Align {
+ crate::paragraph_align::align_of(&self.aligns, i, self.align)
+ }
}
impl Default for AddedText {
@@@ -139,7 -134,7 +144,8 @@@
size: 12.0,
color: [0.0; 3],
align: Align::Left,
+ aligns: Vec::new(),
+ char_spacing: 0.0,
}
}
}
@@@ -241,9 -238,15 +249,15 @@@ fn norm(r: [f64; 4]) -> [f64; 4]
[r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])]
}
+ /// The advance of `s` in the item's standard font: its glyphs' widths and the character spacing
+ /// after each of them, as `Tc` moves the pen (ISO 32000-2 §9.3.2).
+ fn latin_width(t: &AddedText, s: &str) -> f64 {
+ t.family.width(s, t.size, t.bold, t.italic) + t.char_spacing * s.chars().count() as f64
+ }
+
/// The lines of a text item after wrapping to its box width.
pub fn lines(t: &AddedText) -> Vec<String> {
- wrapped(t).into_iter().map(|(line, _)| line).collect()
+ wrapped(t).into_iter().map(|(line, ..)| line).collect()
}
#[cfg(test)]
@@@ -625,8 -666,10 +695,11 @@@ fn draw_laid_shaped
}
let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));
out.extend(format!("BT {} {} {} rg\n", n(cr), n(cg), n(cb)).bytes());
+ if t.char_spacing != 0.0 {
+ out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
+ }
- for (i, (line, rtl, pieces, w)) in laid.iter().enumerate() {
+ let paragraphs: Vec<usize> = laid.iter().map(|(_, _, p, ..)| *p).collect();
+ for (i, (line, rtl, _, pieces, w)) in laid.iter().enumerate() {
// Shaped glyphs are painted in visual order. Keep the original line's typing order
// explicitly, including marks, ligatures, digits and mixed-script punctuation.
let logical: String = line.encode_utf16().map(|u| format!("{u:04X}")).collect();
@@@ -810,14 -861,23 +883,17 @@@ fn draw(doc: &mut Document, c: &Content
let r = text_rect(t);
let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));
out.extend(format!("BT /{name} {} Tf {} {} {} rg\n", n(t.size), n(cr), n(cg), n(cb)).bytes());
+ if t.char_spacing != 0.0 {
+ out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
+ }
- let all = lines(t);
- for (i, line) in all.iter().enumerate() {
+ let all = wrapped(t);
+ let paragraphs: Vec<usize> = all.iter().map(|(_, _, p)| *p).collect();
+ for (i, (line, ..)) in all.iter().enumerate() {
- let w = t.family.width(line, t.size, t.bold, t.italic);
+ let w = latin_width(t, line);
- let x = match t.align {
- Align::Left | Align::Justify => r[0],
- Align::Center => r[0] + ((r[2] - r[0]) - w) / 2.0,
- Align::Right => r[2] - w,
- };
// Baseline: 0.8 em below the line top.
let y = r[3] - (i as f64 * 1.2 + 0.95) * t.size;
- // Justified: word spacing makes every line but the last fill the box.
- let spaces = line.matches(' ').count();
- let tw =
- if t.align == Align::Justify && i + 1 < all.len() && spaces > 0 { ((r[2] - r[0]) - w).max(0.0) / spaces as f64 } else { 0.0 };
+ // Justified: word spacing makes every line of a paragraph but its last fill the box.
+ let (x, tw) = placed(t, r, &paragraphs, i, w, line.matches(' ').count(), false);
out.extend(format!("1 0 0 1 {} {} Tm {} Tw ", n(x), n(y), n(tw)).bytes());
out.extend(literal(&win_ansi(line)));
out.extend_from_slice(b" Tj\n");
@@@ -867,13 -927,19 +943,16 @@@ fn params(c: &Content) -> Dict
d.set(b"Font".to_vec(), Object::name(t.family.base_font(t.bold, t.italic)));
d.set(b"Size".to_vec(), Object::Real(t.size));
d.set(b"Color".to_vec(), arr(&t.color));
- d.set(
- b"Align".to_vec(),
- Object::Int(match t.align {
- Align::Left => 0,
- Align::Center => 1,
- Align::Right => 2,
- Align::Justify => 3,
- }),
- );
+ d.set(b"Align".to_vec(), Object::Int(align_code(t.align)));
+ // Each paragraph's own alignment, or null where it follows /Align.
+ let aligns = crate::paragraph_align::tidy(t.aligns.clone(), t.align);
+ if !aligns.is_empty() {
+ d.set(b"Aligns".to_vec(), Object::Array(aligns.iter().map(|a| a.map_or(Object::Null, |a| Object::Int(align_code(a)))).collect()));
+ }
d.set(b"Rect".to_vec(), arr(&text_rect(t)));
+ if t.char_spacing != 0.0 {
+ d.set(b"CharSpacing".to_vec(), Object::Real(t.char_spacing));
+ }
}
Content::Image(i) => {
d.set(b"Kind".to_vec(), Object::name("Image"));
@@@ -940,8 -977,14 +1019,10 @@@ fn parse(doc: &Document, d: &Dict) -> O
italic,
size: d.get(b"Size").and_then(Object::as_f64).unwrap_or(12.0),
color: if c.len() == 3 { [c[0], c[1], c[2]] } else { [0.0; 3] },
- align: match d.int(b"Align") {
- Some(1) => Align::Center,
- Some(2) => Align::Right,
- Some(3) => Align::Justify,
- _ => Align::Left,
- },
+ align,
+ aligns: crate::paragraph_align::tidy(aligns, align),
+ // Items written before character spacing have none.
+ char_spacing: d.get(b"CharSpacing").and_then(Object::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0),
}))
}
b"Image" => {
diff --cc crates/edit/src/tests.rs
index a20dba68a,3ad46e864..f12430561
--- a/crates/edit/src/tests.rs
+++ b/crates/edit/src/tests.rs
@@@ -6639,171 -6960,418 +6960,615 @@@ fn a_flatten_refused_on_a_later_page_ch
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.
+#[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]);
+}
+
+/// The same in a region of several styles: only the short first row is centred.
+#[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}");
+}
+
+/// Added text: each paragraph is laid out with its own alignment, a justified paragraph's last
+/// line isn't stretched, and the alignments survive saving and reopening.
+#[test]
+fn added_text_paragraphs_keep_their_own_alignments() {
+ let mut doc = fixture();
+ let text = AddedText {
+ rect: [72.0, 600.0, 372.0, 700.0],
+ text: "Left line\nRight line\nCentred line".into(),
+ size: 12.0,
+ aligns: vec![None, Some(Align::Right), Some(Align::Center)],
+ ..AddedText::default()
+ };
+ assert_eq!(text.paragraph_align(1), Align::Right);
+ add_content(&mut doc, 0, &Content::Text(text.clone())).unwrap();
+ let doc = reopen(&doc);
+ let Content::Text(t) = &list_added(&doc)[0].content else { panic!() };
+ assert_eq!(t.aligns, text.aligns, "saved with the item");
+ let page = streams(&doc, 0).join("\n");
+ let x_of = |s: &str| -> f64 {
+ let at = page.find(&format!("({s}) Tj")).unwrap();
+ let tm = page[..at].rfind(" Tm").unwrap();
+ let nums: Vec<f64> = page[..tm].rsplit("1 0 0 1 ").next().unwrap().split_whitespace().filter_map(|v| v.parse().ok()).collect();
+ nums[0]
+ };
+ let w = |s: &str| Family::Helvetica.width(s, 12.0, false, false);
+ assert!((x_of("Left line") - 72.0).abs() < 0.01);
+ assert!((x_of("Right line") - (372.0 - w("Right line"))).abs() < 0.01);
+ assert!((x_of("Centred line") - (72.0 + (300.0 - w("Centred line")) / 2.0)).abs() < 0.01);
+ // A paragraph's own alignment the same as the box's is no entry at all.
+ let tidy = paragraph_align::tidy(vec![Some(Align::Left), Some(Align::Right)], Align::Left);
+ assert_eq!(tidy, [None, Some(Align::Right)]);
+}
+
++/// With character spacing, a paragraph aligned on its own is placed by its spaced width: a
++/// right-aligned line still ends at the box's right edge, and a centred one sits in the middle.
++#[test]
++fn added_text_paragraphs_align_by_their_spaced_width() {
++ let mut doc = fixture();
++ let text = AddedText {
++ rect: [72.0, 600.0, 372.0, 700.0],
++ text: "Left line\nRight line\nCentred line".into(),
++ size: 12.0,
++ aligns: vec![None, Some(Align::Right), Some(Align::Center)],
++ char_spacing: 2.0,
++ ..AddedText::default()
++ };
++ add_content(&mut doc, 0, &Content::Text(text)).unwrap();
++ let page = streams(&reopen(&doc), 0).join("\n");
++ assert!(page.contains("2 Tc"), "{page}");
++ let x_of = |s: &str| -> f64 {
++ let at = page.find(&format!("({s}) Tj")).unwrap();
++ let tm = page[..at].rfind(" Tm").unwrap();
++ let nums: Vec<f64> = page[..tm].rsplit("1 0 0 1 ").next().unwrap().split_whitespace().filter_map(|v| v.parse().ok()).collect();
++ nums[0]
++ };
++ let w = |s: &str| Family::Helvetica.width(s, 12.0, false, false) + 2.0 * s.chars().count() as f64;
++ assert!((x_of("Left line") - 72.0).abs() < 0.01);
++ assert!((x_of("Right line") - (372.0 - w("Right line"))).abs() < 0.01);
++ assert!((x_of("Centred line") - (72.0 + (300.0 - w("Centred line")) / 2.0)).abs() < 0.01);
++}
++
+/// A one-row title over a body column: an alignment picked for it is measured across the column.
+/// Left puts it on the column's left edge, and centring it again leaves it where it is, rather
+/// than aligning it in its own box (a no-op) or toward the page's margin (moving it right each
+/// time). It is aligned as the editor aligns a selected row, in whichever paragraph holds it.
+#[test]
+fn a_lone_row_aligns_across_the_column_it_sits_in() {
+ let mut doc = text_page(
+ "BT /F1 24 Tf 1 0 0 1 250 700 Tm (Title) Tj ET BT /F1 10 Tf 12 TL 72 650 Td (The body of the page runs across the whole column here.) Tj T* (It has a second row that is a little shorter.) Tj ET",
+ );
+ let blocks = text::text_blocks(&doc, 0).unwrap();
+ assert_eq!(blocks[0].text, "Title");
+ let column = [blocks[1].rect[0], blocks[1].rect[2]];
+ let title = |doc: &Document| text::text_lines(doc, 0).unwrap().into_iter().find(|l| l.text == "Title").unwrap().rect;
+ let align = |doc: &mut Document, a: added::Align| {
+ let lines = text::text_lines(doc, 0).unwrap();
+ let line = lines.iter().position(|l| l.text == "Title").unwrap();
+ 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() };
+ text::rewrite_block(doc, 0, index, Some(&block.editor_text), &style).unwrap();
+ };
+ align(&mut doc, added::Align::Center);
+ let centred = title(&doc);
+ assert!(((centred[0] + centred[2]) / 2.0 - (column[0] + column[1]) / 2.0).abs() < 1.0, "centred in the column: {centred:?} vs {column:?}");
+ align(&mut doc, added::Align::Center);
+ assert!((title(&doc)[0] - centred[0]).abs() < 0.5, "centring again leaves it where it is: {:?} vs {centred:?}", title(&doc));
+ align(&mut doc, added::Align::Left);
+ assert!((title(&doc)[0] - column[0]).abs() < 0.5, "left: back on the column's edge, {:?} vs {column:?}", title(&doc));
+ align(&mut doc, added::Align::Right);
+ assert!((title(&doc)[2] - column[1]).abs() < 1.0, "right: on the column's right edge, {:?} vs {column:?}", title(&doc));
+}
+
+/// An edited paragraph's text has a line break between its source rows (`editor_text`), as the
+/// paragraph editor sends it. Those are the rows of one paragraph, not paragraph ends: justified
+/// in a font of its own (the single-style rewrite), every row but the last still fills the width.
+#[test]
+fn a_justified_paragraph_from_the_editor_fills_its_rows() {
+ 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 T* (end) Tj ET");
+ let block = text::text_blocks(&doc, 0).unwrap()[0].clone();
+ assert_eq!(block.editor_text.matches('\n').count(), 2);
+ let style = text::BlockStyle { align: Some(added::Align::Justify), family: Some((Family::Helvetica, true, false)), ..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;
+ let right = row("One")[2];
+ assert!((row("eight")[2] - right).abs() < 1.0, "the second row is stretched: {:?} vs {right}", row("eight"));
+ assert!(row("end")[2] < right - 20.0, "the last row isn't");
+}
+
+/// The same on a page of two columns, where the other column has more rows: a title over the
+/// first column is aligned across the first column, not its own box.
+#[test]
+fn a_lone_row_aligns_across_its_own_column_of_two() {
+ let mut doc = text_page(
+ "BT /F1 18 Tf 1 0 0 1 120 700 Tm (Title) Tj ET \
+ BT /F1 10 Tf 12 TL 50 660 Td (The first column runs to here.) Tj T* (A second row of it.) Tj ET \
+ BT /F1 10 Tf 12 TL 320 660 Td (The second column has more rows.) Tj T* (One.) Tj T* (Two.) Tj T* (Three.) Tj T* (Four.) Tj ET",
+ );
+ 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() };
+ 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:?}");
+}
+
+/// A one-row title in two colours is rewritten by the styled-region path, which is given the
+/// same column frame: centred twice, it stays centred in the column instead of moving right.
+#[test]
+fn a_lone_row_of_two_styles_aligns_across_its_column() {
+ let mut doc = text_page(
+ "BT /F1 18 Tf 1 0 0 1 250 700 Tm (Big ) Tj 1 0 0 rg (Title) Tj ET \
+ BT 0 g /F1 10 Tf 12 TL 72 650 Td (The body of the page runs across the whole column here.) Tj T* (It has a second row that is a little shorter.) Tj ET",
+ );
+ let blocks = text::text_blocks(&doc, 0).unwrap();
+ assert_eq!(blocks[0].text, "Big Title");
+ let column = [blocks[1].rect[0], blocks[1].rect[2]];
+ let title = |doc: &Document| {
+ let lines = text::text_lines(doc, 0).unwrap();
+ let block = text::text_blocks(doc, 0).unwrap().into_iter().find(|b| b.text == "Big Title").unwrap();
+ block.lines.iter().map(|i| lines[*i].rect).reduce(|a, b| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]).unwrap()
+ };
+ 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() };
+ text::rewrite_block(doc, 0, index, Some(&block.editor_text), &style).unwrap();
+ };
+ centre(&mut doc);
+ let centred = title(&doc);
+ assert!(((centred[0] + centred[2]) / 2.0 - (column[0] + column[1]) / 2.0).abs() < 1.0, "centred in the column: {centred:?} vs {column:?}");
+ centre(&mut doc);
+ assert!((title(&doc)[0] - centred[0]).abs() < 0.5, "centring again leaves it where it is: {:?} vs {centred:?}", title(&doc));
+}
++
+ /// How each glyph-showing operator on page 0 is painted, read the way a renderer reads the page:
+ /// its text, `Tr`, stroke colour operators, line width (from `w` or an ExtGState's `/LW`) and
+ /// the ExtGStates selected before it, following `q`/`Q`.
+ #[derive(Clone, Debug, PartialEq)]
+ struct Painted {
+ text: String,
+ render_mode: i64,
+ stroke: Vec<String>,
+ line_width: f64,
+ gs: Vec<String>,
+ }
+
+ fn painted_shows(doc: &Document) -> Vec<Painted> {
+ let (_, ops) = joined_ops(doc);
+ let p = &pdfcraft_model::pages(doc)[0];
+ let res = doc.resolve(p.dict.get(b"Resources").unwrap());
+ let ext = res.as_dict().unwrap().get(b"ExtGState").map(|g| doc.resolve(g).as_dict().cloned().unwrap()).unwrap_or_default();
+ let mut state = Painted { text: String::new(), render_mode: 0, stroke: Vec::new(), line_width: 1.0, gs: Vec::new() };
+ let mut stack = Vec::new();
+ let mut out = Vec::new();
+ let show = |op: &pdfcraft_content::Op| String::from_utf8_lossy(&pdfcraft_content::serialize_ops(std::slice::from_ref(op))).trim().to_string();
+ for op in ops {
+ match op.op.as_slice() {
+ b"q" => stack.push(state.clone()),
+ b"Q" => state = stack.pop().unwrap(),
+ b"Tr" => state.render_mode = op.operands[0].as_int().unwrap(),
+ b"G" | b"RG" | b"K" | b"CS" => state.stroke = vec![show(&op)],
+ b"SC" | b"SCN" => state.stroke.push(show(&op)),
+ b"w" => state.line_width = op.num(0).unwrap(),
+ b"gs" => {
+ let name = op.name(0).unwrap();
+ state.gs.push(String::from_utf8_lossy(name).into_owned());
+ let lw = ext.get(name).and_then(|g| doc.resolve(g).as_dict().and_then(|g| g.get(b"LW")).and_then(|w| w.as_f64()));
+ state.line_width = lw.unwrap_or(state.line_width);
+ }
+ b"Tj" => {
+ let Some(Object::String(s)) = op.operands.last() else { continue };
+ if !s.bytes.is_empty() {
+ out.push(Painted { text: String::from_utf8_lossy(&s.bytes).into_owned(), ..state.clone() });
+ }
+ }
+ _ => {}
+ }
+ }
+ out
+ }
+
+ /// A page with Helvetica as /F1, /GS1, an ExtGState that paints at 20 % opacity, /GS2, one that
+ /// sets the line width to 4, /GS3, another at 20 % opacity, and /GS4, at 20 % opacity and dashed.
+ fn faint_page(content: &str) -> Document {
+ build(&[
+ "<< /Type /Catalog /Pages 2 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /ExtGState << /GS1 6 0 R /GS2 7 0 R /GS3 8 0 R /GS4 9 0 R >> >> >>",
+ &format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
+ "<< /Type /ExtGState /ca 0.2 >>",
+ "<< /Type /ExtGState /LW 4 >>",
+ "<< /Type /ExtGState /ca 0.2 >>",
+ "<< /Type /ExtGState /ca 0.2 /D [[6 3] 0] >>",
+ ])
+ }
+
+ /// Rewriting a paragraph drew it before its text object, restating only the font, spacing and
+ /// fill: a `1 Tr 1 0 0 RG 2 w` set inside `BT` was lost, and red outline text came back filled
+ /// black, even with the text unchanged (#3508). Set before `BT` (the control), it already worked.
+ #[test]
+ fn a_rewritten_paragraph_keeps_the_rendering_mode_stroke_and_width_set_inside_its_text_object() {
+ let outline = |text: &str| Painted { text: text.into(), render_mode: 1, stroke: vec!["1 0 0 RG".into()], line_width: 2.0, gs: Vec::new() };
+ for content in ["BT /F1 72 Tf 1 Tr 1 0 0 RG 2 w 40 400 Td (OUTLINE) Tj ET\n", "1 Tr 1 0 0 RG 2 w BT /F1 72 Tf 40 400 Td (OUTLINE) Tj ET\n"] {
+ assert_eq!(painted_shows(&text_page(content)), [outline("OUTLINE")], "the fixture: {content}");
+ for new in ["OUTLINE", "OUTLINED"] {
+ let mut doc = text_page(content);
+ text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
+ let doc = reopen(&doc);
+ assert_eq!(painted_shows(&doc), [outline(new)], "{content} -> {new}: {}", streams(&doc, 0).join("\n"));
+ }
+ }
+ }
+
+ /// The same for transparency: `/GS1 gs` (`/ca 0.2`) inside `BT` was not in force for the
+ /// rewritten paragraph, so 20 % blue text came back opaque (#3509).
+ #[test]
+ fn a_rewritten_paragraph_keeps_the_extgstate_selected_inside_its_text_object() {
+ for content in ["BT /GS1 gs /F1 72 Tf 0 0 1 rg 40 400 Td (FAINT) Tj ET\n", "/GS1 gs BT /F1 72 Tf 0 0 1 rg 40 400 Td (FAINT) Tj ET\n"] {
+ for new in ["FAINT", "FAINTER"] {
+ let mut doc = faint_page(content);
+ text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
+ let doc = reopen(&doc);
+ let shows = painted_shows(&doc);
+ assert_eq!(shows.len(), 1, "{content} -> {new}: {shows:?}");
+ assert_eq!(
+ (shows[0].text.as_str(), shows[0].gs.as_slice()),
+ (new, ["GS1".to_string()].as_slice()),
+ "{content} -> {new}: {}",
+ streams(&doc, 0).join("\n")
+ );
+ }
+ }
+ }
+
+ /// A paragraph of differently coloured runs goes through the styled rewrite, which draws each
+ /// run in its own text object: each keeps the state its source set inside `BT`.
+ #[test]
+ fn a_styled_rewrite_keeps_the_paint_state_set_inside_the_text_object() {
+ let content = "BT /GS1 gs 1 Tr 1 0 0 RG 2 w /F1 72 Tf 40 400 Td (FAI) Tj 0 0 1 rg (NT) Tj ET\n";
+ let mut doc = faint_page(content);
+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), 2, "two runs on one row");
+ text::rewrite_block(&mut doc, 0, 0, Some("FAINTS"), &BlockStyle::default()).unwrap();
+ let doc = reopen(&doc);
+ let shows = painted_shows(&doc);
+ let joined = streams(&doc, 0).join("\n");
+ assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), "FAINTS", "{joined}");
+ for s in &shows {
+ assert_eq!((s.render_mode, s.stroke.as_slice(), s.line_width), (1, ["1 0 0 RG".to_string()].as_slice(), 2.0), "{s:?}: {joined}");
+ assert_eq!(s.gs, ["GS1"], "{s:?}: {joined}");
+ }
+ }
+
+ /// A `gs` has no inverse, so one run's ExtGState stayed in force for the runs the styled rewrite
+ /// drew after it. Two ExtGStates at the same opacity paint the same (see `Paint`), so their runs
+ /// share a paragraph, but either may set what that doesn't compare (a dash, a line cap): each run
+ /// is drawn with only the ones its source selected.
+ #[test]
+ fn a_styled_rewrite_does_not_carry_one_runs_extgstate_into_the_next() {
+ // "FAI" ends at 40 + 72 * (0.611 + 0.667 + 0.278) = 152.032; "NT" is blue, so another run.
+ let content = "q BT /GS3 gs /F1 72 Tf 40 400 Td (FAI) Tj ET Q BT /GS1 gs /F1 72 Tf 0 0 1 rg 152.032 400 Td (NT) Tj ET
+ ";
+ for new in ["FAINT", "FAINTS"] {
+ let mut doc = faint_page(content);
+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), 2, "two runs on one row");
+ text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
+ let doc = reopen(&doc);
+ let shows = painted_shows(&doc);
+ let joined = streams(&doc, 0).join(
+ "
+ ",
+ );
+ assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), new, "{joined}");
+ let gs: Vec<_> = shows.iter().map(|s| (s.text.as_str(), s.gs.as_slice())).collect();
+ assert_eq!(gs.first(), Some(&("FAI", ["GS3".to_string()].as_slice())), "{gs:?}: {joined}");
+ assert!(gs.iter().skip(1).all(|(_, gs)| *gs == ["GS1"]), "{gs:?}: {joined}");
+ }
+ }
+
+ /// An ExtGState's `/LW` sets the line width as `w` does: `2 w /GS2 gs` (`/LW 4`) outlines at 4,
+ /// and the rewrite replayed `/GS2 gs` and then `2 w`. `/GS2 gs 1 w` outlines at 1, and the
+ /// rewrite replayed only `/GS2 gs`, since 1 is the initial width.
+ #[test]
+ fn a_rewritten_paragraph_keeps_the_line_width_an_extgstate_set() {
+ for (content, width) in [
+ ("BT /F1 72 Tf 1 Tr 2 w /GS2 gs 40 400 Td (OUTLINE) Tj ET\n", 4.0),
+ ("BT /F1 72 Tf 1 Tr /GS2 gs 2 w 40 400 Td (OUTLINE) Tj ET\n", 2.0),
+ ("BT /F1 72 Tf 1 Tr /GS2 gs 1 w 40 400 Td (OUTLINE) Tj ET\n", 1.0),
+ ] {
+ assert_eq!(painted_shows(&faint_page(content))[0].line_width, width, "the fixture: {content}");
+ for new in ["OUTLINE", "OUTLINED"] {
+ let mut doc = faint_page(content);
+ text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
+ let doc = reopen(&doc);
+ let shows = painted_shows(&doc);
+ assert_eq!(
+ shows.iter().map(|s| (s.text.as_str(), s.render_mode, s.line_width)).collect::<Vec<_>>(),
+ [(new, 1, width)],
+ "{content} -> {new}: {}",
+ streams(&doc, 0).join("\n")
+ );
+ }
+ }
+ }
+
+ /// A line is rewritten in the state of its first run, so outline text partway through a text
+ /// object came back filled: "FAI" filled and "NT" a red outline came back all filled. The change
+ /// of `Tr` now starts a run. (A `gs` partway already starts a paragraph; see `Paint`.)
+ #[test]
+ fn a_rendering_mode_partway_through_a_line_starts_a_run_of_its_own() {
+ let content = "BT /F1 72 Tf 40 400 Td (FAI) Tj 1 Tr 1 0 0 RG 2 w (NT) Tj ET
+ ";
+ for new in ["FAINT", "FAINTS"] {
+ let mut doc = faint_page(content);
+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), 2, "two runs on one row");
+ text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
+ let doc = reopen(&doc);
+ let shows = painted_shows(&doc);
+ let joined = streams(&doc, 0).join(
+ "
+ ",
+ );
+ assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), new, "{joined}");
+ let modes: Vec<_> = shows.iter().map(|s| (s.text.as_str(), s.render_mode, s.stroke.as_slice(), s.line_width)).collect();
+ assert_eq!(modes.first().map(|m| (m.0, m.1)), Some(("FAI", 0)), "{modes:?}: {joined}");
+ let outline = ["1 0 0 RG".to_string()];
+ assert!(modes.iter().skip(1).all(|m| (m.1, m.2, m.3) == (1, outline.as_slice(), 2.0)), "{modes:?}: {joined}");
+ }
+ }
+
+ /// Two ExtGStates at the same opacity paint text the same (see `Paint`), but one of them dashes
+ /// its outline: a dashed outline after a solid one in the same text object joined its line and
+ /// came back solid, drawn with the first run's selections. A different dash now starts a run.
+ #[test]
+ fn a_dash_partway_through_an_outlined_line_starts_a_run_of_its_own() {
+ let content = "BT /GS3 gs /F1 72 Tf 1 Tr 1 0 0 RG 2 w 40 400 Td (FAI) Tj /GS4 gs (NT) Tj ET
+ ";
+ for new in ["FAINT", "FAINTS"] {
+ let mut doc = faint_page(content);
+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), 2, "two runs on one row");
+ text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
+ let doc = reopen(&doc);
+ let shows = painted_shows(&doc);
+ let joined = streams(&doc, 0).join(
+ "
+ ",
+ );
+ assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), new, "{joined}");
+ let gs: Vec<_> = shows.iter().map(|s| (s.text.as_str(), s.gs.as_slice())).collect();
+ assert_eq!(gs.first(), Some(&("FAI", ["GS3".to_string()].as_slice())), "{gs:?}: {joined}");
+ assert!(gs.iter().skip(1).all(|(_, gs)| gs.last().is_some_and(|g| g == "GS4")), "{gs:?}: {joined}");
+ }
+ }
+
+ /// The dash and cap are compared as the operators set them too: `d` or `J` partway through an
+ /// outlined line starts a run, and a malformed one (too long, not numbers, out of range) is ignored.
+ #[test]
+ fn a_dash_or_cap_operator_partway_through_an_outlined_line_starts_a_run() {
+ let long = format!("[{}] 0 d", "1 ".repeat(40));
+ for (change, runs) in [("[6 3] 0 d", 2), ("1 J", 2), (long.as_str(), 1), ("[(a) 3] 0 d", 1), ("[6 3] /x d", 1), ("7 J", 1), ("J", 1)] {
+ let content = format!("BT /F1 72 Tf 1 Tr 1 0 0 RG 2 w 40 400 Td (FAI) Tj {change} (NT) Tj ET\n");
+ let mut doc = faint_page(&content);
+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), runs, "{change}");
+ text::rewrite_block(&mut doc, 0, 0, Some("FAINTS"), &BlockStyle::default()).unwrap();
+ let shows = painted_shows(&reopen(&doc));
+ assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), "FAINTS", "{change}");
+ }
+ }
+
+ /// #4199, #3797: every space typed into a paragraph is saved, not folded into one.
+ #[test]
+ fn an_edited_paragraph_keeps_every_space_typed() {
+ for typed in ["Hello world", "Hello world end", " indented and trailing "] {
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
+ assert_eq!(text::replace_block(&mut doc, 0, 0, typed).unwrap().substituted, None);
+ let doc = reopen(&doc);
+ let content = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned();
+ assert!(content.contains(&format!("({typed}) Tj")), "{typed:?}: {content}");
+ assert_eq!(text::text_lines(&doc, 0).unwrap()[0].text, typed);
+ }
+ }
+
+ /// Spaces after a row's last word are kept but take no part in its alignment: a justified row
+ /// still reaches the margin, and a centred or right-aligned one sits where it would without them.
+ #[test]
+ fn spaces_after_a_rows_last_word_do_not_move_its_alignment() {
+ let shown = |text: &str, align: added::Align| {
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
+ let style =
+ text::BlockStyle { family: Some((added::Family::Helvetica, false, false)), align: Some(align), width: Some(300.0), ..Default::default() };
+ text::rewrite_block(&mut doc, 0, 0, Some(text), &style).unwrap();
+ String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned()
+ };
+ for (plain, trailing, align) in [
+ ("aaa bbb ccc\nddd eee", "aaa bbb ccc \nddd eee", added::Align::Justify),
+ ("Title", "Title ", added::Align::Center),
+ ("Title", "Title ", added::Align::Right),
+ ] {
+ let first = trailing.split('\n').next().unwrap();
+ let expected = shown(plain, align);
+ let actual = shown(trailing, align).replace(&format!("({first})"), &format!("({})", first.trim_end()));
+ assert_eq!(actual, expected, "{trailing:?} {align:?}");
+ }
+ }
+
+ /// A justified row runs from the paragraph's left edge to the margin. Word spacing reaches only
+ /// the spaces between its words: the spaces before its first word and after its last are left
+ /// out of a stretched row (as before #4199), so the reopened rows stay inside the paragraph and
+ /// can be edited again in place.
+ #[test]
+ fn a_justified_row_keeps_its_indent_and_ends_at_the_margin() {
+ let style = text::BlockStyle {
+ family: Some((added::Family::Helvetica, false, false)),
+ align: Some(added::Align::Justify),
+ width: Some(300.0),
+ ..Default::default()
+ };
+ for typed in [" Pack my box with five dozen jugs\nof liquor", " Pack my box with five dozen jugs \nof liquor"] {
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
+ text::rewrite_block(&mut doc, 0, 0, Some(typed), &style).unwrap();
+ let mut doc = reopen(&doc);
+ let lines = text::text_lines(&doc, 0).unwrap();
+ let first = lines.iter().find(|l| l.text.contains("Pack")).unwrap();
+ assert_eq!(first.text, "Pack my box with five dozen jugs", "{typed:?}");
+ assert!((first.rect[0] - 72.0).abs() < 0.5, "{typed:?}: {:?}", first.rect);
+ assert!(lines.iter().all(|l| l.rect[0] >= 72.0 - 0.5 && l.rect[2] <= 372.5), "{typed:?}: {lines:?}");
+ let blocks = text::text_blocks(&doc, 0).unwrap();
+ assert_eq!(blocks.len(), 1, "{typed:?}: {blocks:?}");
+ text::replace_block(&mut doc, 0, 0, "Edited again").unwrap();
+ let again = text::text_lines(&reopen(&doc), 0).unwrap();
+ assert!(again.iter().all(|l| l.rect[0] >= 0.0 && l.rect[2] <= 600.0), "{typed:?}: {again:?}");
+ }
+ }
+
+ /// A justified paragraph whose first row was typed with an indent is edited again through the
+ /// styled path (a draft with a line break): its rows keep their scaling and stay one paragraph
+ /// inside its width.
+ #[test]
+ fn a_justified_paragraph_with_an_indent_edits_again_at_its_own_scale() {
+ let style = text::BlockStyle {
+ family: Some((added::Family::Helvetica, false, false)),
+ align: Some(added::Align::Justify),
+ width: Some(300.0),
+ ..Default::default()
+ };
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
+ text::rewrite_block(&mut doc, 0, 0, Some(" aaa bbb ccc \nddd"), &style).unwrap();
+ let mut doc = reopen(&doc);
+ let draft = text::text_blocks(&doc, 0).unwrap()[0].editor_text.replacen("ccc", "cc", 1);
+ assert!(draft.contains('\n'), "{draft:?}");
+ text::replace_block(&mut doc, 0, 0, &draft).unwrap();
+ let content = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned();
+ let scales: Vec<&str> = content.lines().filter(|l| l.ends_with(" Tz")).collect();
+ assert!(scales.iter().all(|l| *l == "100 Tz"), "{scales:?}: {content}");
+ let doc = reopen(&doc);
+ let blocks = text::text_blocks(&doc, 0).unwrap();
+ assert_eq!(blocks.len(), 1, "{blocks:?}");
+ let lines = text::text_lines(&doc, 0).unwrap();
+ assert!(lines.iter().all(|l| l.rect[0] >= 72.0 - 0.5 && l.rect[2] <= 372.5), "{lines:?}");
+ }
+
+ /// A paragraph drawn at `0 Tz` has no width to justify into: nothing is divided by it. The
+ /// writer writes a number that isn't finite as 0, so the test looks for the word spacing and
+ /// the move a division by zero would add, rather than for `NaN`.
+ #[test]
+ fn justifying_text_at_zero_horizontal_scaling_divides_by_nothing() {
+ let mut doc = text_page("BT /F1 12 Tf 0 Tz 72 700 Td (Hello world) Tj ET");
+ let style = text::BlockStyle { family: Some((added::Family::Helvetica, false, false)), align: Some(added::Align::Justify), ..Default::default() };
+ text::rewrite_block(&mut doc, 0, 0, Some(" aaa bbb\nccc"), &style).unwrap();
+ let content = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned();
+ let block = content.split("ET").next().unwrap();
+ assert_eq!(block.matches(" Tw").count(), 1, "only the paragraph's own 0 Tw: {content}");
+ let first_row = block.split(" Tm").nth(1).and_then(|rest| rest.split(" Tj").next()).unwrap();
+ assert!(!first_row.contains(" Td"), "no move before the first row: {content}");
+ }
+
+ /// The preview's box is the box of the rows Apply writes, measured to their last glyphs.
+ #[test]
+ fn a_drafts_box_is_the_box_apply_draws() {
+ let doc = text_page("BT /F1 12 Tf 14 TL 72 700 Td [(First) -2000 (row here )] TJ T* (Second row ) Tj ET");
+ let source = text::text_blocks(&doc, 0).unwrap().swap_remove(0);
+ let draft = source.editor_text.replacen("Second", "Third", 1);
+ let layout = text::text_edit_layout(&doc, 0, 0, &draft, &text::BlockStyle::default()).unwrap();
+ let mut applied = doc.clone();
+ text::replace_block(&mut applied, 0, 0, &draft).unwrap();
+ let boxed = text::text_lines(&applied, 0)
+ .unwrap()
+ .into_iter()
+ .map(|l| {
+ let end = l.ink.iter().map(|r| r[2]).fold(f64::NEG_INFINITY, f64::max);
+ [l.rect[0], l.rect[1], if end.is_finite() { end.min(l.rect[2]) } else { l.rect[2] }, l.rect[3]]
+ })
+ .reduce(|a, r| [a[0].min(r[0]), a[1].min(r[1]), a[2].max(r[2]), a[3].max(r[3])]);
+ let (d, b) = (layout.draft_rect.unwrap(), boxed.unwrap());
+ assert!(d.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01), "{draft:?}: preview {d:?}, applied {b:?}");
+ }
+
+ /// The draft's box is measured to its last glyph, not over the spaces typed after it.
+ #[test]
+ fn a_drafts_box_leaves_out_spaces_after_the_last_word() {
+ let doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
+ let layout = |text: &str| text::text_edit_layout(&doc, 0, 0, text, &text::BlockStyle::default()).unwrap().draft_rect;
+ assert_eq!(layout("Hello there "), layout("Hello there"));
+ }
+
+ /// A lone carriage return (an old Mac line ending) breaks the row, as `\n` and `\r\n` do.
+ #[test]
+ fn a_lone_carriage_return_breaks_an_edited_paragraph() {
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
+ text::replace_block(&mut doc, 0, 0, "one\rtwo").unwrap();
+ let lines: Vec<String> = text::text_lines(&reopen(&doc), 0).unwrap().into_iter().map(|l| l.text).collect();
+ assert_eq!(lines, ["one", "two"]);
+ }
+
+ /// On the styled rewrite path too, `\r\n` is one row break and a lone `\r` another, and no
+ /// carriage return reaches the page: with no other formatting, and with a part set in red.
+ #[test]
+ fn carriage_returns_break_rows_on_the_styled_path() {
+ let draft = "one\r\ntwo\rthree";
+ let red = text::RangeStyle {
+ range: 0..3,
+ family: None,
+ resource: None,
+ size: None,
+ color: Some([1.0, 0.0, 0.0]),
+ underline: None,
+ char_spacing: None,
+ scale: None,
+ };
+ for style in [text::BlockStyle::default(), text::BlockStyle { ranges: vec![red], ..Default::default() }] {
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
+ text::rewrite_block(&mut doc, 0, 0, Some(draft), &style).unwrap();
+ let doc = reopen(&doc);
+ let content = page_content_bytes(&doc, 0);
+ assert!(!content.contains(&b'\r') && !content.windows(2).any(|w| w == b"\\r"), "{}", String::from_utf8_lossy(&content));
+ let lines: Vec<String> = text::text_lines(&doc, 0).unwrap().into_iter().map(|l| l.text).collect();
+ assert_eq!(lines, ["one", "two", "three"], "{style:?}");
+ }
+ }
+
+ /// A subset with no space glyph shows each space as a positioning gap one space wide, so a run
+ /// of spaces still takes a run's width (#4199).
+ #[test]
+ fn a_run_of_spaces_in_a_subset_without_a_space_glyph_keeps_its_width() {
+ let mut doc = text_page("BT /F2 12 Tf 72 700 Td (ab) Tj /F1 12 Tf ( ) Tj /F2 12 Tf (ba) Tj ET");
+ assert_eq!(text::replace_block(&mut doc, 0, 0, "ab ba ab").unwrap().substituted, None);
+ let content = String::from_utf8_lossy(&page_content_bytes(&reopen(&doc), 0)).into_owned();
+ assert_eq!(content.matches("[-330] TJ").count(), 5, "{content}");
+ }
diff --cc crates/edit/src/text.rs
index e8e80d29f,55f2e7ad1..df0067ff3
--- a/crates/edit/src/text.rs
+++ b/crates/edit/src/text.rs
@@@ -2565,29 -2766,38 +2766,38 @@@ fn paragraph_separator(c: char) -> boo
/// Greedy word wrapping to `width` with `advance` giving a string's width. Each `\n` starts a
/// new line. A row may also end inside a word of Chinese or Japanese text ([`crate::linebreak`]);
- /// those pieces join without a space. Each line comes with the `\n`-separated row it is from.
+ /// those pieces join without a space. Every white-space character is written as one space, so
+ /// a run of spaces typed between, before or after words stays (#4199); only the spaces where a
-/// row wraps are dropped.
-fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<String> {
++/// row wraps are dropped. Each line comes with the `\n`-separated row it is from.
+fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<(String, usize)> {
let mut out = Vec::new();
- for row in text.split('\n') {
+ for (index, row) in text.split('\n').enumerate() {
let mut line = String::new();
let start = out.len();
- for word in row.split(paragraph_separator).filter(|word| !word.is_empty()) {
+ // The separators read since the last word: each one boundary between `split` pieces.
+ let mut gap = 0usize;
+ for (k, word) in row.split(paragraph_separator).enumerate() {
+ if k > 0 {
+ gap = gap.saturating_add(1);
+ }
+ if word.is_empty() {
+ continue;
+ }
+ let spaces = " ".repeat(std::mem::take(&mut gap));
for (i, piece) in crate::linebreak::pieces(word).into_iter().enumerate() {
- let candidate = match (line.is_empty(), i) {
- (true, _) => piece.to_string(),
- (false, 0) => format!("{line} {piece}"),
- (false, _) => format!("{line}{piece}"),
- };
- if !line.is_empty() && advance(&candidate) > width {
+ let candidate = if i == 0 { format!("{line}{spaces}{piece}") } else { format!("{line}{piece}") };
+ // A row holding only the spaces that indent it doesn't wrap before its first word.
+ if line.chars().any(|c| c != ' ') && advance(&candidate) > width {
- out.push(std::mem::take(&mut line));
+ out.push((std::mem::take(&mut line), index));
line = piece.to_string();
} else {
line = candidate;
}
}
}
+ line.push_str(&" ".repeat(gap));
if !line.is_empty() || out.len() == start {
- out.push(line);
+ out.push((line, index));
}
}
out
@@@ -2939,11 -3162,10 +3175,12 @@@ fn rewrite_block_from
}
block_ops.extend(state.ops());
block_ops.push(Op::new("Tm", tm.iter().map(|v| n(*v)).collect()));
+ // Each row's alignment: its own, or the paragraph's.
+ let align_of = |row: usize| style.aligns.get(row).copied().flatten().or(align);
// Alignment: each line's offset from the left edge, in text space.
- let offset = |line: &str, align: Option<crate::added::Align>| -> f64 {
- let free = (width - advance(line)).max(0.0) / k;
- // `visible` is the width the line is aligned on (see the loop below).
- let offset = |visible: f64| -> f64 {
++ // `visible` is the width the line is aligned on (see the loop below); `align` is its row's.
++ let offset = |visible: f64, align: Option<crate::added::Align>| -> f64 {
+ let free = (width - visible).max(0.0) / k;
match align {
Some(crate::added::Align::Center) => free / 2.0,
// A right-to-left line anchored at its right edge may start left of the old box.
@@@ -2965,14 -3188,30 +3202,32 @@@
let mut x = 0.0;
let mut tw_set = 0.0;
let mut underlines: Vec<(f64, f64, f64)> = Vec::new(); // (x0, x1, y) in text space
- for (i, line) in wrapped.iter().enumerate() {
+ for (i, (line, row)) in wrapped.iter().enumerate() {
+ let line_align = align_of(*row);
+ let justify = line_align == Some(crate::added::Align::Justify);
- let spaces = line.matches(' ').count();
- let tw =
- if justify && i + 1 < wrapped.len() && spaces > 0 { (width - advance(line)).max(0.0) / k / o_state.scale / spaces as f64 } else { 0.0 };
- // A stretched line fills the width from the left edge.
- let dx = if tw > 0.0 { 0.0 } else { offset(line, line_align) };
+ // A stretched (justified) line shows only its words, as before #4199: word spacing would
+ // reach the spaces before its first word and after its last, so they are left out, and
+ // the line fills the width from the left edge. Nothing to stretch over, or a paragraph
+ // drawn at `0 Tz`, isn't justified.
+ let body = line.trim_matches(' ');
+ let interior = body.matches(' ').count();
+ let tw = if justify && i + 1 < wrapped.len() && interior > 0 && o_state.scale.abs() > 1e-6 {
+ Some((width - advance(body)).max(0.0) / k / o_state.scale / interior as f64).filter(|tw| tw.is_finite())
+ } else {
+ None
+ }
+ .unwrap_or(0.0);
+ // Other lines show every space typed. A left-to-right one is aligned on its width up to
+ // its last word; a right-to-left one on its whole width, since the spaces typed after its
+ // last word are drawn on its left and the ones before its first on its right.
+ let (shown, visible) = if tw > 0.0 {
+ (body, advance(body))
+ } else if crate::bidi::rtl_base(line) {
+ (line.as_str(), advance(line))
+ } else {
+ (line.as_str(), advance(line.trim_end_matches(' ')))
+ };
- let dx = if tw > 0.0 { 0.0 } else { offset(visible) };
++ let dx = if tw > 0.0 { 0.0 } else { offset(visible, line_align) };
if i > 0 || dx != 0.0 {
block_ops.push(Op::new("Td", vec![n(dx - x), n(if i > 0 { -lead } else { 0.0 })]));
}
@@@ -3372,10 -3593,26 +3613,26 @@@ mod tests
#[test]
fn paragraph_wrapping_keeps_ideographic_spaces() {
let width = |s: &str| s.chars().count() as f64;
- assert_eq!(wrap("A  B C", 4.0, width), ["A  B", "C"]);
- assert_eq!(wrap("A\u{a0}B C", 3.0, width), ["A B", "C"]);
- assert_eq!(wrap("A\u{2028}B C", 3.0, width), ["A B", "C"]);
+ assert_eq!(rows(wrap("A  B C", 4.0, width)), ["A  B", "C"]);
+ assert_eq!(rows(wrap("A\u{a0}B C", 3.0, width)), ["A B", "C"]);
+ assert_eq!(rows(wrap("A\u{2028}B C", 3.0, width)), ["A B", "C"]);
- assert_eq!(rows(wrap(" \tA B\r\nC ", 3.0, width)), ["A B", "C"]);
+ }
+
+ /// #4199: a run of spaces stays a run, before, between and after words; the spaces where a
+ /// row wraps go, and each other white-space character is one space.
+ #[test]
+ fn paragraph_wrapping_keeps_every_space_typed() {
+ let width = |s: &str| s.chars().count() as f64;
- assert_eq!(wrap("a b c", 20.0, width), ["a b c"]);
- assert_eq!(wrap(" a b ", 20.0, width), [" a b "]);
- assert_eq!(wrap("a\t\tb", 20.0, width), ["a b"]);
- assert_eq!(wrap("aa bb cc", 6.0, width), ["aa bb", "cc"]);
++ assert_eq!(rows(wrap("a b c", 20.0, width)), ["a b c"]);
++ assert_eq!(rows(wrap(" a b ", 20.0, width)), [" a b "]);
++ assert_eq!(rows(wrap("a\t\tb", 20.0, width)), ["a b"]);
++ assert_eq!(rows(wrap("aa bb cc", 6.0, width)), ["aa bb", "cc"]);
+ // An indent alone on a row doesn't wrap before its first word.
- assert_eq!(wrap(" abc", 3.0, width), [" abc"]);
++ assert_eq!(rows(wrap(" abc", 3.0, width)), [" abc"]);
+ // The rewrite turns `\r\n` and `\r` into `\n` before wrapping.
- assert_eq!(wrap(" \tA B\nC ", 3.0, width), [" A", "B", "C "]);
- assert_eq!(wrap(" ", 3.0, width), [" "]);
- assert_eq!(wrap("", 3.0, width), [""]);
++ assert_eq!(rows(wrap(" \tA B\nC ", 3.0, width)), [" A", "B", "C "]);
++ assert_eq!(rows(wrap(" ", 3.0, width)), [" "]);
++ assert_eq!(rows(wrap("", 3.0, width)), [""]);
}
#[test]
diff --cc crates/edit/src/text_regions.rs
index c8758d442,d4ebe4c44..5d0a01e97
--- a/crates/edit/src/text_regions.rs
+++ b/crates/edit/src/text_regions.rs
@@@ -764,10 -795,13 +824,15 @@@ pub(super) fn rewrite_styled_block
let mut at = 0;
while at < chars.len() {
let Some(item) = chars.get(at) else { break };
+ // The CR of a CRLF: the `\n` after it breaks the row.
+ if item.0 == '\r' {
+ at += 1;
+ continue;
+ }
if item.0 == '\n' {
row_ranges.push(row_start..row_start + row.len());
+ row_lines.push(draft_line);
+ draft_line = draft_line.saturating_add(1);
rows.push(std::mem::take(&mut row));
row_width = 0.0;
at += 1;
diff --cc crates/engine/src/lib.rs
index caeddb02a,ceaaa7952..f63b34bd0
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -55,8 -55,10 +55,11 @@@ pub use pdfcraft_organize::view::{Initi
pub use pdfcraft_cos::Algorithm;
pub use pdfcraft_create::{CONVERTIBLE, CreateError, ImageResolution, SourceKind, decode_text, source_kind};
- pub use pdfcraft_edit::added::{text_rect as added_text_rect, text_width as added_text_width};
+ pub use pdfcraft_edit::added::{
+ CHAR_SPACING_LIMIT as ADDED_CHAR_SPACING_LIMIT, paste_place as added_paste_place, paste_rect as added_paste_rect, text_rect as added_text_rect,
+ text_width as added_text_width,
+ };
+pub use pdfcraft_edit::paragraph_align;
pub use pdfcraft_edit::{
Added, AddedImage, AddedText, Align as TextAlign, Background, Content as AddedContent, Family as FontFamily, HeaderFooter, MarkKind, Watermark,
};
diff --cc crates/engine/src/tests.rs
index 7e2542c5d,f5f438dec..efa1fc93e
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@@ -3155,6 -3319,143 +3319,144 @@@ fn added_text_and_images_render_and_sta
assert_eq!(s.get(id).unwrap().added().len(), 2);
}
+ /// Edit ▸ Copy and Paste of added content (#2636): a text box comes back with all its style, an
+ /// image with its picture and transforms, in the same document and in another.
+ #[test]
+ fn pasted_added_content_keeps_its_style_and_picture() {
+ let (mut s, id) = session_with(2);
+ let text = AddedText {
+ rect: [20.0, 250.0, 180.0, 264.4],
+ text: "Styled note".into(),
+ family: FontFamily::Times,
+ bold: true,
+ italic: true,
+ size: 12.0,
+ color: [0.8, 0.1, 0.2],
+ align: TextAlign::Center,
++ aligns: Vec::new(),
+ char_spacing: 0.0,
+ };
+ s.apply(id, Edit::AddText { page: 0, text: text.clone() }).unwrap();
+ let copied = s.get(id).unwrap().added()[0].content.clone();
+ let moved = copied.with_rect([40.0, 100.0, 200.0, 114.4]);
+ s.apply(id, Edit::PasteContent { page: 1, content: moved.clone(), file: None }).unwrap();
+ let doc = s.get(id).unwrap();
+ assert_eq!(doc.can_undo(), Some("Paste"));
+ assert_eq!(doc.added()[1].page, 1);
+ assert_eq!(doc.added()[1].content, moved, "every part of the style, in the new box");
+
+ // An image, turned, flipped and cropped.
+ let mut png = Vec::new();
+ {
+ let mut enc = png::Encoder::new(&mut png, 20, 10);
+ enc.set_color(png::ColorType::Rgb);
+ let px: Vec<u8> = (0..200).flat_map(|i| [(i % 256) as u8, 40, 200]).collect();
+ enc.write_header().unwrap().write_image_data(&px).unwrap();
+ }
+ s.apply(id, Edit::AddImage { page: 0, rect: Some([50.0, 100.0, 150.0, 150.0]), name: "p.png".into(), bytes: Arc::new(png) }).unwrap();
+ let AddedContent::Image(mut img) = s.get(id).unwrap().added()[1].content.clone() else { panic!("the image is the page's second item") };
+ (img.rotation, img.flip_h, img.crop) = (1, true, [0.1, 0.0, 0.2, 0.05]);
+ s.apply(id, Edit::UpdateContent { page: 0, index: 1, content: AddedContent::Image(img.clone()) }).unwrap();
+ let (ext, file) = s.get(id).unwrap().added_image_file(0, 1).unwrap();
+ assert_eq!(ext, "png");
+ let file = Some(("Pasted image.png".to_string(), Arc::new(file)));
+ assert!(s.get(id).unwrap().added_image_file(0, 0).is_err(), "the first item is text");
+ let pasted = AddedImage { rect: [60.0, 90.0, 160.0, 140.0], ..img.clone() };
+ s.apply(id, Edit::PasteContent { page: 0, content: AddedContent::Image(pasted.clone()), file: file.clone() }).unwrap();
+ let AddedContent::Image(got) = s.get(id).unwrap().added()[2].content.clone() else { panic!("an image was pasted") };
+ assert_eq!(got, pasted, "the same picture object, box, turn, flip and crop");
+
+ // Into another document: the picture comes along as a file of its own.
+ let other = s.open("other.pdf", None, Arc::new(fixture(1)), None).unwrap();
+ s.apply(other, Edit::PasteContent { page: 0, content: AddedContent::Image(pasted.clone()), file: file.clone() }).unwrap();
+ s.apply(other, Edit::PasteContent { page: 0, content: copied.clone(), file: None }).unwrap();
+ let d = s.get(other).unwrap();
+ let AddedContent::Image(theirs) = &d.added()[0].content else { panic!("an image was pasted") };
+ assert_eq!(AddedImage { image: img.image, ..theirs.clone() }, pasted, "the same box and transforms");
+ assert_eq!(d.added_image_file(0, 0).unwrap().1, file.as_ref().unwrap().1.as_slice(), "the same picture");
+ assert_eq!(d.added()[1].content, copied);
+ // Pasted there again, it draws the first paste's picture object rather than storing a third.
+ let first = theirs.image;
+ s.apply(other, Edit::PasteContent { page: 0, content: AddedContent::Image(pasted.clone()), file: file.clone() }).unwrap();
+ let AddedContent::Image(again) = s.get(other).unwrap().added()[2].content.clone() else { panic!("an image was pasted") };
+ assert_eq!(again.image, first, "one picture object for both pastes");
+ // The object holds another picture of the same size (another document's numbering, an undone
+ // add): the file is embedded instead of drawing the wrong picture.
+ let mut other_png = Vec::new();
+ {
+ let mut enc = png::Encoder::new(&mut other_png, 20, 10);
+ enc.set_color(png::ColorType::Rgb);
+ enc.write_header().unwrap().write_image_data(&[7u8; 600]).unwrap();
+ }
+ let other_file = Some(("other.png".to_string(), Arc::new(other_png)));
+ s.apply(id, Edit::PasteContent { page: 0, content: AddedContent::Image(pasted.clone()), file: other_file }).unwrap();
+ let AddedContent::Image(fresh) = s.get(id).unwrap().added()[3].content.clone() else { panic!("an image was pasted") };
+ assert_ne!(fresh.image, img.image, "a picture object of its own");
+ assert_ne!(s.get(id).unwrap().added_image_file(0, 3).unwrap().1, file.as_ref().unwrap().1.as_slice());
+ assert!(matches!(
+ s.apply(id, Edit::PasteContent { page: 0, content: AddedContent::Image(pasted), file: None }),
+ Err(EditError::Edit(pdfcraft_edit::EditError::Invalid(_)))
+ ));
+ // Four items on page 1 and the pasted text on page 2.
+ assert_eq!(s.get(id).unwrap().added().len(), 5, "refused pastes add nothing");
+ s.undo(id).unwrap();
+ assert_eq!(s.get(id).unwrap().added().len(), 4, "a paste is one undo step");
+ }
+
+ /// An added JPEG 2000 picture is copied as the file it was added from: pasted into its own
+ /// document it draws the same object, and into another one it is embedded once.
+ #[test]
+ fn an_added_jpeg_2000_image_is_copied_as_its_file() {
+ // A JP2 file (30 × 20, three components) with a stub codestream, as Add Image takes it.
+ let bx = |ty: &[u8], payload: &[u8]| [((payload.len() + 8) as u32).to_be_bytes().as_slice(), ty, payload].concat();
+ let ihdr = [20u32.to_be_bytes().as_slice(), &30u32.to_be_bytes(), &[0, 3, 7, 7, 0, 0]].concat();
+ let signature = [0, 0, 0, 0x0C, b'j', b'P', b' ', b' ', 0x0D, 0x0A, 0x87, 0x0A];
+ let file = [signature.as_slice(), &bx(b"ftyp", b"jp2 \0\0\0\0jp2 "), &bx(b"jp2h", &bx(b"ihdr", &ihdr)), &bx(b"jp2c", &[0xFF, 0x4F, 0xFF, 0x51])]
+ .concat();
+ let (mut s, id) = session_with(1);
+ s.apply(id, Edit::AddImage { page: 0, rect: Some([50.0, 100.0, 110.0, 140.0]), name: "photo.jp2".into(), bytes: Arc::new(file.clone()) })
+ .unwrap();
+ let (ext, copied) = s.get(id).unwrap().added_image_file(0, 0).unwrap();
+ assert_eq!((ext, &copied), ("jp2", &file), "the file as it was added");
+ let AddedContent::Image(img) = s.get(id).unwrap().added()[0].content.clone() else { panic!("an image was added") };
+ let copied = Arc::new(copied);
+ let file = Some(("Pasted image.jp2".to_string(), copied.clone()));
+ let pasted = AddedContent::Image(AddedImage { rect: [70.0, 80.0, 130.0, 120.0], ..img.clone() });
+ s.apply(id, Edit::PasteContent { page: 0, content: pasted.clone(), file: file.clone() }).unwrap();
+ assert!(matches!(&s.get(id).unwrap().added()[1].content, AddedContent::Image(i) if i.image == img.image), "the same picture object");
+ let other = s.open("other.pdf", None, Arc::new(fixture(1)), None).unwrap();
+ for _ in 0..2 {
+ s.apply(other, Edit::PasteContent { page: 0, content: pasted.clone(), file: file.clone() }).unwrap();
+ }
+ let d = s.get(other).unwrap();
+ let images: Vec<_> = d
+ .added()
+ .iter()
+ .filter_map(|a| match &a.content {
+ AddedContent::Image(i) => Some(i.image),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(images.len(), 2);
+ assert_eq!(images[0], images[1], "embedded once");
+ assert_eq!(d.added_image_file(0, 0).unwrap().1, copied.as_slice());
+ }
+
+ #[test]
+ fn a_batch_of_content_edits_refreshes_the_added_content_and_marks() {
+ let (mut s, id) = session_with(1);
+ let text = |t: &str, y: f64| AddedText { rect: [20.0, y, 180.0, y + 14.4], text: t.into(), ..AddedText::default() };
+ let edits = vec![Edit::AddText { page: 0, text: text("One", 200.0) }, Edit::AddText { page: 0, text: text("Two", 150.0) }];
+ s.apply(id, Edit::Batch { label: "Script".into(), edits }).unwrap();
+ assert_eq!(s.get(id).unwrap().added().len(), 2);
+ s.apply(id, Edit::Batch { label: "Script".into(), edits: vec![Edit::DeleteContent { page: 0, index: 0 }] }).unwrap();
+ assert_eq!(s.get(id).unwrap().added().len(), 1);
+ let watermark =
+ Edit::AddWatermark { pages: vec![0], settings: Watermark { text: "Draft".into(), ..Watermark::default() }, file: None, replace: false };
+ s.apply(id, Edit::Batch { label: "Script".into(), edits: vec![watermark] }).unwrap();
+ assert_eq!(s.get(id).unwrap().marks().len(), 1);
+ }
+
#[test]
fn added_images_rotate_flip_and_crop_as_drawn() {
// A 20×10 image: left half red, right half blue.
@@@ -6369,7 -7005,7 +7006,8 @@@ fn content_edit_keeps_pages_annotations
size: 12.0,
color: [0.0, 0.0, 0.0],
align: TextAlign::Left,
+ aligns: Vec::new(),
+ char_spacing: 0.0,
};
session.apply(id, Edit::AddText { page: 1, text }).unwrap();
let after = session.get(id).unwrap();
@@@ -6409,7 -7045,7 +7047,8 @@@ fn content_refresh_lists_match_the_stor
size: 12.0,
color: [0.0, 0.0, 0.0],
align: TextAlign::Left,
+ aligns: Vec::new(),
+ char_spacing: 0.0,
},
},
Edit::MoveObjects { page: 0, objects: vec![target(crate::ObjectKind::Added)], offset: [1.0, 0.0] },
diff --cc crates/ui-egui/src/content_ui.rs
index 4578d0d9d,d966b04a5..4c9a86774
--- a/crates/ui-egui/src/content_ui.rs
+++ b/crates/ui-egui/src/content_ui.rs
@@@ -603,43 -570,36 +603,46 @@@ pub(crate) fn editor(ctx: &egui::Contex
// The box is white in every theme, so the caret must not follow the theme (pale in dark mode) (#655).
ui.visuals_mut().text_cursor.stroke.color = crate::edit_text_ui::caret_color_on(Color32::WHITE);
let [cr, cg, cb] = t.style.color.map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8);
- // Laid out as the page draws it, so opening the box doesn't show it realigned.
- // shortcut: justified text is shown left-aligned here (TextEdit can't justify), until the editor gets its own layouter.
- let halign = match t.style.align {
- pdfcraft_engine::TextAlign::Center => egui::Align::Center,
- pdfcraft_engine::TextAlign::Right => egui::Align::Max,
- pdfcraft_engine::TextAlign::Left | pdfcraft_engine::TextAlign::Justify => egui::Align::Min,
- };
+ let color = Color32::from_rgb(cr, cg, cb);
+ // Character spacing shows as the page will draw it, scaled like the font.
+ let letter_spacing = (t.style.char_spacing * f64::from(zoom)) as f32;
- let mut spaced = |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap_width: f32| {
- let job = spaced_job(text.as_str(), &font, Color32::from_rgb(cr, cg, cb), letter_spacing, wrap_width, halign);
- ui.fonts_mut(|f| f.layout_job(job))
+ // Laid out as the page draws it, each paragraph with its own alignment, so opening the
+ // box doesn't show it realigned.
+ let style = t.style.clone();
+ let line_font = font.clone();
- let mut layouter =
- |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap: f32| aligned_galley(ui, text.as_str(), &style, &line_font, color, wrap);
++ let mut layouter = |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap: f32| {
++ aligned_galley(ui, text.as_str(), &style, &line_font, color, letter_spacing, wrap)
+ };
+ let before = t.text.clone();
+ let input = input_id();
+ crate::edit_text_ui::forget_typing_before(ui.ctx(), input, doc_id, &mut t.typing_from, &t.style.text);
ui.horizontal_top(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
- let mut edit = egui::TextEdit::multiline(&mut t.text)
- .font(font.clone())
+ let output = egui::TextEdit::multiline(&mut t.text)
+ .font(font)
.desired_width(width)
.desired_rows(1)
- .horizontal_align(halign)
+ .layouter(&mut layouter)
.background_color(if background_ready { Color32::TRANSPARENT } else { Color32::WHITE })
- .text_color(Color32::from_rgb(cr, cg, cb))
+ .text_color(color)
.hint_text(tl!("Type text"))
- .id_salt("added-text-edit");
- if letter_spacing != 0.0 {
- edit = edit.layouter(&mut spaced);
+ .id(input)
+ .show(ui);
+ let resp = output.response;
+ if let Some(cursor) = output.cursor_range {
+ let chars = cursor.as_sorted_char_range();
+ let byte = |index: usize| t.text.char_indices().nth(index).map_or(t.text.len(), |(at, _)| at);
+ t.selection = Some(byte(chars.start.into())..byte(chars.end.into()));
+ }
+ // Each paragraph keeps its own alignment through the typing.
+ if t.text != before {
+ t.style.aligns = pdfcraft_engine::paragraph_align::remap(&before, &t.text, &t.style.aligns);
}
- let resp = ui.add(edit);
if t.focus {
resp.request_focus();
+ if let Some(range) = &t.selection {
+ crate::edit_text_ui::reselect(ui.ctx(), input, &t.text, range);
+ }
t.focus = false;
}
let buttons = egui::Frame::NONE
@@@ -709,55 -659,6 +712,63 @@@ fn finish(cv: &mut ContentView, d: Text
}
}
+/// The added-text box's text field.
+pub(crate) fn input_id() -> egui::Id {
+ egui::Id::new("added-text-input")
+}
+
+/// `text` laid out as added text with `style` is drawn: each paragraph (line typed with Enter) wrapped
+/// to `wrap` and placed by its own alignment, a justified one with every row but its last
+/// stretched.
- fn aligned_galley(ui: &egui::Ui, text: &str, style: &AddedText, font: &egui::FontId, color: Color32, wrap: f32) -> std::sync::Arc<egui::Galley> {
++fn aligned_galley(
++ ui: &egui::Ui,
++ text: &str,
++ style: &AddedText,
++ font: &egui::FontId,
++ color: Color32,
++ letter_spacing: f32,
++ wrap: f32,
++) -> std::sync::Arc<egui::Galley> {
+ use pdfcraft_engine::TextAlign;
+ let job = |text: &str, align: TextAlign| {
- let mut job = egui::text::LayoutJob::simple(text.to_owned(), font.clone(), color, wrap);
++ let mut job = spaced_job(text, font, color, letter_spacing, wrap, egui::Align::Min);
+ job.justify = align == TextAlign::Justify;
+ job
+ };
+ let uniform = text.split('\n').enumerate().all(|(i, _)| style.paragraph_align(i) == style.align);
+ if uniform && style.align != TextAlign::Center && style.align != TextAlign::Right {
+ return ui.fonts_mut(|f| f.layout_job(job(text, style.align)));
+ }
+ // Each paragraph on its own (egui aligns a whole job one way), its rows moved within the
+ // box's width, then joined in order: the caret and selection see one text.
+ let mut galleys = Vec::new();
+ let mut start = 0;
+ for (i, paragraph) in text.split('\n').enumerate() {
+ let end = start + paragraph.len();
+ // The last paragraph keeps a trailing break, as egui's own split does.
+ let last = end + 1 == text.len();
+ let piece = if last { text.get(start..).unwrap_or_default() } else { paragraph };
+ let mut galley = ui.fonts_mut(|f| f.layout_job(job(piece, style.paragraph_align(i))));
+ let g = std::sync::Arc::make_mut(&mut galley);
+ for placed in &mut g.rows {
+ let free = (wrap - placed.row.size.x).max(0.0);
+ placed.pos.x = match style.paragraph_align(i) {
+ TextAlign::Center => free / 2.0,
+ TextAlign::Right => free,
+ TextAlign::Left | TextAlign::Justify => 0.0,
+ };
+ }
+ g.rect = Rect::from_min_max(Pos2::ZERO, Pos2::new(g.rect.width().max(wrap), g.rect.height()));
+ galleys.push(galley);
+ if last {
+ break;
+ }
+ start = end + 1;
+ }
- let whole = std::sync::Arc::new(egui::text::LayoutJob::simple(text.to_owned(), font.clone(), color, wrap));
++ let whole = std::sync::Arc::new(spaced_job(text, font, color, letter_spacing, wrap, egui::Align::Min));
+ std::sync::Arc::new(egui::Galley::concat(whole, &galleys, ui.ctx().pixels_per_point()))
+}
+
/// How to use the tools, under the Add content list.
pub(crate) fn hint(ui: &mut egui::Ui, t: &Tokens) {
ui.label(
diff --cc crates/ui-egui/src/edit_text_ui.rs
index 12adb622f,65c7bd780..563dd4a29
--- a/crates/ui-egui/src/edit_text_ui.rs
+++ b/crates/ui-egui/src/edit_text_ui.rs
@@@ -1924,6 -1838,57 +1924,59 @@@ mod tests
assert!(app.views[0].line_editor.is_some(), "the paragraph stays open for editing");
}
+ #[test]
+ fn save_applies_the_paragraph_open_in_the_editor() {
+ // Save wrote the file without the paragraph still open in the editor (#3496).
+ let (mut app, mut ed) = preview_app();
+ ed.text = "Text preview".into();
+ app.views[0].line_editor = Some(ed);
+ let dir = std::env::temp_dir().join(format!("pdfcraft-ui-open-paragraph-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ app.save_override = Some(dir.join("out.pdf").to_string_lossy().into_owned());
+
+ assert!(app.save_active(crate::SaveTarget::InPlace));
+ assert!(app.views[0].line_editor.is_none());
+ let doc = app.session.get(app.views[0].id).unwrap();
+ assert_eq!(doc.text_lines(0).iter().map(|l| l.text.as_str()).collect::<String>(), "Text preview");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn a_refused_text_box_does_not_lose_the_open_paragraph() {
+ let (mut app, mut ed) = preview_app();
+ ed.text = "Text preview".into();
+ app.views[0].line_editor = Some(ed);
+ let draft = crate::content_ui::TextDraft {
+ page: 9,
+ index: None,
+ rect: [20.0, 20.0, 120.0, 40.0],
+ text: "Typed text".into(),
+ style: crate::content_ui::default_style(),
+ focus: true,
++ selection: None,
++ typing_from: None,
+ };
+ app.views[0].content.draft = Some(draft.clone());
+
+ assert!(!app.commit_typing_in(app.views[0].id));
+ assert_eq!(app.views[0].content.draft, Some(draft), "the refused text box stays open");
+ assert!(app.views[0].line_editor.is_none(), "the paragraph was applied");
+ let doc = app.session.get(app.views[0].id).unwrap();
+ assert_eq!(doc.text_lines(0).iter().map(|l| l.text.as_str()).collect::<String>(), "Text preview");
+ }
+
+ #[test]
+ fn a_refused_paragraph_stays_open_with_its_text() {
+ let (mut app, mut ed) = preview_app();
+ ed.text = "Text preview".into();
+ ed.page = 9;
+ app.views[0].line_editor = Some(ed.clone());
+
+ assert!(!app.commit_typing_in(app.views[0].id));
+ assert_eq!(app.views[0].line_editor, Some(ed), "the paragraph keeps its unsaved text");
+ }
+
#[test]
fn text_background_is_cached_without_editing_and_released_on_cancel() {
let (app, ed) = preview_app();
diff --cc crates/ui-egui/src/editing.rs
index 7b65592c1,7ed6e0795..6040b5c76
--- a/crates/ui-egui/src/editing.rs
+++ b/crates/ui-egui/src/editing.rs
@@@ -1584,46 -1536,32 +1646,74 @@@ mod tests
out
}
+ /// `one_page_pdf`, opening without a password, whose permissions refuse changes.
+ fn no_changes_pdf() -> Vec<u8> {
+ let mut doc = pdfcraft_cos::Document::open(std::sync::Arc::new(one_page_pdf())).unwrap();
+ let encryption = pdfcraft_cos::NewEncryption {
+ algorithm: pdfcraft_cos::Algorithm::Aes256,
+ user_password: "",
+ owner_password: "owner",
+ permissions: -1 ^ 8,
+ encrypt_metadata: true,
+ seed: [4; 32],
+ };
+ doc.set_encryption(&encryption).unwrap();
+ pdfcraft_cos::write_full(&doc, &Default::default()).unwrap()
+ }
+
+ /// Undo with a new text box open on a document that refuses changes: the box is put back as
+ /// it was. Finishing it had asked for the new item to be selected, and that request stayed
+ /// behind once the add was refused.
+ #[test]
+ fn a_refused_text_box_is_put_back_whole() {
+ let mut app = crate::PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.open_bytes("a.pdf", None, no_changes_pdf()).unwrap();
+ let style = crate::content_ui::default_style();
+ app.views[0].content.draft = Some(crate::content_ui::TextDraft {
+ page: 0,
+ index: None,
+ rect: [20.0, 20.0, 120.0, 40.0],
+ text: "Typed".into(),
+ style,
+ focus: false,
+ selection: None,
+ typing_from: None,
+ });
+ app.undo();
+ let content = &app.views[0].content;
+ assert_eq!(content.draft.as_ref().map(|d| d.text.as_str()), Some("Typed"), "the refused box stays open");
+ assert_eq!(content.select_added, None, "nothing was added to select");
+ }
+
+ #[test]
+ fn save_commits_the_open_text_box() {
+ let dir = staging_dir("open-text-box");
+ let dest = dir.join("out.pdf");
+ let mut app = crate::PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.open_bytes("a.pdf", None, one_page_pdf()).unwrap();
+ app.save_override = Some(dest.to_string_lossy().into_owned());
+ let style = crate::content_ui::default_style();
+ app.views[0].content.draft = Some(crate::content_ui::TextDraft {
+ page: 0,
+ index: None,
+ rect: [20.0, 20.0, 120.0, 40.0],
+ text: "Typed text".into(),
+ style,
+ focus: true,
++ selection: None,
++ typing_from: None,
+ });
+
+ assert!(app.save_active(SaveTarget::InPlace));
+ let id = app.views[0].id;
+ let added = app.session.get(id).unwrap().added();
+ assert_eq!(added.len(), 1, "the open text box was committed before the save");
+ assert!(app.views[0].content.draft.is_none());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
#[test]
fn save_asks_where_to_keep_an_email_attachment_and_leaves_the_temporary_copy_alone() {
let dir = staging_dir("mail-temp");
diff --cc crates/ui-egui/tests/it/content.rs
index 8fefd84ec,0d7253707..f8e93ecd2
--- a/crates/ui-egui/tests/it/content.rs
+++ b/crates/ui-egui/tests/it/content.rs
@@@ -764,33 -751,28 +751,55 @@@ fn the_text_editor_aligns_a_narrow_box_
);
}
+ /// Added text takes character spacing from Format text (#4245), typed like a paragraph's; its
+ /// line spacing and horizontal scale stay disabled until added text has them.
+ #[test]
+ fn format_text_sets_character_spacing_for_added_text() {
+ use egui::accesskit::Role;
+ use egui_kittest::kittest::NodeT;
+ let mut h = harness();
+ assert!(h.state_mut().execute("edit.text"));
+ h.run_steps(3);
+ let disabled = |h: &Harness<'static, PdfCraftApp>, label: &str| h.get_by_role_and_label(Role::SpinButton, label).accesskit_node().is_disabled();
+ assert!(disabled(&h, "Horizontal scale"), "added text has no scale yet");
+ assert!(!disabled(&h, "Character spacing"), "added text takes character spacing");
+ h.get_by_role_and_label(Role::SpinButton, "Character spacing").click();
+ h.run_steps(2);
+ h.event(egui::Event::Text("2.5".into()));
+ h.run_steps(1);
+ h.key_press(egui::Key::Enter);
+ h.run_steps(4);
+ assert_eq!(h.state().text_style.char_spacing, 2.5);
+ }
+
+/// The same when the line is right-aligned on its own while the box keeps Left: all its lines
+/// share one alignment, so the editor keeps the box's right edge for them.
+#[test]
+fn the_text_editor_aligns_a_narrow_box_whose_lines_share_an_alignment() {
+ let _gpu = gpu();
+ let mut h = harness();
+ let rect = [40.0, 195.0, 60.0, 210.0];
+ let text = pdfcraft_engine::AddedText { rect, text: "Hi".into(), aligns: vec![Some(pdfcraft_engine::TextAlign::Right)], ..Default::default() };
+ assert_eq!(text.align, pdfcraft_engine::TextAlign::Left);
+ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text }));
+ assert!(h.state_mut().execute("edit.text"));
+ h.run_steps(3);
+ let point = at(&h, 50.0, 195.0);
+ click(&mut h, point);
+ assert_eq!(h.state().views[0].content.draft.as_ref().and_then(|d| d.index), Some(0), "the editor opened on the text");
+ h.run_steps(3);
+ let r = item_on_screen(&h, rect);
+ let pixels = h.render().unwrap();
+ let inside = ink(&pixels, r);
+ let edge = ink(&pixels, egui::Rect::from_min_max(pos2(r.right() - r.width() * 0.25, r.min.y), r.max));
+ let past = ink(&pixels, egui::Rect::from_min_max(pos2(r.right() + 2.0, r.min.y), pos2(r.right() + 40.0, r.max.y)));
+ assert!(
+ inside > 20 && edge > 0 && past == 0,
+ "the text is drawn in its box, up to its right edge ({inside} dark pixels in it, {edge} in its last quarter, {past} past it)"
+ );
+}
+
+ /// Where a mode bar tab is, by its label.
fn mode_tab(h: &Harness<'static, PdfCraftApp>, label: &str) -> egui::Rect {
h.get_all_by_role_and_label(egui::accesskit::Role::Button, label).map(|n| n.rect()).find(|r| r.bottom() < 120.0).expect("a mode tab")
}
diff --cc crates/ui-egui/tests/it/editing.rs
index ae33cfd23,75afd2a01..671d3d12b
--- a/crates/ui-egui/tests/it/editing.rs
+++ b/crates/ui-egui/tests/it/editing.rs
@@@ -6020,269 -6256,32 +6256,299 @@@ fn mode_tabs_keep_the_hand_over_a_parag
assert_eq!(h.state().mode, pdfcraft_ui_egui::Mode::Convert, "the tab takes the click, not the paragraph's editor");
}
+/// The paragraph opened for typing, as a person opens it: a click on its text.
+fn open_paragraph(h: &mut Harness<'static, PdfCraftApp>) {
+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");
+ let at = egui::pos2(r.left() + 40.0 / 200.0 * r.width(), r.top() + (300.0 - 158.0) / 300.0 * r.height());
+ click_at(h, at);
+ assert!(h.state().views[0].line_editor.is_some(), "the paragraph opens for typing");
+}
+
+/// Ctrl+Z after a formatting change, with the paragraph still open: the change is undone and
+/// the editor closes. The box's own Undo used to take the key, putting back the text it had
+/// before the change into a box laid out for the page after it, and the document kept the change.
+#[test]
+fn undo_with_the_paragraph_open_undoes_the_formatting() {
+ let mut h = harness(1, |_| {});
+ assert!(h.state_mut().execute("edit.edit_text"));
+ h.run_steps(2);
+ open_paragraph(&mut h);
+ h.get_by_label("Bold").click();
+ h.run_steps(4);
+ {
+ let s = h.state();
+ let doc = s.session.get(s.views[0].id).unwrap();
+ assert_eq!(doc.can_undo(), Some("Edit text"));
+ assert_eq!(doc.text_blocks(0)[0].base_font, "Helvetica-Bold");
+ assert!(s.views[0].line_editor.is_some(), "still editing");
+ }
+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);
+ h.run_steps(4);
+ let s = h.state();
+ let doc = s.session.get(s.views[0].id).unwrap();
+ assert_eq!(doc.can_undo(), None, "the formatting is undone");
+ assert_eq!(doc.text_blocks(0)[0].base_font, "Helvetica");
+ assert!(s.views[0].line_editor.is_none(), "the editor closed with the step it showed");
+}
+
+/// Undo while typing takes back the typing in the box first; the document is left alone.
+#[test]
+fn undo_while_typing_takes_back_the_typing_first() {
+ let mut h = harness(1, |_| {});
+ assert!(h.state_mut().execute("edit.edit_text"));
+ h.run_steps(2);
+ open_paragraph(&mut h);
+ let original = h.state().views[0].line_editor.as_ref().unwrap().text.clone();
+ h.key_press_modifiers(Modifiers::COMMAND, Key::End);
+ h.event(egui::Event::Text(" more".into()));
+ h.run_steps(2);
+ assert_ne!(h.state().views[0].line_editor.as_ref().unwrap().text, original);
+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);
+ h.run_steps(3);
+ let s = h.state();
+ let ed = s.views[0].line_editor.as_ref().expect("still typing");
+ assert_eq!(ed.text, original, "the typing is taken back");
+ assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), None, "the document is untouched");
+}
+
+/// A paragraph of a short, a wide and a short row, opened in the paragraph editor.
+fn three_row_paragraph() -> Harness<'static, PdfCraftApp> {
+ let bytes = paragraph_drag_fixture("BT /F1 10 Tf 12 TL 60 400 Td (One two) Tj T* (three four five six seven eight) Tj T* (nine ten) Tj ET", 0, 1);
+ let mut h = paragraph_drag_harness(bytes, 0);
+ let (at, _) = paragraph_drag_points(&h, "One two three four five six seven eight nine ten", [0.0, 0.0]);
+ click_at(&mut h, at);
+ assert!(h.state().views[0].line_editor.is_some(), "the paragraph opens for typing");
+ h
+}
+
+/// Format text's alignment flyout, by pointer.
+fn align_by_pointer(h: &mut Harness<'static, PdfCraftApp>, choice: &str) {
+ let button = h.get_by_label("Alignment").rect().center();
+ click_at(h, button);
+ let item = h.get_by_label(choice).rect().center();
+ click_at(h, item);
+}
+
+fn row_rect(h: &Harness<'static, PdfCraftApp>, starts: &str) -> [f64; 4] {
+ let s = h.state();
+ 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.
+#[test]
+fn aligning_a_selected_row_aligns_only_that_row_and_undo_puts_it_back() {
+ let mut h = three_row_paragraph();
+ 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");
+}
+
+/// 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]
+fn redo_after_undoing_typing_puts_the_typing_back() {
+ let mut h = harness(1, |_| {});
+ assert!(h.state_mut().execute("edit.edit_text"));
+ h.run_steps(2);
+ open_paragraph(&mut h);
+ h.get_by_label("Bold").click();
+ h.run_steps(4);
+ // Undo the bold (closing the editor), so the document has it to redo.
+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);
+ h.run_steps(4);
+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().can_redo(), Some("Edit text"));
+ open_paragraph(&mut h);
+ let original = h.state().views[0].line_editor.as_ref().unwrap().text.clone();
+ h.key_press_modifiers(Modifiers::COMMAND, Key::End);
+ h.event(egui::Event::Text(" more".into()));
+ h.run_steps(2);
+ let typed = h.state().views[0].line_editor.as_ref().unwrap().text.clone();
+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);
+ h.run_steps(3);
+ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, original, "the typing is taken back");
+ h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z);
+ h.run_steps(3);
+ let s = h.state();
+ let ed = s.views[0].line_editor.as_ref().expect("still typing");
+ assert_eq!(ed.text, typed, "Redo puts the typing back");
+ let doc = s.session.get(s.views[0].id).unwrap();
+ 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 the
+/// Redo itself then failed: the step was gone. The typing now stays in the box and the Redo
+/// waits; once Undo in the box takes the typing back, Redo from the menu puts it back there.
+#[test]
+fn redo_from_the_menu_with_typing_in_the_box_keeps_the_documents_redo() {
+ let mut h = harness(1, |_| {});
+ assert!(h.state_mut().execute("edit.edit_text"));
+ h.run_steps(2);
+ open_paragraph(&mut h);
+ h.get_by_label("Bold").click();
+ h.run_steps(4);
+ // Undo the bold (closing the editor), so the document has it to redo.
+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);
+ h.run_steps(4);
+ open_paragraph(&mut h);
+ let original = h.state().views[0].line_editor.as_ref().unwrap().text.clone();
+ h.key_press_modifiers(Modifiers::COMMAND, Key::End);
+ h.event(egui::Event::Text(" more".into()));
+ h.run_steps(2);
+ let typed = h.state().views[0].line_editor.as_ref().unwrap().text.clone();
+ assert!(h.state_mut().execute("edit.redo"));
+ h.run_steps(3);
+ {
+ let s = h.state();
+ let ed = s.views[0].line_editor.as_ref().expect("the box stays open");
+ assert_eq!(ed.text, typed, "the typing stays in the box, unapplied");
+ let doc = s.session.get(s.views[0].id).unwrap();
+ assert_eq!((doc.can_redo(), doc.text_blocks(0)[0].base_font.as_str()), (Some("Edit text"), "Helvetica"), "the document's Redo still waits");
+ }
+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);
+ h.run_steps(3);
+ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, original, "Undo takes the typing back in the box");
+ assert!(h.state_mut().execute("edit.redo"));
+ h.run_steps(3);
+ let s = h.state();
+ assert_eq!(s.views[0].line_editor.as_ref().expect("still open").text, typed, "Redo from the menu puts the typing back");
+ assert_eq!(s.session.get(s.views[0].id).unwrap().can_redo(), Some("Edit text"), "the document's Redo still waits");
+}
+
+/// Two copies of a document, the same paragraph open in each. The paragraph boxes share one text
+/// box, and so one Undo history: a box opened on the same text as another tab's didn't clear it.
+/// Typing in one tab, taken back with Undo, then came back with Redo (the key or the menu) in the
+/// other tab.
+#[test]
+fn typing_in_one_tab_never_reaches_another_tabs_paragraph() {
+ let mut h = harness(1, |app| {
+ app.open_bytes("copy.pdf", None, fixture(1)).expect("the copy opens");
+ });
+ let open_in = |h: &mut Harness<'static, PdfCraftApp>, tab: usize| {
+ h.state_mut().active = Some(tab);
+ h.run_steps(2);
+ assert!(h.state_mut().execute("edit.edit_text"));
+ h.run_steps(2);
+ let r = h.state().views[tab].page_screen_rect(0).expect("on screen");
+ click_at(h, egui::pos2(r.left() + 40.0 / 200.0 * r.width(), r.top() + (300.0 - 158.0) / 300.0 * r.height()));
+ assert!(h.state().views[tab].line_editor.is_some(), "the paragraph opens for typing");
+ };
+ open_in(&mut h, 1);
+ let original = h.state().views[1].line_editor.as_ref().unwrap().text.clone();
+ open_in(&mut h, 0);
+ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, original, "the same paragraph");
+ h.key_press_modifiers(Modifiers::COMMAND, Key::End);
+ h.event(egui::Event::Text(" secret".into()));
+ h.run_steps(2);
+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);
+ h.run_steps(3);
+ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, original, "taken back");
+ // The copy, its paragraph still open: Redo there has nothing of its own to put back.
+ h.state_mut().active = Some(1);
+ h.run_steps(3);
+ h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z);
+ h.run_steps(3);
+ let text = h.state().views[1].line_editor.as_ref().map(|ed| ed.text.clone());
+ assert!(!text.as_deref().unwrap_or_default().contains("secret"), "the other tab's typing came in: {text:?}");
+ // Nor through what the menu's Redo runs, which reads the box's history itself (the menu item
+ // is off here, as the copy's document has nothing to redo).
+ h.state_mut().redo();
+ h.run_steps(3);
+ let s = h.state();
+ let text = s.views[1].line_editor.as_ref().map(|ed| ed.text.clone());
+ assert!(!text.as_deref().unwrap_or_default().contains("secret"), "the other tab's typing came in from the menu: {text:?}");
+ assert_eq!(s.session.get(s.views[1].id).unwrap().text_blocks(0)[0].text, s.session.get(s.views[0].id).unwrap().text_blocks(0)[0].text);
+}
++
+ /// A paragraph selected by its frame goes with one Delete (or Backspace), as in Acrobat, instead
+ /// of being emptied a typed character at a time, and undo brings it back.
+ #[test]
+ fn a_paragraph_selected_by_its_frame_deletes_with_one_key() {
+ for key in [Key::Delete, Key::Backspace] {
+ let mut h = harness(2, |_| {});
+ assert!(h.state_mut().execute("edit.edit_text"));
+ h.run_steps(2);
+ let id = h.state().views[0].id;
+ let blocks = |h: &Harness<'static, PdfCraftApp>| h.state().session.get(id).unwrap().text_blocks(0);
+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");
+ let k = r.width() / 200.0;
+ let screen = |x: f64, y: f64| egui::pos2(r.left() + x as f32 * k, r.top() + (300.0 - y as f32) * k);
+ let b = blocks(&h)[0].clone();
+ click_at(&mut h, screen((b.rect[0] + b.rect[2]) / 2.0, (b.rect[1] + b.rect[3]) / 2.0));
+ assert!(h.state().views[0].line_editor.is_some(), "a click on the text opens it for typing");
+ click_at(&mut h, screen((b.rect[0] + b.rect[2]) / 2.0, b.rect[3]) - egui::vec2(0.0, 4.0));
+ assert!(h.state().views[0].line_editor.is_none(), "the frame selects the box");
+ press(&mut h, Modifiers::NONE, key);
+ assert!(blocks(&h).is_empty(), "{key:?} deletes the whole paragraph: {:?}", blocks(&h));
+ assert!(h.state().views[0].line_editor.is_none(), "no empty editor is left behind");
+ assert!(h.query_all_by_label_contains("object selected").next().is_none(), "the deleted paragraph is no longer selected");
+ assert_eq!(h.state().session.get(id).unwrap().text_blocks(1)[0].text, "Page 2", "the next page keeps its text");
+ assert_eq!(h.state().session.get(id).unwrap().info.pages.len(), 2, "Delete removed the paragraph, not a page");
+ assert!(h.state_mut().execute("edit.undo"));
+ h.run_steps(2);
+ assert_eq!(blocks(&h).iter().map(|b| b.text.as_str()).collect::<Vec<_>>(), ["Page 1"], "undo restores it");
+ }
+ }