diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index e304e3add4..5d7fcd9bec 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -186,6 +186,9 @@ impl PdfCraftApp { } return; } + // An explicit empty paste can fall back to the app's copied comments, after object and + // image precedence has been resolved using the actual clipboard contents. + let text = pasted.and_then(|c| c.text.as_deref()).filter(|t| t.is_empty()).map(str::to_owned).or(text); if let Some(text) = text { if !text.is_empty() { self.last_copied_image = None; diff --git a/crates/ui-egui/src/canvas/page_tools.rs b/crates/ui-egui/src/canvas/page_tools.rs index 1d16a600e1..afd78502c0 100644 --- a/crates/ui-egui/src/canvas/page_tools.rs +++ b/crates/ui-egui/src/canvas/page_tools.rs @@ -324,9 +324,14 @@ pub(crate) fn page_tool<'a>( // part took goes on to the text. Highlight shares Redact's area-box mechanism off text (L-262). _ => { let snap = caret_snap(tool, &cx, &session.texts, session.comments.tool.page); + let aspect = session + .comments + .primary() + .and_then(|(page, index)| session.signature_drag.aspect_ratio(page, index).map(|r| (page, index, r))); let view = &mut session.comments; let map = comments::PageMap::new(cx.info, cx.pages, cx.rotation, cx.view); let annotate = CommentsTool::new(&mut view.tool, &mut view.paste, map, &mut view.tool_done, &mut view.tool_pressed) + .image_aspect(aspect) .settings(tool, cx.comment_prefs, cx.allowed, cx.doc.comments_hidden()) .outcome(&mut session.pending_edit, &mut view.notice); let annotate = match snap { @@ -365,6 +370,8 @@ pub(crate) fn page_tool<'a>( // A Fill & Sign tool runs the comments tool over its placing: its own marks already placed are picked up, // moved and resized (`bridge::annotations` reaches only them), and a press anywhere else places the mark. QuickTool::Fill(fill_tool) => { + let aspect = + session.comments.primary().and_then(|(page, index)| session.signature_drag.aspect_ratio(page, index).map(|r| (page, index, r))); let view = &mut session.comments; let input = FillInput { tool: fill_tool, @@ -381,6 +388,7 @@ pub(crate) fn page_tool<'a>( let place = FillSignTool::new(&cx, input, fill, *press); let map = comments::PageMap::new(cx.info, cx.pages, cx.rotation, cx.view); let annotate = CommentsTool::new(&mut view.tool, &mut view.paste, map, &mut view.tool_done, &mut view.tool_pressed) + .image_aspect(aspect) .settings(tool, cx.comment_prefs, cx.allowed, cx.doc.comments_hidden()) .outcome(&mut session.pending_edit, &mut view.notice) .over(place); diff --git a/crates/ui-egui/src/tools/comments/bridge.rs b/crates/ui-egui/src/tools/comments/bridge.rs index 7c8892b921..1420bc7007 100644 --- a/crates/ui-egui/src/tools/comments/bridge.rs +++ b/crates/ui-egui/src/tools/comments/bridge.rs @@ -237,6 +237,10 @@ fn bounds(points: &[Point]) -> Option { /// stamp, typed text, a sound) the nearest that behaves alike. // PLAN: `DocInfo` carries no line endings, so an arrow reads as a Line here. pub(crate) fn kind_of(all: &[Annotation], a: &Annotation) -> AnnotationKind { + // A drawn signature is picked by its box, including the spaces between its strokes. + if a.fill_sign && a.subtype == "Ink" { + return AnnotationKind::Rectangle; + } tool_for_default(all, a, None).and_then(CommentTool::kind).unwrap_or(match a.subtype.as_str() { "FreeText" => AnnotationKind::TextBox, "Stamp" => AnnotationKind::Rectangle, @@ -447,7 +451,8 @@ pub(crate) fn parts( return vec![PagePart::new(owner, page, shape, PageLayer::Comment).context_only()]; } let tip = tips(info, prefs, tool).into_iter().find(|(t, _)| *t == id).map(|(_, tip)| tip); - let part = PagePart::new(owner, page, shape, PageLayer::Comment).passes_drag().cursor(icon); + let layer = if engine(info, page, index).is_some_and(|a| a.fill_sign) { PageLayer::Placed } else { PageLayer::Comment }; + let part = PagePart::new(owner, page, shape, layer).passes_drag().cursor(icon); vec![match tip { Some(tip) => part.tip_now(tip), None => part, diff --git a/crates/ui-egui/src/tools/comments/tool.rs b/crates/ui-egui/src/tools/comments/tool.rs index 6232ddfa50..a5105db58b 100644 --- a/crates/ui-egui/src/tools/comments/tool.rs +++ b/crates/ui-egui/src/tools/comments/tool.rs @@ -51,6 +51,7 @@ pub(crate) struct CommentsTool<'a> { allowed: bool, hidden: bool, caret: Option, + image_aspect: Option<(craft::review::AnnotationId, f64)>, } impl<'a> CommentsTool<'a> { @@ -78,6 +79,7 @@ impl<'a> CommentsTool<'a> { allowed: false, hidden: false, caret: None, + image_aspect: None, } } @@ -94,6 +96,30 @@ impl<'a> CommentsTool<'a> { self } + /// The embedded image's proportions, in the displayed view's axes. + pub(crate) fn image_aspect(mut self, aspect: Option<(usize, usize, f32)>) -> Self { + self.image_aspect = aspect.map(|(page, index, ratio)| { + let ratio = if self.map.rotation.is_multiple_of(180) { ratio } else { ratio.recip() }; + (bridge::id_of(page, index), f64::from(ratio)) + }); + self + } + + fn annotations(&self, page: usize) -> Vec { + bridge::annotations(self.map.info, &self.map, self.quick, self.allowed) + .into_iter() + .filter(|a| a.page == page) + .map(|mut a| { + if let Some((id, ratio)) = self.image_aspect + && a.id == id + { + a.aspect = Some(ratio); + } + a + }) + .collect() + } + /// Where a paste click's edit and notice go. pub(crate) fn outcome(mut self, placed: &'a mut Option, notice: &'a mut Option<&'static str>) -> Self { self.placed = Some(placed); @@ -177,7 +203,7 @@ impl CanvasTool for CommentsTool<'_> { } let page = self.annotate.page; self.annotate.tool = annotation_tool(self.quick); - set_page(self.annotate, page, &self.map, self.quick, self.allowed, self.hidden); + self.annotate.annotations = if self.hidden { Vec::new() } else { self.annotations(page) }; let mut eraser_width = 2.0; if let (Some(prefs), QuickTool::Comment(comment)) = (self.prefs, self.quick) { let style = prefs.style(comment); @@ -245,7 +271,8 @@ impl CanvasTool for CommentsTool<'_> { && let Some(page) = self.page_under(pointer.pos) && page != self.annotate.page { - set_page(self.annotate, page, &self.map, self.quick, self.allowed, self.hidden); + self.annotate.page = page; + self.annotate.annotations = if self.hidden { Vec::new() } else { self.annotations(page) }; } let action = self.annotate.press(pointer, cx); *self.pressed = action != ToolAction::Ignored; diff --git a/crates/ui-egui/src/tools/fill_sign.rs b/crates/ui-egui/src/tools/fill_sign.rs index 97bc52038d..0773314fab 100644 --- a/crates/ui-egui/src/tools/fill_sign.rs +++ b/crates/ui-egui/src/tools/fill_sign.rs @@ -14,7 +14,7 @@ use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, Props as _, SelectM use craft::ui::list::ThumbAspect; use craft::ui::primitives::Draw; use craft::ui::style::DataColor; -use craft::ui::tile_grid::{Tile, TileActionPlace, TileGrid}; +use craft::ui::tile_grid::{Tile, TileActionPlace, TileGrid, TilePartEvent}; use egui::Pos2; use pdfcraft_engine::{BorderShape, Edit, FillMark, NewAnnotation, Rgb, Shape, Style}; use pdfcraft_render::{DocInfo, PageInfo}; @@ -549,13 +549,16 @@ pub(crate) fn signature_entries(ui: &mut egui::Ui, app: &mut crate::PdfCraftApp) .thumb(ThumbAspect::new(3, 1), move |cx, rect| { cx.with_draw(|draw| paint_signature(cx.painter.ctx(), draw, rect, saved, DataColor::new(cx.ink()))); }) - .action(IconId::new("pencil"), CommandRef::new(slot.change_id)) - .action(IconId::new("x"), CommandRef::new(slot.remove_id)) + .action_named(IconId::new("pencil"), CommandRef::new(slot.change_id), ctx_less_label("Change {what}", slot.what)) + .action_named(IconId::new("x"), CommandRef::new(slot.remove_id), ctx_less_label("Remove saved {what}", slot.what)) }); for event in out.response.events { - if let CollectionEvent::Activate(key) = event { - command = shown.get(key).map(|s| s.use_id); - } + command = match event { + CollectionEvent::Activate(key) => shown.get(key).map(|s| s.use_id), + CollectionEvent::Item(key, TilePartEvent::Action(0)) => shown.get(key).map(|s| s.change_id), + CollectionEvent::Item(key, TilePartEvent::Action(1)) => shown.get(key).map(|s| s.remove_id), + _ => command, + }; } command } diff --git a/crates/ui-egui/tests/it/comments.rs b/crates/ui-egui/tests/it/comments.rs index e003afb799..f70c40ad6f 100644 --- a/crates/ui-egui/tests/it/comments.rs +++ b/crates/ui-egui/tests/it/comments.rs @@ -5133,7 +5133,7 @@ fn comment_menu_rows_follow_permissions_and_run_their_action() { assert_eq!(h.state().views[0].session.comments.selection(), vec![(0, 0)], "{what}: the click selected the comment"); } right_click_pt(&mut h, point); - let disabled = h.get_by_label(label).accesskit_node().is_disabled(); + let disabled = h.get_by_role_and_label(Role::MenuItem, label).accesskit_node().is_disabled(); assert_eq!(disabled, matches!(does, Does::Disabled), "{what}: the row is greyed out only where the rights forbid it"); if disabled { h.key_press(egui::Key::Escape); @@ -5143,7 +5143,7 @@ fn comment_menu_rows_follow_permissions_and_run_their_action() { assert_eq!(h.state().session.get(id).unwrap().can_undo(), None, "{what}: no edit was made"); continue; } - h.get_by_label(label).click(); + h.get_by_role_and_label(Role::MenuItem, label).click(); h.run_steps(4); match does { Does::Marks => assert!(comments(&h).iter().any(|a| a.state.as_deref() == Some("Marked")), "{what}"), diff --git a/crates/ui-egui/tests/it/editing.rs b/crates/ui-egui/tests/it/editing.rs index 340db59e6e..84e69cc3c5 100644 --- a/crates/ui-egui/tests/it/editing.rs +++ b/crates/ui-egui/tests/it/editing.rs @@ -2262,29 +2262,39 @@ fn zoomed_pages_in_view_are_rendered_at_the_size_drawn() { app.set_option(&egui::Context::default(), "organize", "on").unwrap(); app.set_option(&egui::Context::default(), "grid-zoom", "300").unwrap(); }); - // The 200 × 300 fixture fits by height; keep its aspect ratio instead of stretching - // it to the full cell width. Request enough pixels for that actual preview width. - let drawn = 194.0 * 3.0 * (200.0 / 300.0) * h.ctx.pixels_per_point(); - // The one page's grid texture is width × 1.5 width × 4 bytes (RGBA, the fixture's 2:3), the only - // texture in Organize: its width is read back from the view's texture statistics. - let sharp = |h: &Harness<'static, PdfCraftApp>, _page: usize| { - let bytes = h.state().views[0].textures.bytes; - (bytes > 0).then(|| ((bytes as f64) / 6.0).sqrt() as u32) + // The grid keeps each page picture in the shared thumbnail store. + let picture = |h: &Harness<'static, PdfCraftApp>, page: usize| { + use craft::ui::primitives::textures::{Revision, ThumbnailOptions, Thumbnails}; + Thumbnails::::in_context(&h.ctx, "page-thumbnails", ThumbnailOptions::new()).cache().state(&h.ctx, &page, Revision::of(&())).shown() + }; + let drawn = |h: &Harness<'static, PdfCraftApp>| { + let texture = picture(h, 0)?; + h.output().shapes.iter().find_map(|s| match &s.shape { + egui::Shape::Mesh(mesh) if mesh.texture_id == texture.id => Some(mesh.calc_bounds().width() * h.ctx.pixels_per_point()), + _ => None, + }) }; for _ in 0..200 { - if sharp(&h, 0).is_some_and(|w| w as f32 >= drawn * 0.9) { + if picture(&h, 0).zip(drawn(&h)).is_some_and(|(texture, width)| texture.size.width as f32 >= width * 0.9) { break; } std::thread::sleep(std::time::Duration::from_millis(20)); h.run_steps(1); } - let width = sharp(&h, 0).expect("the first page has a sharp render"); + let width = picture(&h, 0).expect("the first page has a sharp render").size.width; + let drawn = drawn(&h).expect("the first page picture is drawn"); assert!((drawn * 0.9..=drawn * 1.6).contains(&(width as f32)), "{width} for {drawn}"); - assert!(sharp(&h, 399).is_none(), "pages out of view have none"); - // Zoomed out again, thumbnails are enough and the sharp renders are dropped. + assert!(picture(&h, 399).is_none(), "pages out of view have none"); + // Zooming out replaces the sharp picture with a smaller thumbnail. h.set_option("grid-zoom", "50").unwrap(); - h.run_steps(3); - assert!(sharp(&h, 0).is_none(), "page 0 still has a sharp render: {:?}", sharp(&h, 0)); + for _ in 0..200 { + h.run_steps(1); + if picture(&h, 0).is_some_and(|small| small.size.width < width) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + assert!(picture(&h, 0).is_some_and(|small| small.size.width < width), "page 0 still has a sharp render: {:?}", picture(&h, 0)); } #[test] @@ -5062,7 +5072,7 @@ fn the_format_panel_toggles_superscript_and_subscript_on_selection() { // Click Superscript: "1" becomes "¹" assert!(h.query_all_by_label("Format text").next().is_some(), "the Format text section shows"); - let btn = h.get_by_label("Superscript"); + let btn = h.get_by_role_and_label(Role::Button, "Superscript"); btn.click(); h.run_steps(4); @@ -5078,7 +5088,7 @@ fn the_format_panel_toggles_superscript_and_subscript_on_selection() { h.run_steps(1); // Click Superscript again: "¹" toggles back to "1" - h.get_by_label("Superscript").click(); + h.get_by_role_and_label(Role::Button, "Superscript").click(); h.run_steps(4); let s2 = h.state(); let doc2 = s2.session.get(s2.views[0].id).unwrap(); @@ -5092,11 +5102,11 @@ fn the_format_panel_toggles_superscript_and_subscript_on_selection() { h.state_mut().views[0].session.content.draft = Some(draft); h.run_steps(2); - h.get_by_label("Subscript").click(); + h.get_by_role_and_label(Role::Button, "Subscript").click(); h.run_steps(2); assert_eq!(h.state().views[0].session.content.draft.as_ref().map(|d| d.text.as_str()), Some("H₂O")); - h.get_by_label("Subscript").click(); + h.get_by_role_and_label(Role::Button, "Subscript").click(); h.run_steps(2); assert_eq!(h.state().views[0].session.content.draft.as_ref().map(|d| d.text.as_str()), Some("H2O")); } @@ -6502,6 +6512,11 @@ fn the_caret_on_a_small_row_is_as_tall_as_that_row() { .shapes .iter() .find_map(|s| match &s.shape { + egui::Shape::Path(path) if path.points.len() == 2 => { + let [a, b] = [path.points[0], path.points[1]]; + ((a.x - b.x).abs() < 0.01 && (left..right).contains(&a.x) && a.y.min(b.y) < middle && a.y.max(b.y) > middle) + .then_some((b.y - a.y).abs()) + } egui::Shape::LineSegment { points: [a, b], .. } if (a.x - b.x).abs() < 0.01 && (left..right).contains(&a.x) && a.y.min(b.y) < middle && a.y.max(b.y) > middle => { diff --git a/crates/ui-egui/tests/it/fill_sign.rs b/crates/ui-egui/tests/it/fill_sign.rs index 06b2d831c4..7b8601f35f 100644 --- a/crates/ui-egui/tests/it/fill_sign.rs +++ b/crates/ui-egui/tests/it/fill_sign.rs @@ -407,7 +407,7 @@ fn dragging_the_font_size_resizes_the_selected_text_to_where_the_drag_ends() { let dragged = h.state().fill_text_size; assert!(dragged > before, "the drag made the size larger: {before} -> {dragged}"); let placed = h.state().session.get(id).unwrap().comment_props(annotation.0, annotation.1).and_then(|p| p.font_size); - assert_eq!(placed, Some(dragged), "the selected text has the size the drag ended at"); + assert_eq!(placed.map(|size| format!("{size:.3}")), Some(format!("{dragged:.3}")), "the selected text has the size the drag ended at"); } /// The font sizes of the texts `text` drawn in the last frame. @@ -1254,10 +1254,6 @@ fn image_signature_live_resize_and_move_preserve_background_and_hide_moving_hand h.hover_at(end); // Wait only for the one-time background preparation. Later pointer frames are immediate. h.run_steps(1); - eprintln!( - "DIAG image_signature_live_resize_and_move_preserve_background_and_hide_moving_handles: in_flight={:?}", - h.state().views[0].session.comments.tool.in_flight() - ); rendered_ink(&mut h, 160.0, 242.0); let end = at(&h, 220.0, 236.0); h.hover_at(end); @@ -1386,10 +1382,6 @@ fn embedded_image_signature_live_gestures_follow_document_and_view_rotation() { h.hover_at(end); let [x, y] = u(160.0, 242.0); h.run_steps(1); - eprintln!( - "DIAG embedded_image_signature_live_gestures_follow_document_and_view_rotation: in_flight={:?}", - h.state().views[0].session.comments.tool.in_flight() - ); rendered_ink(&mut h, x, y); let pixels = h.render().unwrap(); let [x, y] = u(58.0, 254.0); @@ -1462,10 +1454,6 @@ fn image_signature_corners_restore_original_aspect_after_edge_resize_and_reopen( let end = at(&h, x + hx * 10.0, y + hy * 10.0); h.hover_at(end); h.run_steps(1); - eprintln!( - "DIAG image_signature_corners_restore_original_aspect_after_edge_resize_and_reopen: in_flight={:?}", - h.state().views[0].session.comments.tool.in_flight() - ); let expected = [ if hx < 0.0 { 16.0 } else { 70.0 }, if hy < 0.0 { 160.0 } else { 170.0 }, @@ -1747,11 +1735,6 @@ fn fill_and_sign_tools_pick_up_placed_marks_to_move_and_resize_them() { assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Move, "{tool}: a placed mark can be picked up"); drag(&mut h, mid, (mid.0 + 40.0, mid.1 - 60.0)); - eprintln!( - "DIAG fill_and_sign_tools_pick_up_placed_marks_to_move_and_resize_them: tool={tool} selection={:?} rects={:?}", - h.state().views[0].session.comments.primary(), - rects(&h) - ); assert!(matches!(h.state().quick_tool, QuickTool::Fill(_)), "{tool}: the tool stays"); let moved = [placed[0] + 40.0, placed[1] - 60.0, placed[2] + 40.0, placed[3] - 60.0]; let [now] = rects(&h)[..] else { panic!("{tool}: still one mark: {:?}", rects(&h)) }; @@ -1897,10 +1880,6 @@ fn lines_grow_and_shrink_with_their_handles_before_release() { h.run_steps(1); h.hover_at(along(&h, 60.0)); h.run_steps(1); - eprintln!( - "DIAG lines_grow_and_shrink_with_their_handles_before_release: in_flight={:?}", - h.state().views[0].session.comments.tool.in_flight() - ); // Wait only for the one-time layers. Later pointer frames are immediate. let mut grown = h.render().unwrap(); for _ in 0..50 { @@ -2024,10 +2003,10 @@ fn settle_scan(h: &mut Harness<'static, PdfCraftApp>) -> bool { /// Draw a new scan frame on the pad's photo from one point of the photo (800 × 600) to another. fn drag_frame(h: &mut Harness<'static, PdfCraftApp>, from: (f32, f32), to: (f32, f32)) -> bool { let area = h.get_by_label("Photo").rect(); - let fit = area.shrink(8.0); - let scale = (fit.width() / 800.0).min(fit.height() / 600.0); - let origin = fit.center() - egui::vec2(400.0, 300.0) * scale; - let to_screen = |p: (f32, f32)| origin + egui::vec2(p.0, p.1) * scale; + let mut view = craft::behavior::CanvasView::new(area, craft::behavior::kurbo::Point::ORIGIN, 1.0); + let target = craft::ui::canvas::ViewTarget::new(craft::behavior::kurbo::Size::new(800.0, 600.0)); + craft::ui::canvas::ViewCommands::FitOnScreen.apply(&mut view, &target, None, h.ctx.pixels_per_point()); + let to_screen = |p: (f32, f32)| view.to_screen(craft::behavior::kurbo::Point::new(f64::from(p.0), f64::from(p.1))); let (a, b) = (to_screen(from), to_screen(to)); h.hover_at(a); h.run_steps(1); @@ -2744,10 +2723,10 @@ fn fill_and_sign_bar_controls_pick_tools_and_restyle_the_selection() { let keeps_date: Row = |h| { fill_slot(h, "Fill & Sign: sign").click_secondary(); h.run_steps(2); - fill_flyout_row(h, "Fill & Sign: date").click(); + fill_flyout_row(h, "Fill Sign: date").click(); h.run_steps(2); assert_eq!(h.state().quick_tool, QuickTool::Fill(FillTool::Date)); - h.get_by_label("Select (V)").click(); + h.key_press(egui::Key::V); h.run_steps(2); assert_eq!(h.state().quick_tool, QuickTool::Select); let ctx_h = h.ctx.clone(); @@ -2758,7 +2737,7 @@ fn fill_and_sign_bar_controls_pick_tools_and_restyle_the_selection() { h.run_steps(2); assert_eq!(h.state().quick_tool, QuickTool::Fill(FillTool::Date), "a click picks the shown tool, not the default"); assert!(!pad_open(h), "the default tool's dialog stays closed"); - h.get_by_label("Select (V)").click(); + h.key_press(egui::Key::V); h.run_steps(2); h.state_mut().close_tab(1); h.state_mut().close_tab(0); @@ -2785,10 +2764,7 @@ fn typing_a_fill_text_size_that_rounds_to_the_stored_one_adds_no_undo_step() { h.get_by_label("Font size").click(); h.run_steps(2); let type_size = |h: &mut Harness<'static, PdfCraftApp>, value: &str| { - h.query_all_by_role(egui::accesskit::Role::SpinButton) - .find(|n| n.value().is_some_and(|v| v.ends_with(" pt"))) - .expect("the Font size control") - .click(); + h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Font size").click(); h.run_steps(2); h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); h.event(egui::Event::Text(value.into())); @@ -2882,16 +2858,14 @@ fn fill_sign_enter_adds_lines_outside_click_commits_and_escape_cancels() { assert_eq!(h.state().views[0].session.fill_text.as_ref().unwrap().text, text); assert!(items(&h).is_empty(), "Enter never places an annotation"); // The page editor paints each line separately, including the empty lines' space. - let line = |text| { - h.output() - .shapes - .iter() - .find_map(|s| match &s.shape { - egui::Shape::Text(t) if t.galley.text() == text => Some(t), - _ => None, - }) - .unwrap() - }; + fn text_shape<'a>(shape: &'a egui::Shape, text: &str) -> Option<&'a egui::epaint::TextShape> { + match shape { + egui::Shape::Text(t) if t.galley.text() == text => Some(t), + egui::Shape::Vec(shapes) => shapes.iter().find_map(|s| text_shape(s, text)), + _ => None, + } + } + let line = |text| h.output().shapes.iter().find_map(|s| text_shape(&s.shape, text)).unwrap(); let (ada, lovelace) = (line("Ada"), line("Lovelace")); assert_eq!(ada.galley.rows.len(), 1, "short typed lines fit without accidental soft wraps"); assert_eq!(lovelace.galley.rows.len(), 1, "short typed lines fit without accidental soft wraps");