PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M7: rotate an existing page image by any angle (#1940)
vangel760871543fd8d9
diff --git a/ROADMAP.md b/ROADMAP.mdindex 66b967756..19c328abd 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -157,6 +157,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md| 8 | 1.0 polish: performance, right-to-left, missing languages, keyboard-only (M14) | 55–95 |## Progress log+- **2026-10-13 (M7, free image rotation):** A selected page image has a rotate knob (Shift: 15 degree steps) and `image_edit` a `rotate_by` action; the angle is written as one undoable `cm`. Snapping to page edges while moving is in #1740; resize snapping is not done. Estimates unchanged.- **2026-10-15 (M2, gap 12):** `cargo xtask text-oracle` scores reading order as well as word F1: the longest common subsequence of the two word sequences over the longer one. F1 is a bag of words and cannot see order at all -- measuring #2431, a change that moves text and nothing else, it called 26 of the 29 files whose output changed identical, where the order score separated 18 improvements from 6 regressions. Reports, does not gate; a disagreement with Poppler, not a verdict. Estimates unchanged.- **2026-10-15 (M2, #2305 follow-up):** WinAnsiEncoding 0xA0 and 0xAD and MacRomanEncoding 0xCA extract as the ordinary space and hyphen Annex D.2 names them, in the vendored hayro tables (patch 30) as well as `crates/fonts`, so search, copy and redaction see characters that were hidden behind U+00A0 and U+00AD. Across the pdf.js corpus the soft hyphens we extract fall 117 to 13 and the non-breaking spaces 30 to 26; the rest come from `/ToUnicode`. An explicit `/Differences` name keeps its glyph list value, as pdftotext does. Estimates unchanged.- **2026-10-13 (community, M3, #1569 review):** Pixel-only Wayland wheel, wheel-tilt and continuous input use standalone moved events, so Ctrl zoom does not remain latched after the modifier is released (#991); vendored winit patch (13), with a policy test. Estimates unchanged.diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rsindex 88856305b..9bc70f74a 100644--- a/crates/automation/src/lib.rs+++ b/crates/automation/src/lib.rs@@ -491,6 +491,11 @@ impl Automation {let (u0, u1) = (info.view_to_user(r[0] as f32, r[1] as f32), info.view_to_user(r[2] as f32, r[3] as f32));ImageEdit::Move([u0[0].min(u1[0]) as f64, u0[1].min(u1[1]) as f64, u0[0].max(u1[0]) as f64, u0[1].max(u1[1]) as f64])}+ "rotate_by" => ImageEdit::RotateBy(+ a.get("degrees")+ .and_then(Value::as_f64)+ .ok_or_else(|| ToolError::InvalidArgs("rotate_by needs degrees: a number (clockwise)".into()))?,+ ),"rotate" => ImageEdit::Rotate(a.opt_int("quarters")?.unwrap_or(1) as i32),"crop" => {let r: Vec<f64> =diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rsindex 5e89aef78..0ac2eac1d 100644--- a/crates/automation/src/tools.rs+++ b/crates/automation/src/tools.rs@@ -1241,16 +1241,17 @@ pub fn tools() -> Vec<ToolDef> {.ro().cmd("edit.edit_text").with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 } }), &["doc", "page"])),- t("image_edit", "Edit an image", "Change one of a page's images (number from page_images): action move (rect: new full placement box in top-left-origin points, based on page_images.rect), crop (rect: the part to keep, top-left-origin points; the pixels stay in place and page_images.visible_rect shows the result; a later move carries the crop along), rotate (quarters clockwise, default 1), flip_horizontal, flip_vertical, replace (path: an image file, drawn in the same place) or delete. Undoable. The selected image crop transforms with its pixels, isolating shared path scopes while retaining neighboring painting. Text-outline clips return a clear error. Rotation/flip use the visible centre. Form artwork supports move/resize/rotate/flip/delete as a group; replace and image_save only support raster images.")+ t("image_edit", "Edit an image", "Change one of a page's images (number from page_images): action move (rect: new full placement box in top-left-origin points, based on page_images.rect), crop (rect: the part to keep, top-left-origin points; the pixels stay in place and page_images.visible_rect shows the result; a later move carries the crop along), rotate (quarters clockwise, default 1), rotate_by (degrees: any angle clockwise about the visible centre; the box in page_images then becomes the turned image's bounding box), flip_horizontal, flip_vertical, replace (path: an image file, drawn in the same place) or delete. Undoable. The selected image crop transforms with its pixels, isolating shared path scopes while retaining neighboring painting. Text-outline clips return a clear error. Rotation/flip use the visible centre. Form artwork supports move/resize/rotate/flip/delete as a group; replace and image_save only support raster images.").cmd("edit.edit_text").with(schema(json!({"doc": doc(),"page": { "type": "integer", "minimum": 1 },"image": { "type": "integer", "minimum": 1 },- "action": { "type": "string", "enum": ["move", "crop", "rotate", "flip_horizontal", "flip_vertical", "replace", "delete"] },+ "action": { "type": "string", "enum": ["move", "crop", "rotate", "rotate_by", "flip_horizontal", "flip_vertical", "replace", "delete"] },"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },"quarters": { "type": "integer" },+ "degrees": { "type": "number" },"path": { "type": "string" },}),&["doc", "page", "image", "action"],diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rsindex 1e662d8f3..a37ccba90 100644--- a/crates/automation/tests/automation.rs+++ b/crates/automation/tests/automation.rs@@ -2551,6 +2551,15 @@ fn editing_page_images_through_tools() {assert_eq!(cropped["visible_rect"], json!([10.0, 10.0, 25.0, 30.0]));ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "rotate" }));ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "flip_horizontal" }));+ // Any angle: the box grows to the turned picture's bounds, and it undoes like a quarter turn.+ let before = ok(&mut a, "page_images", json!({ "doc": made, "page": 1 }))["images"][0]["rect"].clone();+ let r = ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "rotate_by", "degrees": 30.5 }));+ assert_eq!(r["undo"], "Rotate image");+ let turned = ok(&mut a, "page_images", json!({ "doc": made, "page": 1 }))["images"][0]["rect"].clone();+ assert_ne!(turned, before);+ ok(&mut a, "edit_undo", json!({ "doc": made }));+ assert_eq!(ok(&mut a, "page_images", json!({ "doc": made, "page": 1 }))["images"][0]["rect"], before);+ assert!(matches!(a.call("image_edit", &json!({ "doc": made, "page": 1, "image": 1, "action": "rotate_by" })), Err(ToolError::InvalidArgs(_))));let saved = ok(&mut a, "image_save", json!({ "doc": made, "page": 1, "image": 1, "path": "out/picture" }));assert_eq!(saved["format"], "png");assert!(std::fs::read(dir.join("out/picture.png")).unwrap().starts_with(b"\x89PNG"));diff --git a/crates/edit/src/images.rs b/crates/edit/src/images.rsindex fb6212588..bb6955506 100644--- a/crates/edit/src/images.rs+++ b/crates/edit/src/images.rs@@ -403,6 +403,20 @@ pub fn turn_about_centre(rect: [f64; 4], quarters: i32, flip_h: bool, flip_v: bo[a, b, c, d, cx - a * cx - c * cy, cy - b * cx - d * cy]}+/// Turn the image `degrees` clockwise (as drawn, whatever the page's `/Rotate`) about the centre+/// of `rect`. `None` for a non-finite angle; whole turns of 360 are the identity.+pub fn turn_by_degrees(rect: [f64; 4], degrees: f64) -> Option<[f64; 6]> {+ if !degrees.is_finite() {+ return None;+ }+ let (cx, cy) = ((rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0);+ let t = (degrees % 360.0).to_radians();+ let (s, c) = t.sin_cos();+ // Clockwise in a y-up space: (x, y) -> (x cos t + y sin t, -x sin t + y cos t).+ let (a, b, cc, d) = (c, -s, s, c);+ Some([a, b, cc, d, cx - a * cx - cc * cy, cy - b * cx - d * cy])+}+/// For a `Do` at `op` that sits alone in `q re W n cm Do Q`: the index of the `re` and the `cm` matrix./// That clip belongs to this image only, so it may move with it. A `cm` this move put before the/// `re` earlier (`q cm re W n cm Do Q`) keeps the pattern, so the image can be moved again.diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rsindex 515f17d8d..f81e952eb 100644--- a/crates/edit/src/lib.rs+++ b/crates/edit/src/lib.rs@@ -650,7 +650,7 @@ pub use objects::{EditableObject, MAX_MOVE_OBJECTS, ObjectKind, ObjectTarget, edmod flatten;pub use flatten::{flatten, flatten_fill_sign};pub mod images;-pub use images::{ImageChange, PageImage, change_image, page_images, reading_images, rect_to_rect, turn_about_centre};+pub use images::{ImageChange, PageImage, change_image, page_images, reading_images, rect_to_rect, turn_about_centre, turn_by_degrees};pub mod bidi;pub mod indic;mod linebreak;diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex b542142df..d3acb3c80 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -54,6 +54,27 @@ fn cx() -> Context {Context { date: (2026, 10, 1) }}+#[test]+fn an_image_turns_by_any_angle_about_its_centre_and_saves_the_matrix() {+ // 100,100..300,200 is 200 x 100 around (200, 150).+ let mut doc = image_page();+ let r0 = images::page_images(&doc, 0).unwrap()[0].rect;+ let t = images::turn_by_degrees(r0, 30.0).unwrap();+ images::change_image(&mut doc, 0, 0, &images::ImageChange::Transform(t)).unwrap();+ let doc = reopen(&doc);+ let r = images::page_images(&doc, 0).unwrap()[0].rect;+ let (c, s) = (30f64.to_radians().cos(), 30f64.to_radians().sin());+ let (w, h) = (200.0 * c + 100.0 * s, 200.0 * s + 100.0 * c);+ assert!(close(r, [200.0 - w / 2.0, 150.0 - h / 2.0, 200.0 + w / 2.0, 150.0 + h / 2.0]), "{r:?}");+ // 90 degrees is the quarter turn; whole turns and non-finite angles are harmless.+ let q = images::turn_about_centre(r0, 1, false, false);+ let d = images::turn_by_degrees(r0, 90.0).unwrap();+ assert!(q.iter().zip(&d).all(|(a, b)| (a - b).abs() < 1e-9), "{q:?} {d:?}");+ let full = images::turn_by_degrees(r0, 720.0).unwrap();+ assert!(full.iter().zip([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]).all(|(a, b)| (a - b).abs() < 1e-9));+ assert!(images::turn_by_degrees(r0, f64::NAN).is_none() && images::turn_by_degrees(r0, f64::INFINITY).is_none());+}+#[test]fn tokens_expand() {let c = cx();diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 01f162ae7..a95d143b2 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -76,6 +76,8 @@ pub enum ImageEdit {Move([f64; 4]),/// Quarter turns clockwise about its centre.Rotate(i32),+ /// Any angle in degrees clockwise about its centre (the unit is degrees, not quarter turns).+ RotateBy(f64),Flip {horizontal: bool,},@@ -1993,7 +1995,7 @@ impl Edit {Edit::MoveObjects { objects, .. } => plural("Move object", "Move objects", objects.len()),Edit::EditPageImage { change, .. } => Label::of(match change {ImageEdit::Move(_) => "Move image",- ImageEdit::Rotate(_) => "Rotate image",+ ImageEdit::Rotate(_) | ImageEdit::RotateBy(_) => "Rotate image",ImageEdit::Crop(_) => "Crop image",ImageEdit::Flip { .. } => "Flip image",ImageEdit::Replace { .. } => "Replace image",@@ -2496,6 +2498,11 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) ->ImageEdit::Rotate(q) => {pdfcraft_edit::ImageChange::Transform(pdfcraft_edit::turn_about_centre(img.visible_rect.unwrap_or(img.rect), *q, false, false))}+ ImageEdit::RotateBy(degrees) => {+ let t = pdfcraft_edit::turn_by_degrees(img.visible_rect.unwrap_or(img.rect), *degrees)+ .ok_or_else(|| EditError::Edit(pdfcraft_edit::EditError::Invalid("the rotation angle must be a finite number".into())))?;+ pdfcraft_edit::ImageChange::Transform(t)+ }ImageEdit::Flip { horizontal } => pdfcraft_edit::ImageChange::Transform(pdfcraft_edit::turn_about_centre(img.visible_rect.unwrap_or(img.rect),0,diff --git a/crates/ui-egui/src/edit_text_ui.rs b/crates/ui-egui/src/edit_text_ui.rsindex d8881ba47..464f66141 100644--- a/crates/ui-egui/src/edit_text_ui.rs+++ b/crates/ui-egui/src/edit_text_ui.rs@@ -358,6 +358,8 @@ pub struct ImageSelection {drag: Option<(Pos2, Option<Pos2>)>,/// Crop mode (Acrobat's crop handles): the box kept so far.pub crop: Option<CropMode>,+ /// The drag is turning the picture by its rotate handle (the `drag` start is then unused).+ turning: bool,}/// Cropping a page image: the handles trim instead of resizing, the part that will go is@@ -620,6 +622,23 @@ pub(crate) enum ImageAction {Recognize(usize),}+/// Where the rotate knob sits: above the middle of the top edge.+fn rotate_knob(b: Rect) -> Pos2 {+ b.center_top() - egui::vec2(0.0, 22.0)+}++/// Degrees clockwise (-180..=180) that turn "straight up" from `centre` onto the pointer; `snap`+/// rounds to steps of 15 degrees (Shift). A pointer on the centre turns nothing.+fn turn_degrees(centre: Pos2, pointer: Pos2, snap: bool) -> f32 {+ let v = pointer - centre;+ if !(v.x.is_finite() && v.y.is_finite()) || v.length() < 4.0 {+ return 0.0;+ }+ // Screen y points down: up is (0, -1); clockwise is atan2(x, -y).+ let d = v.x.atan2(-v.y).to_degrees();+ if snap { (d / 15.0).round() * 15.0 } else { d }+}+fn user_box(xf: &PageXform, info: &DocInfo, page: usize, r: Rect) -> [f64; 4] {let p = &info.pages[page];let (a, b) = (xf.screen_to_view(r.min), xf.screen_to_view(r.max));@@ -704,10 +723,28 @@ pub(crate) fn image_input(if allow_interaction && let Some(corner) = hover_pos.and_then(|p| corners.iter().position(|c| c.distance(p) < 8.0)) {ui.ctx().set_cursor_icon(if matches!(corner, 0 | 3) { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw });}+ // The rotate handle: a knob above the top edge, joined to it by a short stem.+ let knob = rotate_knob(b);+ if view.image_selection.as_ref().is_some_and(|s| s.drag.is_none()) {+ painter.line_segment([b.center_top(), knob], Stroke::new(1.0, ACCENT));+ painter.circle(knob, 5.0, Color32::WHITE, Stroke::new(1.0, ACCENT));+ if allow_interaction && hover_pos.is_some_and(|p| p.distance(knob) < 8.0) {+ ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);+ }+ }let origin = ui.input(|i| i.pointer.press_origin());if allow_interaction&& resp.drag_started()&& let Some(o) = origin+ && o.distance(knob) < 8.0+ {+ if let Some(s) = view.image_selection.as_mut() {+ s.drag = Some((o, None));+ s.turning = true;+ }+ } else if allow_interaction+ && resp.drag_started()+ && let Some(o) = origin{let corner = corners.iter().position(|c| c.distance(o) < 8.0);if corner.is_some() || image_contains(i, o) {@@ -717,6 +754,32 @@ pub(crate) fn image_input(}}}+ if view.image_selection.as_ref().is_some_and(|s| s.turning) {+ let shift = ui.input(|i| i.modifiers.shift);+ let degrees = hover_pos.map_or(0.0, |p| turn_degrees(b.center(), p, shift));+ // The turned outline as a preview; the engine redraws the pixels on release.+ let centre = b.center();+ let (sin, cos) = degrees.to_radians().sin_cos();+ let turn = |c: Pos2| {+ let v = c - centre;+ centre + egui::vec2(v.x * cos - v.y * sin, v.x * sin + v.y * cos)+ };+ let outline = [b.left_top(), b.right_top(), b.right_bottom(), b.left_bottom()].map(turn).to_vec();+ painter.add(egui::Shape::closed_line(outline, Stroke::new(1.5, ACCENT)));+ painter.text(turn(knob), egui::Align2::CENTER_BOTTOM, format!("{degrees:.0}\u{b0}"), egui::FontId::proportional(12.0), ACCENT);+ ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);+ if resp.drag_stopped() || !ui.input(|i| i.pointer.primary_down()) {+ if let Some(s) = view.image_selection.as_mut() {+ s.drag = None;+ s.turning = false;+ }+ if degrees.abs() >= 0.05 {+ view.pending_edit =+ Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::RotateBy(f64::from(degrees)) });+ }+ }+ return true;+ }if let Some((start, opposite)) = view.image_selection.as_ref().and_then(|s| s.drag)&& let Some(p) = hover_pos{@@ -832,7 +895,7 @@ pub(crate) fn image_input(_ => egui::CursorIcon::PointingHand,});if resp.clicked() || resp.secondary_clicked() {- view.image_selection = Some(ImageSelection { page, index: hit, drag: None, crop: None });+ view.image_selection = Some(ImageSelection { page, index: hit, drag: None, crop: None, turning: false });}if resp.secondary_clicked() {ui.ctx().data_mut(|d| d.insert_temp(menu_key, true));@@ -1444,6 +1507,20 @@ pub(crate) fn caret_color_on(fill: Color32) -> Color32 {mod tests {use super::*;+ #[test]+ fn the_rotate_knob_measures_clockwise_degrees_from_straight_up() {+ let c = Pos2::new(100.0, 100.0);+ let at = |x: f32, y: f32| turn_degrees(c, Pos2::new(x, y), false);+ assert!(at(100.0, 0.0).abs() < 1e-3);+ assert!((at(200.0, 100.0) - 90.0).abs() < 1e-3, "right is a clockwise quarter");+ assert!((at(0.0, 100.0) + 90.0).abs() < 1e-3);+ assert!((at(100.0, 200.0).abs() - 180.0).abs() < 1e-3);+ // Shift rounds to 15 degrees; the centre and non-finite points turn nothing.+ assert_eq!(turn_degrees(c, Pos2::new(180.0, 50.0), true) % 15.0, 0.0);+ assert_eq!(at(101.0, 101.0), 0.0);+ assert_eq!(at(f32::NAN, 5.0), 0.0);+ }+/// An app with one text document open, and an editor on its first paragraph.fn preview_app() -> (crate::PdfCraftApp, LineEditor) {let mut app = crate::PdfCraftApp::new();diff --git a/crates/ui-egui/tests/editing.rs b/crates/ui-egui/tests/editing.rsindex f8db52575..1beccc965 100644--- a/crates/ui-egui/tests/editing.rs+++ b/crates/ui-egui/tests/editing.rs@@ -2778,6 +2778,51 @@ fn editing_existing_images_on_the_page() {check_existing_artwork("picture.png", png);}+#[test]+fn dragging_the_rotate_knob_turns_a_page_image() {+ let mut png = Vec::new();+ image::RgbImage::from_pixel(80, 40, image::Rgb([200, 40, 40])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {+ let mut app = PdfCraftApp::new();+ app.set_option("language", "en").unwrap();+ app.open_bytes("picture.png", None, png.clone()).expect("opens");+ app+ });+ h.run_steps(4);+ let id = h.state().views[0].id;+ let before = h.state().session.get(id).unwrap().page_images(0)[0].rect;+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(2);+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");+ let c = r.center();+ // Select the picture.+ h.hover_at(c);+ h.run_steps(1);+ h.drag_at(c);+ h.run_steps(1);+ h.drop_at(c);+ h.run_steps(2);+ assert!(h.state().views[0].image_selection.is_some(), "selected");+ // Grab the knob above the top edge and swing it a quarter turn clockwise (to the right).+ let knob = egui::pos2(c.x, r.top() - 22.0);+ let to = egui::pos2(c.x + 100.0, c.y);+ h.hover_at(knob);+ h.run_steps(1);+ h.drag_at(knob);+ h.run_steps(1);+ for k in 1..=4 {+ h.hover_at(knob + (to - knob) * (k as f32 / 4.0));+ h.run_steps(1);+ }+ h.drop_at(to);+ h.run_steps(4);+ let doc = h.state().session.get(id).unwrap();+ assert_eq!(doc.can_undo(), Some("Rotate image"));+ let turned = doc.page_images(0)[0].rect;+ let (w, hh) = (before[2] - before[0], before[3] - before[1]);+ assert!((turned[2] - turned[0] - hh).abs() < 1.5 && (turned[3] - turned[1] - w).abs() < 1.5, "{before:?} -> {turned:?}");+}+#[test]fn editing_existing_form_artwork_on_the_page() {use pdfcraft_cos::{Dict, Document, Object, SaveOptions, Stream, write_incremental};diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.tomlindex 533013b54..831ddd353 100644--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@ -2085,6 +2085,18 @@ tools = ["image_edit"]evidence = ["crates/edit/src/tests.rs::page_images_move_turn_replace_and_delete", "crates/ui-egui/tests/editing.rs::editing_existing_images_on_the_page", "crates/automation/tests/automation.rs::editing_page_images_through_tools"]notes = "existing page images (right-click ▸ Replace Image) and added images: the new picture is drawn in the same place"+[[feature]]+id = "edit.image-rotate-free"+title = "Rotate an existing page image by any angle"+area = "C"+tier = "P1"+milestone = "M7"+status = "partial"+commands = ["edit.edit_text"]+tools = ["image_edit"]+evidence = ["crates/edit/src/tests.rs::an_image_turns_by_any_angle_about_its_centre_and_saves_the_matrix", "crates/ui-egui/tests/editing.rs::dragging_the_rotate_knob_turns_a_page_image", "crates/automation/tests/automation.rs::editing_page_images_through_tools"]+notes = "drag the knob above a selected image (Shift: 15 degree steps) or image_edit action rotate_by with degrees; the angle is clockwise about the visible centre and is written as one extra cm (undoable). Missing: no numeric angle field, no live pixel preview while turning (an outline is drawn), the selection frame and corner handles of a turned image are its axis-aligned bounds, corner handles of an already turned image scale its axis-aligned bounds (not tested), no angle shown for an already turned image"+[[feature]]id = "edit.image-crop"title = "Crop an image"