PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge branch 'main' into main
Combilerbeb1a70d7134
diff --cc crates/edit/src/images.rsindex 84dd40459,e90d8e4f1..2abd6a850--- a/crates/edit/src/images.rs+++ b/crates/edit/src/images.rs@@@ -51,8 -30,8 +51,10 @@@ pub struct PageImage/// Pixel size; zero for vector/grouped Form artwork.pub width: u32,pub height: u32,+ /// Active soft mask identity at the image placement, if any.+ pub smask: Option<MaskIdentity>,+ /// The content stream its `Do` (its first token) is in, and the `Do`'s index among the+ /// operators of the page's streams joined ([`Pieces`]).stream: usize,op: usize,/// CTM before `Do`, excluding a Form's own Matrix.@@@ -236,78 -220,72 +243,95 @@@ impl ImageStatepub fn page_images(doc: &Document, page: usize) -> Result<Vec<PageImage>, EditError> {let p = page_of(doc, page)?;let xo = xobjects(doc, &p.dict);+ let res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();+ let ext_gstates = res.get(b"ExtGState").map(|g| doc.resolve(g)).and_then(|g| g.as_dict().cloned()).unwrap_or_default();let mut out = Vec::new();- // The graphics state carries over from one stream to the next.+ // The streams are one stream in pieces, so the graphics state and operators carry over.let mut state = ImageState::new(Matrix::IDENTITY, p.crop(doc), Vec::new());- let mut tracker = ExtendedGStateTracker::default();- for (si, (_, data)) in streams(doc, &p.dict).into_iter().enumerate() {- for (i, op) in parse(&data).ops.iter().enumerate() {- let pieces = joined(&streams(doc, &p.dict));- for (i, op) in pieces.parse().ops.iter().enumerate() {- state.apply(op)?;- let ctm = state.placement.matrix;- if op.is("Do") {- let Some(name) = op.name(0) else { continue };- let Some(resource) = xo.get(name) else { continue };- let obj = doc.resolve(resource);- let Object::Stream(s) = &*obj else { continue };- let is_form = s.dict.name(b"Subtype") == Some(b"Form");- let (matrix, bounds) = if is_form {- let Some(bounds) = s.dict.get(b"BBox").map(|v| doc.resolve(v)).and_then(|v| {- v.as_array().and_then(|a| {- if a.len() != 4 {- return None;- }- let mut b = [0.0; 4];- for (n, v) in b.iter_mut().zip(a) {- *n = v.as_f64()?;++let mut tracker = ExtendedGStateTracker::default();++ let pieces = joined(&streams(doc, &p.dict));++ for (i, op) in pieces.parse().ops.iter().enumerate() {+ state.apply(op)?;+ tracker.step(op, &ext_gstates, doc, state.placement.matrix)?;+ let ctm = state.placement.matrix;+ if op.is("Do") {+ let Some(name) = op.name(0) else { continue };+ let Some(resource) = xo.get(name) else { continue };+ let obj = doc.resolve(resource);+ let Object::Stream(s) = &*obj else { continue };+ let is_form = s.dict.name(b"Subtype") == Some(b"Form");+ let (matrix, bounds) = if is_form {+ let Some(bounds) = s.dict.get(b"BBox").map(|v| doc.resolve(v)).and_then(|v| {+ v.as_array().and_then(|a| {+ if a.len() != 4 {+ return None;+ }+ let mut b = [0.0; 4];+ for (n, v) in b.iter_mut().zip(a) {+ *n = v.as_f64()?;- }- Some(b)- })- }) else {- continue;- };- let matrix = match s.dict.get(b"Matrix") {- Some(v) => {- let v = doc.resolve(v);- let Some(m) = v.as_array().and_then(|a| Matrix::from_operands(a)) else { continue };- m}- None => Matrix::IDENTITY,- };- (matrix.then(&ctm), bounds)- } else if s.dict.name(b"Subtype") == Some(b"Image") {- (ctm, [0.0, 0.0, 1.0, 1.0])- } else {+ Some(b)+ })+ }) else {continue;};- let rect = matrix.bbox(bounds);- if !bounds.iter().chain(matrix.0.iter()).chain(rect.iter()).all(|v| v.is_finite())- || bounds[2] <= bounds[0]- || bounds[3] <= bounds[1]- || rect[2] <= rect[0]- || rect[3] <= rect[1]- {- continue;- }- out.push(PageImage {- rect,- visible_rect: intersection(rect, state.placement.clip),- clip_rect: Some(state.placement.clip),- matrix: matrix.0,- name: String::from_utf8_lossy(name).into_owned(),- object: resource.as_ref(),- is_form,- width: if is_form { 0 } else { s.dict.int(b"Width").unwrap_or(0).clamp(0, u32::MAX as i64) as u32 },- height: if is_form { 0 } else { s.dict.int(b"Height").unwrap_or(0).clamp(0, u32::MAX as i64) as u32 },- smask: tracker.current_state.smask.clone(),- stream: si,- op: i,- draw_matrix: ctm.0,- clips: state.placement.clips.clone(),- });- let matrix = match s.dict.get(b"Matrix") {- Some(v) => {- let v = doc.resolve(v);- let Some(m) = v.as_array().and_then(|a| Matrix::from_operands(a)) else { continue };- m- }- None => Matrix::IDENTITY,- };- (matrix.then(&ctm), bounds)- } else if s.dict.name(b"Subtype") == Some(b"Image") {- (ctm, [0.0, 0.0, 1.0, 1.0])- } else {- continue;- };- let rect = matrix.bbox(bounds);- if !bounds.iter().chain(matrix.0.iter()).chain(rect.iter()).all(|v| v.is_finite())- || bounds[2] <= bounds[0]- || bounds[3] <= bounds[1]- || rect[2] <= rect[0]- || rect[3] <= rect[1]- {- continue;++let matrix = match s.dict.get(b"Matrix") {++ Some(v) => {++ let v = doc.resolve(v);++ let Some(m) = v.as_array().and_then(|a| Matrix::from_operands(a)) else { continue };++ m+ }++ None => Matrix::IDENTITY,++ };++ (matrix.then(&ctm), bounds)++ } else if s.dict.name(b"Subtype") == Some(b"Image") {++ (ctm, [0.0, 0.0, 1.0, 1.0])++ } else {++ continue;++ };++++ let rect = matrix.bbox(bounds);++ if !bounds.iter().chain(matrix.0.iter()).chain(rect.iter()).all(|v| v.is_finite())++ || bounds[2] <= bounds[0]++ || bounds[3] <= bounds[1]++ || rect[2] <= rect[0]++ || rect[3] <= rect[1]++ {++ continue;++ }++++ out.push(PageImage {++ rect,++ visible_rect: intersection(rect, state.placement.clip),++ clip_rect: Some(state.placement.clip),++ matrix: matrix.0,++ name: String::from_utf8_lossy(name).into_owned(),++ object: resource.as_ref(),++ is_form,++ width: if is_form { 0 } else { s.dict.int(b"Width").unwrap_or(0).clamp(0, u32::MAX as i64) as u32 },++ height: if is_form { 0 } else { s.dict.int(b"Height").unwrap_or(0).clamp(0, u32::MAX as i64) as u32 },++ smask: tracker.current_state.smask.clone(),++ stream: si,++ op: i,++ draw_matrix: ctm.0,++ clips: state.placement.clips.clone(),++ });+ }+ out.push(PageImage {+ rect,+ visible_rect: intersection(rect, state.placement.clip),+ clip_rect: Some(state.placement.clip),+ matrix: matrix.0,+ name: String::from_utf8_lossy(name).into_owned(),+ object: resource.as_ref(),+ is_form,+ width: if is_form { 0 } else { s.dict.int(b"Width").unwrap_or(0).clamp(0, u32::MAX as i64) as u32 },+ height: if is_form { 0 } else { s.dict.int(b"Height").unwrap_or(0).clamp(0, u32::MAX as i64) as u32 },+ stream: pieces.piece_of(op.span.start),+ op: i,+ draw_matrix: ctm.0,+ clips: state.placement.clips.clone(),+ });}}Ok(out)@@@ -375,8 -354,7 +400,8 @@@ pub fn reading_images(doc: &Document, pis_form: false,width: s.dict.int(b"Width").unwrap_or(0).max(0) as u32,height: s.dict.int(b"Height").unwrap_or(0).max(0) as u32,+ smask: None,- stream,+ stream: stream(op),op: i,draw_matrix: ctm.0,clips: st.placement.clips.clone(),@@@ -1559,62 -663,19 +1567,62 @@@ fn crop_image_implif !keep.iter().all(|v| v.is_finite() && v.abs() <= 1e12) {return Err(EditError::Invalid("the crop box must be finite and no larger than 1e12".into()));}- let [x0, y0, x1, y1] = [keep[0].min(keep[2]), keep[1].min(keep[3]), keep[0].max(keep[2]), keep[1].max(keep[3])];- if x1 - x0 < 1e-6 || y1 - y0 < 1e-6 {+ let is_normalized = keep[0] >= 0.0+ && keep[1] >= 0.0+ && keep[2] <= 1.0+ && keep[3] <= 1.0+ && keep[2] > keep[0]+ && keep[3] > keep[1]+ && ((image.rect[2] - image.rect[0]).abs() > 1.5 || (image.rect[3] - image.rect[1]).abs() > 1.5);++ let (u0, v0, u1, v1) = if is_normalized {+ (keep[0], keep[1], keep[2], keep[3])+ } else {+ let [x0, y0, x1, y1] = [keep[0].min(keep[2]), keep[1].min(keep[3]), keep[0].max(keep[2]), keep[1].max(keep[3])];+ if x1 - x0 < 1e-6 || y1 - y0 < 1e-6 {+ return Err(EditError::Invalid("the crop box has no area".into()));+ }+ let inv = Matrix(image.matrix).invert().ok_or_else(|| EditError::Invalid("the image has no area".into()))?;+ let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].map(|(x, y)| inv.apply(x, y));+ let min_u = corners.iter().map(|(u, _)| *u).fold(f64::INFINITY, f64::min).clamp(0.0, 1.0);+ let max_u = corners.iter().map(|(u, _)| *u).fold(f64::NEG_INFINITY, f64::max).clamp(0.0, 1.0);+ let min_v = corners.iter().map(|(_, v)| *v).fold(f64::INFINITY, f64::min).clamp(0.0, 1.0);+ let max_v = corners.iter().map(|(_, v)| *v).fold(f64::NEG_INFINITY, f64::max).clamp(0.0, 1.0);+ if max_u - min_u < 1e-6 || max_v - min_v < 1e-6 {+ return Err(EditError::Invalid("the crop box has no area".into()));+ }+ (min_u, min_v, max_u, max_v)+ };++ if u1 - u0 < 1e-6 || v1 - v0 < 1e-6 {return Err(EditError::Invalid("the crop box has no area".into()));}++ let m = Matrix(image.matrix);+ let p00 = m.apply(u0, v0);+ let p10 = m.apply(u1, v0);+ let p11 = m.apply(u1, v1);+ let p01 = m.apply(u0, v1);++ let mut offset = 0_usize;+ for (_, data) in streams.iter().take(image.stream) {+ offset = offset+ .checked_add(data.len())+ .and_then(|n| n.checked_add(1))+ .ok_or_else(|| EditError::Invalid("the image content is too large".into()))?;+ }+ let data = streams.get(image.stream).ok_or_else(|| EditError::Invalid("the image stream is missing".into()))?;+ let op = parse(&data.1).ops.get(image.op).cloned().ok_or_else(|| EditError::Invalid("the image operation is missing".into()))?;+ let span = offset.checked_add(op.span.start).ok_or_else(|| EditError::Invalid("the image content is too large".into()))?;- let pieces = pdfcraft_content::Pieces::join(&streams.iter().map(|(_, data)| data.as_slice()).collect::<Vec<_>>());+ let pieces = joined(streams);let ops = pieces.parse().ops;- let target = ops- .iter()- .position(|op| op.span.start == span && op.is("Do"))- .ok_or_else(|| EditError::Invalid("the image operation could not be located".into()))?;+ let target = image.op;+ if !ops.get(target).is_some_and(|op| op.is("Do")) {+ return Err(EditError::Invalid("the image operation could not be located".into()));+ }let (start, end, placement) = image_transform_scope(&ops, target)?.unwrap_or((target, target, Matrix(image.draw_matrix)));let inverse = placement.invert().ok_or_else(|| EditError::Invalid("the image has no area".into()))?;- let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].map(|(x, y)| inverse.apply(x, y));+ let corners = [p00, p10, p11, p01].map(|(x, y)| inverse.apply(x, y));if !corners.iter().all(|(x, y)| x.is_finite() && y.is_finite() && x.abs() <= 1e12 && y.abs() <= 1e12) {return Err(EditError::Invalid("the crop box is too large for the image's placement".into()));}diff --cc crates/edit/src/tests.rsindex daf29de78,879ebc6c6..b219eff3f--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@@ -5041,36 -4782,102 +5571,555 @@@ fn japanese_paragraphs_wrap_between_cha}#[test]- fn test_image_move_does_not_emit_whiteout() {- let mut doc = image_page();- let imgs = images::page_images(&doc, 0).unwrap();- assert_eq!(imgs.len(), 1);- let original_rect = imgs[0].rect;-fn rewritten_paragraph_is_drawn_after_backgrounds_between_its_rows() {- // Each row has its own background box drawn immediately before its BT..ET, as cards and- // highlighted headings exported from LibreOffice or browsers do (#2377).- let card = "0 0.45 0.25 rg 60 696 240 16 re f BT /F1 10 Tf 1 1 1 rg 64 700 Td (SEMINARIO ONLINE) Tj ET \- 0 0.45 0.25 rg 60 668 240 24 re f BT /F1 16 Tf 1 1 1 rg 64 674 Td (Dalla teoria alla pratica:) Tj ET \- 0 0.45 0.25 rg 60 632 240 32 re f BT /F1 24 Tf 1 1 1 rg 64 640 Td (gestire con metodo) Tj ET \- 0 0.45 0.25 rg 60 596 240 32 re f BT /F1 24 Tf 1 1 1 rg 64 604 Td (un progetto complesso) Tj ET";- let shown_at = |ops: &[pdfcraft_content::Op], needle: &str| {- ops.iter()- .position(|op| {- matches!(op.op.as_slice(), b"Tj" | b"TJ")- && op.operands.iter().any(|o| matches!(o, Object::String(s) if String::from_utf8_lossy(&s.bytes).contains(needle)))- })- .unwrap()- };++#[test]++fn image_copy_cut_paste_keyboard_and_context_menu() {++ let mut png = Vec::new();++ image::RgbImage::from_pixel(60, 40, image::Rgb([180, 50, 50])).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.system_clipboard = false;++ app.open_bytes("picture.png", None, png.clone()).expect("opens");++ app++ });++ h.run_steps(4);++ assert!(h.state_mut().execute("edit.edit_text"));++ h.run_steps(2);++++ let id = h.state().views[0].id;++ let initial_count = h.state().session.get(id).unwrap().page_images(0).len();++ assert_eq!(initial_count, 1, "starts with 1 image");++++ let r = h.state().views[0].page_screen_rect(0).expect("on screen");++ let c = r.center();++++ // 1. Select the image++ 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(), "image selected");++++ // 2. Copy via keyboard shortcut (COMMAND+C / Event::Copy)++ h.event(egui::Event::Copy);++ h.run_steps(2);++ assert!(h.state().last_copied_image.is_some(), "image copied to clipboard buffer");++++ // 3. Paste via keyboard shortcut (COMMAND+V / Event::Paste)++ h.event(egui::Event::Paste("".into()));++ h.run_steps(3);++ let after_paste = h.state().session.get(id).unwrap().page_images(0).len();++ assert_eq!(after_paste, 2, "now has 2 images");++ assert_eq!(h.state().views[0].image_selection.as_ref().map(|s| s.index), Some(1), "new image is selected");++++ // 4. Cut via keyboard shortcut (COMMAND+X / Event::Cut)++ h.event(egui::Event::Cut);++ h.run_steps(3);++ let after_cut = h.state().session.get(id).unwrap().page_images(0).len();++ assert_eq!(after_cut, 1, "cut deleted the pasted image");++ assert!(h.state().views[0].image_selection.is_none(), "selection cleared after cut");++++ // 5. Paste again via context menu on the page++ h.hover_at(c);++ h.run_steps(1);++ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });++ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });++ h.run_steps(2);++ h.get_by_label_contains("Paste").click();++ h.run_steps(3);++ let after_paste2 = h.state().session.get(id).unwrap().page_images(0).len();++ assert_eq!(after_paste2, 2, "pasted via context menu");++}++++#[test]++fn stale_clipboard_plain_text_does_not_paste_image() {++ let mut h = harness(1, |_| {});++ h.run_steps(4);++ // Put an image into internal cache++ h.state_mut().last_copied_image = Some((10, 10, vec![0; 400]));++ h.state_mut().last_copied_file = Some(("cached.png".to_string(), vec![1, 2, 3]));++ // The text arrives in the paste event, as it does from the OS. The real system clipboard is++ // shared by every test thread, so this test doesn't write it.++ h.state_mut().system_clipboard = false;++++ // A paste event containing plain text clears internal image cache and does not paste image++ h.event(egui::Event::Paste("just plain text".into()));++ h.run_steps(2);++++ // can_paste_image should now be false because the clipboard has text, not an image!++ assert!(!h.state().can_paste_image(), "cannot paste image when the clipboard has text");++++ // paste_image should fail and return false without pasting++ assert!(!h.state_mut().paste_image(0, None), "must not paste stale cached image");++++ let doc = h.state().session.get(h.state().views[0].id).unwrap();++ assert_eq!(doc.page_images(0).len(), 0, "no image pasted on the page");++}++++#[test]++fn rotated_image_selection_and_crop() {++ 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);++ assert!(h.state_mut().execute("edit.edit_text"));++ h.run_steps(2);++ let id = h.state().views[0].id;++ let r = h.state().views[0].page_screen_rect(0).expect("on screen");++ let c = r.center();+- // Move the image to a new location- let target_rect = [original_rect[0] + 50.0, original_rect[1] + 100.0, original_rect[2] + 50.0, original_rect[3] + 100.0];- let t = images::rect_to_rect(original_rect, target_rect);- images::change_image(&mut doc, 0, 0, &images::ImageChange::Transform(t)).unwrap();- let doc = reopen(&doc);++ // Select the image++ 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");+- // Inspect the resulting PDF content stream- let bytes = page_content_bytes(&doc, 0);- let content = String::from_utf8_lossy(&bytes);++ // Right-click and rotate clockwise++ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });++ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });++ h.run_steps(2);++ h.get_by_label("Rotate Clockwise").click();++ h.run_steps(3);+- // Assert that no white fill operators were added- assert!(!content.contains("1 1 1 rg"), "must not emit white fill rgb: {content}");- assert!(!content.contains("1 g"), "must not emit white fill gray: {content}");- assert!(!content.contains("re\nf") && !content.contains("re f"), "must not emit whiteout rect fill: {content}");++ let doc = h.state().session.get(id).unwrap();++ let im_rotated = &doc.page_images(0)[0];++ assert!(im_rotated.matrix[1].abs() > 1.0 || im_rotated.matrix[2].abs() > 1.0, "matrix is rotated: {:?}", im_rotated.matrix);+- // Assert that the image's cm was cleanly updated to the new position- let moved_imgs = images::page_images(&doc, 0).unwrap();- assert_eq!(moved_imgs.len(), 1);- assert!(close(moved_imgs[0].rect, target_rect), "rect matches target: {:?}", moved_imgs[0].rect);- assert!(- content.contains(&format!("{} {} cm", moved_imgs[0].matrix[4] as i64, moved_imgs[0].matrix[5] as i64))- || content.contains("cm\n /Im0 Do")- || content.contains("cm /Im0 Do"),- "cm cleanly updated: {content}"++ // Enter crop mode with normalized bounds [0.2, 0.2, 0.8, 0.8]++ h.state_mut().views[0].image_selection.as_mut().unwrap().crop = Some(pdfcraft_ui_egui::CropMode::new([0.2, 0.2, 0.8, 0.8]));++ h.run_steps(2);++++ // Apply crop via Enter key++ h.key_press(egui::Key::Enter);++ h.run_steps(4);++++ let doc = h.state().session.get(id).unwrap();++ assert_eq!(doc.can_undo(), Some("Crop image"));++ let im_cropped = &doc.page_images(0)[0];++ assert!(im_cropped.matrix[1].abs() > 1.0 || im_cropped.matrix[2].abs() > 1.0, "matrix remains rotated: {:?}", im_cropped.matrix);++ assert!(h.state().views[0].image_selection.as_ref().is_some_and(|s| s.crop.is_none()), "crop mode ended");++}+- // 1. Editing the title rows emits all rewritten rows after all four background fills.- let mut doc = text_page(card);- assert_eq!(text::text_blocks(&doc, 0).unwrap().len(), 1);- let edited = "SEMINARIO ONLINE\nDalla teoria alla pratica:\ngestire con criterio\nun progetto nuovo";- text::rewrite_block(&mut doc, 0, 0, Some(edited), &text::BlockStyle::default()).unwrap();- let doc = reopen(&doc);- assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].editor_text, edited);- let ops = pdfcraft_content::parse(&page_content_bytes(&doc, 0)).ops;- let fills: Vec<usize> = ops.iter().enumerate().filter_map(|(i, op)| op.is("f").then_some(i)).collect();- assert_eq!(fills.len(), 4);- assert!(- shown_at(&ops, "criterio") > fills[3] && shown_at(&ops, "nuovo") > fills[3],- "rewritten title rows must be drawn after their row background fills (fills at {fills:?}): {ops:?}"- );++#[test]++fn test_image_rotated_45_deg_obb_and_proportional_scale() {++ use pdfcraft_ui_egui::ImageHandle;++ use pdfcraft_ui_egui::canvas::ImageObb;++ use std::f32::consts::FRAC_PI_4;+- // 2. Partial edit with a kept suffix row: rewritten rows 0..=2 are drawn after fills[0..=2]- // and still before kept row 3, preserving reading order.- let mut doc = text_page(card);- let partial = "WORKSHOP ONLINE\nDalla teoria alla pratica:\ngestire con criterio\nun progetto complesso";- text::rewrite_block(&mut doc, 0, 0, Some(partial), &text::BlockStyle::default()).unwrap();- let doc = reopen(&doc);- assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].editor_text, partial);- let ops = pdfcraft_content::parse(&page_content_bytes(&doc, 0)).ops;- let fills: Vec<usize> = ops.iter().enumerate().filter_map(|(i, op)| op.is("f").then_some(i)).collect();- assert!(- shown_at(&ops, "WORKSHOP") > fills[2]- && shown_at(&ops, "pratica:") > fills[2]- && shown_at(&ops, "criterio") > fills[2]- && shown_at(&ops, "criterio") < shown_at(&ops, "complesso")- && shown_at(&ops, "complesso") > fills[3],- "rewritten prefix rows must follow their fills and precede the kept final row"- );++ let center = egui::pos2(200.0, 200.0);++ let width = 100.0_f32;++ let height = 50.0_f32;++ let theta = FRAC_PI_4;+- // 3. Editing row 2 so that it wraps pushes row 3 down; all rewritten rows must follow fills[3].- let mut doc = text_page(card);- let wrapped_edit = "SEMINARIO ONLINE\nDalla teoria alla pratica:\ngestire con criterio e metodo approfondito\nun progetto complesso";- text::rewrite_block(&mut doc, 0, 0, Some(wrapped_edit), &text::BlockStyle::default()).unwrap();- let doc = reopen(&doc);- let ops = pdfcraft_content::parse(&page_content_bytes(&doc, 0)).ops;- let last_fill = ops.iter().rposition(|op| op.is("f")).unwrap();- assert!(- shown_at(&ops, "approfondito") > last_fill && shown_at(&ops, "complesso") > last_fill,- "wrapped rows and pushed-down suffix row must follow all row background fills"- );++ let obb = ImageObb::from_center_size_angle(center, width, height, theta);+- // 4. Single-style paragraph path across a CTM change between rows, with movement, underline,- // and a trailing unrelated line sharing the second row's BT..ET.- let cross_ctm = "0.9 0.9 0.2 rg 60 696 240 18 re f BT /F1 12 Tf 0 0 0 rg 64 700 Td (First highlighted row) Tj ET \- q 1 0 0 1 10 12 cm 0.9 0.9 0.2 rg 50 668 240 18 re f \- BT /F1 12 Tf 0 0 0 rg 54 672 Td (Second highlighted row) Tj 246 -40 Td (Side footer) Tj ET Q";- let mut doc = text_page(cross_ctm);- let para = text::text_blocks(&doc, 0).unwrap().into_iter().position(|b| b.text.starts_with("First highlighted")).unwrap();- assert_eq!(text::text_blocks(&doc, 0).unwrap()[para].rows.len(), 2);- text::rewrite_block(- &mut doc,- 0,- para,- Some("Updated first highlighted row and updated second highlighted row"),- &text::BlockStyle { offset: Some([6.0, -4.0]), underline: Some(true), ..Default::default() },- )- .unwrap();- let doc = reopen(&doc);- let ops = pdfcraft_content::parse(&page_content_bytes(&doc, 0)).ops;- let last_fill = ops.iter().rposition(|op| op.is("f")).unwrap();- assert!(- shown_at(&ops, "Updated first") > last_fill && shown_at(&ops, "Side footer") > shown_at(&ops, "Updated first"),- "cross-CTM single-style rewrite must follow both background fills and precede the shared BT's trailing line"- );- let lines = text::text_lines(&doc, 0).unwrap();- let updated_first = lines.iter().find(|l| l.text.starts_with("Updated first")).unwrap();- let side_footer = lines.iter().find(|l| l.text == "Side footer").unwrap();- assert!(- (updated_first.baseline()[0] - 70.0).abs() < 0.01 && (updated_first.baseline()[1] - 696.0).abs() < 0.01,- "offset baseline in user space across CTM: {:?}",- updated_first.baseline()- );- assert!(- (side_footer.baseline()[0] - 310.0).abs() < 0.01 && (side_footer.baseline()[1] - 644.0).abs() < 0.01,- "trailing line in shared BT keeps its tlm across CTM: {:?}",- side_footer.baseline()++ // 1. Verify it outputs an OBB (not an AABB):++ assert!(obb.is_rotated);++ let corners = obb.corners();++ assert!((corners[0].x - corners[1].x).abs() > 1.0);++ assert!((corners[0].y - corners[1].y).abs() > 1.0);++ assert!((corners[1].x - corners[2].x).abs() > 1.0);++ assert!((corners[1].y - corners[2].y).abs() > 1.0);++++ let edge_u = (corners[1] - corners[0]).length();++ let edge_v = (corners[3] - corners[0]).length();++ assert!((edge_u - width).abs() < 1e-4, "edge_u={edge_u}, width={width}");++ assert!((edge_v - height).abs() < 1e-4, "edge_v={edge_v}, height={height}");++++ let dot = (corners[1] - corners[0]).dot(corners[3] - corners[0]);++ assert!(dot.abs() < 1e-4, "adjacent edges must be perpendicular for OBB");++++ let handles = obb.handles();++ assert_eq!(handles.len(), 8);++++ // 2. Drag TopRight handle with a pointer delta along local axes:++ let delta = egui::vec2(10.0 * theta.cos(), 10.0 * theta.sin());++ let anchor_before = obb.s00;++++ let scaled_obb = obb.scale_proportional(ImageHandle::TopRight, delta, 5.0);++++ // The diagonally opposite corner (s00) MUST remain locked as the fixed anchor point:++ assert!((scaled_obb.s00.x - anchor_before.x).abs() < 1e-4);++ assert!((scaled_obb.s00.y - anchor_before.y).abs() < 1e-4);++++ // Dimensions scale proportionally along local axes (aspect ratio preserved):++ let new_aspect = scaled_obb.width / scaled_obb.height;++ let old_aspect = width / height;++ assert!((new_aspect - old_aspect).abs() < 1e-4, "aspect ratio preserved: {new_aspect} vs {old_aspect}");++ assert!(scaled_obb.width > width, "width increased");++ assert!(scaled_obb.height > height, "height increased proportionally");++++ // Rotation angle is preserved without skewing:++ assert!((scaled_obb.theta - theta).abs() < 1e-4);++}++++trait RectExt {++ fn width(&self) -> f64;++}++++impl RectExt for [f64; 4] {++ fn width(&self) -> f64 {++ (self[2] - self[0]).abs()++ }++}++++impl RectExt for egui::Rect {++ fn width(&self) -> f64 {++ f64::from(self.width())++ }++}++++#[test]++fn test_image_8_handles_render_and_drag() {++ let mut png = Vec::new();++ image::RgbImage::from_pixel(100, 100, image::Rgb([100, 150, 200]))++ .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("square.png", None, png.clone()).expect("opens");++ app++ });++ h.run_steps(4);++ 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 image++ 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");++++ let view = &h.state().views[0];++ let sel = view.image_selection.as_ref().unwrap();++ let doc = h.state().session.get(view.id).unwrap();++ let img = &doc.page_images(sel.page)[sel.index];++ let xf =++ pdfcraft_ui_egui::canvas::PageXform { rect: r, rot: view.rotation, pw: doc.info.pages[sel.page].width, ph: doc.info.pages[sel.page].height };++ let obb = pdfcraft_ui_egui::canvas::ImageObb::from_image(img, &xf, &doc.info, sel.page);++++ // Assert that exactly 8 unique resize handles (4 corners, 4 midpoints) are generated++ let handles = obb.handles();++ assert_eq!(handles.len(), 8, "exactly 8 resize handles generated");++++ let corners = [++ pdfcraft_ui_egui::ImageHandle::TopLeft,++ pdfcraft_ui_egui::ImageHandle::TopRight,++ pdfcraft_ui_egui::ImageHandle::BottomRight,++ pdfcraft_ui_egui::ImageHandle::BottomLeft,++ ];++ let midpoints = [++ pdfcraft_ui_egui::ImageHandle::TopCenter,++ pdfcraft_ui_egui::ImageHandle::RightCenter,++ pdfcraft_ui_egui::ImageHandle::BottomCenter,++ pdfcraft_ui_egui::ImageHandle::LeftCenter,++ ];++ for corner in &corners {++ assert!(handles.iter().any(|(h, _)| h == corner), "missing corner handle: {:?}", corner);++ }++ for midpoint in &midpoints {++ assert!(handles.iter().any(|(h, _)| h == midpoint), "missing midpoint handle: {:?}", midpoint);++ }++++ for i in 0..8 {++ for j in (i + 1)..8 {++ assert!((handles[i].1 - handles[j].1).length() > 1.0, "handles {} and {} must be unique positions", i, j);++ }++ }++++ // Simulate a pointer drag on a corner that shrinks the image to 5x5 pixels and assert it does not panic++ let tr_pos = obb.handle_pos(pdfcraft_ui_egui::ImageHandle::TopRight);++ let anchor = obb.s00;++ let shrink_target = anchor + egui::vec2(5.0, 5.0);++ h.hover_at(tr_pos);++ h.run_steps(1);++ h.drag_at(tr_pos);++ h.run_steps(1);++ h.hover_at(shrink_target);++ h.run_steps(2);++ h.drop_at(shrink_target);++ h.run_steps(4);++}++++#[test]++fn test_image_context_menu_precedence() {++ 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);++ 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 image++ 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");++++ // Simulate a secondary click strictly inside an image's bounds++ h.hover_at(c);++ h.run_steps(1);++ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });++ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });++ h.run_steps(2);++++ // Assert that the image widget consumes the click and the canvas background menu does not trigger++ h.get_by_label("Rotate Clockwise");++ h.get_by_label("Flip horizontal");++ assert!(h.query_all_by_label("Rotate view clockwise").next().is_none(), "canvas background menu must not trigger");++ assert!(h.query_all_by_label("Add bookmark").next().is_none(), "canvas background menu must not trigger");++ assert!(h.query_all_by_label("Take a snapshot").next().is_none(), "canvas background menu must not trigger");++}++++#[test]++fn test_crop_updates_rect_instantly() {++ let mut png = Vec::new();++ image::RgbImage::from_pixel(100, 50, image::Rgb([100, 150, 200])).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("form.pdf", None, include_bytes!("data/form.pdf").to_vec()).unwrap();++ app++ });++ h.run_steps(4);++ assert!(h.state_mut().execute("edit.text"));++ h.run_steps(2);++++ // Add image via content_ui++ h.state_mut().add_image("logo.png".into(), png);++ h.run_steps(3);++++ let id = h.state().views[0].id;++ let initial_img = match &h.state().session.get(id).unwrap().added()[0].content {++ pdfcraft_engine::AddedContent::Image(img) => img.clone(),++ _ => panic!("expected AddedContent::Image"),++ };++ let initial_w = initial_img.rect.width();++++ // Trigger a crop event that removes 50% of an image's width++ let mut cropped = initial_img.clone();++ pdfcraft_ui_egui::content_ui::update_image_crop(&mut cropped, [0.5, 0.0, 0.0, 0.0]);++ let update_edit = pdfcraft_engine::Edit::UpdateContent { page: 0, index: 0, content: pdfcraft_engine::AddedContent::Image(cropped) };++ h.state_mut().apply_edit(update_edit);++++ // Assert that in the immediate next frame, the image.rect.width() is exactly 50% of the original, with no padding left over++ h.run_steps(1);++ let doc = h.state().session.get(id).unwrap();++ let img = match &doc.added()[0].content {++ pdfcraft_engine::AddedContent::Image(img) => img.clone(),++ _ => panic!("expected AddedContent::Image"),++ };++ let w = img.rect.width();++ let expected_w = initial_w * 0.5;++ assert!((w - expected_w).abs() < 1e-3, "image.rect.width() must be exactly 50% ({expected_w}), got {w}");++}++++#[test]++fn crop_action_pills_interactive_and_apply_cancel_reset() {++ let mut png = Vec::new();++ image::RgbImage::from_pixel(100, 100, image::Rgb([100, 150, 200]))++ .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("square.png", None, png.clone()).expect("opens");++ app++ });++ h.run_steps(4);++ 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 image++ 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());++++ // Enter crop mode++ let doc_id = h.state().views[0].id;++ let original_rect = h.state().session.get(doc_id).unwrap().page_images(0)[0].rect;++ h.state_mut().views[0].image_selection.as_mut().unwrap().crop = Some(pdfcraft_ui_egui::CropMode::new(original_rect));++ h.state_mut().views[0].image_selection.as_mut().unwrap().crop_mode = true;++ h.run_steps(2);++++ // Set smaller crop rect (50x50 in center)++ let smaller = egui::Rect::from_center_size(c, egui::vec2(50.0, 50.0));++ h.state_mut().views[0].image_selection.as_mut().unwrap().crop_rect = Some(smaller);++ h.run_steps(2);++++ let pill_y = smaller.max.y + 17.0;++ let done_pos = egui::pos2(smaller.max.x - 20.0, pill_y);++ h.hover_at(done_pos);++ h.run_steps(1);++ assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand, "Done pill has PointingHand cursor");++++ let cancel_pos = egui::pos2(smaller.max.x - 85.0, pill_y);++ h.hover_at(cancel_pos);++ h.run_steps(1);++ assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand, "Cancel pill has PointingHand cursor");++++ // Click Cancel pill: exits crop mode without applying changes++ click_at(&mut h, cancel_pos);++ h.run_steps(3);++ assert!(h.state().views[0].image_selection.as_ref().is_some_and(|s| s.crop.is_none() && !s.crop_mode), "Cancel exits crop mode");++ assert_eq!(h.state().session.get(doc_id).unwrap().page_images(0)[0].visible_rect, Some(original_rect), "image is uncropped");++++ // Re-enter crop mode and set crop rect++ h.state_mut().views[0].image_selection.as_mut().unwrap().crop = Some(pdfcraft_ui_egui::CropMode::new(original_rect));++ h.state_mut().views[0].image_selection.as_mut().unwrap().crop_mode = true;++ h.state_mut().views[0].image_selection.as_mut().unwrap().crop_rect = Some(smaller);++ h.run_steps(2);++++ // Click "Remove Crop" pill++ let reset_pos = egui::pos2(smaller.max.x - 170.0, pill_y);++ h.hover_at(reset_pos);++ h.run_steps(1);++ assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand, "Remove Crop pill has PointingHand cursor");++ click_at(&mut h, reset_pos);++ h.run_steps(2);++ let current_keep = h.state().views[0].image_selection.as_ref().unwrap().crop.as_ref().unwrap().keep;++ assert_eq!(current_keep, original_rect, "Remove Crop restored crop to full bounds");++++ // Re-set smaller crop and click "Done" pill to apply++ h.state_mut().views[0].image_selection.as_mut().unwrap().crop_rect = Some(smaller);++ h.run_steps(2);++ let done_pos_after = egui::pos2(smaller.max.x - 20.0, pill_y);++ click_at(&mut h, done_pos_after);++ h.run_steps(4);++++ assert!(h.state().views[0].image_selection.as_ref().is_some_and(|s| s.crop.is_none() && !s.crop_mode), "Done exits crop mode");++ let after_images = h.state().session.get(doc_id).unwrap().page_images(0);++ assert_ne!(after_images[0].visible_rect, Some(original_rect), "crop was applied");++}++++#[test]++fn test_cropped_image_selection_and_bounding_box() {++ let mut png = Vec::new();++ image::RgbImage::from_pixel(100, 100, image::Rgb([100, 150, 200]))++ .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("square.png", None, png.clone()).expect("opens");++ app++ });++ h.run_steps(4);++++ let doc_id = h.state().views[0].id;++ let full_rect = h.state().session.get(doc_id).unwrap().page_images(0)[0].rect;++++ // Apply crop to the center quarter: [0.25, 0.25, 0.75, 0.75]++ let crop_keep = [++ full_rect[0] + (full_rect[2] - full_rect[0]) * 0.25,++ full_rect[1] + (full_rect[3] - full_rect[1]) * 0.25,++ full_rect[0] + (full_rect[2] - full_rect[0]) * 0.75,++ full_rect[1] + (full_rect[3] - full_rect[1]) * 0.75,++ ];++ h.state_mut().apply_edit(pdfcraft_engine::Edit::EditPageImage { page: 0, index: 0, change: pdfcraft_engine::ImageEdit::Crop(crop_keep) });++ h.run_steps(4);++++ let img = &h.state().session.get(doc_id).unwrap().page_images(0)[0];++ assert_eq!(img.rect, full_rect, "underlying CTM rect is non-destructively preserved");++ let vis = img.visible_rect.expect("has visible_rect");++ assert!((vis[0] - crop_keep[0]).abs() < 1e-3);++ assert!((vis[1] - crop_keep[1]).abs() < 1e-3);++ assert!((vis[2] - crop_keep[2]).abs() < 1e-3);++ assert!((vis[3] - crop_keep[3]).abs() < 1e-3);++++ // Verify selectable bounds helper gives the cropped intersection++ assert_eq!(pdfcraft_ui_egui::canvas::image_selectable_bounds(img), vis);++++ // Select tool (mouse tool)++ h.state_mut().quick_tool = pdfcraft_ui_egui::QuickTool::Select;++ h.run_steps(2);++++ let page_rect = h.state().views[0].page_screen_rect(0).expect("on screen");++ // Center point is inside the cropped area:++ let center = page_rect.center();++ click_at(&mut h, center);++ h.run_steps(2);++++ let picked = h.state().views[0].picked_image.expect("image is picked when clicking inside crop");++ assert_eq!(picked.page, 0);++ assert_eq!(picked.index, 0);++ // The selection bounding box wraps the visible cropped area, NOT the full CTM rect!++ assert_eq!(picked.rect, vis, "picked rect wraps the cropped bounds");++++ // Deselect++ h.key_press(egui::Key::Escape);++ h.run_steps(2);++ assert!(h.state().views[0].picked_image.is_none());++++ // Corner point (e.g. top-left corner of the page) is outside the crop box but inside full CTM rect++ let corner = page_rect.min + egui::vec2(10.0, 10.0);++ click_at(&mut h, corner);++ h.run_steps(2);++ assert!(h.state().views[0].picked_image.is_none(), "clicking cropped-away region must not hit-test or select the image");++}++++/// The Read mode command (not the mode bar) applies a paragraph still open in the editor, as++/// putting the Edit text tool down does; left open, it would stay drawn in Read mode with no tool.++#[test]++fn read_mode_shortcut_applies_the_open_paragraph() {++ use pdfcraft_ui_egui::{Mode, QuickTool};++ let mut h = harness(1, |_| {});++ assert!(h.state_mut().execute("edit.edit_text"));++ h.run_steps(2);++ // The line "Page 1" sits at (20, 150) on a 200 × 300 page, 24 pt.++ 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());++ h.hover_at(at);++ h.run_steps(1);++ h.drag_at(at);++ h.run_steps(1);++ h.drop_at(at);++ h.run_steps(3);++ assert!(h.state().views[0].line_editor.is_some(), "the line opens for editing");++ h.state_mut().views[0].line_editor.as_mut().unwrap().text = "Chapter One".into();++ h.run_steps(1);++ h.state_mut().run_command("view.read_mode");++ h.run_steps(3);++ let s = h.state();++ assert_eq!(s.mode, Mode::Read);++ assert_eq!(s.quick_tool, QuickTool::Select);++ assert!(s.views[0].line_editor.is_none(), "no editor stays open in Read mode");++ assert_eq!(s.session.get(s.views[0].id).unwrap().text_lines(0)[0].text, "Chapter One", "the edit is applied");++});}diff --cc crates/ui-egui/src/canvas.rsindex bef745197,eb9244a28..f8e40e4de--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@ -1464,14 -1056,9 +1489,15 @@@ impl DocViewself.texts.get(&page).cloned()}+ /// Whether `page`'s text layer has arrived from the renderer. Selecting text, the I-beam and+ /// find matches on a page all wait for it (tests and automation).+ pub fn has_page_text(&self, page: usize) -> bool {+ self.texts.contains_key(&page)+ }+pub(crate) fn clear_selection(&mut self) {self.selection = None;+ self.actions_dismissed = None;}/// Select text on `page` from glyph `from` to glyph `to` (tests and automation).@@@ -5837,10 -5314,21 +6065,23 @@@ fn grayscale(mut img: egui::ColorImageimg}+pub use crate::image_engine::{HandleId, MIN_RECT_SIZE, apply_crop, apply_resize, apply_resize_proportional, reset_crop};+#[cfg(test)]mod tests {+ #[test]+ fn zoom_anchor_scroll_stays_within_the_content() {+ let (content, viewport) = (vec2(1000.0, 2000.0), vec2(800.0, 600.0));+ // Past the end: clamped to the maximum (200, 1400), not left for egui to snap back.+ assert_eq!(anchored_scroll(pos2(900.0, 1900.0), vec2(0.0, 0.0), content, viewport), vec2(200.0, 1400.0));+ // Before the start.+ assert_eq!(anchored_scroll(pos2(10.0, 10.0), vec2(300.0, 300.0), content, viewport), Vec2::ZERO);+ // Inside: unchanged.+ assert_eq!(anchored_scroll(pos2(150.0, 800.0), vec2(100.0, 100.0), content, viewport), vec2(50.0, 700.0));+ // Content smaller than the viewport: no scrolling.+ assert_eq!(anchored_scroll(pos2(400.0, 400.0), Vec2::ZERO, vec2(500.0, 500.0), viewport), vec2(0.0, 0.0));+ }+#[test]fn page_size_hint_zone_is_the_bottom_left_quadrant() {let area = Rect::from_min_max(pos2(100.0, 50.0), pos2(500.0, 450.0));diff --cc crates/ui-egui/src/editing.rsindex 7c2553cdf,91480ac7b..0aece231b--- a/crates/ui-egui/src/editing.rs+++ b/crates/ui-egui/src/editing.rs@@@ -972,9 -1001,9 +1001,12 @@@ fn is_form_edit(edit: &Edit) -> bool/// classic Outlook (`Temporary Internet Files\Content.Outlook\` on older Windows), and the/// `Microsoft.OutlookForWindows` package folder for the new Outlook. Saving there either fails,/// because Outlook can still hold the file, or appears to work while the edits stay out of the+/// email and are deleted with the cache. Matched on either separator and in any case, so it can+/// be tested on every platform.+#[allow(dead_code)]+ /// email and are deleted with the cache. Apple Mail opens one from `Mail Downloads/<UUID>/` in+ /// its sandbox container, where other apps can't write, so saving there fails (#2751). Matched on+ /// either separator and in any case, so it can be tested on every platform.pub(crate) fn is_mail_temp_copy(path: &str) -> bool {let p = path.replace('\\', "/").to_ascii_lowercase();p.contains("/inetcache/content.outlook/")diff --cc crates/ui-egui/src/image_pick.rsindex 0dc879d09,53e4bdf15..51cd161b2--- a/crates/ui-egui/src/image_pick.rs+++ b/crates/ui-egui/src/image_pick.rs@@@ -43,17 -45,19 +45,36 @@@ pub(crate) fn page_inputlet (vx, vy) = xf.screen_to_view(p);let u = info_page.view_to_user(vx, vy);let at = [f64::from(u[0]), f64::from(u[1])];+ view.picked_image = doc.page_image_at(page, at).and_then(|index| {+ doc.page_images(page).get(index).and_then(|i| {+ let screen_rect = crate::canvas::image_screen_rect(i, xf, info, page);+ if screen_rect.is_positive() && screen_rect.contains(p) {+ Some(PickedImage { page, index, rect: crate::canvas::image_selectable_bounds(i) })+ } else {+ None+ }+ })+ });- }+ let generation = doc.edit_generation();- view.picked_image =- doc.page_image_at(page, at).and_then(|index| doc.page_images(page).get(index).map(|i| PickedImage { page, index, rect: i.rect, generation }));-}--/// Forget the selected picture once the document has been edited since it was picked: Edit text &-/// images (or Undo) may have deleted or moved it, and its highlight would stay behind on an empty-/// spot of the page.-pub(crate) fn drop_stale(doc: &pdfcraft_engine::Document, view: &mut DocView) {- if view.picked_image.is_some_and(|p| p.generation != doc.edit_generation()) {- view.picked_image = None;++ view.picked_image = doc.page_image_at(page, at).and_then(|index| {++ doc.page_images(page).get(index).and_then(|i| {++ let screen_rect = crate::canvas::image_screen_rect(i, xf, info, page);++ if screen_rect.is_positive() && screen_rect.contains(p) {++ Some(PickedImage { page, index, rect: crate::canvas::image_selectable_bounds(i), generation })++ } else {++ None++ }++ })++ });+ }-}++++ /// Forget the selected picture once the document has been edited since it was picked: Edit text &++ /// images (or Undo) may have deleted or moved it, and its highlight would stay behind on an empty++ /// spot of the page.++ pub(crate) fn drop_stale(doc: &pdfcraft_engine::Document, view: &mut DocView) {++ if view.picked_image.is_some_and(|p| p.generation != doc.edit_generation()) {++ view.picked_image = None;++ }/// The selected picture's highlight on page `page`.pub(crate) fn paint(painter: &egui::Painter, xf: &PageXform, page: usize, info: &DocInfo, view: &DocView) {diff --cc crates/ui-egui/src/panels.rsindex 301df9d17,0f2c60149..95a620c43--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@@ -414,170 -381,44 +414,160 @@@ fn format_section(app: &mut PdfCraftApplet mut ed = ed;let mut changed = false;let font_choices = app.session.get(app.views[i].id).map(|d| d.text_editor_fonts(ed.page)).unwrap_or_default();- egui::ComboBox::from_id_salt("document-font-resource")- .selected_text(- ed.font_resource- .as_ref()- .and_then(|r| font_choices.iter().find(|f| &f.resource == r))- .map_or(tl!("Keep source fonts"), |f| f.face.as_str()),- )- .show_ui(ui, |ui| {- changed |= ui.selectable_value(&mut ed.font_resource, None, tl!("Keep source fonts")).changed();- for font in font_choices.iter().filter(|f| !f.resource.starts_with("PCApproved")) {- changed |= ui.selectable_value(&mut ed.font_resource, Some(font.resource.clone()), &font.face).changed();+ let current_font_label = if let Some(r) = ed.font_resource.as_ref() {+ font_choices.iter().find(|f| &f.resource == r).map_or_else(|| r.clone(), |f| f.face.clone())+ } else if ed.look.family != pdfcraft_engine::FontFamily::Helvetica {+ ed.look.family.label().to_string()+ } else {+ tl!("Keep source fonts").to_string()+ };++ crate::widgets::section_title(ui, "FORMAT TEXT");+ egui::ComboBox::from_id_salt("text-font-dropdown").selected_text(current_font_label).width(ui.available_width().max(180.0)).show_ui(+ ui,+ |ui| {+ if ui.selectable_label(ed.font_resource.is_none(), tl!("Keep source fonts")).clicked() {+ ed.font_resource = None;+ changed = true;}- });- if ui.button(tl!("Load font…")).clicked() {- app.pick_files(crate::files::FilePurpose::TextFont { page: ed.page }, false);- }- #[cfg(not(target_arch = "wasm32"))]- egui::ComboBox::from_id_salt("installed-document-font").selected_text(tl!("Installed fonts…")).show_ui(ui, |ui| {- if let Some(fonts) = crate::files::installed_font_files(ui.ctx()) {- if fonts.is_empty() {- ui.label(tl!("No openly licensed document fonts found. Load a font file."));+ if !font_choices.is_empty() {+ ui.separator();+ ui.label(egui::RichText::new("Document fonts").weak().small());+ for font in font_choices.iter().filter(|f| !f.resource.starts_with("PCApproved")) {+ let is_current = ed.font_resource.as_ref() == Some(&font.resource);+ if ui.selectable_label(is_current, &font.face).clicked() {+ ed.font_resource = Some(font.resource.clone());+ changed = true;+ }+ }}- for font in fonts {- if ui.selectable_label(false, &font.face).clicked() {- app.use_paths(crate::files::FilePurpose::TextFont { page: ed.page }, &[font.path]);+ ui.separator();+ ui.label(egui::RichText::new("Standard fonts").weak().small());+ for f in [pdfcraft_engine::FontFamily::Helvetica, pdfcraft_engine::FontFamily::Times, pdfcraft_engine::FontFamily::Courier] {+ let is_current = ed.font_resource.is_none() && ed.look.family == f;+ if ui.selectable_label(is_current, f.label()).clicked() {+ ed.font_resource = None;+ ed.look.family = f;+ changed = true;}}- } else {- ui.label(tl!("Finding document fonts…"));+ #[cfg(not(target_arch = "wasm32"))]+ {+ ui.separator();+ ui.label(egui::RichText::new("Installed fonts").weak().small());+ if let Some(installed) = crate::files::installed_font_files(ui.ctx()) {+ if installed.is_empty() {+ ui.label(egui::RichText::new("No installed fonts found.").weak().small());+ } else {+ for font in &installed {+ let is_current =+ ed.font_resource.as_ref().is_some_and(|r| font_choices.iter().any(|f| &f.resource == r && f.face == font.face));+ if ui.selectable_label(is_current, &font.face).clicked()+ && let Ok(bytes) = std::fs::read(&font.path)+ {+ let edit = pdfcraft_engine::Edit::RegisterTextFont { page: ed.page, bytes: std::sync::Arc::new(bytes.clone()) };+ if app.apply_edit(edit)+ && let Some(doc) = app.session.get(app.views[i].id)+ {+ if let Some(f) = doc.text_editor_fonts(ed.page).into_iter().find(|f| f.bytes == bytes) {+ ed.font_resource = Some(f.resource);+ changed = true;+ }+ ed.fonts = crate::edit_text_ui::install_source_fonts(ui.ctx(), doc, ed.page);+ }+ }+ }+ }+ } else {+ ui.label(egui::RichText::new("Finding installed fonts…").weak().small());+ }+ }+ ui.separator();+ if ui.button("Load font from file…").clicked() {+ app.pick_files(crate::files::FilePurpose::TextFont { page: ed.page }, false);+ }+ },+ );++ ui.horizontal(|ui| {+ // Font size ComboBox+ egui::ComboBox::from_id_salt("font-size").selected_text(format!("{:.1}", ed.look.size)).width(55.0).show_ui(ui, |ui| {+ for size in [6.0, 8.0, 9.0, 10.0, 10.5, 11.0, 12.0, 14.0, 16.0, 18.0, 20.0, 24.0, 28.0, 36.0, 48.0, 72.0] {+ changed |= ui.selectable_value(&mut ed.look.size, size, format!("{size}")).changed();+ }+ });+ // Color swatch square+ let (color_rect, color_resp) = ui.allocate_exact_size(egui::vec2(20.0, 20.0), egui::Sense::click());+ let color_val = crate::comments::color32(ed.look.color);+ ui.painter().rect_filled(color_rect, t.radius, color_val);+ ui.painter().rect_stroke(color_rect, t.radius, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside);+ let show_palette_id = ui.id().with("show-palette");+ let mut show_palette = ui.data(|d| d.get_temp::<bool>(show_palette_id)).unwrap_or(false);+ if color_resp.on_hover_text("Text color").clicked() {+ show_palette = !show_palette;+ ui.data_mut(|d| d.insert_temp(show_palette_id, show_palette));+ }+ ui.add_space(2.0);+ // Bullet list button+ let is_bullet = crate::edit_text_ui::is_bulleted(&ed.text);+ if crate::icons::button(ui, "list", 24.0, is_bullet, "Bullet list").clicked() {+ changed |= crate::edit_text_ui::toggle_bullet_list(&mut ed.text);+ }+ // Numbered list button+ let is_num = crate::edit_text_ui::is_numbered(&ed.text);+ if crate::icons::button(ui, "list-ordered", 24.0, is_num, "Numbered list").clicked() {+ changed |= crate::edit_text_ui::toggle_numbered_list(&mut ed.text);+ }+ ui.add_space(2.0);+ // Alignment buttons+ for (a, icon, tip) in [+ (pdfcraft_engine::TextAlign::Left, "align-left", tl!("Align left")),+ (pdfcraft_engine::TextAlign::Center, "align-center", tl!("Centre")),+ (pdfcraft_engine::TextAlign::Right, "align-right", tl!("Align right")),+ (pdfcraft_engine::TextAlign::Justify, "align-justify", tl!("Justify")),+ ] {+ if crate::icons::button(ui, icon, 24.0, ed.look.align == a, tip).clicked() {+ ed.look.align = a;+ changed = true;+ }}});- if let Some(look) = crate::content_ui::format_panel(ui, t, &ed.look) {- ed.look = look;++ // Color Swatch Grid (when toggled or open)+ let show_palette_id = ui.id().with("show-palette");+ if ui.data(|d| d.get_temp::<bool>(show_palette_id)).unwrap_or(false)+ && let Some(picked) = crate::comments::swatch_grid(ui, Some(ed.look.color))+ {+ ed.look.color = picked;changed = true;}++ // Formatting Buttons: Bold, Italic, Underline, Superscript, Subscript+ ui.horizontal(|ui| {+ let b_resp = ui.selectable_label(ed.look.bold, egui::RichText::new("B").strong()).on_hover_text(tl!("Bold"));+ if b_resp.clicked() {+ ed.look.bold = !ed.look.bold;+ changed = true;+ }+ let i_resp = ui.selectable_label(ed.look.italic, egui::RichText::new("I").italics()).on_hover_text(tl!("Italic"));+ if i_resp.clicked() {+ ed.look.italic = !ed.look.italic;+ changed = true;+ }+ let sup_resp = ui.selectable_label(false, egui::RichText::new("T¹").size(13.0)).on_hover_text("Superscript");+ if sup_resp.clicked() {+ changed |= crate::edit_text_ui::toggle_superscript(&mut ed);+ }+ let sub_resp = ui.selectable_label(false, egui::RichText::new("T₁").size(13.0)).on_hover_text("Subscript");+ if sub_resp.clicked() {+ changed |= crate::edit_text_ui::toggle_subscript(&mut ed);+ }+ });++ // Spacing: Value-based line spacing, paragraph spacing, horizontal scale, character spacingchanged |= crate::edit_text_ui::extras_panel(ui, &mut ed.extras);if changed {- let edit = pdfcraft_engine::Edit::EditTextBlock { page: ed.page, block: ed.block, text: ed.text.clone(), style: ed.style() };- if app.apply_edit(edit) {- ed.applied();- if let Some(doc) = app.session.get(app.views[i].id)- && let Some(block) = doc.text_blocks(ed.page).get(ed.block)- {- ed.refresh_source(block, doc.text_lines(ed.page));- ed.fonts = crate::edit_text_ui::install_source_fonts(ui.ctx(), doc, ed.page);- }- }- app.views[i].line_editor = Some(ed);+ app.apply_line_format(i, ed, Some(ui.ctx()));}ui.add_space(6.0);ui.separator();diff --cc crates/ui-egui/tests/editing.rsindex cb7d4a0ec,d41041e52..3273c257e--- a/crates/ui-egui/tests/editing.rs+++ b/crates/ui-egui/tests/editing.rs@@@ -4910,523 -4877,31 +5113,553 @@@ fn leaving_organize_goes_back_to_the_woassert_eq!(h.state().left, LeftPanel::AllTools);}+#[test]+fn image_copy_cut_paste_keyboard_and_context_menu() {+ let mut png = Vec::new();+ image::RgbImage::from_pixel(60, 40, image::Rgb([180, 50, 50])).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.system_clipboard = false;+ app.open_bytes("picture.png", None, png.clone()).expect("opens");+ app+ });+ h.run_steps(4);+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(2);++ let id = h.state().views[0].id;+ let initial_count = h.state().session.get(id).unwrap().page_images(0).len();+ assert_eq!(initial_count, 1, "starts with 1 image");++ let r = h.state().views[0].page_screen_rect(0).expect("on screen");+ let c = r.center();++ // 1. Select the image+ 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(), "image selected");++ // 2. Copy via keyboard shortcut (COMMAND+C / Event::Copy)+ h.event(egui::Event::Copy);+ h.run_steps(2);+ assert!(h.state().last_copied_image.is_some(), "image copied to clipboard buffer");++ // 3. Paste via keyboard shortcut (COMMAND+V / Event::Paste)+ h.event(egui::Event::Paste("".into()));+ h.run_steps(3);+ let after_paste = h.state().session.get(id).unwrap().page_images(0).len();+ assert_eq!(after_paste, 2, "now has 2 images");+ assert_eq!(h.state().views[0].image_selection.as_ref().map(|s| s.index), Some(1), "new image is selected");++ // 4. Cut via keyboard shortcut (COMMAND+X / Event::Cut)+ h.event(egui::Event::Cut);+ h.run_steps(3);+ let after_cut = h.state().session.get(id).unwrap().page_images(0).len();+ assert_eq!(after_cut, 1, "cut deleted the pasted image");+ assert!(h.state().views[0].image_selection.is_none(), "selection cleared after cut");++ // 5. Paste again via context menu on the page+ h.hover_at(c);+ h.run_steps(1);+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });+ h.run_steps(2);+ h.get_by_label_contains("Paste").click();+ h.run_steps(3);+ let after_paste2 = h.state().session.get(id).unwrap().page_images(0).len();+ assert_eq!(after_paste2, 2, "pasted via context menu");+}++#[test]+fn stale_clipboard_plain_text_does_not_paste_image() {+ let mut h = harness(1, |_| {});+ h.run_steps(4);+ // Put an image into internal cache+ h.state_mut().last_copied_image = Some((10, 10, vec![0; 400]));+ h.state_mut().last_copied_file = Some(("cached.png".to_string(), vec![1, 2, 3]));+ // The text arrives in the paste event, as it does from the OS. The real system clipboard is+ // shared by every test thread, so this test doesn't write it.+ h.state_mut().system_clipboard = false;++ // A paste event containing plain text clears internal image cache and does not paste image+ h.event(egui::Event::Paste("just plain text".into()));+ h.run_steps(2);++ // can_paste_image should now be false because the clipboard has text, not an image!+ assert!(!h.state().can_paste_image(), "cannot paste image when the clipboard has text");++ // paste_image should fail and return false without pasting+ assert!(!h.state_mut().paste_image(0, None), "must not paste stale cached image");++ let doc = h.state().session.get(h.state().views[0].id).unwrap();+ assert_eq!(doc.page_images(0).len(), 0, "no image pasted on the page");+}++#[test]+fn rotated_image_selection_and_crop() {+ 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);+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(2);+ let id = h.state().views[0].id;+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");+ let c = r.center();++ // Select the image+ 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");++ // Right-click and rotate clockwise+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });+ h.run_steps(2);+ h.get_by_label("Rotate Clockwise").click();+ h.run_steps(3);++ let doc = h.state().session.get(id).unwrap();+ let im_rotated = &doc.page_images(0)[0];+ assert!(im_rotated.matrix[1].abs() > 1.0 || im_rotated.matrix[2].abs() > 1.0, "matrix is rotated: {:?}", im_rotated.matrix);++ // Enter crop mode with normalized bounds [0.2, 0.2, 0.8, 0.8]+ h.state_mut().views[0].image_selection.as_mut().unwrap().crop = Some(pdfcraft_ui_egui::CropMode::new([0.2, 0.2, 0.8, 0.8]));+ h.run_steps(2);++ // Apply crop via Enter key+ h.key_press(egui::Key::Enter);+ h.run_steps(4);++ let doc = h.state().session.get(id).unwrap();+ assert_eq!(doc.can_undo(), Some("Crop image"));+ let im_cropped = &doc.page_images(0)[0];+ assert!(im_cropped.matrix[1].abs() > 1.0 || im_cropped.matrix[2].abs() > 1.0, "matrix remains rotated: {:?}", im_cropped.matrix);+ assert!(h.state().views[0].image_selection.as_ref().is_some_and(|s| s.crop.is_none()), "crop mode ended");+}++#[test]+fn test_image_rotated_45_deg_obb_and_proportional_scale() {+ use pdfcraft_ui_egui::ImageHandle;+ use pdfcraft_ui_egui::canvas::ImageObb;+ use std::f32::consts::FRAC_PI_4;++ let center = egui::pos2(200.0, 200.0);+ let width = 100.0_f32;+ let height = 50.0_f32;+ let theta = FRAC_PI_4;++ let obb = ImageObb::from_center_size_angle(center, width, height, theta);++ // 1. Verify it outputs an OBB (not an AABB):+ assert!(obb.is_rotated);+ let corners = obb.corners();+ assert!((corners[0].x - corners[1].x).abs() > 1.0);+ assert!((corners[0].y - corners[1].y).abs() > 1.0);+ assert!((corners[1].x - corners[2].x).abs() > 1.0);+ assert!((corners[1].y - corners[2].y).abs() > 1.0);++ let edge_u = (corners[1] - corners[0]).length();+ let edge_v = (corners[3] - corners[0]).length();+ assert!((edge_u - width).abs() < 1e-4, "edge_u={edge_u}, width={width}");+ assert!((edge_v - height).abs() < 1e-4, "edge_v={edge_v}, height={height}");++ let dot = (corners[1] - corners[0]).dot(corners[3] - corners[0]);+ assert!(dot.abs() < 1e-4, "adjacent edges must be perpendicular for OBB");++ let handles = obb.handles();+ assert_eq!(handles.len(), 8);++ // 2. Drag TopRight handle with a pointer delta along local axes:+ let delta = egui::vec2(10.0 * theta.cos(), 10.0 * theta.sin());+ let anchor_before = obb.s00;++ let scaled_obb = obb.scale_proportional(ImageHandle::TopRight, delta, 5.0);++ // The diagonally opposite corner (s00) MUST remain locked as the fixed anchor point:+ assert!((scaled_obb.s00.x - anchor_before.x).abs() < 1e-4);+ assert!((scaled_obb.s00.y - anchor_before.y).abs() < 1e-4);++ // Dimensions scale proportionally along local axes (aspect ratio preserved):+ let new_aspect = scaled_obb.width / scaled_obb.height;+ let old_aspect = width / height;+ assert!((new_aspect - old_aspect).abs() < 1e-4, "aspect ratio preserved: {new_aspect} vs {old_aspect}");+ assert!(scaled_obb.width > width, "width increased");+ assert!(scaled_obb.height > height, "height increased proportionally");++ // Rotation angle is preserved without skewing:+ assert!((scaled_obb.theta - theta).abs() < 1e-4);+}++trait RectExt {+ fn width(&self) -> f64;+}++impl RectExt for [f64; 4] {+ fn width(&self) -> f64 {+ (self[2] - self[0]).abs()+ }+}++impl RectExt for egui::Rect {+ fn width(&self) -> f64 {+ f64::from(self.width())+ }+}++#[test]+fn test_image_8_handles_render_and_drag() {+ let mut png = Vec::new();+ image::RgbImage::from_pixel(100, 100, image::Rgb([100, 150, 200]))+ .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("square.png", None, png.clone()).expect("opens");+ app+ });+ h.run_steps(4);+ 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 image+ 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");++ let view = &h.state().views[0];+ let sel = view.image_selection.as_ref().unwrap();+ let doc = h.state().session.get(view.id).unwrap();+ let img = &doc.page_images(sel.page)[sel.index];+ let xf =+ pdfcraft_ui_egui::canvas::PageXform { rect: r, rot: view.rotation, pw: doc.info.pages[sel.page].width, ph: doc.info.pages[sel.page].height };+ let obb = pdfcraft_ui_egui::canvas::ImageObb::from_image(img, &xf, &doc.info, sel.page);++ // Assert that exactly 8 unique resize handles (4 corners, 4 midpoints) are generated+ let handles = obb.handles();+ assert_eq!(handles.len(), 8, "exactly 8 resize handles generated");++ let corners = [+ pdfcraft_ui_egui::ImageHandle::TopLeft,+ pdfcraft_ui_egui::ImageHandle::TopRight,+ pdfcraft_ui_egui::ImageHandle::BottomRight,+ pdfcraft_ui_egui::ImageHandle::BottomLeft,+ ];+ let midpoints = [+ pdfcraft_ui_egui::ImageHandle::TopCenter,+ pdfcraft_ui_egui::ImageHandle::RightCenter,+ pdfcraft_ui_egui::ImageHandle::BottomCenter,+ pdfcraft_ui_egui::ImageHandle::LeftCenter,+ ];+ for corner in &corners {+ assert!(handles.iter().any(|(h, _)| h == corner), "missing corner handle: {:?}", corner);+ }+ for midpoint in &midpoints {+ assert!(handles.iter().any(|(h, _)| h == midpoint), "missing midpoint handle: {:?}", midpoint);+ }++ for i in 0..8 {+ for j in (i + 1)..8 {+ assert!((handles[i].1 - handles[j].1).length() > 1.0, "handles {} and {} must be unique positions", i, j);+ }+ }++ // Simulate a pointer drag on a corner that shrinks the image to 5x5 pixels and assert it does not panic+ let tr_pos = obb.handle_pos(pdfcraft_ui_egui::ImageHandle::TopRight);+ let anchor = obb.s00;+ let shrink_target = anchor + egui::vec2(5.0, 5.0);+ h.hover_at(tr_pos);+ h.run_steps(1);+ h.drag_at(tr_pos);+ h.run_steps(1);+ h.hover_at(shrink_target);+ h.run_steps(2);+ h.drop_at(shrink_target);+ h.run_steps(4);+}++#[test]+fn test_image_context_menu_precedence() {+ 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);+ 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 image+ 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");++ // Simulate a secondary click strictly inside an image's bounds+ h.hover_at(c);+ h.run_steps(1);+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });+ h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });+ h.run_steps(2);++ // Assert that the image widget consumes the click and the canvas background menu does not trigger+ h.get_by_label("Rotate Clockwise");+ h.get_by_label("Flip horizontal");+ assert!(h.query_all_by_label("Rotate view clockwise").next().is_none(), "canvas background menu must not trigger");+ assert!(h.query_all_by_label("Add bookmark").next().is_none(), "canvas background menu must not trigger");+ assert!(h.query_all_by_label("Take a snapshot").next().is_none(), "canvas background menu must not trigger");+}++#[test]+fn test_crop_updates_rect_instantly() {+ let mut png = Vec::new();+ image::RgbImage::from_pixel(100, 50, image::Rgb([100, 150, 200])).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("form.pdf", None, include_bytes!("data/form.pdf").to_vec()).unwrap();+ app+ });+ h.run_steps(4);+ assert!(h.state_mut().execute("edit.text"));+ h.run_steps(2);++ // Add image via content_ui+ h.state_mut().add_image("logo.png".into(), png);+ h.run_steps(3);++ let id = h.state().views[0].id;+ let initial_img = match &h.state().session.get(id).unwrap().added()[0].content {+ pdfcraft_engine::AddedContent::Image(img) => img.clone(),+ _ => panic!("expected AddedContent::Image"),+ };+ let initial_w = initial_img.rect.width();++ // Trigger a crop event that removes 50% of an image's width+ let mut cropped = initial_img.clone();+ pdfcraft_ui_egui::content_ui::update_image_crop(&mut cropped, [0.5, 0.0, 0.0, 0.0]);+ let update_edit = pdfcraft_engine::Edit::UpdateContent { page: 0, index: 0, content: pdfcraft_engine::AddedContent::Image(cropped) };+ h.state_mut().apply_edit(update_edit);++ // Assert that in the immediate next frame, the image.rect.width() is exactly 50% of the original, with no padding left over+ h.run_steps(1);+ let doc = h.state().session.get(id).unwrap();+ let img = match &doc.added()[0].content {+ pdfcraft_engine::AddedContent::Image(img) => img.clone(),+ _ => panic!("expected AddedContent::Image"),+ };+ let w = img.rect.width();+ let expected_w = initial_w * 0.5;+ assert!((w - expected_w).abs() < 1e-3, "image.rect.width() must be exactly 50% ({expected_w}), got {w}");+}++#[test]+fn crop_action_pills_interactive_and_apply_cancel_reset() {+ let mut png = Vec::new();+ image::RgbImage::from_pixel(100, 100, image::Rgb([100, 150, 200]))+ .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("square.png", None, png.clone()).expect("opens");+ app+ });+ h.run_steps(4);+ 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 image+ 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());++ // Enter crop mode+ let doc_id = h.state().views[0].id;+ let original_rect = h.state().session.get(doc_id).unwrap().page_images(0)[0].rect;+ h.state_mut().views[0].image_selection.as_mut().unwrap().crop = Some(pdfcraft_ui_egui::CropMode::new(original_rect));+ h.state_mut().views[0].image_selection.as_mut().unwrap().crop_mode = true;+ h.run_steps(2);++ // Set smaller crop rect (50x50 in center)+ let smaller = egui::Rect::from_center_size(c, egui::vec2(50.0, 50.0));+ h.state_mut().views[0].image_selection.as_mut().unwrap().crop_rect = Some(smaller);+ h.run_steps(2);++ let pill_y = smaller.max.y + 17.0;+ let done_pos = egui::pos2(smaller.max.x - 20.0, pill_y);+ h.hover_at(done_pos);+ h.run_steps(1);+ assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand, "Done pill has PointingHand cursor");++ let cancel_pos = egui::pos2(smaller.max.x - 85.0, pill_y);+ h.hover_at(cancel_pos);+ h.run_steps(1);+ assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand, "Cancel pill has PointingHand cursor");++ // Click Cancel pill: exits crop mode without applying changes+ click_at(&mut h, cancel_pos);+ h.run_steps(3);+ assert!(h.state().views[0].image_selection.as_ref().is_some_and(|s| s.crop.is_none() && !s.crop_mode), "Cancel exits crop mode");+ assert_eq!(h.state().session.get(doc_id).unwrap().page_images(0)[0].visible_rect, Some(original_rect), "image is uncropped");++ // Re-enter crop mode and set crop rect+ h.state_mut().views[0].image_selection.as_mut().unwrap().crop = Some(pdfcraft_ui_egui::CropMode::new(original_rect));+ h.state_mut().views[0].image_selection.as_mut().unwrap().crop_mode = true;+ h.state_mut().views[0].image_selection.as_mut().unwrap().crop_rect = Some(smaller);+ h.run_steps(2);++ // Click "Remove Crop" pill+ let reset_pos = egui::pos2(smaller.max.x - 170.0, pill_y);+ h.hover_at(reset_pos);+ h.run_steps(1);+ assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand, "Remove Crop pill has PointingHand cursor");+ click_at(&mut h, reset_pos);+ h.run_steps(2);+ let current_keep = h.state().views[0].image_selection.as_ref().unwrap().crop.as_ref().unwrap().keep;+ assert_eq!(current_keep, original_rect, "Remove Crop restored crop to full bounds");++ // Re-set smaller crop and click "Done" pill to apply+ h.state_mut().views[0].image_selection.as_mut().unwrap().crop_rect = Some(smaller);+ h.run_steps(2);+ let done_pos_after = egui::pos2(smaller.max.x - 20.0, pill_y);+ click_at(&mut h, done_pos_after);+ h.run_steps(4);++ assert!(h.state().views[0].image_selection.as_ref().is_some_and(|s| s.crop.is_none() && !s.crop_mode), "Done exits crop mode");+ let after_images = h.state().session.get(doc_id).unwrap().page_images(0);+ assert_ne!(after_images[0].visible_rect, Some(original_rect), "crop was applied");+}++#[test]+fn test_cropped_image_selection_and_bounding_box() {+ let mut png = Vec::new();+ image::RgbImage::from_pixel(100, 100, image::Rgb([100, 150, 200]))+ .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("square.png", None, png.clone()).expect("opens");+ app+ });+ h.run_steps(4);++ let doc_id = h.state().views[0].id;+ let full_rect = h.state().session.get(doc_id).unwrap().page_images(0)[0].rect;++ // Apply crop to the center quarter: [0.25, 0.25, 0.75, 0.75]+ let crop_keep = [+ full_rect[0] + (full_rect[2] - full_rect[0]) * 0.25,+ full_rect[1] + (full_rect[3] - full_rect[1]) * 0.25,+ full_rect[0] + (full_rect[2] - full_rect[0]) * 0.75,+ full_rect[1] + (full_rect[3] - full_rect[1]) * 0.75,+ ];+ h.state_mut().apply_edit(pdfcraft_engine::Edit::EditPageImage { page: 0, index: 0, change: pdfcraft_engine::ImageEdit::Crop(crop_keep) });+ h.run_steps(4);++ let img = &h.state().session.get(doc_id).unwrap().page_images(0)[0];+ assert_eq!(img.rect, full_rect, "underlying CTM rect is non-destructively preserved");+ let vis = img.visible_rect.expect("has visible_rect");+ assert!((vis[0] - crop_keep[0]).abs() < 1e-3);+ assert!((vis[1] - crop_keep[1]).abs() < 1e-3);+ assert!((vis[2] - crop_keep[2]).abs() < 1e-3);+ assert!((vis[3] - crop_keep[3]).abs() < 1e-3);++ // Verify selectable bounds helper gives the cropped intersection+ assert_eq!(pdfcraft_ui_egui::canvas::image_selectable_bounds(img), vis);++ // Select tool (mouse tool)+ h.state_mut().quick_tool = pdfcraft_ui_egui::QuickTool::Select;+ h.run_steps(2);++ let page_rect = h.state().views[0].page_screen_rect(0).expect("on screen");+ // Center point is inside the cropped area:+ let center = page_rect.center();+ click_at(&mut h, center);+ h.run_steps(2);++ let picked = h.state().views[0].picked_image.expect("image is picked when clicking inside crop");+ assert_eq!(picked.page, 0);+ assert_eq!(picked.index, 0);+ // The selection bounding box wraps the visible cropped area, NOT the full CTM rect!+ assert_eq!(picked.rect, vis, "picked rect wraps the cropped bounds");++ // Deselect+ h.key_press(egui::Key::Escape);+ h.run_steps(2);+ assert!(h.state().views[0].picked_image.is_none());++ // Corner point (e.g. top-left corner of the page) is outside the crop box but inside full CTM rect+ let corner = page_rect.min + egui::vec2(10.0, 10.0);+ click_at(&mut h, corner);+ h.run_steps(2);+ assert!(h.state().views[0].picked_image.is_none(), "clicking cropped-away region must not hit-test or select the image");+}+++ /// The Read mode command (not the mode bar) applies a paragraph still open in the editor, as+ /// putting the Edit text tool down does; left open, it would stay drawn in Read mode with no tool.+ #[test]+ fn read_mode_shortcut_applies_the_open_paragraph() {+ use pdfcraft_ui_egui::{Mode, QuickTool};+ let mut h = harness(1, |_| {});+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(2);+ // The line "Page 1" sits at (20, 150) on a 200 × 300 page, 24 pt.+ 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());+ h.hover_at(at);+ h.run_steps(1);+ h.drag_at(at);+ h.run_steps(1);+ h.drop_at(at);+ h.run_steps(3);+ assert!(h.state().views[0].line_editor.is_some(), "the line opens for editing");+ h.state_mut().views[0].line_editor.as_mut().unwrap().text = "Chapter One".into();+ h.run_steps(1);+ h.state_mut().run_command("view.read_mode");+ h.run_steps(3);+ let s = h.state();+ assert_eq!(s.mode, Mode::Read);+ assert_eq!(s.quick_tool, QuickTool::Select);+ assert!(s.views[0].line_editor.is_none(), "no editor stays open in Read mode");+ assert_eq!(s.session.get(s.views[0].id).unwrap().text_lines(0)[0].text, "Chapter One", "the edit is applied");+ }++}