PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Fill & Sign marks stay upright on rotated pages (#2392)
Adriana0c106268c39
diff --git a/crates/annot/src/appearance.rs b/crates/annot/src/appearance.rsindex 3e1dd4a6b..55ed5d353 100644--- a/crates/annot/src/appearance.rs+++ b/crates/annot/src/appearance.rs@@ -593,7 +593,28 @@ pub fn build(d: &Dict) -> Option<Stream> {// Only PdfCraft's own Fill & Sign marks are drawn here.let name = d.name(b"Name")?;let col = stroke.unwrap_or([0.0; 3]);- let [x0, y0, x1, y1] = rect;+ // A mark or stamp placed on a turned page is drawn upright in its displayed box, then+ // mapped into `/Rect` the way the page maps display space into user space. Viewers+ // fit that box to `/Rect`; the page rotation then shows it the right way up.+ let turn = stamp_turn(d);+ let draw = if turn == 0 {+ rect+ } else {+ let (rw, rh) = (rect[2] - rect[0], rect[3] - rect[1]);+ let (dw, dh) = if matches!(turn, 90 | 270) { (rh, rw) } else { (rw, rh) };+ if dw < 1.0 || dh < 1.0 {+ return None;+ }+ [0.0, 0.0, dw, dh]+ };+ let turned = |mut stream: Stream| {+ if turn != 0 {+ let m = pdfcraft_model::view_matrix_for(turn, rect);+ stream.dict.set(b"Matrix".to_vec(), Object::Array(m.iter().copied().map(Object::Real).collect()));+ }+ stream+ };+ let [x0, y0, x1, y1] = draw;let (w, h) = (x1 - x0, y1 - y0);let lw = w.min(h) * 0.12;match name {@@ -643,28 +664,12 @@ pub fn build(d: &Dict) -> Option<Stream> {}let kind = crate::StampKind::from_name(other)?;let by = d.get(b"PCByLine").and_then(|o| o.as_string()).map(PdfString::to_text);- let turn = stamp_turn(d);- let draw = if turn == 0 {- rect- } else {- let (rw, rh) = (rect[2] - rect[0], rect[3] - rect[1]);- let (dw, dh) = if matches!(turn, 90 | 270) { (rh, rw) } else { (rw, rh) };- if dw < 1.0 || dh < 1.0 {- return None;- }- [0.0, 0.0, dw, dh]- };- let mut stream = stamp(kind, draw, stroke.unwrap_or(kind.color()), by.as_deref(), opacity, res);- if turn != 0 {- // Upright in the stamp's displayed box, then mapped into `/Rect` the way- // the page maps display space into user space. Viewers fit that box to- // `/Rect`; the page rotation then shows the label the right way up.- let m = pdfcraft_model::view_matrix_for(turn, rect);- stream.dict.set(b"Matrix".to_vec(), Object::Array(m.iter().copied().map(Object::Real).collect()));- }- return Some(stream);+ return Some(turned(stamp(kind, draw, stroke.unwrap_or(kind.color()), by.as_deref(), opacity, res)));}}+ if turn != 0 {+ return Some(turned(form(draw, c.as_bytes(), res)));+ }}b"FreeText" => {let (text_color, size) = parse_da(d);diff --git a/crates/annot/src/lib.rs b/crates/annot/src/lib.rsindex 587cd4466..47aabef79 100644--- a/crates/annot/src/lib.rs+++ b/crates/annot/src/lib.rs@@ -125,6 +125,14 @@ impl FillMark {FillMark::Line => "Line",}}++ /// The user-space box of the mark placed at `at` on a page turned by `rotation`: centred+ /// there and sized in displayed axes, so a line runs across the page as displayed (#2392).+ pub fn rect_at(self, at: [f64; 2], rotation: i64) -> [f64; 4] {+ let (w, h) = if self == FillMark::Line { (36.0, 4.0) } else { (12.0, 12.0) };+ let (w, h) = if matches!(rotation.rem_euclid(360), 90 | 270) { (h, w) } else { (w, h) };+ [at[0] - w / 2.0, at[1] - h / 2.0, at[0] + w / 2.0, at[1] + h / 2.0]+ }}/// The stamps of Acrobat's stamp palette (drawn in PdfCraft's own style).@@ -1081,6 +1089,11 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> Rd.set(b"C".to_vec(), rgb(style.color));d.set(b"Name".to_vec(), Object::name(mark.name()));border(&mut d);+ // Drawn upright for the page as displayed, as a stamp is (#2392).+ let turn = pdfcraft_model::pages(doc).get(new.page).map_or(0, |p| p.rotation(doc));+ if matches!(turn, 90 | 180 | 270) {+ d.set(b"PCStampRotate".to_vec(), Object::Int(turn));+ }}Shape::Stamp { stamp, by, .. } => {d.set(b"C".to_vec(), rgb(style.color));diff --git a/crates/automation/src/comments.rs b/crates/automation/src/comments.rsindex 302688f72..5fa1d5bb4 100644--- a/crates/automation/src/comments.rs+++ b/crates/automation/src/comments.rs@@ -551,8 +551,7 @@ impl Automation {"line" => FillMark::Line,other => return Err(ToolError::InvalidArgs(format!("unknown type {other:?}"))),};- let (w, h) = if mark == FillMark::Line { (36.0, 4.0) } else { (12.0, 12.0) };- (Shape::Mark { rect: [at[0] - w / 2.0, at[1] - h / 2.0, at[0] + w / 2.0, at[1] + h / 2.0], mark }, String::new())+ (Shape::Mark { rect: mark.rect_at(at, i64::from(info.rotation)), mark }, String::new())}};let style = Style::default_for(&shape);diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rsindex cbf40f196..fe767ce41 100644--- a/crates/automation/tests/automation.rs+++ b/crates/automation/tests/automation.rs@@ -4320,6 +4320,60 @@ fn typed_signatures_stay_upright_on_rotated_pages() {check(&mut a, reopened);}+/// #2392: a Fill & Sign checkmark and line look the same on a turned page as on an unturned one:+/// the checkmark isn't upside down or sideways, and the line runs across as displayed.+#[test]+fn fill_sign_marks_stay_upright_on_rotated_pages() {+ let dir = workdir("marks-upright");+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_create", json!({ "from": "blank", "width": 200, "height": 300, "pages": 4 }))["doc"].as_u64().unwrap();+ for (page, degrees) in [(2, 90), (3, 180), (4, 270)] {+ ok(&mut a, "page_rotate", json!({ "doc": doc, "pages": [page], "degrees": degrees }));+ }+ for page in 1..=4 {+ ok(&mut a, "fill_sign_add", json!({ "doc": doc, "page": page, "type": "check", "at": [40, 60] }));+ ok(&mut a, "fill_sign_add", json!({ "doc": doc, "page": page, "type": "line", "at": [120, 60] }));+ }+ let check = |a: &mut Automation, doc: u64| {+ let mut upright = Vec::new();+ for page in 1..=4 {+ // 144 dpi: two pixels a point.+ let output = a.call("page_render", &json!({ "doc": doc, "page": page, "dpi": 144 })).unwrap();+ let Content::Png { data, .. } = &output[0] else { panic!() };+ let pixels = image::load_from_memory(data).unwrap().to_rgba8();+ let dark: Vec<bool> = pixels.pixels().map(|p| p.0[..3].iter().all(|v| *v < 128)).collect();+ let width = pixels.width();+ // The line, 36 × 4 pt displayed, runs across.+ let mut b = [u32::MAX, u32::MAX, 0, 0];+ for (x, y, p) in pixels.enumerate_pixels() {+ if x.abs_diff(240) < 60 && y.abs_diff(120) < 60 && p.0[..3].iter().all(|v| *v < 128) {+ b = [b[0].min(x), b[1].min(y), b[2].max(x), b[3].max(y)];+ }+ }+ assert!(b[0] <= b[2], "page {page}: no line drawn");+ assert!(b[2] - b[0] > 60 && b[3] - b[1] < 10, "page {page}: the line should run across: {b:?}");+ if page == 1 {+ upright = dark;+ continue;+ }+ // Same pixels as the unturned page where both pages are (pages 2 and 4 are wider).+ let (mut differ, mut ink) = (0, 0);+ for y in 0..400 {+ for x in 0..400 {+ let (want, got) = (upright[(y * 400 + x) as usize], dark[(y * width + x) as usize]);+ ink += usize::from(want);+ differ += usize::from(want != got);+ }+ }+ assert!(ink > 0 && differ * 10 < ink, "page {page}: {differ} of {ink} ink pixels differ from the unturned page");+ }+ };+ check(&mut a, doc);+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "marked.pdf" }));+ let reopened = ok(&mut a, "doc_open", json!({ "path": "marked.pdf" }))["doc"].as_u64().unwrap();+ check(&mut a, reopened);+}+#[test]fn comment_checkmarks_locks_hiding_and_summaries_through_tools() {let dir = workdir("comment-polish");diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex f125c41da..f53473942 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -196,6 +196,59 @@ fn rubber_stamps_point_left_as_displayed_on_rotated_pages() {}}+/// #2392: Fill & Sign marks are drawn as displayed on every page rotation, including after save:+/// a checkmark's long stroke rises to the right, and a line runs across.+#[test]+fn fill_sign_marks_are_upright_as_displayed_on_rotated_pages() {+ for degrees in [0, 90, 180, 270] {+ let (mut session, id) = rotated_blank(degrees);+ let info = session.get(id).unwrap().info.pages[0].clone();+ // Displayed boxes: a 40 pt checkmark centred at (50, 50), an 80 × 8 pt line at (130, 50).+ for (mark, vx, w, h) in [(FillMark::Check, 50.0, 40.0, 40.0), (FillMark::Line, 130.0, 80.0, 8.0)] {+ let shape = Shape::Mark { rect: displayed_rect(&info, vx, 50.0, w, h), mark };+ session+ .apply(+ id,+ Edit::AddAnnotation(NewAnnotation {+ page: 0,+ style: Style::default_for(&shape),+ shape,+ contents: String::new(),+ author: "Test".into(),+ }),+ )+ .unwrap();+ }+ let check = |session: &Session, id: DocId| {+ let rendered = render_page(session, id);+ // Dark pixels in a displayed box, rendered at scale 2.+ let ink = |x0: u32, y0: u32, x1: u32, y1: u32| -> Vec<(u32, u32)> {+ (y0 * 2..y1 * 2)+ .flat_map(|y| (x0 * 2..x1 * 2).map(move |x| (x, y)))+ .filter(|&(x, y)| stamp_pixel(&rendered, x, y)[..3].iter().all(|c| *c < 128))+ .collect()+ };+ let tick = ink(30, 30, 70, 70);+ assert!(!tick.is_empty(), "rotation {degrees}: no checkmark drawn");+ let top = tick.iter().min_by_key(|p| p.1).unwrap();+ let bottom = tick.iter().max_by_key(|p| p.1).unwrap();+ // The long stroke ends at the top right; the short one meets it low, left of centre.+ assert!(top.0 > bottom.0 + 20, "rotation {degrees}: highest ink {top:?} should be right of the lowest {bottom:?}");+ assert!(bottom.0 < 100 && top.0 > 110, "rotation {degrees}: checkmark {bottom:?} .. {top:?} is not upright");+ let line = ink(85, 40, 175, 60);+ assert!(!line.is_empty(), "rotation {degrees}: no line drawn");+ let (x0, x1) = (line.iter().map(|p| p.0).min().unwrap(), line.iter().map(|p| p.0).max().unwrap());+ let (y0, y1) = (line.iter().map(|p| p.1).min().unwrap(), line.iter().map(|p| p.1).max().unwrap());+ assert!((x1 - x0) > 10 * (y1 - y0 + 1), "rotation {degrees}: line {x0}..{x1} x {y0}..{y1} should run across");+ };+ check(&session, id);+ let saved = session.save_bytes(id).unwrap();+ let mut reopened = Session::new().with_clock(|| 1_700_000_000);+ let again = reopened.open("drawing.pdf", None, saved, None).unwrap();+ check(&reopened, again);+ }+}+/// Fill & Sign text and text boxes read across as displayed on turned pages (scanned forms are/// often stored sideways with `/Rotate`), including after save.#[test]diff --git a/crates/ui-egui/src/fill_sign.rs b/crates/ui-egui/src/fill_sign.rsindex 794fe0bf1..dfd0b8e2a 100644--- a/crates/ui-egui/src/fill_sign.rs+++ b/crates/ui-egui/src/fill_sign.rs@@ -676,8 +676,7 @@ pub(crate) fn page_input(},mark => {let mark = mark.mark()?;- let (w, h) = if mark == FillMark::Line { (36.0, 4.0) } else { (12.0, 12.0) };- let rect = [at[0] - w / 2.0, at[1] - h / 2.0, at[0] + w / 2.0, at[1] + h / 2.0];+ let rect = mark.rect_at(at, rotation);Some(FillAction::Edit(Box::new(new(page, Shape::Mark { rect, mark }, String::new(), author))))}}diff --git a/crates/ui-egui/tests/fill_sign.rs b/crates/ui-egui/tests/fill_sign.rsindex 27fd6dd8a..c01b1b2b4 100644--- a/crates/ui-egui/tests/fill_sign.rs+++ b/crates/ui-egui/tests/fill_sign.rs@@ -101,6 +101,29 @@ fn rendered_ink(h: &mut Harness<'static, PdfCraftApp>, x: f32, y: f32) -> image:panic!("signature ink did not render at ({x}, {y})");}+/// #2392: the Line tool's line runs across the page as displayed, on turned pages too (its box was+/// sized in the page's own axes, so a quarter turn stood it on end).+#[test]+fn the_line_mark_runs_across_turned_pages() {+ for degrees in [0, 90, 180, 270] {+ let mut h = harness();+ {+ let s = h.state_mut();+ let id = s.views[0].id;+ s.session.apply(id, pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees }).unwrap();+ }+ h.run_steps(4);+ assert!(h.state_mut().execute("sign.fill.line"));+ click(&mut h, 150.0, 350.0);+ let s = h.state();+ let info = &s.session.get(s.views[0].id).unwrap().info;+ let r = info.annotations.last().expect("a line was placed").rect;+ let (a, b) = (info.pages[0].user_to_view(r[0], r[1]), info.pages[0].user_to_view(r[2], r[3]));+ let (w, h) = ((a[0] - b[0]).abs(), (a[1] - b[1]).abs());+ assert!(w > 4.0 * h, "rotation {degrees}: the line's displayed box is {w} × {h}, not across");+ }+}+#[test]fn text_marks_and_date() {let mut h = harness();