From 6cc43b67fffc5f1c6ea6dfdbf8481f9d604291e5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:26 -0500 Subject: [PATCH] pdf-edit-w9: net change of 3 commits - pdf-edit-w9: written from its sheet - pdf-edit-w9: repair 1 - pdf-edit-w9: review fixes (review-1) --- crates/ui-egui/src/image_engine.rs | 578 ------- .../ui-egui/src/tools/edit_text_ui/image.rs | 1529 ++++++----------- 2 files changed, 512 insertions(+), 1595 deletions(-) delete mode 100644 crates/ui-egui/src/image_engine.rs diff --git a/crates/ui-egui/src/image_engine.rs b/crates/ui-egui/src/image_engine.rs deleted file mode 100644 index 518bea0223..0000000000 --- a/crates/ui-egui/src/image_engine.rs +++ /dev/null @@ -1,578 +0,0 @@ -//! Image manipulation engine for non-destructive crop, anchor-based resize, and movement. -//! -//! Contributor-original clean-room design with zero-panic safety and lockstep pixel-scale invariance. - -use egui::{Color32, Pos2, Rect, Stroke, Vec2, pos2}; - -use crate::edit_text_ui::ImageHandle; - -// ============================================================================ -// 1. MATHEMATICAL CORE: ANCHOR-BASED RESIZE & CROP -// ============================================================================ - -/// Minimum allowed dimensions in pixels to prevent panics, zero divisions, or inverted rects. -pub const MIN_RECT_SIZE: f32 = 10.0; - -/// **Anchor-Based Resize System** -/// -/// Recalculates the screen bounding box by locking the diagonally opposite point/edge as -/// a fixed anchor. -/// -/// Math breakdown: -/// - Corner handles: The diagonally opposite corner is fixed in both X and Y. -/// Width and height are calculated relative to that anchor, clamped to >= `MIN_RECT_SIZE`, -/// and the new bounding box is constructed from `anchor` and the clamped dragged coordinate. -/// - Mid-edge handles: The opposite edge coordinate is fixed in 1D. The perpendicular axis is -/// completely unaffected. -pub fn apply_resize(image_rect: Rect, handle: ImageHandle, delta: Vec2) -> Rect { - if !image_rect.is_finite() || !delta.x.is_finite() || !delta.y.is_finite() { - return image_rect; - } - let mut min = image_rect.min; - let mut max = image_rect.max; - - match handle { - // Dragging TopLeft: Fixed Anchor = BottomRight (max.x, max.y) - ImageHandle::TopLeft => { - let anchor = max; - let target = min + delta; - let new_w = (anchor.x - target.x).max(MIN_RECT_SIZE); - let new_h = (anchor.y - target.y).max(MIN_RECT_SIZE); - min.x = anchor.x - new_w; - min.y = anchor.y - new_h; - } - - // Dragging TopCenter: Fixed Anchor = Bottom edge (max.y) - ImageHandle::TopCenter => { - let anchor_y = max.y; - let target_y = min.y + delta.y; - let new_h = (anchor_y - target_y).max(MIN_RECT_SIZE); - min.y = anchor_y - new_h; - } - - // Dragging TopRight: Fixed Anchor = BottomLeft (min.x, max.y) - ImageHandle::TopRight => { - let anchor_x = min.x; - let anchor_y = max.y; - let target_x = max.x + delta.x; - let target_y = min.y + delta.y; - let new_w = (target_x - anchor_x).max(MIN_RECT_SIZE); - let new_h = (anchor_y - target_y).max(MIN_RECT_SIZE); - max.x = anchor_x + new_w; - min.y = anchor_y - new_h; - } - - // Dragging RightCenter: Fixed Anchor = Left edge (min.x) - ImageHandle::RightCenter => { - let anchor_x = min.x; - let target_x = max.x + delta.x; - let new_w = (target_x - anchor_x).max(MIN_RECT_SIZE); - max.x = anchor_x + new_w; - } - - // Dragging BottomRight: Fixed Anchor = TopLeft (min.x, min.y) - ImageHandle::BottomRight => { - let anchor = min; - let target = max + delta; - let new_w = (target.x - anchor.x).max(MIN_RECT_SIZE); - let new_h = (target.y - anchor.y).max(MIN_RECT_SIZE); - max.x = anchor.x + new_w; - max.y = anchor.y + new_h; - } - - // Dragging BottomCenter: Fixed Anchor = Top edge (min.y) - ImageHandle::BottomCenter => { - let anchor_y = min.y; - let target_y = max.y + delta.y; - let new_h = (target_y - anchor_y).max(MIN_RECT_SIZE); - max.y = anchor_y + new_h; - } - - // Dragging BottomLeft: Fixed Anchor = TopRight (max.x, min.y) - ImageHandle::BottomLeft => { - let anchor_x = max.x; - let anchor_y = min.y; - let target_x = min.x + delta.x; - let target_y = max.y + delta.y; - let new_w = (anchor_x - target_x).max(MIN_RECT_SIZE); - let new_h = (target_y - anchor_y).max(MIN_RECT_SIZE); - min.x = anchor_x - new_w; - max.y = anchor_y + new_h; - } - - // Dragging LeftCenter: Fixed Anchor = Right edge (max.x) - ImageHandle::LeftCenter => { - let anchor_x = max.x; - let target_x = min.x + delta.x; - let new_w = (anchor_x - target_x).max(MIN_RECT_SIZE); - min.x = anchor_x - new_w; - } - } - - Rect::from_min_max(min, max) -} - -/// **Anchor-Based Proportional Resize System** -/// -/// Recalculates the screen bounding box by locking the diagonally opposite point as -/// a fixed anchor while preserving the aspect ratio. -/// -/// For corner handles, uses the axis with the larger relative change to scale both -/// width and height uniformly from the locked anchor point, clamped to `>= MIN_RECT_SIZE`. -/// For mid-edge handles, delegates to `apply_resize`. -pub fn apply_resize_proportional(image_rect: Rect, handle: ImageHandle, delta: Vec2) -> Rect { - if !image_rect.is_finite() || !delta.x.is_finite() || !delta.y.is_finite() { - return image_rect; - } - let w0 = image_rect.width().max(1.0); - let h0 = image_rect.height().max(1.0); - - match handle { - ImageHandle::TopLeft => { - let horizontal = -delta.x / w0; - let vertical = -delta.y / h0; - let d = if horizontal.abs() > vertical.abs() { horizontal } else { vertical }; - let k = (1.0 + d).max(MIN_RECT_SIZE / w0).max(MIN_RECT_SIZE / h0); - let (w, h) = (w0 * k, h0 * k); - Rect::from_min_max(Pos2::new(image_rect.max.x - w, image_rect.max.y - h), image_rect.max) - } - ImageHandle::TopRight => { - let horizontal = delta.x / w0; - let vertical = -delta.y / h0; - let d = if horizontal.abs() > vertical.abs() { horizontal } else { vertical }; - let k = (1.0 + d).max(MIN_RECT_SIZE / w0).max(MIN_RECT_SIZE / h0); - let (w, h) = (w0 * k, h0 * k); - Rect::from_min_max(Pos2::new(image_rect.min.x, image_rect.max.y - h), Pos2::new(image_rect.min.x + w, image_rect.max.y)) - } - ImageHandle::BottomLeft => { - let horizontal = -delta.x / w0; - let vertical = delta.y / h0; - let d = if horizontal.abs() > vertical.abs() { horizontal } else { vertical }; - let k = (1.0 + d).max(MIN_RECT_SIZE / w0).max(MIN_RECT_SIZE / h0); - let (w, h) = (w0 * k, h0 * k); - Rect::from_min_max(Pos2::new(image_rect.max.x - w, image_rect.min.y), Pos2::new(image_rect.max.x, image_rect.min.y + h)) - } - ImageHandle::BottomRight => { - let horizontal = delta.x / w0; - let vertical = delta.y / h0; - let d = if horizontal.abs() > vertical.abs() { horizontal } else { vertical }; - let k = (1.0 + d).max(MIN_RECT_SIZE / w0).max(MIN_RECT_SIZE / h0); - let (w, h) = (w0 * k, h0 * k); - Rect::from_min_max(image_rect.min, Pos2::new(image_rect.min.x + w, image_rect.min.y + h)) - } - mid => apply_resize(image_rect, mid, delta), - } -} - -/// Trim a screen rectangle and its UVs together, keeping the opposite edge fixed. -/// The pixel scale stays unchanged, and each edge stops at the texture boundary. -pub fn apply_crop(image_rect: Rect, uv_rect: Rect, handle: ImageHandle, delta: Vec2) -> (Rect, Rect) { - if !delta.is_finite() || !image_rect.is_finite() || !uv_rect.is_finite() || !image_rect.is_positive() || !uv_rect.is_positive() { - return (image_rect, uv_rect); - } - let scale = image_rect.size() / uv_rect.size(); - if !scale.is_finite() || scale.x <= 0.0 || scale.y <= 0.0 { - return (image_rect, uv_rect); - } - let minimum = (egui::vec2(MIN_RECT_SIZE, MIN_RECT_SIZE) / scale).min(uv_rect.size() * 0.95); - let mut uv = uv_rect; - if matches!(handle, ImageHandle::TopLeft | ImageHandle::LeftCenter | ImageHandle::BottomLeft) { - uv.min.x = (uv.min.x + delta.x / scale.x).clamp(0.0, (uv.max.x - minimum.x).max(0.0)); - } else if matches!(handle, ImageHandle::TopRight | ImageHandle::RightCenter | ImageHandle::BottomRight) { - uv.max.x = (uv.max.x + delta.x / scale.x).clamp((uv.min.x + minimum.x).min(1.0), 1.0); - } - if matches!(handle, ImageHandle::TopLeft | ImageHandle::TopCenter | ImageHandle::TopRight) { - uv.min.y = (uv.min.y + delta.y / scale.y).clamp(0.0, (uv.max.y - minimum.y).max(0.0)); - } else if matches!(handle, ImageHandle::BottomLeft | ImageHandle::BottomCenter | ImageHandle::BottomRight) { - uv.max.y = (uv.max.y + delta.y / scale.y).clamp((uv.min.y + minimum.y).min(1.0), 1.0); - } - // Reconstruct from the fixed opposite edge, rather than adding a nearly full-width - // shift to the moved edge. Calculate in f64 so each screen coordinate rounds only - // once to f32; small crops far from the origin otherwise lose multiple ulps. - let span = |min: f32, max: f32| f64::from(max) - f64::from(min); - let width = span(image_rect.min.x, image_rect.max.x) * span(uv.min.x, uv.max.x) / span(uv_rect.min.x, uv_rect.max.x); - let height = span(image_rect.min.y, image_rect.max.y) * span(uv.min.y, uv.max.y) / span(uv_rect.min.y, uv_rect.max.y); - let mut screen = image_rect; - if uv.min.x != uv_rect.min.x { - screen.min.x = (f64::from(image_rect.max.x) - width) as f32; - } else if uv.max.x != uv_rect.max.x { - screen.max.x = (f64::from(image_rect.min.x) + width) as f32; - } - if uv.min.y != uv_rect.min.y { - screen.min.y = (f64::from(image_rect.max.y) - height) as f32; - } else if uv.max.y != uv_rect.max.y { - screen.max.y = (f64::from(image_rect.min.y) + height) as f32; - } - if !screen.is_finite() || !screen.is_positive() { - return (image_rect, uv_rect); - } - (screen, uv) -} - -// ============================================================================ -// 2. VISUAL RENDERING HELPERS -// ============================================================================ - -/// Vibrant amber/orange color for Crop Mode. -pub const CROP_ACCENT: Color32 = Color32::from_rgb(230, 126, 34); - -/// Renders the Rule-of-Thirds composition grid inside the given crop rectangle. -pub fn draw_rule_of_thirds(painter: &egui::Painter, rect: Rect, stroke: Stroke) { - let w = rect.width(); - let h = rect.height(); - if w <= 0.0 || h <= 0.0 { - return; - } - - let x1 = rect.min.x + w / 3.0; - let x2 = rect.min.x + (2.0 * w) / 3.0; - painter.line_segment([pos2(x1, rect.min.y), pos2(x1, rect.max.y)], stroke); - painter.line_segment([pos2(x2, rect.min.y), pos2(x2, rect.max.y)], stroke); - - let y1 = rect.min.y + h / 3.0; - let y2 = rect.min.y + (2.0 * h) / 3.0; - painter.line_segment([pos2(rect.min.x, y1), pos2(rect.max.x, y1)], stroke); - painter.line_segment([pos2(rect.min.x, y2), pos2(rect.max.x, y2)], stroke); -} - -/// Renders a circular handle with shadow, fill, and accent stroke using the image tool accent. -pub fn draw_handle(painter: &egui::Painter, center: Pos2, is_active: bool, is_hovered: bool, crop_mode: bool, accent_color: Color32) { - let base_radius = 6.5; - let circle_radius = if is_active { - base_radius + 2.0 - } else if is_hovered { - base_radius + 1.2 - } else { - base_radius - }; - - let fill_color = if crop_mode { - if is_active || is_hovered { Color32::from_rgb(255, 230, 150) } else { Color32::from_rgb(255, 255, 255) } - } else if is_active || is_hovered { - Color32::from_rgb(210, 235, 255) - } else { - Color32::from_rgb(255, 255, 255) - }; - - // Draw handle shadow/glow - painter.circle_filled(center, circle_radius + 1.5, Color32::from_rgba_unmultiplied(0, 0, 0, 80)); - - // Draw handle circle - painter.circle_filled(center, circle_radius, fill_color); - painter.circle_stroke(center, circle_radius, Stroke::new(1.8, accent_color)); -} - -// ============================================================================ -// 3. UNIT TESTS: MATHEMATICAL VERIFICATION -// ============================================================================ - -#[cfg(test)] -mod tests { - use super::*; - use egui::vec2; - - // Verify scale in screen space: dividing an endpoint's rounding error by a tiny - // retained UV span would magnify it and make a fixed scale tolerance invalid. - fn crop_scale_preserved(before: Rect, uv_before: Rect, after: Rect, uv_after: Rect) -> bool { - let axis = |lo: f32, hi: f32, u0: f32, u1: f32, new_lo: f32, new_hi: f32, v0: f32, v1: f32| { - let span = f64::from(hi) - f64::from(lo); - let expected = span * (f64::from(v1) - f64::from(v0)) / (f64::from(u1) - f64::from(u0)); - let actual = f64::from(new_hi) - f64::from(new_lo); - // One moved endpoint rounds once to f32. EPSILON * coordinate magnitude - // bounds one ulp (conservatively twice the nearest-rounding error). - // The f64 term also covers the two arithmetic operations above. - let magnitude = f64::from(new_lo).abs().max(f64::from(new_hi).abs()).max(expected.abs()); - let bound = f64::from(f32::EPSILON) * magnitude + 4.0 * f64::EPSILON * span.abs(); - (actual - expected).abs() <= bound - }; - axis(before.min.x, before.max.x, uv_before.min.x, uv_before.max.x, after.min.x, after.max.x, uv_after.min.x, uv_after.max.x) - && axis(before.min.y, before.max.y, uv_before.min.y, uv_before.max.y, after.min.y, after.max.y, uv_after.min.y, uv_after.max.y) - } - - #[test] - fn crop_scale_at_large_screen_offset() { - let screen = Rect::from_min_size(pos2(813.7157, 0.0), vec2(495.0725, 50.0)); - let uv = Rect::from_min_size(pos2(0.114936605, 0.0), vec2(0.32074833, 0.3)); - let (cropped, kept) = apply_crop(screen, uv, ImageHandle::BottomLeft, vec2(1255.676, 0.0)); - let width = (f64::from(screen.max.x) - f64::from(screen.min.x)) * (f64::from(kept.max.x) - f64::from(kept.min.x)) - / (f64::from(uv.max.x) - f64::from(uv.min.x)); - assert_eq!(cropped.min.x, (f64::from(screen.max.x) - width) as f32, "moved edge rounds once from the fixed anchor"); - assert_eq!(cropped.max.x, screen.max.x, "opposite horizontal edge stays fixed"); - assert_eq!(cropped.min.y, screen.min.y, "opposite vertical edge stays fixed"); - assert!(crop_scale_preserved(screen, uv, cropped, kept)); - let stretched = Rect::from_min_max(cropped.min - vec2(0.1, 0.0), cropped.max); - assert!(!crop_scale_preserved(screen, uv, stretched, kept), "a visible stretch must exceed the rounding bound"); - } - - #[test] - fn test_resize_bottom_right_anchor() { - let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(300.0, 200.0)); - let res = apply_resize(r, ImageHandle::BottomRight, vec2(50.0, 25.0)); - assert_eq!(res.min, pos2(100.0, 100.0), "TopLeft anchor must remain fixed"); - assert_eq!(res.max, pos2(350.0, 225.0), "BottomRight must expand by delta"); - } - - #[test] - fn test_resize_top_left_anchor() { - let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(300.0, 200.0)); - let res = apply_resize(r, ImageHandle::TopLeft, vec2(20.0, 15.0)); - assert_eq!(res.max, pos2(300.0, 200.0), "BottomRight anchor must remain fixed"); - assert_eq!(res.min, pos2(120.0, 115.0), "TopLeft must move by delta"); - } - - #[test] - fn test_resize_clamping_prevents_inversion() { - let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(200.0, 200.0)); - let res = apply_resize(r, ImageHandle::TopLeft, vec2(500.0, 500.0)); - assert_eq!(res.max, pos2(200.0, 200.0)); - assert_eq!(res.min, pos2(200.0 - MIN_RECT_SIZE, 200.0 - MIN_RECT_SIZE)); - assert!(res.width() >= MIN_RECT_SIZE); - assert!(res.height() >= MIN_RECT_SIZE); - } - - #[test] - fn test_resize_top_right_anchor() { - let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(300.0, 200.0)); - let res = apply_resize(r, ImageHandle::TopRight, vec2(10.0, -10.0)); - assert_eq!(res.min.x, 100.0, "min.x (BL) anchor fixed"); - assert_eq!(res.max.y, 200.0, "max.y (BL) anchor fixed"); - assert_eq!(res.max.x, 310.0); - assert_eq!(res.min.y, 90.0); - } - - #[test] - fn test_resize_bottom_left_anchor() { - let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(300.0, 200.0)); - let res = apply_resize(r, ImageHandle::BottomLeft, vec2(-15.0, 20.0)); - assert_eq!(res.max.x, 300.0, "max.x (TR) anchor fixed"); - assert_eq!(res.min.y, 100.0, "min.y (TR) anchor fixed"); - assert_eq!(res.min.x, 85.0); - assert_eq!(res.max.y, 220.0); - } - - #[test] - fn test_resize_mid_edges() { - let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(300.0, 200.0)); - - let tm = apply_resize(r, ImageHandle::TopCenter, vec2(50.0, -30.0)); - assert_eq!(tm.min.x, 100.0, "X min unaffected"); - assert_eq!(tm.max.x, 300.0, "X max unaffected"); - assert_eq!(tm.max.y, 200.0, "Y max anchor locked"); - assert_eq!(tm.min.y, 70.0); - - let rm = apply_resize(r, ImageHandle::RightCenter, vec2(40.0, 50.0)); - assert_eq!(rm.min.x, 100.0, "X min anchor locked"); - assert_eq!(rm.max.x, 340.0); - assert_eq!(rm.min.y, 100.0, "Y unaffected"); - assert_eq!(rm.max.y, 200.0, "Y unaffected"); - } - - #[test] - fn test_crop_lockstep_ratio_preservation() { - let screen = Rect::from_min_max(pos2(100.0, 100.0), pos2(500.0, 400.0)); - let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); - - let initial_px_per_uv_x = screen.width() / uv.width(); - let initial_px_per_uv_y = screen.height() / uv.height(); - - let (new_screen, new_uv) = apply_crop(screen, uv, ImageHandle::RightCenter, vec2(-80.0, 0.0)); - - assert_eq!(new_screen.min.x, 100.0, "Left edge anchored"); - assert_eq!(new_screen.max.x, 420.0, "Right edge moved in by 80px"); - assert_eq!(new_screen.width(), 320.0); - - assert_eq!(new_uv.min.x, 0.0); - assert!((new_uv.max.x - 0.8).abs() < 1e-4); - - let new_px_per_uv_x = new_screen.width() / new_uv.width(); - assert!((new_px_per_uv_x - initial_px_per_uv_x).abs() < 1e-4, "Pixel scale must remain invariant in crop mode"); - - let new_px_per_uv_y = new_screen.height() / new_uv.height(); - assert!((new_px_per_uv_y - initial_px_per_uv_y).abs() < 1e-4, "Pixel scale Y must remain invariant"); - } - - #[test] - fn test_crop_left_edge_anchoring() { - let screen = Rect::from_min_max(pos2(100.0, 100.0), pos2(500.0, 400.0)); - let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); - - let (new_screen, new_uv) = apply_crop(screen, uv, ImageHandle::LeftCenter, vec2(50.0, 0.0)); - - assert_eq!(new_screen.max.x, 500.0, "Right edge must remain strictly anchored"); - assert_eq!(new_screen.min.x, 150.0, "Left edge must move by 50px"); - assert_eq!(new_screen.width(), 350.0); - - assert!((new_uv.min.x - 0.125).abs() < 1e-4); - assert_eq!(new_uv.max.x, 1.0); - } - - #[test] - fn test_crop_uncrop_clamped_at_zero_and_one() { - let screen = Rect::from_min_max(pos2(100.0, 100.0), pos2(500.0, 400.0)); - let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); - - let (new_screen, new_uv) = apply_crop(screen, uv, ImageHandle::LeftCenter, vec2(-100.0, 0.0)); - assert_eq!(new_uv.min.x, 0.0, "UV min cannot go below 0.0"); - assert_eq!(new_screen.min.x, 100.0, "Screen min clamped at initial position"); - - let (new_screen2, new_uv2) = apply_crop(screen, uv, ImageHandle::RightCenter, vec2(100.0, 0.0)); - assert_eq!(new_uv2.max.x, 1.0, "UV max cannot exceed 1.0"); - assert_eq!(new_screen2.max.x, 500.0, "Screen max clamped at initial position"); - } - - #[test] - fn test_apply_resize_proportional_horizontal_only_scales_both_dimensions() { - let rect = Rect::from_min_max(pos2(100.0, 100.0), pos2(200.0, 200.0)); // 100 x 100 - // TopRight corner moved horizontally by -25px (from x=200 to x=175) - let resized = apply_resize_proportional(rect, ImageHandle::TopRight, vec2(-25.0, 0.0)); - assert_eq!(resized.min.x, 100.0, "Left anchor preserved"); - assert_eq!(resized.max.y, 200.0, "Bottom anchor preserved"); - assert_eq!(resized.width(), 75.0, "Width scaled to 75%"); - assert_eq!(resized.height(), 75.0, "Height scaled to 75% proportionally"); - assert_eq!(resized.max.x, 175.0); - assert_eq!(resized.min.y, 125.0); - } - - #[test] - fn test_apply_resize_proportional_bottom_right_anchor_locked() { - let rect = Rect::from_min_max(pos2(50.0, 50.0), pos2(150.0, 250.0)); // 100 x 200 - // BottomRight moved down/right by (20px, 40px) - let resized = apply_resize_proportional(rect, ImageHandle::BottomRight, vec2(20.0, 40.0)); - assert_eq!(resized.min, pos2(50.0, 50.0), "TopLeft anchor strictly locked"); - assert_eq!(resized.width(), 120.0); - assert_eq!(resized.height(), 240.0); - } - - #[cfg(test)] - mod proptests { - use super::*; - use proptest::prelude::*; - - fn arb_handle() -> impl Strategy { - prop_oneof![ - Just(ImageHandle::TopLeft), - Just(ImageHandle::TopCenter), - Just(ImageHandle::TopRight), - Just(ImageHandle::RightCenter), - Just(ImageHandle::BottomRight), - Just(ImageHandle::BottomCenter), - Just(ImageHandle::BottomLeft), - Just(ImageHandle::LeftCenter), - ] - } - - proptest! { - #[test] - fn prop_apply_resize_never_inverts_and_respects_min_size( - min_x in -5000.0f32..5000.0, - min_y in -5000.0f32..5000.0, - w in 10.0f32..2000.0, - h in 10.0f32..2000.0, - handle in arb_handle(), - dx in -10000.0f32..10000.0, - dy in -10000.0f32..10000.0, - ) { - let rect = Rect::from_min_size(pos2(min_x, min_y), vec2(w, h)); - let res = apply_resize(rect, handle, vec2(dx, dy)); - prop_assert!(res.is_finite()); - prop_assert!(res.width() >= MIN_RECT_SIZE - 1e-3); - prop_assert!(res.height() >= MIN_RECT_SIZE - 1e-3); - prop_assert!(res.min.x <= res.max.x); - prop_assert!(res.min.y <= res.max.y); - } - - #[test] - fn prop_apply_resize_proportional_preserves_aspect_ratio( - min_x in -2000.0f32..2000.0, - min_y in -2000.0f32..2000.0, - w in 20.0f32..1000.0, - h in 20.0f32..1000.0, - handle in arb_handle(), - dx in -5000.0f32..5000.0, - dy in -5000.0f32..5000.0, - ) { - let rect = Rect::from_min_size(pos2(min_x, min_y), vec2(w, h)); - let res = apply_resize_proportional(rect, handle, vec2(dx, dy)); - prop_assert!(res.is_finite()); - prop_assert!(res.width() >= MIN_RECT_SIZE - 1e-3); - prop_assert!(res.height() >= MIN_RECT_SIZE - 1e-3); - - let is_corner = matches!(handle, ImageHandle::TopLeft | ImageHandle::TopRight | ImageHandle::BottomLeft | ImageHandle::BottomRight); - if is_corner { - let orig_ratio = w / h; - let new_ratio = res.width() / res.height(); - prop_assert!((orig_ratio - new_ratio).abs() <= 1e-3 * orig_ratio.max(1.0), "orig: {orig_ratio}, new: {new_ratio}"); - } - } - - #[test] - fn prop_apply_crop_uv_clamped( - min_x in 0.0f32..1000.0, - min_y in 0.0f32..1000.0, - w in 50.0f32..500.0, - h in 50.0f32..500.0, - uv_u0 in 0.0f32..0.4, - uv_v0 in 0.0f32..0.4, - uv_w in 0.3f32..0.5, - uv_h in 0.3f32..0.5, - handle in arb_handle(), - dx in -2000.0f32..2000.0, - dy in -2000.0f32..2000.0, - ) { - let screen = Rect::from_min_size(pos2(min_x, min_y), vec2(w, h)); - let uv = Rect::from_min_size(pos2(uv_u0, uv_v0), vec2(uv_w, uv_h)); - let (new_screen, new_uv) = apply_crop(screen, uv, handle, vec2(dx, dy)); - - prop_assert!(new_screen.is_finite()); - prop_assert!(new_uv.is_finite()); - prop_assert!(new_uv.min.x >= 0.0 - 1e-5); - prop_assert!(new_uv.min.y >= 0.0 - 1e-5); - prop_assert!(new_uv.max.x <= 1.0 + 1e-5); - prop_assert!(new_uv.max.y <= 1.0 + 1e-5); - prop_assert!(new_uv.width() > 0.0); - prop_assert!(new_uv.height() > 0.0); - - if !matches!(handle, ImageHandle::TopLeft | ImageHandle::LeftCenter | ImageHandle::BottomLeft) { - prop_assert_eq!(new_screen.min.x, screen.min.x, "stationary left edge moved"); - } - if !matches!(handle, ImageHandle::TopRight | ImageHandle::RightCenter | ImageHandle::BottomRight) { - prop_assert_eq!(new_screen.max.x, screen.max.x, "stationary right edge moved"); - } - if !matches!(handle, ImageHandle::TopLeft | ImageHandle::TopCenter | ImageHandle::TopRight) { - prop_assert_eq!(new_screen.min.y, screen.min.y, "stationary top edge moved"); - } - if !matches!(handle, ImageHandle::BottomLeft | ImageHandle::BottomCenter | ImageHandle::BottomRight) { - prop_assert_eq!(new_screen.max.y, screen.max.y, "stationary bottom edge moved"); - } - - prop_assert!(crop_scale_preserved(screen, uv, new_screen, new_uv), - "screen/UV scale changed beyond endpoint rounding: {screen:?} {uv:?} => {new_screen:?} {new_uv:?}"); - } - - #[test] - fn prop_quad_contains_never_panics( - q0_x in -1000.0f32..1000.0, - q0_y in -1000.0f32..1000.0, - q1_x in -1000.0f32..1000.0, - q1_y in -1000.0f32..1000.0, - q2_x in -1000.0f32..1000.0, - q2_y in -1000.0f32..1000.0, - q3_x in -1000.0f32..1000.0, - q3_y in -1000.0f32..1000.0, - px in -2000.0f32..2000.0, - py in -2000.0f32..2000.0, - ) { - let quad = [pos2(q0_x, q0_y), pos2(q1_x, q1_y), pos2(q2_x, q2_y), pos2(q3_x, q3_y)]; - let p = pos2(px, py); - let _ = crate::edit_text_ui::quad_contains(quad, p); - } - } - - #[test] - fn degenerate_quad_does_not_contain_points() { - let zero_quad = [pos2(0.0, 0.0), pos2(0.0, 0.0), pos2(0.0, 0.0), pos2(0.0, 0.0)]; - assert!(!crate::edit_text_ui::quad_contains(zero_quad, pos2(10.0, 10.0))); - assert!(!crate::edit_text_ui::quad_contains(zero_quad, pos2(0.0, 0.0))); - } - } -} diff --git a/crates/ui-egui/src/tools/edit_text_ui/image.rs b/crates/ui-egui/src/tools/edit_text_ui/image.rs index 7b9d27630a..1fa2581f58 100644 --- a/crates/ui-egui/src/tools/edit_text_ui/image.rs +++ b/crates/ui-egui/src/tools/edit_text_ui/image.rs @@ -1,115 +1,78 @@ -use super::{ACCENT, Color32, CornerRadius, DocInfo, DocView, Edit, MAX_OUTLINES, PagePointer, PageXform, Pos2, Rect, Stroke, pos2, user_box}; -use crate::canvas::{ImageObb, PainterExt, image_screen_rect}; -use crate::image_engine::{CROP_ACCENT, apply_crop, apply_resize, apply_resize_proportional, draw_handle, draw_rule_of_thirds}; -use crate::page_cursor::Layer; -use crate::page_keys::PageKeys; -use crate::page_router::{CropPart, Hit, Owner, PagePress, PicturePart}; +use super::{DocInfo, DocView, Edit, MAX_OUTLINES, PageXform, Pos2, Rect, user_box}; +use crate::canvas::page_parts::{Owner, PageLayer, PagePart, PagePress}; +use craft::behavior::geometry::{BoxAllow, BoxRules, BoxState, CropBox, CropGuide, ScaleRule, TransformMode}; +use craft::behavior::kurbo::{BezPath, Point, Rect as DocRect, Vec2}; +use craft::behavior::{CursorIcon, EditEvent, HitShape, IconId, PointerButton}; +use craft::draw::ui::transform::{RotateZone, TransformBox}; +use craft::imaging::ui::transform_preview::{PreviewMap, PreviewPixels, PreviewTextures, TransformPreview}; +use craft::pages::ui::{PageBody, PlacedPage}; +use craft::ui::canvas::crop::{CropOutside, CropOverlay}; +use craft::ui::canvas_controls::{SelectionOutline, TaskBar}; +use craft::ui::contract::{Bind, Props as _, Show as _}; +use craft::ui::buttons::Button; +use craft::ui::display::Divider; +use craft::ui::menu::{Menu, MenuIcon, MenuIconRow, MenuItem}; -/// What the pointer and the page are, for the image tools on one page. -#[derive(Clone, Copy)] -pub(crate) struct ImageCx<'a> { - pub ui: &'a egui::Ui, - pub resp: &'a egui::Response, - pub xf: &'a PageXform, - pub ptr: &'a PagePointer, - pub page: usize, - pub doc: &'a pdfcraft_engine::Document, - pub info: &'a DocInfo, - /// What the press the pages hold is to this page. - pub press: PagePress, - /// Edit text's input is open: no dialog, palette, other window or other tab has it. - pub gate: bool, -} +pub(crate) use pdfcraft_content::Matrix; -/// The 8 resize handles on an image (4 corners + 4 edge centers). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum ImageHandle { - TopLeft, - TopCenter, - TopRight, - RightCenter, - BottomRight, - BottomCenter, - BottomLeft, - LeftCenter, -} +/// A change smaller than this, in document units, is no change. +const EPS: f64 = 1e-6; +/// A turn smaller than this, in degrees, is no turn. +const MIN_TURN: f64 = 0.05; -impl ImageHandle { - /// The resize cursor for this handle on an upright box. - pub(crate) fn cursor_icon(self) -> egui::CursorIcon { - match self { - ImageHandle::TopLeft | ImageHandle::BottomRight => egui::CursorIcon::ResizeNwSe, - ImageHandle::TopRight | ImageHandle::BottomLeft => egui::CursorIcon::ResizeNeSw, - ImageHandle::TopCenter | ImageHandle::BottomCenter => egui::CursorIcon::ResizeVertical, - ImageHandle::LeftCenter | ImageHandle::RightCenter => egui::CursorIcon::ResizeHorizontal, - } - } -} - -/// The handles in the order [`crop_handles`] places them: corners, then the top, right, bottom -/// and left edge midpoints. -const GRIPS: [ImageHandle; 8] = [ - ImageHandle::TopLeft, - ImageHandle::TopRight, - ImageHandle::BottomLeft, - ImageHandle::BottomRight, - ImageHandle::TopCenter, - ImageHandle::RightCenter, - ImageHandle::BottomCenter, - ImageHandle::LeftCenter, -]; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum DragTarget { - Move, - Handle(ImageHandle), - Rotate, -} - -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct ImageDrag { - pub start: Pos2, - pub target: DragTarget, - pub initial_rect: Rect, - /// Captured user-space frame: the visible crop for resizing, full placement for moving. - pub initial_matrix: [f64; 6], -} - -/// A selected page image, and what the pointer is doing to it. -#[derive(Clone, Debug, PartialEq)] +/// A selected page image, and the pixels shown while it is being changed. pub struct ImageSelection { pub page: usize, pub index: usize, - /// Dragging in progress. - pub drag: Option, /// Crop mode: the box kept so far. pub crop: Option, - /// The drag is turning the picture by its rotate handle (the `drag` start is then unused). - pub turning: bool, /// A move or resize applied on release: the frame it had and the one it got, in the page's /// 0..1 coordinates, while the page raster still has the picture where it was. pub settled: Option<(Rect, Rect)>, + /// The picture's pixels, cut from the page render when a gesture begins, drawn through the + /// box's map until the page render shows the picture where it went. It is the framework's + /// session object and is not cloned or compared. + pub(crate) preview: Option, + /// The frame the moving picture left on its page, in page units, rewritten every pass while the + /// preview shows: the page's content painter fills it with paper so the picture's old pixels do + /// not show beside the preview. Not cloned or compared. + // PLAN: the page's content painter (pdfcraft-canvas-w8) reads this and fills the quad with paper. + pub(crate) paper: Option<[Point; 4]>, +} + +impl Clone for ImageSelection { + fn clone(&self) -> Self { + Self { page: self.page, index: self.index, crop: self.crop.clone(), settled: self.settled, preview: None, paper: None } + } +} + +impl PartialEq for ImageSelection { + fn eq(&self, other: &Self) -> bool { + (self.page, self.index, &self.crop, self.settled) == (other.page, other.index, &other.crop, other.settled) + } +} + +impl std::fmt::Debug for ImageSelection { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ImageSelection") + .field("page", &self.page) + .field("index", &self.index) + .field("crop", &self.crop) + .field("settled", &self.settled) + .field("previewing", &self.preview.is_some()) + .finish() + } } impl ImageSelection { /// Select a page image without an active gesture. pub fn at(page: usize, index: usize) -> Self { - Self { page, index, drag: None, crop: None, turning: false, settled: None } + Self { page, index, crop: None, settled: None, preview: None, paper: None } } - /// Cancel an in-progress text, rotation or crop drag and restore the crop it was previewing. - pub(crate) fn cancel_pointer_gesture(&mut self) { - self.drag = None; - self.turning = false; - if let Some(crop) = &mut self.crop - && let Some((_, _, before)) = crop.drag.take() - { - crop.keep = before; - } - } - - pub(crate) fn dragging(&self) -> bool { - self.drag.is_some() + /// Whether a gesture is running: the pixels are cut and the page has not yet been edited. + fn gesturing(&self) -> bool { + self.preview.is_some() && self.settled.is_none() } } @@ -119,84 +82,14 @@ impl ImageSelection { pub struct CropMode { /// The box to keep (user space or normalized UV). pub keep: [f64; 4], - /// A drag in progress: the grip (0–7 handles, 8 inside), where it started and the box then. - pub(crate) drag: Option<(usize, Pos2, [f64; 4])>, - /// Where its Done, Cancel and Remove Crop controls were drawn last (screen): the hand shows - /// over them ([`crop_hit`]). - pub(crate) controls: Vec, } impl CropMode { pub fn new(keep: [f64; 4]) -> Self { - Self { keep, drag: None, controls: Vec::new() } + Self { keep } } } -/// How far from a crop grip a press still takes it, and the pointer shows its cursor (screen). -const CROP_GRIP_REACH: f32 = 10.0; - -/// The picture `image` being cropped to `keep`, on screen: its whole frame, and the box kept -/// within it. `None` when either has no area. -fn crop_frames(xf: &PageXform, info: &DocInfo, page: usize, image: &pdfcraft_engine::PageImage, keep: [f64; 4]) -> Option<(Rect, Rect)> { - let full = xf.user_rect(info, page, image.rect.map(|v| v as f32)); - let b = if full.is_positive() { full } else { xf.user_rect(info, page, image.visible_rect.unwrap_or(image.rect).map(|v| v as f32)) }; - let k = xf.user_rect(info, page, keep.map(|v| v as f32)).intersect(b); - (b.is_finite() && b.is_positive() && b.size().is_finite() && k.is_finite() && k.is_positive()).then_some((b, k)) -} - -pub(crate) use pdfcraft_content::Matrix; - -/// The displayed crop frame, expressed in page user space, rather than the full image placement. -fn resize_frame(obb: &ImageObb, xf: &PageXform, info: &DocInfo, page: usize) -> Matrix { - let p00 = screen_to_user(xf, info, page, obb.s00); - let p10 = screen_to_user(xf, info, page, obb.s10); - let p01 = screen_to_user(xf, info, page, obb.s01); - Matrix([p10.0 - p00.0, p10.1 - p00.1, p01.0 - p00.0, p01.1 - p00.1, p00.0, p00.1]) -} - -/// Resize from the captured press displacement in the frame's actual affine basis. -fn resize_affine_frame(frame: Matrix, handle: ImageHandle, delta: (f64, f64), proportional: bool) -> Option { - if !frame.0.iter().all(|v| v.is_finite()) || !delta.0.is_finite() || !delta.1.is_finite() { - return None; - } - if delta == (0.0, 0.0) { - return Some(frame); - } - let [a, b, c, d, _, _] = frame.0; - let inverse_basis = Matrix([a, b, c, d, 0.0, 0.0]).invert()?; - let (du, dv) = inverse_basis.apply(delta.0, delta.1); - if !du.is_finite() || !dv.is_finite() { - return None; - } - let (u, v) = match handle { - ImageHandle::TopRight => (1.0, 1.0), - ImageHandle::TopLeft => (-1.0, 1.0), - ImageHandle::BottomLeft => (-1.0, -1.0), - ImageHandle::BottomRight => (1.0, -1.0), - ImageHandle::RightCenter => (1.0, 0.0), - ImageHandle::LeftCenter => (-1.0, 0.0), - ImageHandle::TopCenter => (0.0, 1.0), - ImageHandle::BottomCenter => (0.0, -1.0), - }; - let (minimum_u, minimum_v) = (5.0 / a.hypot(b), 5.0 / c.hypot(d)); - let (mut su, mut sv) = (1.0 + u * du, 1.0 + v * dv); - if proportional && u != 0.0 && v != 0.0 { - let scale = if (su - 1.0).abs() >= (sv - 1.0).abs() { su } else { sv }; - su = scale.max(minimum_u).max(minimum_v); - sv = su; - } else { - if u != 0.0 { - su = su.max(minimum_u); - } - if v != 0.0 { - sv = sv.max(minimum_v); - } - } - let local = Matrix([su, 0.0, 0.0, sv, if u < 0.0 { 1.0 - su } else { 0.0 }, if v < 0.0 { 1.0 - sv } else { 0.0 }]); - let resized = local.then(&frame); - resized.0.iter().all(|v| v.is_finite()).then_some(resized) -} - pub(crate) fn user_to_screen(xf: &PageXform, info: &DocInfo, page: usize, x: f64, y: f64) -> Pos2 { let Some(p) = info.pages.get(page) else { return Pos2::ZERO }; let v = p.user_to_view(x as f32, y as f32); @@ -210,261 +103,260 @@ fn screen_to_user(xf: &PageXform, info: &DocInfo, page: usize, pt: Pos2) -> (f64 (f64::from(u[0]), f64::from(u[1])) } -pub(crate) fn quad_contains(quad: [Pos2; 4], p: Pos2) -> bool { - if !p.x.is_finite() || !p.y.is_finite() || quad.iter().any(|pt| !pt.x.is_finite() || !pt.y.is_finite()) { - return false; - } - let mut sign = 0; - for i in 0..4 { - let p1 = quad[i]; - let p2 = quad[(i + 1) % 4]; - let cross = (p2.x - p1.x) * (p.y - p1.y) - (p2.y - p1.y) * (p.x - p1.x); - if cross.abs() > 1e-4 { - let s = if cross > 0.0 { 1 } else { -1 }; - if sign == 0 { - sign = s; - } else if sign != s { - return false; - } - } - } - sign != 0 -} - -/// The screen positions of the crop's eight handles: corners, then the top, right, bottom and left edge midpoints. -fn crop_handles(k: Rect) -> [Pos2; 8] { - [k.left_top(), k.right_top(), k.left_bottom(), k.right_bottom(), k.center_top(), k.right_center(), k.center_bottom(), k.left_center()] -} - -// Keep a dragged crop inside the image, including images smaller than six screen pixels. -fn clamp_crop(b: Rect, new_screen: Rect) -> Rect { - if !b.is_finite() || !b.is_positive() || !b.size().is_finite() || !new_screen.is_finite() { - return new_screen; - } - let (min_w, min_h) = (6.0_f32.min(b.width()), 6.0_f32.min(b.height())); - Rect::from_min_max( - pos2(new_screen.min.x.clamp(b.min.x, b.max.x - min_w), new_screen.min.y.clamp(b.min.y, b.max.y - min_h)), - pos2(new_screen.max.x.clamp(b.min.x + min_w, b.max.x), new_screen.max.y.clamp(b.min.y + min_h, b.max.y)), - ) -} - -#[cfg(test)] -mod crop_bounds_tests { - use super::*; - - #[test] - fn crop_drag_rejects_nonfinite_bounds() { - for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - let bounds = Rect { min: pos2(value, 0.0), max: pos2(100.0, 100.0) }; - let keep = Rect::from_min_max(pos2(10.0, 10.0), pos2(50.0, 50.0)); - assert_eq!(clamp_crop(bounds, keep), keep); - } - } -} - fn same_rect(a: [f64; 4], b: [f64; 4]) -> bool { a.into_iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-3) } -/// Crop mode for the selected image `i` whose visible frame is `b` (screen). Returns `true` -/// (the pointer is the crop's while it lasts; its keys are read by [`picture_keys`]). -#[allow(clippy::cognitive_complexity)] -fn crop_input(cx: &ImageCx<'_>, view: &mut DocView, i: usize, image: &pdfcraft_engine::PageImage) -> bool { - let ImageCx { ui, resp, xf, ptr, page, info, press, gate, .. } = *cx; - let painter = ui.painter(); - let Some(mode) = view.image_selection.as_mut().and_then(|s| s.crop.as_mut()) else { return false }; - let hover_pos = ptr.pos; - let Some((b, k)) = crop_frames(xf, info, page, image, mode.keep) else { - mode.drag = None; - return true; +/// The four corners of the picture's frame on screen, top left, top right, bottom right and bottom +/// left of the picture as the box takes them: the selectable bounds when the picture is upright, +/// else the matrix's unit square. +fn picture_quad(xf: &PageXform, info: &DocInfo, page: usize, image: &pdfcraft_engine::PageImage) -> [Pos2; 4] { + let [a, b, c, d, ..] = image.matrix; + let turned = b.abs() > 1e-4 || c.abs() > 1e-4 || a < 0.0 || d < 0.0; + let bounds = crate::canvas::image_selectable_bounds(image); + let frame = if !turned && bounds[2] > bounds[0] && bounds[3] > bounds[1] { + Matrix([bounds[2] - bounds[0], 0.0, 0.0, bounds[3] - bounds[1], bounds[0], bounds[1]]) + } else { + Matrix(image.matrix) }; - let keep_screen = |keep: [f64; 4]| xf.user_rect(info, page, keep.map(|v| v as f32)).intersect(b); + matrix_corners(xf, info, page, frame.0) +} - // A drag takes what its press was on ([`crop_hit`]). - if gate - && ptr.drag_started - && let Some(o) = ptr.origin - && let PagePress::Mine(Owner::Picture { part: PicturePart::Crop(part), .. }) = press +/// The corners of the unit square under `matrix` on screen, top left clockwise as the picture's +/// pixels run. +fn matrix_corners(xf: &PageXform, info: &DocInfo, page: usize, matrix: [f64; 6]) -> [Pos2; 4] { + let frame = Matrix(matrix); + [(0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)].map(|(u, v)| { + let p = frame.apply(u, v); + user_to_screen(xf, info, page, p.0, p.1) + }) +} + +/// What the controls of the selected picture read of its page. +#[derive(Clone, Copy)] +struct PagePicture<'a> { + placed: &'a PlacedPage, + xf: &'a PageXform, + info: &'a DocInfo, + index: usize, + image: &'a pdfcraft_engine::PageImage, +} + +/// The least side a resize or crop leaves, in document units: one device pixel, so a side never +/// collapses to nothing or flips. +fn least_side(ui: &egui::Ui, placed: &PlacedPage) -> f64 { + 1.0 / (placed.scale.max(1e-6) * f64::from(ui.ctx().pixels_per_point()).max(1e-6)) +} + +fn bounds_of(q: &[Point; 4]) -> DocRect { + let xs = q.iter().map(|p| p.x); + let ys = q.iter().map(|p| p.y); + DocRect::new(xs.clone().fold(f64::INFINITY, f64::min), ys.clone().fold(f64::INFINITY, f64::min), xs.fold(f64::NEG_INFINITY, f64::max), ys.fold(f64::NEG_INFINITY, f64::max)) +} + +fn corners_of(r: DocRect) -> [Point; 4] { + [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)] +} + +/// The map that takes the parallelogram `from` onto `to`, corner for corner. +fn affine_between(from: [Point; 4], to: [Point; 4]) -> impl Fn(Point) -> Point { + let (e1, e2) = (from[1] - from[0], from[3] - from[0]); + let det = e1.x * e2.y - e1.y * e2.x; + let (f1, f2) = (to[1] - to[0], to[3] - to[0]); + move |p| { + let d = p - from[0]; + if det.abs() < 1e-12 { + return to[0] + d; + } + let a = (d.x * e2.y - d.y * e2.x) / det; + let b = (e1.x * d.y - e1.y * d.x) / det; + to[0] + f1 * a + f2 * b + } +} + +/// The picture's own decoded pixels, as the preview's texture: they cover the picture's whole +/// frame, so the preview follows the box whatever else the page shows there. +fn cut_preview(doc: &pdfcraft_engine::Document, placed: &PlacedPage, index: usize) -> Option { + let (w, h, rgba) = doc.page_image_rgba(placed.page, index).ok()?; + let size = [usize::try_from(w).ok()?, usize::try_from(h).ok()?]; + if size[0] == 0 || size[1] == 0 || rgba.len() != size[0].checked_mul(size[1])?.checked_mul(4)? { + return None; + } + let image = egui::ColorImage::from_rgba_premultiplied(size, &rgba); + Some(PreviewTextures::new(format!("picture-{}-{index}", placed.page), PreviewPixels::new(image, [1.0, 1.0]))) +} + +fn norm_rect(placed: &PlacedPage, xf: &PageXform, r: DocRect) -> Rect { + let n = |x: f64, y: f64| { + let (u, v) = xf.screen_to_norm(placed.to_screen(Point::new(x, y))); + Pos2::new(u, v) + }; + Rect::from_two_pos(n(r.x0, r.y0), n(r.x1, r.y1)) +} + +fn doc_rect(placed: &PlacedPage, xf: &PageXform, r: Rect) -> DocRect { + let d = |p: Pos2| placed.to_page(xf.norm_to_screen(p.x, p.y)); + DocRect::from_points(d(r.min), d(r.max)) +} + +fn path_of(q: &[Point; 4]) -> BezPath { + let mut path = BezPath::new(); + path.move_to(q[0]); + for p in &q[1..] { + path.line_to(*p); + } + path.close_path(); + path +} + +/// The controls of the selected picture on every page shown, and the faint outlines of the +/// pictures beside it. The edit a gesture commits comes back for the caller to queue. +pub(crate) fn picture_controls(ui: &mut egui::Ui, body: &PageBody<'_>, view: &mut DocView, doc: &pdfcraft_engine::Document, info: &DocInfo) -> Option { + let mut edit = None; + for placed in body.pages { + let Some(xf) = view.page_xform(placed.page) else { continue }; + let images = doc.page_images(placed.page); + let selection = view.image_selection.as_ref().filter(|s| s.page == placed.page && s.index < images.len()); + let selected = selection.map(|s| s.index); + let moving = selection.is_some_and(ImageSelection::gesturing); + let all = images.len() <= MAX_OUTLINES; + // Past MAX_OUTLINES only the selected picture is outlined: the hovered one is not in `PageBody`, and no hover state is kept between passes. + let paths: Vec = images + .iter() + .enumerate() + .filter(|(i, _)| !(moving && Some(*i) == selected) && (all || Some(*i) == selected)) + .map(|(_, image)| path_of(&picture_quad(&xf, info, placed.page, image).map(|p| placed.to_page(p)))) + .collect(); + if !paths.is_empty() { + let _ = SelectionOutline::faint(tl!("Pictures"), &paths).show(ui); + } + let Some(index) = selected else { continue }; + let Some(image) = images.get(index) else { continue }; + let cropping = view.image_selection.as_ref().is_some_and(|s| s.crop.is_some()); + let pic = PagePicture { placed, xf: &xf, info, index, image }; + let made = if cropping { crop_controls(ui, body, view, &pic) } else { box_controls(ui, body, view, doc, &pic) }; + edit = edit.or(made); + } + edit +} + +fn box_controls(ui: &mut egui::Ui, body: &PageBody<'_>, view: &mut DocView, doc: &pdfcraft_engine::Document, pic: &PagePicture<'_>) -> Option { + let PagePicture { placed, xf, info, index, image } = *pic; + let page = placed.page; + if !view.page_out_of_date(page) + && let Some(s) = view.image_selection.as_mut() + && s.settled.take().is_some() { - let grip = match part { - CropPart::Grip(g) => Some(g), - CropPart::Keep => Some(8), - CropPart::Cut | CropPart::Page => None, - }; - if let Some(g) = grip { - mode.drag = Some((g, o, mode.keep)); + s.preview = None; + } + let quad = picture_quad(xf, info, page, image).map(|p| placed.to_page(p)); + let bounds = bounds_of(&quad); + let pivot = bounds.center(); + let rules = BoxRules::in_mode(TransformMode::Free) + .with_scale(ScaleRule::Proportional) + .with_allow(BoxAllow::new(true, false, false)) + .with_min_side(least_side(ui, placed)); + let shown = TransformBox::new(tl!("Picture"), Bind::given(BoxState::new(quad, pivot)), bounds, 0.0) + .rules(rules) + .reference_point(false) + .rotate_zone(RotateZone::Knob) + // The arrow keys nudge through the tool (`EditTextTool::key`). + .session_arrows(false) + .show_at(ui, body.rect); + let to_user = |p: Point| screen_to_user(xf, info, page, placed.to_screen(p)); + let mut edit = None; + for event in shown.edit.events.iter() { + match event { + EditEvent::Begin { .. } => { + let cut = cut_preview(doc, placed, index); + if let Some(s) = view.image_selection.as_mut() { + s.preview = cut; + s.settled = None; + } + } + EditEvent::Commit { after, .. } => { + edit = picture_edit(page, index, image.matrix, image.rect, quad, after.quad, &to_user); + if let Some(s) = view.image_selection.as_mut() { + s.settled = edit.as_ref().map(|_| (norm_rect(placed, xf, bounds), norm_rect(placed, xf, bounds_of(&after.quad)))); + if s.settled.is_none() { + s.preview = None; + } + } + } + EditEvent::Cancel { .. } => { + if let Some(s) = view.image_selection.as_mut() { + s.preview = None; + } + } + _ => {} } } + // `shown.discard` (Escape with no drag) is ignored: a selected picture has no Escape outside crop mode. + let Some(s) = view.image_selection.as_mut() else { return edit }; + s.paper = None; + let Some(textures) = s.preview.as_ref() else { return edit }; + let (from, to) = match s.settled { + Some((from, to)) => (corners_of(doc_rect(placed, xf, from)), corners_of(doc_rect(placed, xf, to))), + None => (quad, shown.edit.shown.as_ref().and_then(|m| m.same()).map_or(quad, |state| state.quad)), + }; + s.paper = Some(from); + let full = matrix_corners(xf, info, page, image.matrix).map(|p| placed.to_page(p)); + let map = affine_between(from, to); + let _ = TransformPreview::new(tl!("Picture"), textures).map(PreviewMap::Quad(full.map(map))).picture().show(ui); + edit +} - if let Some((grip, start, at_start)) = mode.drag - && let Some(p) = hover_pos - { - let d = p - start; - let k0 = keep_screen(at_start); - if !d.is_finite() || !k0.is_finite() || !k0.is_positive() { - mode.drag = None; - return true; - } - if let Some(&handle) = GRIPS.get(grip) { - let uv0 = if b.width() > 0.0 && b.height() > 0.0 { - Rect::from_min_max( - pos2(((k0.min.x - b.min.x) / b.width()).clamp(0.0, 1.0), ((k0.min.y - b.min.y) / b.height()).clamp(0.0, 1.0)), - pos2(((k0.max.x - b.min.x) / b.width()).clamp(0.0, 1.0), ((k0.max.y - b.min.y) / b.height()).clamp(0.0, 1.0)), - ) - } else { - Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)) - }; - let (new_screen, _) = apply_crop(k0, uv0, handle, d); - let clamped = clamp_crop(b, new_screen); - mode.keep = user_box(xf, info, page, clamped); - } else { - let shift = egui::vec2(d.x.clamp(b.min.x - k0.min.x, b.max.x - k0.max.x), d.y.clamp(b.min.y - k0.min.y, b.max.y - k0.max.y)); - mode.keep = user_box(xf, info, page, Rect::from_min_max(k0.min + shift, k0.max + shift)); - } - if resp.drag_stopped() || !ptr.primary_down { - mode.drag = None; +fn crop_controls(ui: &mut egui::Ui, body: &PageBody<'_>, view: &mut DocView, pic: &PagePicture<'_>) -> Option { + let PagePicture { placed, xf, info, image, .. } = *pic; + let page = placed.page; + let keep = view.image_selection.as_ref().and_then(|s| s.crop.as_ref()).map(|c| c.keep)?; + let frame = picture_quad(xf, info, page, image).map(|p| placed.to_page(p)); + let kept_screen = xf.user_rect(info, page, keep.map(|v| v as f32)); + let kept = DocRect::from_points(placed.to_page(kept_screen.min), placed.to_page(kept_screen.max)); + let before = CropBox::upright(kept); + let mut crop = before; + let shown = CropOverlay::new(tl!("Crop"), Bind::bound(&mut crop)) + .outside(CropOutside::Apply) + .area(frame) + .bounds(bounds_of(&frame)) + .min_side(least_side(ui, placed)) + .guide((CropGuide::Thirds, 0)) + .show_at(ui, body.rect); + if crop.is_finite() && crop.rect != before.rect { + let to_screen = |p: Point| placed.to_screen(p); + let moved = Rect::from_two_pos(to_screen(Point::new(crop.rect.x0, crop.rect.y0)), to_screen(Point::new(crop.rect.x1, crop.rect.y1))); + let keep = user_box(xf, info, page, moved); + if let Some(mode) = view.image_selection.as_mut().and_then(|s| s.crop.as_mut()) { + mode.keep = keep; } } - - // Faint ghost outline of the full uncropped image underneath - painter.rect_stroke(b, CornerRadius::ZERO, Stroke::new(1.0, Color32::from_rgba_unmultiplied(200, 200, 200, 80)), egui::StrokeKind::Outside); - - // Dim outer excluded bands - let dim = Color32::from_black_alpha(96); - if k.min.y > b.min.y { - painter.rect_filled(Rect::from_min_max(b.min, Pos2::new(b.max.x, k.min.y)), CornerRadius::ZERO, dim); - } - if k.max.y < b.max.y { - painter.rect_filled(Rect::from_min_max(Pos2::new(b.min.x, k.max.y), b.max), CornerRadius::ZERO, dim); - } - if k.min.x > b.min.x { - painter.rect_filled(Rect::from_min_max(Pos2::new(b.min.x, k.min.y), Pos2::new(k.min.x, k.max.y)), CornerRadius::ZERO, dim); - } - if k.max.x < b.max.x { - painter.rect_filled(Rect::from_min_max(Pos2::new(k.max.x, k.min.y), Pos2::new(b.max.x, k.max.y)), CornerRadius::ZERO, dim); - } - - // Rule-of-Thirds Grid inside crop area - draw_rule_of_thirds(painter, k, Stroke::new(1.0, CROP_ACCENT.gamma_multiply(0.45))); - - // Crop border stroke - painter.rect_stroke(k, CornerRadius::ZERO, Stroke::new(1.5, CROP_ACCENT), egui::StrokeKind::Outside); - - // Crop handles - for (idx, h) in crop_handles(k).iter().enumerate() { - let is_active = mode.drag.as_ref().is_some_and(|d| d.0 == idx); - let is_hovered = hover_pos.is_some_and(|p| p.distance(*h) < CROP_GRIP_REACH); - draw_handle(painter, *h, is_active, is_hovered, true, CROP_ACCENT); - } - - // Action pills - let font = egui::FontId::proportional(12.5); - let done_w = painter.layout_no_wrap(tl!("Done").to_string(), font.clone(), Color32::WHITE).size().x + 22.0; - let cancel_w = painter.layout_no_wrap(tl!("Cancel").to_string(), font.clone(), Color32::WHITE).size().x + 22.0; + let keep = view.image_selection.as_ref().and_then(|s| s.crop.as_ref()).map_or(keep, |c| c.keep); let initial_keep = image.visible_rect.unwrap_or(image.rect); - let has_crop = image.has_editor_crop() || !same_rect(mode.keep, initial_keep); - let reset_w = - if has_crop { Some(painter.layout_no_wrap(tl!("Remove Crop").to_string(), font.clone(), Color32::WHITE).size().x + 22.0) } else { None }; - let spacing = 6.0; - let total_w = done_w + spacing + cancel_w + reset_w.map_or(0.0, |w| w + spacing); - - // Position pills below crop box if there's room, otherwise above - let y = if k.max.y + 32.0 < xf.rect.max.y { - k.max.y + 6.0 - } else if k.min.y - 28.0 > xf.rect.min.y { - k.min.y - 28.0 - } else { - k.max.y + 6.0 - }; - - // Right-align pills with k.max.x, clamped inside the page bounds - let mut right = k.max.x.min(xf.rect.max.x - 8.0); - if right - total_w < xf.rect.min.x + 8.0 { - right = (xf.rect.min.x + 8.0 + total_w).min(xf.rect.max.x - 8.0); - } - - let done = Rect::from_min_size(Pos2::new(right - done_w, y), egui::vec2(done_w, 22.0)); - let cancel = Rect::from_min_size(Pos2::new(done.min.x - spacing - cancel_w, y), egui::vec2(cancel_w, 22.0)); - let reset = reset_w.map(|w| Rect::from_min_size(Pos2::new(cancel.min.x - spacing - w, y), egui::vec2(w, 22.0))); - mode.controls = [Some(done), Some(cancel), reset].into_iter().flatten().collect(); - - let done_id = ui.scope_id().with("crop_pill_done").with(page).with(i); - let cancel_id = ui.scope_id().with("crop_pill_cancel").with(page).with(i); - let reset_id = ui.scope_id().with("crop_pill_reset").with(page).with(i); - - let done_resp = ui.interact(done, done_id, egui::Sense::click()); - let cancel_resp = ui.interact(cancel, cancel_id, egui::Sense::click()); - let reset_resp = reset.map(|r| ui.interact(r, reset_id, egui::Sense::click())); - done_resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, gate, tl!("Done"))); - cancel_resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, gate, tl!("Cancel"))); - if let Some(response) = &reset_resp { - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, gate, tl!("Remove Crop"))); - } - - let t = crate::theme::Tokens::get(ui.ctx()); - - // Done button (accent colored) - let done_bg = if done_resp.is_pointer_button_down_on() { - ACCENT.gamma_multiply(0.8) - } else if done_resp.hovered() { - Color32::from_rgb(40, 145, 255) - } else { - ACCENT - }; - painter.rect_filled(done, CornerRadius::same(11), done_bg); - painter.text(done.center(), egui::Align2::CENTER_CENTER, tl!("Done"), font.clone(), Color32::WHITE); - - let neutral_pill = |r: Rect, response: &egui::Response, label: &str| { - let background = if response.is_pointer_button_down_on() { - t.pressed - } else if response.hovered() { - t.hover - } else { - t.card - }; - let border = Stroke::new(1.0, if response.hovered() { ACCENT } else { t.border }); - let text = if response.hovered() { ACCENT } else { t.text }; - painter.rect(r, CornerRadius::same(11), background, border, egui::StrokeKind::Inside); - painter.text(r.center(), egui::Align2::CENTER_CENTER, label, font.clone(), text); - }; - neutral_pill(cancel, &cancel_resp, tl!("Cancel")); - if let (Some(r), Some(response)) = (reset, reset_resp.as_ref()) { - neutral_pill(r, response, tl!("Remove Crop")); - } - - // The cursor is the hit's ([`crop_hit`]), and a grip's or the box's being dragged. - if let Some((grip, ..)) = mode.drag { - view.cursor.claim(Layer::Drag, GRIPS.get(grip).map_or(egui::CursorIcon::Grabbing, |g| g.cursor_icon())); - } - - let done_clicked = gate && (done_resp.clicked() || (resp.clicked() && hover_pos.is_some_and(|p| done.contains(p)))); - let cancel_clicked = gate && (cancel_resp.clicked() || (resp.clicked() && hover_pos.is_some_and(|p| cancel.contains(p)))); - let reset_clicked = gate - && reset - .is_some_and(|r| reset_resp.as_ref().is_some_and(|res| res.clicked()) || (resp.clicked() && hover_pos.is_some_and(|p| r.contains(p)))); - // A click away from the picture (its shape, uncropped, not its bounds) and its crop box and - // handles applies the crop and lets the picture go, as Done and then that click would - // (#6422). It is pressed away too ([`CropPart::Page`]), so a press on the picture let go just - // past it is not one; a control's click is the control's. - let pressed_away = matches!(press, PagePress::Mine(Owner::Picture { part: PicturePart::Crop(CropPart::Page), .. })); - let away_clicked = gate - && resp.clicked() - && pressed_away - && !(done_clicked || cancel_clicked || reset_clicked) - && hover_pos.is_some_and(|p| matches!(crop_part(xf, info, page, Some(image), mode, p), None | Some(CropPart::Page))); - - if reset_clicked { - mode.keep = if image.has_editor_crop() { image.rect } else { initial_keep }; - mode.drag = None; - } else if done_clicked || away_clicked { - apply_crop_mode(view, image); - if away_clicked { - view.image_selection = None; + let has_crop = image.has_editor_crop() || !same_rect(keep, initial_keep); + let (mut reset, mut cancel, mut done) = (false, false, false); + let anchor = corners_of(crop.rect); + let _ = TaskBar::fixed(tl!("Crop"), &anchor).show(ui, body.rect, |ui, _| { + if has_crop { + reset |= Button::new(tl!("Remove Crop")).show(ui).clicks > 0; } - } else if cancel_clicked && let Some(s) = view.image_selection.as_mut() { + cancel |= Button::new(tl!("Cancel")).show(ui).clicks > 0; + done |= Button::new(tl!("Done")).show(ui).clicks > 0; + }); + if reset { + if let Some(mode) = view.image_selection.as_mut().and_then(|s| s.crop.as_mut()) { + mode.keep = if image.has_editor_crop() { image.rect } else { initial_keep }; + } + return None; + } + // PLAN: framework gap F-9: `CropOverlayOutput::apply` does not say it was an away click, so the selection stays after one. + if done || shown.apply { + apply_crop_mode(view, image); + } else if (cancel || shown.discard) + && let Some(s) = view.image_selection.as_mut() + { s.crop = None; } - true + None } /// Done in crop mode: it ends, and the picture `image` of the selection keeps the box kept (or @@ -482,181 +374,125 @@ fn apply_crop_mode(view: &mut DocView, image: &pdfcraft_engine::PageImage) { } } -/// The keys of the picture selected on `page`, a page being drawn, so the page grid and the Pages -/// panel have had theirs; nothing while the page is off the screen, as pages near it are drawn too. -/// Delete or Backspace removes it, wherever on the pages the pointer is, unless it is being cropped or -/// a button is down: the press held would then name another picture. In crop mode -/// Enter applies the crop and Escape leaves it, though not while a button is down (`held`): Escape -/// then cancels the press the pages hold, if any (`canvas::cancel_on_escape`), and crop mode stays. -/// Nothing while a text field has the keyboard. -pub(crate) fn picture_keys(ctx: &egui::Context, keys: PageKeys, view: &mut DocView, page: usize, images: &[pdfcraft_engine::PageImage], held: bool) { - if ctx.egui_wants_keyboard_input() || view.page_screen_rect(page).is_none() { - return; - } - let Some(s) = view.image_selection.as_ref().filter(|s| s.page == page) else { return }; - let index = s.index; - let key = |k: egui::Key| keys.pressed(ctx, k); - let image = images.get(index); - if s.crop.is_some() { - if key(egui::Key::Enter) { - if let Some(image) = image { - apply_crop_mode(view, image); - } - } else if !held - && key(egui::Key::Escape) - && let Some(s) = view.image_selection.as_mut() - { - s.crop = None; - } - } else if !held && !s.dragging() && !s.turning && (key(egui::Key::Delete) || key(egui::Key::Backspace)) && image.is_some() { - // The key is the picture's: added content's own Delete runs later this frame. - keys.take(ctx, egui::Key::Delete); - keys.take(ctx, egui::Key::Backspace); - view.image_selection = None; - // Added content's selection follows the picture's (`content_ui::sync_image_selection`), and - // goes with it: once the picture is gone it would be the next added item's. - view.content.selected = None; - view.pending_edit = Some(Edit::EditPageImage { page, index, change: pdfcraft_engine::ImageEdit::Delete }); - } -} - -/// The page raster's picture of the box `from`, stretched into `to`, over blanks at `blank` (where -/// the screen may still show the picture). -fn stretched_picture(painter: &egui::Painter, xf: &PageXform, tex: egui::TextureId, blank: &[Rect], from: Rect, to: Rect) { - let clipped = painter.with_clip_rect(painter.clip_rect().intersect(xf.rect)); - for r in blank { - clipped.rect_filled(*r, CornerRadius::ZERO, Color32::WHITE); - } - // The raster has no pixels beyond the page. Clip the source and its corresponding - // destination together, rather than stretching clamped edge texels into the preview. - let source = from.intersect(xf.rect); - if !source.is_positive() || !from.is_positive() { - return; - } - let target = egui::emath::RectTransform::from_to(from, to).transform_rect(source); - mapped_picture( - &clipped, - xf, - tex, - [source.left_top(), source.right_top(), source.right_bottom(), source.left_bottom()], - [target.left_top(), target.right_top(), target.right_bottom(), target.left_bottom()], - ); -} - -fn mapped_picture(painter: &egui::Painter, xf: &PageXform, tex: egui::TextureId, from: [Pos2; 4], to: [Pos2; 4]) { - let mut mesh = egui::Mesh::with_texture(tex); - for (from, to) in from.into_iter().zip(to) { - let (u, v) = xf.screen_to_norm(from); - mesh.vertices.push(egui::epaint::Vertex { pos: to, uv: Pos2::new(u, v), color: Color32::WHITE }); - } - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(0, 2, 3); - painter.add(egui::Shape::mesh(mesh)); -} - -fn picture_frame(painter: &egui::Painter, obb: &ImageObb, upright: Rect, fill: Color32, stroke: Stroke) { - if obb.is_rotated { - painter.polygon(obb.corners().to_vec(), fill, stroke); - } else if upright.is_positive() { - painter.rect(upright, CornerRadius::ZERO, fill, stroke, egui::StrokeKind::Outside); - } -} - -/// The selected picture's grips under `p`: its corners and its rotate knob. They are asked after -/// the paragraphs, so text on top of a picture cannot take them; `clip` is the pages' visible -/// area, which the knob stays inside. -#[allow(clippy::too_many_arguments)] -pub(crate) fn handle_hit( - clip: Rect, - xf: &PageXform, +/// The edit a box change makes to a picture of `matrix` and `rect`, from its corners `start` to +/// `end` (document units, top left clockwise); `to_user` takes a document point to user space. A +/// change of nothing is no edit, a translation or an upright resize is a move, a pure turn is a +/// turn, and anything else is the transform that takes the old corners onto the new. +fn picture_edit( page: usize, - info: &DocInfo, - images: &[pdfcraft_engine::PageImage], - view: &DocView, - p: Pos2, -) -> Option { - let s = view.image_selection.as_ref().filter(|s| s.page == page && s.crop.is_none())?; - let image = images.get(s.index)?; - let b = image_screen_rect(image, xf, info, page); - let obb = ImageObb::from_image(image, xf, info, page); - let picture = |part| Owner::Picture { index: s.index, part }; - let knob = if obb.is_rotated { obb.s_rot } else { rotate_knob(b, clip).0 }; - if knob.distance(p) < 8.0 { - return Some(Hit::new(picture(PicturePart::Knob), Layer::Handle, egui::CursorIcon::Grab)); - } - let (grip, (handle, _)) = obb.handles().into_iter().enumerate().find(|(_, (_, point))| point.distance(p) < 8.0)?; - Some(Hit::new(picture(PicturePart::Corner(grip)), Layer::Handle, obb.handle_cursor(handle))) + index: usize, + matrix: [f64; 6], + rect: [f64; 4], + start: [Point; 4], + end: [Point; 4], + to_user: &dyn Fn(Point) -> (f64, f64), +) -> Option { + let change = picture_change(matrix, rect, start, end, to_user)?; + Some(Edit::EditPageImage { page, index, change }) } -/// The picture being cropped on `page`, under `p`: crop mode holds every press on its page, the -/// controls beside its frame included, so the paragraphs under it and the empty page's marquee -/// never take a crop button's press before the picture does. A grip of the box kept (within -/// [`CROP_GRIP_REACH`], past the page's edge too), the box itself, the picture outside it (its frame -/// shown or its whole frame), or the rest of the page; and the controls past the page's edge, where -/// they show the hand. `None` when no picture on `page` is being cropped, or `p` is off the page, -/// its grips and its controls: the box and the picture stop at the page's edge, as a clipped -/// artwork's whole frame can reach over the next pages. -pub(crate) fn crop_hit(xf: &PageXform, page: usize, info: &DocInfo, images: &[pdfcraft_engine::PageImage], view: &DocView, p: Pos2) -> Option { - let s = view.image_selection.as_ref().filter(|s| s.page == page)?; - let mode = s.crop.as_ref()?; - let part = crop_part(xf, info, page, images.get(s.index), mode, p)?; - let icon = match part { - CropPart::Page if mode.controls.iter().any(|r| r.contains(p)) => egui::CursorIcon::PointingHand, - CropPart::Grip(g) => GRIPS.get(g).map_or(egui::CursorIcon::Default, |grip| grip.cursor_icon()), - CropPart::Keep => egui::CursorIcon::Grab, - CropPart::Page | CropPart::Cut => egui::CursorIcon::Default, - }; - Some(Hit::new(Owner::Picture { index: s.index, part: PicturePart::Crop(part) }, Layer::Editor, icon)) -} - -/// What of crop mode `mode` on the picture `image` lies under `p` ([`crop_hit`]): a control (as -/// [`CropPart::Page`]), a grip, the box kept, the picture outside it, or the rest of the page; -/// `None` off the page, its grips and its controls. -fn crop_part(xf: &PageXform, info: &DocInfo, page: usize, image: Option<&pdfcraft_engine::PageImage>, mode: &CropMode, p: Pos2) -> Option { - if mode.controls.iter().any(|r| r.contains(p)) { - return Some(CropPart::Page); - } - let kept = image.and_then(|image| crop_frames(xf, info, page, image, mode.keep)).map(|(_, k)| k); - // The grips reach past the page's edge, where those of a picture filling its page lie half. - if let Some(g) = kept.and_then(|k| crop_handles(k).iter().position(|h| h.distance(p) < CROP_GRIP_REACH)) { - return Some(CropPart::Grip(g)); - } - if !xf.rect.contains(p) { +fn picture_change(matrix: [f64; 6], rect: [f64; 4], start: [Point; 4], end: [Point; 4], to_user: &dyn Fn(Point) -> (f64, f64)) -> Option { + use pdfcraft_engine::ImageEdit as E; + let (s, e) = (start.map(to_user), end.map(to_user)); + if s.iter().chain(&e).any(|p| !p.0.is_finite() || !p.1.is_finite()) { return None; } - if kept.is_some_and(|k| k.contains(p)) { - return Some(CropPart::Keep); + let (dx, dy) = (e[0].0 - s[0].0, e[0].1 - s[0].1); + if (0..4).all(|i| (e[i].0 - s[i].0 - dx).abs() < EPS && (e[i].1 - s[i].1 - dy).abs() < EPS) { + if dx.abs() < EPS && dy.abs() < EPS { + return None; + } + return Some(E::Move([rect[0] + dx, rect[1] + dy, rect[2] + dx, rect[3] + dy])); } - let on_picture = image.is_some_and(|image| { - let shown = ImageObb::from_image(image, xf, info, page); - let whole = ImageObb::from_matrix(image.matrix, xf, info, page); - quad_contains(shown.corners(), p) || quad_contains(whole.corners(), p) - }); - Some(if on_picture { CropPart::Cut } else { CropPart::Page }) + let (sw, sh, ew, eh) = (start[1] - start[0], start[3] - start[0], end[1] - end[0], end[3] - end[0]); + let turn = |a: Vec2, b: Vec2| { + let d = b.atan2() - a.atan2(); + (d + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI + }; + let (tw, th) = (turn(sw, ew), turn(sh, eh)); + if (ew.hypot() - sw.hypot()).abs() < EPS && (eh.hypot() - sh.hypot()).abs() < EPS && (tw - th).abs() < EPS { + let degrees = tw.to_degrees(); + return (degrees.abs() >= MIN_TURN).then_some(E::RotateBy(degrees)); + } + let [a, b, c, d, ..] = matrix; + let upright_start = b.abs() < 1e-4 && c.abs() < 1e-4 && a > 0.0 && d > 0.0; + let (u, v) = ((e[2].0 - e[3].0, e[2].1 - e[3].1), (e[0].0 - e[3].0, e[0].1 - e[3].1)); + let upright_end = u.1.abs() < EPS && v.0.abs() < EPS && u.0 > 0.0 && v.1 > 0.0; + if upright_start && upright_end { + let (fw, fh) = (s[2].0 - s[3].0, s[0].1 - s[3].1); + if fw.abs() > 1e-9 && fh.abs() > 1e-9 { + let (kx, ky) = (u.0 / fw, v.1 / fh); + let at = |x: f64, y: f64| (e[3].0 + (x - s[3].0) * kx, e[3].1 + (y - s[3].1) * ky); + let (p0, p1) = (at(rect[0], rect[1]), at(rect[2], rect[3])); + return Some(E::Move([p0.0, p0.1, p1.0, p1.1])); + } + } + let frame = |c: [(f64, f64); 4]| Matrix([c[2].0 - c[3].0, c[2].1 - c[3].1, c[0].0 - c[3].0, c[0].1 - c[3].1, c[3].0, c[3].1]); + let t = frame(s).invert()?.then(&frame(e)); + t.0.iter().all(|v| v.is_finite()).then_some(E::Transform(t.0)) } -/// The picture under `p` (its shape, not only its box; for the selected one, its frame, a hole in it -/// included): a click selects it, a drag moves the selected one. On the text layer, asked before -/// the paragraphs: editable text on top of a picture takes the press. -pub(crate) fn body_hit(xf: &PageXform, page: usize, info: &DocInfo, images: &[pdfcraft_engine::PageImage], view: &DocView, p: Pos2) -> Option { - if !xf.rect.contains(p) { +/// The parts of the pictures of `page`, in paint order so the topmost wins a press: a picture's +/// visible shape, and for the selected one its whole frame, a hole in it included. None while +/// the picture is cropped, whose crop overlay holds the page. +pub(crate) fn picture_parts(view: &DocView, doc: &pdfcraft_engine::Document, page: usize, placed: &PlacedPage) -> Vec { + let Some(xf) = view.page_xform(page) else { return Vec::new() }; + let selection = view.image_selection.as_ref().filter(|s| s.page == page); + if selection.is_some_and(|s| s.crop.is_some()) { + return Vec::new(); + } + let selected = selection.map(|s| s.index); + doc.page_images(page) + .iter() + .enumerate() + .map(|(index, image)| { + let quad = picture_quad(&xf, &doc.info, page, image); + let visible = image.visible_rect.map(|r| xf.user_rect(&doc.info, page, r.map(|v| v as f32)).intersect(placed.rect)); + let (shape, icon) = if selected == Some(index) { + (HitShape::Polygon(quad.to_vec()), CursorIcon::Move) + } else { + (visible.map_or_else(|| HitShape::Polygon(quad.to_vec()), HitShape::Rect), CursorIcon::PointingHand) + }; + PagePart::new(Owner::Picture { index }, page, shape, PageLayer::Picture).cursor(icon) + }) + .collect() +} + +/// A press that went to a picture: a click selects it, or on grouped artwork with text prepares +/// the page so the paragraph clicked opens (a drag still moves the group selected). +pub(crate) fn picture_press(view: &mut DocView, doc: &pdfcraft_engine::Document, press: &PagePress) -> Option { + let Owner::Picture { index } = press.owner else { return None }; + let start = press.phase.start().filter(|s| s.button == PointerButton::Primary)?; + if !press.phase.is_click() { return None; } - let (x, y) = xf.screen_to_view(p); - let user = info.pages.get(page)?.view_to_user(x, y).map(f64::from); - let on_picture = |im: &pdfcraft_engine::PageImage| { - im.visible_rect.is_some_and(|r| xf.user_rect(info, page, r.map(|v| v as f32)).contains(p)) && im.contains(user) - }; - // The selected picture's frame is its own, a hole in it and a picture over it included. - let framed = - view.image_selection.as_ref().filter(|s| s.page == page && s.crop.is_none()).map(|s| s.index).filter(|i| { - images.get(*i).is_some_and(|image| on_picture(image) || quad_contains(ImageObb::from_image(image, xf, info, page).corners(), p)) - }); - let index = images.iter().rposition(on_picture).or(framed)?; - let selected = view.image_selection.as_ref().is_some_and(|s| s.page == page && s.index == index); - let icon = if selected { egui::CursorIcon::Move } else { egui::CursorIcon::PointingHand }; - let part = if framed.is_some_and(|i| i != index) { PicturePart::OverSelected } else { PicturePart::Body }; - Some(Hit::new(Owner::Picture { index, part }, Layer::Text, icon)) + let page = press.page; + let grouped = doc.page_images(page).get(index).is_some_and(|im| im.is_form) + && view.pending_edit.is_none() + && view.line_editor.is_none() + && doc.grouped_text_at(page, index); + if grouped && let Some(xf) = view.page_xform(page) { + let (x, y) = screen_to_user(&xf, &doc.info, page, start.origin); + view.image_selection = None; + view.grouped_text_click = Some((page, [x, y])); + return Some(Edit::PrepareText { page }); + } + view.image_selection = Some(ImageSelection::at(page, index)); + None +} + +/// Delete or Backspace on the selected picture, while its page is shown and it is not being cropped +/// or changed. +pub(crate) fn delete_picture(view: &mut DocView, placed: &[PlacedPage]) -> Option { + let s = view.image_selection.as_ref().filter(|s| s.crop.is_none() && !s.gesturing())?; + if !placed.iter().any(|p| p.page == s.page) { + return None; + } + let (page, index) = (s.page, s.index); + view.image_selection = None; + // Added content's selection follows the picture's, and goes with it. + view.content.selected = None; + Some(Edit::EditPageImage { page, index, change: pdfcraft_engine::ImageEdit::Delete }) } /// What a right-click on a selected image asks for. @@ -679,367 +515,6 @@ pub enum ImageAction { AddComment(usize, usize), } -/// Where the rotate knob sits, and the edge point its stem starts from: above the middle of the -/// top edge, or below the bottom edge when the area on screen (`view`) has no room above. -pub(super) fn rotate_knob(b: Rect, view: Rect) -> (Pos2, Pos2) { - let above = b.center_top() - egui::vec2(0.0, 22.0); - if above.y - 6.0 >= view.top() { (above, b.center_top()) } else { (b.center_bottom() + egui::vec2(0.0, 22.0), b.center_bottom()) } -} - -/// Degrees clockwise (-180..=180) that turn from `start` onto `pointer` around `centre`; `snap` -/// rounds to steps of 15 degrees (Shift). A pointer on the centre turns nothing. -pub(super) fn turn_degrees_delta(centre: Pos2, start: Pos2, pointer: Pos2, snap: bool) -> f32 { - let v_start = start - centre; - let v_curr = pointer - centre; - if !(v_curr.x.is_finite() && v_curr.y.is_finite()) - || v_curr.length() < 4.0 - || !(v_start.x.is_finite() && v_start.y.is_finite()) - || v_start.length() < 4.0 - { - return 0.0; - } - // Screen y points down: up is (0, -1); clockwise is atan2(x, -y). - let theta_start = v_start.x.atan2(-v_start.y).to_degrees(); - let theta_curr = v_curr.x.atan2(-v_curr.y).to_degrees(); - let mut d = theta_curr - theta_start; - d = ((d + 180.0).rem_euclid(360.0)) - 180.0; - if snap { (d / 15.0).round() * 15.0 } else { d } -} - -/// 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. -#[cfg(test)] -pub(super) fn turn_degrees(centre: Pos2, pointer: Pos2, snap: bool) -> f32 { - turn_degrees_delta(centre, centre - egui::vec2(0.0, 10.0), pointer, snap) -} - -/// Images on a page: the press that is a picture's (`press`, [`body_hit`] and [`handle_hit`]) -/// selects it, a drag of the selected one moves, resizes or turns it. Returns `true` when the -/// pointer was used. -#[allow(clippy::cognitive_complexity)] -pub(crate) fn image_input(cx: &ImageCx<'_>, images: &[pdfcraft_engine::PageImage], view: &mut DocView) -> bool { - let ImageCx { ui, resp, xf, ptr, page, doc, info, press, gate } = *cx; - let boxes: Vec = images.iter().map(|im| crate::canvas::image_screen_rect(im, xf, info, page)).collect(); - let painter = ui.painter(); - let hover_pos = ptr.pos; - let image_contains = |index: usize, point: Pos2| { - let (x, y) = xf.screen_to_view(point); - let Some(p) = info.pages.get(page) else { return false }; - let user = p.view_to_user(x, y); - images.get(index).is_some_and(|im| im.contains(user.map(f64::from))) - }; - let selected = view.image_selection.as_ref().filter(|s| s.page == page).map(|s| s.index).filter(|i| *i < boxes.len()); - let dragging = view.image_selection.as_ref().is_some_and(|s| s.drag.is_some()); - let faint_all = boxes.len() <= MAX_OUTLINES; - let moving = selected.filter(|_| dragging); - if faint_all { - for (idx, im) in images.iter().enumerate() { - if moving == Some(idx) { - continue; - } - if let Some(b) = boxes.get(idx).filter(|b| b.is_positive()) { - let obb = ImageObb::from_image(im, xf, info, page); - if obb.is_rotated { - let pts = obb.corners(); - for k in 0..4 { - painter.line_segment([pts[k], pts[(k + 1) % 4]], Stroke::new(0.75, ACCENT.gamma_multiply(0.35))); - } - } else { - painter.rect_stroke(*b, CornerRadius::ZERO, Stroke::new(0.75, ACCENT.gamma_multiply(0.35)), egui::StrokeKind::Outside); - } - } - } - } - let hovered_box = hover_pos.and_then(|p| { - boxes.iter().enumerate().rposition(|(i, b)| { - b.is_positive() && images.get(i).is_some_and(|img| ImageObb::from_image(img, xf, info, page).contains(*b, p)) && image_contains(i, p) - }) - }); - if !faint_all { - for i in selected.filter(|_| moving.is_none()).into_iter().chain(hovered_box.filter(|h| Some(*h) != selected)) { - if let (Some(b), Some(img)) = (boxes.get(i).filter(|b| b.is_positive()), images.get(i)) { - let obb = ImageObb::from_image(img, xf, info, page); - picture_frame(painter, &obb, *b, Color32::TRANSPARENT, Stroke::new(0.75, ACCENT.gamma_multiply(0.35))); - } - } - } - for i in selected.into_iter().chain(hovered_box).collect::>() { - let (Some(b), Some(img)) = (boxes.get(i).copied().filter(|b| b.is_positive()), images.get(i)) else { continue }; - let obb = ImageObb::from_image(img, xf, info, page); - if selected == Some(i) { - if !dragging { - picture_frame(painter, &obb, b, ACCENT.gamma_multiply(0.04), Stroke::NONE); - } - } else { - picture_frame(painter, &obb, b, Color32::TRANSPARENT, Stroke::new(1.5, ACCENT.gamma_multiply(0.7))); - } - } - - // The selected image: frame, corner handles, dragging. - if let Some(i) = selected.filter(|i| boxes.get(*i).is_some_and(|b| b.is_positive())) { - let Some(b) = boxes.get(i).copied() else { return false }; - let Some(image) = images.get(i) else { return false }; - let obb = ImageObb::from_image(image, xf, info, page); - let (out_of_date, raster_old, raster) = (view.page_out_of_date(page), view.page_raster_out_of_date(page), view.page_raster(page)); - let screen = |r: Rect| Rect::from_two_pos(xf.norm_to_screen(r.min.x, r.min.y), xf.norm_to_screen(r.max.x, r.max.y)); - let left_at = view.image_selection.as_ref().and_then(|s| s.settled).filter(|_| out_of_date).map(|(from, _)| from); - if let Some(s) = view.image_selection.as_mut().filter(|s| s.drag.is_none()) { - match (s.settled, raster) { - (Some((from, to)), Some(tex)) if out_of_date => { - let source = if raster_old { from } else { to }; - stretched_picture(painter, xf, tex, &[screen(from)], screen(source), screen(to)); - } - _ if !out_of_date => s.settled = None, - _ => {} - } - } - - if view.image_selection.as_ref().is_some_and(|s| s.crop.is_some()) { - return crop_input(cx, view, i, image); - } - let (knob, stem) = rotate_knob(b, ui.clip_rect()); - let shown_knob = if obb.is_rotated { obb.s_rot } else { knob }; - if view.image_selection.as_ref().is_some_and(|s| s.drag.is_none()) { - picture_frame(painter, &obb, b, Color32::TRANSPARENT, Stroke::new(1.5, ACCENT)); - if obb.is_rotated { - painter.line_segment([obb.s_tc, obb.s_rot], Stroke::new(1.2, ACCENT)); - painter.circle(obb.s_rot, 4.5, Color32::WHITE, Stroke::new(1.0, ACCENT)); - } else { - painter.line_segment([stem, knob], Stroke::new(1.0, ACCENT)); - painter.circle(knob, 5.0, Color32::WHITE, Stroke::new(1.0, ACCENT)); - } - for (_, h) in obb.handles() { - let is_hovered = hover_pos.is_some_and(|p| p.distance(h) < 10.0); - draw_handle(painter, h, false, is_hovered, false, ACCENT); - } - } - - // A drag of the selected picture takes what its press was on ([`body_hit`], [`handle_hit`]): - // the rotate knob turns it, a grip resizes it, the picture itself moves. The knob and the - // grips take it from the press, so a move too short to be a drag of the page counts; the - // picture waits for that, as a click selects. - let at_press = |part| matches!(part, PicturePart::Knob | PicturePart::Corner(_)); - if gate - && let Some(o) = ptr.origin - && let PagePress::Mine(Owner::Picture { index, part }) = press - && (index == i || part == PicturePart::OverSelected) - && (ptr.drag_started || at_press(part) && ptr.pressed().is_some()) - && let Some(s) = view.image_selection.as_mut().filter(|s| s.drag.is_none()) - { - match part { - PicturePart::Knob => { - s.drag = Some(ImageDrag { start: o, target: DragTarget::Rotate, initial_rect: b, initial_matrix: image.matrix }); - s.turning = true; - } - PicturePart::Corner(grip) => { - if let Some((h, _)) = obb.handles().get(grip) { - s.drag = Some(ImageDrag { - start: o, - target: DragTarget::Handle(*h), - initial_rect: b, - initial_matrix: resize_frame(&obb, xf, info, page).0, - }); - } - } - PicturePart::Body | PicturePart::OverSelected => { - s.drag = Some(ImageDrag { start: o, target: DragTarget::Move, initial_rect: b, initial_matrix: image.matrix }); - } - PicturePart::Crop(_) => {} - } - } - - if view.image_selection.as_ref().is_some_and(|s| s.turning) { - let shift = ui.input(|i| i.modifiers.shift); - let visible = image.visible_rect.unwrap_or(image.rect); - let centre = user_to_screen(xf, info, page, visible[0] * 0.5 + visible[2] * 0.5, visible[1] * 0.5 + visible[3] * 0.5); - let rot_knob = shown_knob; - let drag_start = view.image_selection.as_ref().and_then(|s| s.drag).map_or(rot_knob, |d| d.start); - let degrees = hover_pos.map_or(0.0, |p| turn_degrees_delta(centre, drag_start, p, shift)); - 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 = obb.corners().map(turn).to_vec(); - painter.add(egui::Shape::closed_line(outline, Stroke::new(1.5, ACCENT))); - let galley = painter.layout_no_wrap(format!("{degrees:.0}\u{b0}"), egui::FontId::proportional(12.0), ACCENT); - let label = Rect::from_center_size(turn(rot_knob) - egui::vec2(0.0, 14.0), galley.size() + egui::vec2(8.0, 4.0)); - painter.rect(label, CornerRadius::same(3), Color32::WHITE, Stroke::new(1.0, ACCENT), egui::StrokeKind::Middle); - painter.galley(label.center() - galley.size() / 2.0, galley, ACCENT); - view.cursor.claim(Layer::Drag, egui::CursorIcon::Grabbing); - if resp.drag_stopped() || !ptr.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(drag) = view.image_selection.as_ref().and_then(|s| s.drag) - && let Some(p) = hover_pos - { - if !obb.is_rotated && !matches!(drag.target, DragTarget::Rotate) { - let preview = match drag.target { - DragTarget::Handle(handle) => { - let delta = p - drag.start; - let is_corner = - matches!(handle, ImageHandle::TopLeft | ImageHandle::TopRight | ImageHandle::BottomLeft | ImageHandle::BottomRight); - let shift = ui.input(|inp| inp.modifiers.shift); - if is_corner && !shift { - apply_resize_proportional(drag.initial_rect, handle, delta) - } else { - apply_resize(drag.initial_rect, handle, delta) - } - } - DragTarget::Move => drag.initial_rect.translate(p - drag.start), - _ => drag.initial_rect, - }; - - let raw = images.get(i).map_or(b, |im| xf.user_rect(info, page, im.rect.map(|v| v as f32))); - let ratio = |new: f32, old: f32| if old.abs() > 1e-3 && (new / old).is_finite() { new / old } else { 1.0 }; - let factor = egui::vec2(ratio(preview.width(), b.width()), ratio(preview.height(), b.height())); - let f_min = egui::vec2((raw.min.x - b.min.x) * factor.x, (raw.min.y - b.min.y) * factor.y); - let f_max = egui::vec2((raw.max.x - b.min.x) * factor.x, (raw.max.y - b.min.y) * factor.y); - let target = Rect::from_min_max(preview.min + f_min, preview.min + f_max); - let visible = preview.intersect(xf.rect); - - if visible.is_positive() { - if preview != b - && let Some(tex) = raster - { - let source = left_at.filter(|_| raster_old).map_or(b, screen); - let blank: Vec = left_at.map(screen).into_iter().chain(std::iter::once(b)).collect(); - stretched_picture(painter, xf, tex, &blank, source, preview); - } - painter.rect_filled(visible, CornerRadius::ZERO, ACCENT.gamma_multiply(0.04)); - painter.rect_stroke(visible, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside); - for h in [ - preview.left_top(), - preview.right_top(), - preview.left_bottom(), - preview.right_bottom(), - preview.center_top(), - preview.right_center(), - preview.center_bottom(), - preview.left_center(), - ] { - draw_handle(painter, h, false, false, false, ACCENT); - } - } - - if resp.drag_stopped() || !ptr.primary_down { - if let Some(s) = view.image_selection.as_mut() { - s.drag = None; - let norm = |r: Rect| { - let ((u0, v0), (u1, v1)) = (xf.screen_to_norm(r.min), xf.screen_to_norm(r.max)); - Rect::from_two_pos(Pos2::new(u0, v0), Pos2::new(u1, v1)) - }; - s.settled = (preview != b).then(|| (left_at.unwrap_or_else(|| norm(b)), norm(preview))); - } - if preview != b { - view.pending_edit = - Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Move(user_box(xf, info, page, target)) }); - } - } - - let icon = match drag.target { - DragTarget::Handle(handle) => obb.handle_cursor(handle), - DragTarget::Move => egui::CursorIcon::Grabbing, - _ => egui::CursorIcon::Move, - }; - view.cursor.claim(Layer::Drag, icon); - return true; - } - let m_init = Matrix(drag.initial_matrix); - let [a0, b0, c0, d0, e0, f0] = drag.initial_matrix; - let (sx, sy) = screen_to_user(xf, info, page, drag.start); - let (px, py) = screen_to_user(xf, info, page, p); - - let (m_new, cursor_icon) = match drag.target { - DragTarget::Move => { - let (dx, dy) = (px - sx, py - sy); - (Matrix([a0, b0, c0, d0, e0 + dx, f0 + dy]), egui::CursorIcon::Move) - } - DragTarget::Handle(handle) => { - let proportional = !ui.input(|input| input.modifiers.shift); - let resized = resize_affine_frame(m_init, handle, (px - sx, py - sy), proportional).unwrap_or(m_init); - (resized, obb.handle_cursor(handle)) - } - // Turning is handled above. - DragTarget::Rotate => (m_init, egui::CursorIcon::Default), - }; - - let preview_obb = ImageObb::from_matrix(m_new.0, xf, info, page); - if let Some(tex) = view.page_raster(page) { - let clipped = painter.with_clip_rect(painter.clip_rect().intersect(xf.rect)); - let mut from = obb.corners(); - let mut to = preview_obb.corners(); - from.reverse(); - to.reverse(); - mapped_picture(&clipped, xf, tex, from, to); - } - - let visible = Rect::from_two_pos(preview_obb.s01, preview_obb.s10).intersect(xf.rect); - picture_frame(painter, &preview_obb, visible, ACCENT.gamma_multiply(0.04), Stroke::new(1.5, ACCENT)); - for (_, h) in preview_obb.handles() { - draw_handle(painter, h, false, false, false, ACCENT); - } - - if resp.drag_stopped() || !ptr.primary_down { - if let Some(s) = view.image_selection.as_mut() { - s.drag = None; - } - if m_new.0 != drag.initial_matrix { - if matches!(drag.target, DragTarget::Move) { - let (dx, dy) = (px - sx, py - sy); - let new_rect = [image.rect[0] + dx, image.rect[1] + dy, image.rect[2] + dx, image.rect[3] + dy]; - view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Move(new_rect) }); - } else if let Some(inv) = Matrix(drag.initial_matrix).invert() { - let t = inv.then(&m_new); - view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Transform(t.0) }); - } - } - } - view.cursor.claim(Layer::Drag, cursor_icon); - return true; - } - } - // A click selects the picture its press was on; its cursor is the hit's. One on grouped - // artwork with text prepares the page instead (one undoable step), and the paragraph clicked - // opens once it has (`edit_text_ui::page_input`): a drag still moves the group selected. Not - // while an edit is queued or a paragraph is open, whose typing that edit would overtake. One - // nobody holds on this page leaves the picture unselected (where the page's objects can be - // selected together, the area selection the press starts has done so already). - let owner = match press { - PagePress::Mine(Owner::Picture { index, .. }) => Some(index), - _ => None, - }; - if gate && resp.clicked() { - // Where grouped artwork with text was clicked; the page is read for it once, on the click. - let grouped_text = owner - .filter(|i| images.get(*i).is_some_and(|im| im.is_form) && view.pending_edit.is_none() && view.line_editor.is_none()) - .zip(ptr.released.or(ptr.origin)) - .filter(|(i, _)| doc.grouped_text_at(page, *i)); - match (owner, grouped_text) { - (_, Some((_, at))) => { - let (x, y) = screen_to_user(xf, info, page, at); - view.image_selection = None; - view.pending_edit = Some(Edit::PrepareText { page }); - view.grouped_text_click = Some((page, [x, y])); - } - (Some(index), None) => view.image_selection = Some(ImageSelection::at(page, index)), - (None, _) if press == PagePress::Free && ptr.released.is_some_and(|p| xf.rect.contains(p)) => view.image_selection = None, - (None, _) => {} - } - } - owner.is_some() -} - /// A right-click on `page` that went to its picture `index` (on it or a grip of it) selects it for /// its menu, keeping it as it is if it was selected (crop mode included); one that went to anything /// else (`None`) unselects the picture selected. @@ -1053,76 +528,71 @@ pub(crate) fn picture_context(page: usize, index: Option, view: &mut DocV } } -/// The right-click context menu for a selected image. -#[allow(clippy::too_many_arguments)] -pub(crate) fn image_context_menu( - ui: &mut egui::Ui, - view: &mut DocView, - images: &[pdfcraft_engine::PageImage], - page: usize, - hit: usize, - can_paste: bool, - action: &mut Option, - at: Option<[f64; 2]>, - rotation: u16, -) { - let Some(img) = images.get(hit) else { return }; +/// One row of the menu: whether it ran. +fn item(ui: &mut egui::Ui, enabled: bool, label: &str) -> bool { + MenuItem::new(label).enabled(enabled).show(ui).ran +} + +/// What the picture menu needs to know of its target: the pictures of `page`, the selected one +/// `hit`, whether a picture can be pasted, where a paste would go and the page's rotation. +#[derive(Clone, Copy)] +pub(crate) struct PictureMenu<'a> { + pub(crate) images: &'a [pdfcraft_engine::PageImage], + pub(crate) page: usize, + pub(crate) hit: usize, + pub(crate) can_paste: bool, + pub(crate) at: Option<[f64; 2]>, + pub(crate) rotation: u16, +} + +/// The right-click menu of the selected picture `menu.hit` on `menu.page`; the action it asks the +/// caller to run, if any (edits it makes itself are queued on `view`). +pub(crate) fn picture_menu(ui: &mut egui::Ui, view: &mut DocView, menu: &PictureMenu<'_>) -> Option { + let PictureMenu { images, page, hit, can_paste, at, rotation } = *menu; + let img = images.get(hit)?; use pdfcraft_engine::ImageEdit as E; let raster = !img.is_form; - - // Whether `entry` was clicked; a click closes the menu. - let picked = |ui: &mut egui::Ui, entry: egui::Response| { - let clicked = entry.clicked(); - if clicked { - egui::Popup::close_all(ui.ctx()); - ui.close(); - } - clicked - }; - let item = |ui: &mut egui::Ui, enabled: bool, label: &str| { - let entry = ui.add_enabled(enabled, egui::Button::new(label)); - picked(ui, entry) - }; + let mut action = None; let edit = |change| Some(Edit::EditPageImage { page, index: hit, change }); - // Top horizontal icon bar: Comment, Crop, Rotate CCW, Rotate CW - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - let icon = |ui: &mut egui::Ui, name: &str, tip: &str| { - let entry = crate::icons::button(ui, name, 24.0, false, tip); - picked(ui, entry) - }; - if icon(ui, "message-square", tl!("Add a sticky note here")) { - *action = Some(ImageAction::AddComment(page, hit)); + #[derive(Clone, Copy)] + enum Pick { + Note, + Crop, + Ccw, + Cw, + } + let mut picks = vec![(Pick::Note, "message-square", tl!("Add a sticky note here"))]; + if raster { + picks.push((Pick::Crop, "crop", tl!("Crop"))); + } + picks.push((Pick::Ccw, "rotate-ccw", tl!("Rotate Counterclockwise"))); + picks.push((Pick::Cw, "rotate-cw", tl!("Rotate Clockwise"))); + let icons: Vec> = picks.iter().map(|(_, name, label)| MenuIcon::new(IconId::new(*name), *label)).collect(); + if let Some(picked) = MenuIconRow::new(tl!("Picture"), &icons).show(ui).picked.and_then(|i| picks.get(i)) { + match picked.0 { + Pick::Note => action = Some(ImageAction::AddComment(page, hit)), + Pick::Crop => { + if let Some(s) = view.image_selection.as_mut() { + s.crop = Some(CropMode::new(img.visible_rect.unwrap_or(img.rect))); + } + } + Pick::Ccw => view.pending_edit = edit(E::Rotate(3)), + Pick::Cw => view.pending_edit = edit(E::Rotate(1)), } - if raster - && icon(ui, "crop", tl!("Crop")) - && let Some(s) = view.image_selection.as_mut() - { - s.crop = Some(CropMode::new(img.visible_rect.unwrap_or(img.rect))); - } - if icon(ui, "rotate-ccw", tl!("Rotate Counterclockwise")) { - view.pending_edit = edit(E::Rotate(3)); - } - if icon(ui, "rotate-cw", tl!("Rotate Clockwise")) { - view.pending_edit = edit(E::Rotate(1)); - } - }); - - ui.separator(); + } + let _ = Divider::horizontal().show(ui); if item(ui, true, tl!("Cut Image")) { - *action = Some(ImageAction::Cut(page, hit)); + action = Some(ImageAction::Cut(page, hit)); } if item(ui, true, tl!("Copy Image")) { - *action = Some(ImageAction::Copy(page, hit)); + action = Some(ImageAction::Copy(page, hit)); } if item(ui, can_paste, tl!("Paste")) { - *action = Some(ImageAction::Paste(page, at)); + action = Some(ImageAction::Paste(page, at)); } - - ui.separator(); - + let _ = Divider::horizontal().show(ui); if raster && img.has_editor_crop() && item(ui, true, tl!("Remove crop")) { view.pending_edit = edit(E::RemoveCrop); } @@ -1132,8 +602,7 @@ pub(crate) fn image_context_menu( if item(ui, true, tl!("Flip vertical")) { view.pending_edit = edit(E::Flip { horizontal: flip_user_axis(false, rotation) }); } - - ui.menu_button(tl!("Arrange image"), |ui| { + let _ = Menu::submenu_row(ui, tl!("Arrange image"), |ui, _| { use pdfcraft_engine::ArrangeOrder as A; for (order, label) in [ (A::BringToFront, tl!("Bring to front")), @@ -1146,7 +615,6 @@ pub(crate) fn image_context_menu( } } }); - // Grouped Form artwork: draw its content in place, so its text and pictures edit one by // one (#2964, #3005). if img.is_form && item(ui, true, tl!("Ungroup")) { @@ -1154,36 +622,31 @@ pub(crate) fn image_context_menu( view.pending_edit = edit(E::Ungroup); } if item(ui, raster, tl!("Replace image")) { - *action = Some(ImageAction::Replace(page, hit)); + action = Some(ImageAction::Replace(page, hit)); } if item(ui, raster, tl!("Save Image As…")) { - *action = Some(ImageAction::Save(page, hit)); + action = Some(ImageAction::Save(page, hit)); } - - ui.separator(); - + let _ = Divider::horizontal().show(ui); if item(ui, true, tl!("Draw freehand")) { - *action = Some(ImageAction::DrawFreehand); + action = Some(ImageAction::DrawFreehand); } if item(ui, true, tl!("Redact Image")) { - *action = Some(ImageAction::Redact(page, hit)); + action = Some(ImageAction::Redact(page, hit)); } - - ui.separator(); - + let _ = Divider::horizontal().show(ui); if item(ui, true, tl!("Create Link…")) { - *action = Some(ImageAction::Link(page, hit)); + action = Some(ImageAction::Link(page, hit)); } if item(ui, true, tl!("Recognize Text…")) { - *action = Some(ImageAction::Recognize(page)); + action = Some(ImageAction::Recognize(page)); } - - ui.separator(); - + let _ = Divider::horizontal().show(ui); if item(ui, true, tl!("Delete")) { view.image_selection = None; view.pending_edit = edit(E::Delete); } + action } fn flip_user_axis(horizontal: bool, rotation: u16) -> bool { @@ -1193,17 +656,7 @@ fn flip_user_axis(horizontal: bool, rotation: u16) -> bool { #[cfg(test)] mod screen_orientation_tests { use super::*; - - #[test] - fn affine_resize_rejects_degenerate_or_nonfinite_frames() { - for frame in [[1.0, 1.0, 1.0, 1.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0 + 1e-13, 0.0, 0.0], [f64::INFINITY, 0.0, 0.0, 1.0, 0.0, 0.0]] { - assert!(resize_affine_frame(Matrix(frame), ImageHandle::TopRight, (1.0, 1.0), true).is_none(), "{frame:?}"); - } - let frame = Matrix([100.0, 0.0, 50.0, 100.0, 100.0, 100.0]); - assert!(resize_affine_frame(frame, ImageHandle::TopRight, (10.0, 10.0), true).is_some()); - assert!(resize_affine_frame(frame, ImageHandle::TopRight, (f64::NAN, 0.0), true).is_none()); - assert!(resize_affine_frame(frame, ImageHandle::TopRight, (0.0, f64::INFINITY), true).is_none()); - } + use pdfcraft_engine::ImageEdit as E; #[test] fn flip_labels_follow_the_screen_axis() { @@ -1212,4 +665,46 @@ mod screen_orientation_tests { assert_eq!(flip_user_axis(false, rotation), rotation % 180 != 0); } } + + /// The box corners of a `w` by `h` frame whose top left is `at`, turned by `degrees` about its centre. + fn quad(at: (f64, f64), w: f64, h: f64, degrees: f64) -> [Point; 4] { + let c = (at.0 + w / 2.0, at.1 + h / 2.0); + let (sin, cos) = degrees.to_radians().sin_cos(); + [(at.0, at.1), (at.0 + w, at.1), (at.0 + w, at.1 + h), (at.0, at.1 + h)].map(|(x, y)| { + let (dx, dy) = (x - c.0, y - c.1); + Point::new(c.0 + dx * cos - dy * sin, c.1 + dx * sin + dy * cos) + }) + } + + fn user(p: Point) -> (f64, f64) { + (p.x, 100.0 - p.y) + } + + fn frame(c: [Point; 4]) -> [f64; 6] { + let u = c.map(user); + [u[2].0 - u[3].0, u[2].1 - u[3].1, u[0].0 - u[3].0, u[0].1 - u[3].1, u[3].0, u[3].1] + } + + #[test] + fn a_committed_frame_becomes_one_picture_edit() { + let start = quad((10.0, 10.0), 20.0, 10.0, 0.0); + let (matrix, rect) = (frame(start), [10.0, 80.0, 30.0, 90.0]); + let change = |end| picture_change(matrix, rect, start, end, &user); + + let moved = start.map(|p| Point::new(p.x + 5.0, p.y + 3.0)); + assert!(matches!(change(moved), Some(E::Move(r)) if r == [15.0, 77.0, 35.0, 87.0]), "a translation is a move"); + assert!(change(start).is_none(), "no movement is no edit"); + assert!(change(quad((10.0, 10.0), 20.0, 10.0, 0.01)).is_none(), "a turn under 0.05 degrees is none"); + assert!(matches!(change(quad((10.0, 10.0), 20.0, 10.0, 30.0)), Some(E::RotateBy(d)) if (d - 30.0).abs() < 1e-6), "a clockwise turn is positive"); + assert!(matches!(change(quad((10.0, 10.0), 40.0, 20.0, 0.0)), Some(E::Move(r)) if r == [10.0, 70.0, 50.0, 90.0]), "an upright resize is a move"); + + let turned = quad((10.0, 10.0), 20.0, 10.0, 30.0); + let tm = frame(turned); + let end = turned.map(|p| Point::new(turned[3].x + (p.x - turned[3].x) * 1.5, turned[3].y + (p.y - turned[3].y) * 1.5)); + let Some(E::Transform(t)) = picture_change(tm, rect, turned, end, &user) else { panic!("a resize of a turned picture is a transform") }; + for (s, e) in turned.map(user).into_iter().zip(end.map(user)) { + let (x, y) = Matrix(t).apply(s.0, s.1); + assert!((x - e.0).abs() < 1e-6 && (y - e.1).abs() < 1e-6, "old corner {s:?} lands on the new {e:?}"); + } + } }