diff --git a/crates/render/src/inspect/model.rs b/crates/render/src/inspect/model.rs index 00f967153a..6c94c1c53d 100644 --- a/crates/render/src/inspect/model.rs +++ b/crates/render/src/inspect/model.rs @@ -111,8 +111,15 @@ impl PageInfo { /// A point in view space (points, y down, after `/Rotate`; what the text layer uses) → /// PDF user space. pub fn view_to_user(&self, x: f32, y: f32) -> [f32; 2] { - let [cx0, cy0, cx1, cy1] = self.crop; - let (a, b) = (x / self.width.max(1e-3), y / self.height.max(1e-3)); + let [ux, uy] = self.view_to_user_f64(f64::from(x), f64::from(y)); + [ux as f32, uy as f32] + } + + /// [`Self::view_to_user`] in f64, for maps whose points must come back where they were (a moved comment's + /// offset): the f32 page geometry is widened, never rounded again on the way. + pub fn view_to_user_f64(&self, x: f64, y: f64) -> [f64; 2] { + let [cx0, cy0, cx1, cy1] = self.crop.map(f64::from); + let (a, b) = (x / f64::from(self.width).max(1e-3), y / f64::from(self.height).max(1e-3)); let (u, v) = match self.rotation { 90 => (b, 1.0 - a), 180 => (1.0 - a, 1.0 - b), @@ -124,7 +131,13 @@ impl PageInfo { /// PDF user space → view space (the inverse of [`Self::view_to_user`]). pub fn user_to_view(&self, x: f32, y: f32) -> [f32; 2] { - let [cx0, cy0, cx1, cy1] = self.crop; + let [vx, vy] = self.user_to_view_f64(f64::from(x), f64::from(y)); + [vx as f32, vy as f32] + } + + /// [`Self::user_to_view`] in f64 (the inverse of [`Self::view_to_user_f64`]). + pub fn user_to_view_f64(&self, x: f64, y: f64) -> [f64; 2] { + let [cx0, cy0, cx1, cy1] = self.crop.map(f64::from); let (u, v) = ((x - cx0) / (cx1 - cx0).max(1e-3), (cy1 - y) / (cy1 - cy0).max(1e-3)); let (a, b) = match self.rotation { 90 => (1.0 - v, u), @@ -132,7 +145,7 @@ impl PageInfo { 270 => (v, 1.0 - u), _ => (u, v), }; - [a * self.width, b * self.height] + [a * f64::from(self.width), b * f64::from(self.height)] } /// A point as displayed (points from the page's top-left, y down, before any view rotation) diff --git a/crates/ui-egui/src/canvas/page_overlays.rs b/crates/ui-egui/src/canvas/page_overlays.rs index e9bae9bc96..a31a39db26 100644 --- a/crates/ui-egui/src/canvas/page_overlays.rs +++ b/crates/ui-egui/src/canvas/page_overlays.rs @@ -284,11 +284,11 @@ pub(crate) fn follow_link(links: &PageLinks<'_>, press: &PagePress) -> Option<(L } } -/// A link part: click-only, with the pointing hand and the link's target as its tip. +/// A link part: click-only, with the pointing hand and the link's target as its tip, shown at once as a comment's is. fn link_part(owner: Owner, page: usize, shape: HitShape, tip: Option) -> PagePart { let part = PagePart::new(owner, page, shape, PageLayer::Link).cursor(CursorIcon::PointingHand).passes_drag(); match tip { - Some(tip) => part.tip(tip), + Some(tip) => part.tip_now(tip), None => part, } } diff --git a/crates/ui-egui/src/canvas/page_parts.rs b/crates/ui-egui/src/canvas/page_parts.rs index e3198f46a5..324fcc0755 100644 --- a/crates/ui-egui/src/canvas/page_parts.rs +++ b/crates/ui-egui/src/canvas/page_parts.rs @@ -167,7 +167,8 @@ pub(crate) struct PagePart { /// Its family, which ranks it against overlapping parts. pub(crate) layer: PageLayer, cursor: Option, - tip: Option, + tip: Option<(String, TooltipWhen)>, + stacking: Option, passes_drag: bool, context_only: bool, focusable: bool, @@ -177,7 +178,27 @@ impl PagePart { /// `owner` on `page`, hit by `shape`, ranked by `layer`. It takes clicks, drags and secondary clicks, and shows the /// default cursor and no tip. pub(crate) fn new(owner: Owner, page: usize, shape: impl Into, layer: PageLayer) -> Self { - PagePart { owner, page, shape: shape.into(), layer, cursor: None, tip: None, passes_drag: false, context_only: false, focusable: false } + PagePart { + owner, + page, + shape: shape.into(), + layer, + cursor: None, + tip: None, + stacking: None, + passes_drag: false, + context_only: false, + focusable: false, + } + } + + /// Where the part stacks among the parts of its layer, the higher on top, in place of its place in the list: for + /// parts listed in another order than they overlap (form fields go in tab order, while the earlier field in the + /// form takes a press where two overlap). + #[must_use] + pub(crate) fn stacked(mut self, order: u32) -> Self { + self.stacking = Some(order); + self } /// The part takes only secondary clicks: a primary press goes to what lies below (a highlight over a link, whose @@ -195,10 +216,18 @@ impl PagePart { self } - /// The tip shown beside the pointer over the part. + /// The tip shown beside the pointer over the part, after the hover delay. #[must_use] pub(crate) fn tip(mut self, tip: impl Into) -> Self { - self.tip = Some(tip.into()); + self.tip = Some((tip.into(), TooltipWhen::Hover)); + self + } + + /// The tip shown beside the pointer as soon as it is over the part: what a comment says or where a link goes, + /// which the page states at once (a form field's own tooltip waits for the hover delay, as other tooltips do). + #[must_use] + pub(crate) fn tip_now(mut self, tip: impl Into) -> Self { + self.tip = Some((tip.into(), TooltipWhen::Now)); self } @@ -366,13 +395,13 @@ impl Component for PageParts<'_> { continue; } declared.push(at); - let mut builder = cx.part(at, part.shape.clone()).sense(part.sense()).priority(part.layer.priority()).stacking(order); + let mut builder = + cx.part(at, part.shape.clone()).sense(part.sense()).priority(part.layer.priority()).stacking(part.stacking.unwrap_or(order)); if let Some(cursor) = part.cursor { builder = builder.cursor(cursor); } - if let Some(tip) = &part.tip { - // A page part's tip shows as the pointer comes onto the part, beside the pointer, as production's did. - builder = builder.tooltip(TooltipSpec::new(Label::from(tip.clone())).at(TooltipAt::Pointer).when(TooltipWhen::Now)); + if let Some((tip, when)) = &part.tip { + builder = builder.tooltip(TooltipSpec::new(Label::from(tip.clone())).at(TooltipAt::Pointer).when(*when)); } if part.focusable { builder.focusable(); diff --git a/crates/ui-egui/src/canvas/page_select.rs b/crates/ui-egui/src/canvas/page_select.rs index ad5dc14ff8..88b8236bca 100644 --- a/crates/ui-egui/src/canvas/page_select.rs +++ b/crates/ui-egui/src/canvas/page_select.rs @@ -1,7 +1,7 @@ //! The Select tool on the page view: the framework's text selection, and the pick of a picture under a click. use craft::behavior::{CancelReason, Cursor}; -use craft::pages::ui::{PageTexts, PlacedPage, TextSelectState, TextSelectTool}; +use craft::pages::ui::{PageTexts, PlacedPage, TextSelectState, TextSelectTool, TextSelection}; use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer}; use craft::ui::primitives::Draw; use pdfcraft_render::DocInfo; @@ -9,16 +9,22 @@ use pdfcraft_render::DocInfo; use crate::canvas::PageXform; use crate::canvas::image_pick::PickedImage; -/// The two places a pick lives: the click whose picture is still being looked for, and the picture found. +/// What a press on the page sets or lets go: the click whose picture is still being looked for, the picture found, +/// and the selection whose action bar Copy closed. pub(crate) struct PickSlots<'a> { pending: &'a mut Option<(usize, [f64; 2], u64)>, picked: &'a mut Option, + dismissed: &'a mut Option, } impl<'a> PickSlots<'a> { - /// The slots over the view's `pending_pick` and `picked_image`. - pub(crate) fn new(pending: &'a mut Option<(usize, [f64; 2], u64)>, picked: &'a mut Option) -> Self { - Self { pending, picked } + /// The slots over the view's `pending_pick`, `picked_image` and `actions_dismissed`. + pub(crate) fn new( + pending: &'a mut Option<(usize, [f64; 2], u64)>, + picked: &'a mut Option, + dismissed: &'a mut Option, + ) -> Self { + Self { pending, picked, dismissed } } fn let_go(&mut self) { @@ -88,6 +94,9 @@ impl CanvasTool for PageSelectTool<'_> { } fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction { + // A drag replaces the selection without passing through none, so a re-drag over words whose bar Copy closed + // would keep the bar hidden. + *self.picks.dismissed = None; let action = self.text.press(pointer, cx); self.pick(pointer); action diff --git a/crates/ui-egui/src/canvas/page_tools.rs b/crates/ui-egui/src/canvas/page_tools.rs index a8a7d30d78..d46b09cd0b 100644 --- a/crates/ui-egui/src/canvas/page_tools.rs +++ b/crates/ui-egui/src/canvas/page_tools.rs @@ -24,7 +24,6 @@ use super::selection::DocTexts; use super::zoom_snap::SnapshotTool; use super::{PageGeometry, PageSession, PageXform, presenter}; use crate::QuickTool; -use crate::image_pick::PickedImage; use crate::tools::camera_ui::{CameraQuad, CameraTool}; use crate::tools::comments::{self, CommentsTool}; use crate::tools::edit_text_tool::EditTextTool; @@ -241,11 +240,10 @@ fn select_tool<'a>( cx: &PageToolCx<'a>, text: &'a mut TextSelectState, texts: &'a dyn PageTexts, - pending_pick: &'a mut Option<(usize, [f64; 2], u64)>, - picked_image: &'a mut Option, + picks: PickSlots<'a>, xforms: &'a [(usize, PageXform)], ) -> PageSelectTool<'a> { - PageSelectTool::new(cx.pages, texts, text, cx.info, PickSlots::new(pending_pick, picked_image), xforms, cx.doc.edit_generation()) + PageSelectTool::new(cx.pages, texts, text, cx.info, picks, xforms, cx.doc.edit_generation()) } /// The Insert text tool's snap on `page`, the page the comments tool works on: the caret's tip and side in the page's @@ -297,7 +295,8 @@ pub(crate) fn page_tool<'a>( QuickTool::Select if cx.preparing => Arm::Area(Box::new(PrepareTool::new(None, cx.can_modify, cx.form, session, cx.info, xforms))), QuickTool::Select | QuickTool::ColumnSelect | QuickTool::Comment(_) | QuickTool::Redact => { let texts: &'a DocTexts<'a> = texts_slot.insert(DocTexts::new(&session.texts, &session.text_failed, cx.rotation, cx.sizes)); - let select = select_tool(&cx, &mut session.text, texts, &mut session.pending_pick, &mut session.picked_image, xforms); + let picks = PickSlots::new(&mut session.pending_pick, &mut session.picked_image, &mut session.actions_dismissed); + let select = select_tool(&cx, &mut session.text, texts, picks, xforms); match tool { QuickTool::ColumnSelect => Arm::Select(select.column(true)), QuickTool::Redact => { diff --git a/crates/ui-egui/src/hotbar.rs b/crates/ui-egui/src/hotbar.rs index aac06726bb..7b9cd64e64 100644 --- a/crates/ui-egui/src/hotbar.rs +++ b/crates/ui-egui/src/hotbar.rs @@ -214,7 +214,8 @@ pub(crate) fn show_rail(app: &mut PdfCraftApp, ui: &mut egui::Ui) { if let Some(next) = output.last_used { app.hotbar.last_used = next; } - if output.edit_toolbar.as_ref().is_some_and(|opener| opener.clicked()) { + // A click by the pointer or by keyboard activation. + if output.edit_toolbar.as_ref().is_some_and(craft::ui::contract::clicked) { app.hotbar.drawer_open = true; } if !app.hotbar.drawer_open { @@ -284,8 +285,11 @@ fn fill_text_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp) { tl!("Colour"), |ui| Swatch::new(tl!("Colour").to_string(), to_srgba(current)).show(ui).response, |ui| { - colour = comments::palette(ui, tl!("Colour"), Some(current), "hotbar.fill-text-colour", &app.recent_colours); - colour.picked.is_some() + let pick = comments::palette(ui, tl!("Colour"), Some(current), "hotbar.fill-text-colour", &app.recent_colours); + let done = pick.picked.is_some(); + colour.picked = colour.picked.take().or(pick.picked); + colour.request = colour.request.take().or(pick.request); + done }, ); if let Some(color) = colour.picked { @@ -309,7 +313,7 @@ fn fill_text_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp) { |ui| { let field = SliderField::new(tl!("Font size"), Bind::bound(&mut size), min..=max).scale(SliderScale::Log).unit_kind(UnitKind::Points).show(ui); - committed = field.edit.events.committed().is_some(); + committed |= field.edit.events.committed().is_some(); false }, ); @@ -428,8 +432,11 @@ fn border_colour_control( tl!("Border colour"), |ui| Swatch::new(tl!("Border colour").to_string(), to_srgba(own.unwrap_or(text))).show(ui).response, |ui| { - pick = comments::border_choice(ui, own, key, recent); - pick.choice.is_some() + let this = comments::border_choice(ui, own, key, recent); + let done = this.choice.is_some(); + pick.choice = pick.choice.take().or(this.choice); + pick.request = pick.request.take().or(this.request); + done }, ); pick diff --git a/crates/ui-egui/src/tools/comments/bridge.rs b/crates/ui-egui/src/tools/comments/bridge.rs index 94136c7fd3..bf02749258 100644 --- a/crates/ui-egui/src/tools/comments/bridge.rs +++ b/crates/ui-egui/src/tools/comments/bridge.rs @@ -83,7 +83,7 @@ impl<'a> PageMap<'a> { /// its displayed point stands in. pub(crate) fn to_doc(&self, page: usize, user: [f64; 2]) -> Point { let shown = match self.info.pages.get(page) { - Some(p) => turned_point(p, self.rotation, [user[0] as f32, user[1] as f32]), + Some(p) => turned_point(p, self.rotation, user), None => Point::new(user[0], user[1]), }; match self.frame(page) { @@ -202,30 +202,29 @@ impl PageFrame { } /// A user-space point as the displayed point of a page the view turns clockwise by `rotation` degrees. -fn turned_point(page: &PageInfo, rotation: u16, user: [f32; 2]) -> Point { - let [x, y] = page.user_to_view(user[0], user[1]); - let (w, h) = (page.width, page.height); +fn turned_point(page: &PageInfo, rotation: u16, user: [f64; 2]) -> Point { + let [x, y] = page.user_to_view_f64(user[0], user[1]); + let (w, h) = (f64::from(page.width), f64::from(page.height)); let (a, b) = match rotation { 90 => (h - y, x), 180 => (w - x, h - y), 270 => (y, w - x), _ => (x, y), }; - Point::new(f64::from(a), f64::from(b)) + Point::new(a, b) } /// The user-space point under the displayed point `at` of a page the view turns clockwise by `rotation` degrees. fn unturned_point(page: &PageInfo, rotation: u16, at: Point) -> [f64; 2] { - let (a, b) = (at.x as f32, at.y as f32); - let (w, h) = (page.width, page.height); + let (a, b) = (at.x, at.y); + let (w, h) = (f64::from(page.width), f64::from(page.height)); let (x, y) = match rotation { 90 => (b, h - a), 180 => (w - a, h - b), 270 => (w - b, a), _ => (a, b), }; - let u = page.view_to_user(x, y); - [f64::from(u[0]), f64::from(u[1])] + page.view_to_user_f64(x, y) } fn bounds(points: &[Point]) -> Option { @@ -324,11 +323,11 @@ pub(crate) fn annotations(info: &DocInfo, map: &PageMap<'_>, tool: QuickTool, al members.entry(*p).or_default().push(m); } } - all.iter() - .enumerate() - .filter(|(_, a)| a.is_comment() && a.subtype != "Popup" && map.shows(a.page) && pick(a)) - .filter_map(|(i, a)| marked(map, a, members.get(&i).map_or(&[][..], Vec::as_slice), allowed)) - .collect() + let mut shown: Vec<(usize, &Annotation)> = + all.iter().enumerate().filter(|(_, a)| a.is_comment() && a.subtype != "Popup" && map.shows(a.page) && pick(a)).collect(); + // In paint order (`/Annots`), not the inspection's: the framework takes the last listed as the topmost. + shown.sort_by_key(|(_, a)| (a.page, a.index)); + shown.into_iter().filter_map(|(i, a)| marked(map, a, members.get(&i).map_or(&[][..], Vec::as_slice), allowed)).collect() } fn marker_boxes(map: &PageMap<'_>, anns: &[Marked], icon_side: f64) -> Vec<(AnnotationId, Rect)> { @@ -417,22 +416,22 @@ pub(crate) fn parts( }; let index = key_of(id).1; let owner = Owner::Comment { index }; + // A part has one shape, and the page parts keep one per comment: the line (or marker) the pointer is on, which + // `pick_at` took the comment from. A markup's other lines get theirs when the pointer reaches them. + let pointer = egui::pos2(screen.x as f32, screen.y as f32); + let Some(shape) = screen_shapes.into_iter().min_by(|a, b| a.distance_sq_to_pos(pointer).total_cmp(&b.distance_sq_to_pos(pointer))) else { + return Vec::new(); + }; if on_link && tool == QuickTool::Select && engine(info, page, index).is_some_and(|a| a.subtype == "Highlight") { // The link's hand and tip show there. - return screen_shapes.into_iter().map(|shape| PagePart::new(owner, page, shape, PageLayer::Comment).context_only()).collect(); + 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); - // A part has one shape: a markup's lines are one part each, which a press resolves to the same comment. - screen_shapes - .into_iter() - .map(|shape| { - let part = PagePart::new(owner, page, shape, PageLayer::Comment).passes_drag().cursor(icon); - match &tip { - Some(tip) => part.tip(tip.clone()), - None => part, - } - }) - .collect() + let part = PagePart::new(owner, page, shape, PageLayer::Comment).passes_drag().cursor(icon); + vec![match tip { + Some(tip) => part.tip_now(tip), + None => part, + }] } fn engine(info: &DocInfo, page: usize, index: usize) -> Option<&Annotation> { diff --git a/crates/ui-egui/src/tools/comments/composer.rs b/crates/ui-egui/src/tools/comments/composer.rs index 9b147b24a6..936e0c96c3 100644 --- a/crates/ui-egui/src/tools/comments/composer.rs +++ b/crates/ui-egui/src/tools/comments/composer.rs @@ -39,13 +39,23 @@ pub(crate) fn composer(ui: &mut egui::Ui, view: &mut DocView, info: &DocInfo, pr anchor = None; } } + let hint = match c.kind { + ComposerKind::TextBox { .. } | ComposerKind::Callout { .. } => tl!("Type text"), + ComposerKind::Caret { .. } => tl!("Text to insert"), + ComposerKind::Replace => tl!("Replacement text"), + _ => tl!("Add a comment"), + }; let draft = match c.kind { ComposerKind::Edit(_) if typewriter_edit => ComposerDraft::EditVerbatim, ComposerKind::Edit(_) => ComposerDraft::Edit, _ => ComposerDraft::New, }; - let output = - CommentComposer::new(anchor, &mut c.text).header(tl!(title), &prefs.author).draft_kind(draft).close(ComposerClose::OnPostOrCancel).show(ui); + let output = CommentComposer::new(anchor, &mut c.text) + .header(tl!(title), &prefs.author) + .hint(hint) + .draft_kind(draft) + .close(ComposerClose::OnPostOrCancel) + .show(ui); if output.cancelled { view.session.comments.composer = None; return None; diff --git a/crates/ui-egui/src/tools/comments/menu.rs b/crates/ui-egui/src/tools/comments/menu.rs index 59e9f48eee..ec371b6c1f 100644 --- a/crates/ui-egui/src/tools/comments/menu.rs +++ b/crates/ui-egui/src/tools/comments/menu.rs @@ -225,7 +225,9 @@ pub(crate) struct QuickBarPick { /// A control that opens a popover under it: `opener` draws the control, a click on it opens and closes the /// popover, and `body` fills it; a body that reports it is done (a choice that ends the popover's use) closes it. The -/// popover's open flag is the opener's own, kept in the UI's memory. +/// popover's open flag is the opener's own, kept in the UI's memory. The framework runs `body` in each of its passes +/// (sizing, then the one that takes input), so a body keeps what a pass picked rather than overwrite it with a later +/// pass's nothing. pub(crate) fn popover_from( ui: &mut egui::Ui, label: &str, @@ -265,7 +267,9 @@ pub(crate) fn quick_bar_controls(ui: &mut egui::Ui, tool: CommentTool, prefs: &m prefs.set_color(tool, c); out.colour = Some(c); } - out.request = pick.request; + if pick.request.is_some() { + out.request = pick.request; + } false }, ); diff --git a/crates/ui-egui/src/tools/comments/state.rs b/crates/ui-egui/src/tools/comments/state.rs index e09c587c61..bb4e5e3118 100644 --- a/crates/ui-egui/src/tools/comments/state.rs +++ b/crates/ui-egui/src/tools/comments/state.rs @@ -347,9 +347,10 @@ impl CommentView { self.member = cx.picked(p, self.primary()); } - /// Open the inline editor on the root message of comment (page, index) with `text`. + /// Open the inline editor on the root message of comment (page, index) with `text`; it takes + /// the keyboard when its card is next built. pub(crate) fn open_editor(&mut self, page: usize, index: usize, text: String) { - self.panel.editing = Some((bridge::thread_id(page, index), 0, text)); + self.panel.edit(bridge::thread_id(page, index), 0, text); } /// A comment was just added. An empty editor open on another one closes; one holding text diff --git a/crates/ui-egui/src/tools/comments/tests.rs b/crates/ui-egui/src/tools/comments/tests.rs index 2373fc3daf..c20edac942 100644 --- a/crates/ui-egui/src/tools/comments/tests.rs +++ b/crates/ui-egui/src/tools/comments/tests.rs @@ -571,9 +571,10 @@ fn the_hover_outline_goes_round_what_a_press_would_take() { assert_eq!(parts(&view, Some(over)).len(), 1, "one part for the comment under the pointer"); assert!(parts(&view, None).is_empty(), "no pointer, no part"); assert!(parts(&view, Some(Point::new(5.0, 5.0))).is_empty(), "nor where nothing would take the press"); - // Over the comment that is selected, no outline part: the handles are what is there. + // A selected comment keeps its part, so its tip shows as production's did; the overlay draws no outline round it + // (the handles are what is there), and a drag on it still passes to the tool. view.session.comments.select_only((0, 0)); - assert!(parts(&view, Some(over)).is_empty(), "no outline over a selected comment"); + assert_eq!(parts(&view, Some(over)).len(), 1, "the selected comment is still pressed and tipped where it is"); } /// A silent transform error would carry into every saved comment: the user point survives the trip through the document diff --git a/crates/ui-egui/src/tools/forms_ui.rs b/crates/ui-egui/src/tools/forms_ui.rs index 6a387a15e8..b411376318 100644 --- a/crates/ui-egui/src/tools/forms_ui.rs +++ b/crates/ui-egui/src/tools/forms_ui.rs @@ -390,7 +390,10 @@ pub(crate) fn field_parts( (true, FormFieldKind::Text) => CursorIcon::Text, _ => CursorIcon::PointingHand, }; - let mut part = PagePart::new(Owner::Field { field: fi, widget: wi }, page, HitShape::Polygon(corners), PageLayer::Field).cursor(icon); + // Where widgets overlap, the field earlier in the form takes the press, whatever the tab order. + let stacking = u32::try_from(form.len().saturating_sub(fi)).unwrap_or(u32::MAX); + let mut part = + PagePart::new(Owner::Field { field: fi, widget: wi }, page, HitShape::Polygon(corners), PageLayer::Field).cursor(icon).stacked(stacking); if let Some(tip) = f.tooltip.as_deref().filter(|t| !t.trim().is_empty()) { part = part.tip(tip.to_owned()); } diff --git a/crates/ui-egui/tests/it/comments.rs b/crates/ui-egui/tests/it/comments.rs index 9759b53130..69b0b6f409 100644 --- a/crates/ui-egui/tests/it/comments.rs +++ b/crates/ui-egui/tests/it/comments.rs @@ -52,6 +52,27 @@ fn harness_with_bytes(bytes: Vec, setup: impl FnOnce(&mut PdfCraftApp) + 'st h } +/// Like [`harness`], with the clipboard the app copies to, which the test reads back. +fn harness_copying(setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> (Harness<'static, PdfCraftApp>, support::RecordingClipboard) { + let clipboard = support::RecordingClipboard::default(); + let kept = clipboard.clone(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |cc| { + crate::support::install_runtime(&cc.egui_ctx); + { + let mut app = crate::support::app_with_clipboard(clipboard); + app.set_option(&egui::Context::default(), "language", "en").unwrap(); + app.open_bytes(&egui::Context::default(), "text.pdf", None, TEXT_FIXTURE.to_vec()).expect("opens"); + app.set_option(&egui::Context::default(), "left", "closed").unwrap(); + app.set_option(&egui::Context::default(), "author", "Tester").unwrap(); + setup(&mut app); + app + } + }); + h.run_steps(4); + crate::support::settle(&mut h); + (h, kept) +} + /// Like [`harness`], on a host whose file picker answers from `files`. fn harness_on_files(files: std::sync::Arc, setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> Harness<'static, PdfCraftApp> { let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |cc| { @@ -1675,14 +1696,47 @@ const REPLY_THREAD: &[u8] = b"%PDF-1.7 trailer << /Root 1 0 R >> %%EOF"; -/// The "…" of the reply row that shows `text`: the last one above it (it sits on the row's -/// author line). +/// Whether `label` names a reply row showing `text`: replies are group nodes in their card, named +/// "{author}: {text}" and the reply's age. +fn names_reply(label: &str, text: &str) -> bool { + label.split_once(": ").is_some_and(|(_, rest)| rest == text || rest.strip_prefix(text).is_some_and(|age| age.starts_with(", "))) +} + +/// The reply rows of the Comments panel. +fn reply_rows<'a>(h: &'a Harness<'static, PdfCraftApp>) -> Vec> { + h.query_all_by(|n| n.role() == Role::Group && n.label().is_some_and(|l| l.contains(": "))).collect() +} + +/// The reply row that shows `text`. +fn reply_row<'a>(h: &'a Harness<'static, PdfCraftApp>, text: &str) -> egui_kittest::Node<'a> { + let wanted = text.to_owned(); + h.query_all_by(move |n| n.role() == Role::Group && n.label().is_some_and(|l| names_reply(&l, &wanted))) + .next() + .unwrap_or_else(|| panic!("no reply row shows {text:?}")) +} + +/// How many reply rows show `text`. +fn reply_rows_showing(h: &Harness<'static, PdfCraftApp>, text: &str) -> usize { + let text = text.to_owned(); + h.query_all_by(move |n| n.role() == Role::Group && n.label().is_some_and(|l| names_reply(&l, &text))).count() +} + +/// The "…" (More) of the reply row that shows `text`: the one inside that row. fn reply_options<'a>(h: &'a Harness<'static, PdfCraftApp>, text: &str) -> egui_kittest::Node<'a> { - let y = h.get_by_label(text).rect().top(); - h.query_all_by_label("Options for this reply") - .filter(|b| b.rect().top() <= y) - .max_by(|a, b| a.rect().top().total_cmp(&b.rect().top())) - .expect("a reply menu") + let row = reply_row(h, text).rect(); + h.query_all_by_label("More").find(|b| row.contains(b.rect().center())).expect("a reply menu") +} + +/// The "…" (More) of a card itself, outside every reply row. +fn card_options<'a>(h: &'a Harness<'static, PdfCraftApp>) -> egui_kittest::Node<'a> { + let replies: Vec = reply_rows(h).iter().map(|r| r.rect()).collect(); + h.query_all_by_label("More").find(|b| !replies.iter().any(|r| r.contains(b.rect().center()))).expect("a card menu") +} + +/// How many reply rows have their own "…". +fn reply_menus(h: &Harness<'static, PdfCraftApp>) -> usize { + let replies: Vec = reply_rows(h).iter().map(|r| r.rect()).collect(); + h.query_all_by_label("More").filter(|b| replies.iter().any(|r| r.contains(b.rect().center()))).count() } /// Row of `panel_and_card_actions_become_engine_edits`: one reply is deleted from its own "…" @@ -1697,7 +1751,7 @@ fn delete_one_reply_row() { let texts = |h: &Harness<'static, PdfCraftApp>| -> Vec { comments(h).iter().filter_map(|a| a.contents.clone()).collect() }; let all = ["Wrong reply", "The comment", "Right reply", "Answer to the wrong reply", "Accepted set by Ben"]; assert_eq!(texts(&h), all); - assert_eq!(h.query_all_by_label("Options for this reply").count(), 3, "each reply has one; the status is a badge"); + assert_eq!(reply_menus(&h), 3, "each reply has one; the status is a badge"); reply_options(&h, "Wrong reply").click(); h.run_steps(2); @@ -1707,9 +1761,9 @@ fn delete_one_reply_row() { let id = h.state().views[0].id; assert_eq!(h.state().session.get(id).unwrap().info.annotations[0].index, 0, "its pop-up went too"); assert_eq!(h.state().views[0].session.comments.selection(), vec![(0, 0)], "the card stays selected where the comment now is"); - assert_eq!(h.query_all_by_label("Wrong reply").count(), 0); - assert_eq!(h.query_all_by_label("Answer to the wrong reply").count(), 0); - h.get_by_label("Right reply"); + assert_eq!(reply_rows_showing(&h, "Wrong reply"), 0); + assert_eq!(reply_rows_showing(&h, "Answer to the wrong reply"), 0); + reply_row(&h, "Right reply"); h.get_by_label("Ben: Accepted"); // One badge per reviewer. assert_eq!(h.state().session.get(id).unwrap().can_undo(), Some("Delete comment"), "one undo step"); @@ -1743,7 +1797,7 @@ fn delete_one_reply_row() { assert_eq!(texts(&h), ["The comment", "Right reply, reworded", "Accepted set by Ben"]); // The locked reply keeps its comment too: deleting the comment would take it along. - h.get_by_label("More").click(); + card_options(&h).click(); h.run_steps(2); assert!(h.get_by_label("Delete").accesskit_node().is_disabled(), "the comment of a locked reply isn't deleted"); h.key_press(egui::Key::Escape); @@ -1754,7 +1808,7 @@ fn delete_one_reply_row() { undo(&mut h); h.run_steps(3); assert_eq!(texts(&h), all, "undo brings the reply and its answer back"); - h.get_by_label("Wrong reply"); + reply_row(&h, "Wrong reply"); } // Contributor-original PDF: a comment and its replies A, B and C, in that `/Annots` order. @@ -1923,7 +1977,7 @@ fn a_checkmark_on_a_reply_does_not_mark_its_comment() { }); click_pt(&mut h, (110.0, 110.0)); assert_eq!(h.state().views[0].session.comments.selection(), vec![(0, 0)], "the comment is selected"); - h.get_by_label("Checked reply"); + reply_row(&h, "Checked reply"); h.get_by_label("Mark with checkmark"); // The card's checkmark. assert_eq!(h.query_all_by_label("Accepted").count(), 0, "no status badge"); let p = at(&h, 110.0, 110.0); @@ -1951,7 +2005,7 @@ fn the_panel_reveals_edits_and_reopens_a_late_thread_without_changing_its_replie h.get_by_label_contains("Late root"); h.get_by_label_contains("Late thread reply"); assert_eq!(h.state().views[0].session.comments.panel.collapsed_pages, vec![0]); - h.get_by_label("More").click(); + card_options(&h).click(); h.run_steps(2); h.query_all_by_label("Edit").last().expect("comment menu edit, after the toolbar tab").click(); h.run_steps(2); @@ -1977,10 +2031,11 @@ fn the_panel_reveals_edits_and_reopens_a_late_thread_without_changing_its_replie app.views[0].session.comments.panel.search = "late thread reply".into(); app.views[0].session.comments.panel.search_open = true; }); - h.get_by_label("Late root edited exactly"); - reopened.get_by_label("Late root edited exactly"); - reopened.get_by_label("Late thread reply"); - assert_eq!(reopened.query_all_by_label("First root").count(), 0); + // The panel names a card by its author, text and date. + h.get_by_label_contains("Late root edited exactly"); + reopened.get_by_label_contains("Late root edited exactly"); + reply_row(&reopened, "Late thread reply"); + assert_eq!(reopened.query_all_by_label_contains("First root").count(), 0); let after = comments(&reopened); assert_eq!(after.len(), before.len()); for (original, saved) in before.iter().zip(&after) { @@ -1992,8 +2047,8 @@ fn the_panel_reveals_edits_and_reopens_a_late_thread_without_changing_its_replie assert_eq!(after.iter().find(|a| a.name.as_deref() == Some("late-reply")).unwrap().in_reply_to.as_deref(), Some("late")); reopened.state_mut().views[0].session.comments.panel.sort = CommentSort::Author; reopened.run_steps(2); - assert_eq!(reopened.query_all_by_label("Delta").count(), 2, "the author group and its card remain visible after sorting"); - reopened.get_by_label("Late root edited exactly"); + reopened.get_by_label("Delta"); // The author group. + reopened.get_by_label_contains("Delta: Late root edited exactly"); // And its card, still shown after sorting. } /// A page with one rectangle comment ("Reviewed"), the Comments panel open and nothing selected. @@ -2046,7 +2101,7 @@ fn flatten_from_the_panel_menu_row() { #[test] fn comments_take_checkmarks_lock_hide_and_summarize() { - let mut h = harness(|app| { + let (mut h, clipboard) = harness_copying(|app| { app.set_option(&egui::Context::default(), "panel", "comments").unwrap(); app.set_option(&egui::Context::default(), "quick", "square").unwrap(); }); @@ -2067,13 +2122,8 @@ fn comments_take_checkmarks_lock_hide_and_summarize() { h.get_by_label("More").click(); h.run_steps(2); h.get_by_label("Copy text").click(); - let mut copied = false; - for _ in 0..4 { - h.step(); - copied |= h.output().platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(t) if t == "Copy me")); - } - assert!(copied, "the text is copied"); - h.run_steps(2); + h.run_steps(4); + assert_eq!(clipboard.copied().as_deref(), Some("Copy me"), "the text is copied"); // Properties ▸ Locked. open_comment_props(&mut h, 0, 0); @@ -2104,7 +2154,7 @@ fn comments_take_checkmarks_lock_hide_and_summarize() { h.run_steps(2); h.get_by_label("Create PDF comment summary…").click(); h.run_steps(2); - h.get_by_label("Summarize Options"); + h.get_by_role_and_label(Role::Dialog, "Summarize Options"); h.get_by_label("Create PDF Comment Summary").click(); h.run_steps(3); let s = h.state(); diff --git a/crates/ui-egui/tests/it/folders.rs b/crates/ui-egui/tests/it/folders.rs index 29333bec31..265fc038f7 100644 --- a/crates/ui-egui/tests/it/folders.rs +++ b/crates/ui-egui/tests/it/folders.rs @@ -128,12 +128,14 @@ fn clicking_a_pinned_pdf_opens_it_and_adds_it_to_recent() { }); s.settle(); s.h.get_by_label_contains("scan.pdf").click(); - s.h.run_steps(3); + // The file is read on a job, as every open is. + s.settle(); // The tab strip names the open document. - assert!(s.h.query_by_label_contains("scan.pdf").is_some(), "the PDF opens in a tab"); - // PLAN: assumed `settings_snapshot()` serialises with a `recent` list of `{ path }` entries (pdf-shell-w9). + s.h.get_by_role_and_label(egui::accesskit::Role::Tab, "scan.pdf"); + // The settings keep the recent files, newest first, as JSON text. let saved = serde_json::to_value(s.h.state().settings_snapshot()).unwrap(); - assert_eq!(saved["recent"][0]["path"].as_str(), Some(path.to_string_lossy().as_ref())); + let recent: serde_json::Value = serde_json::from_str(saved["recent"]["recent"].as_str().expect("the recent files are saved")).unwrap(); + assert_eq!(recent[0]["path"].as_str(), Some(path.to_string_lossy().as_ref())); } #[test] @@ -217,8 +219,11 @@ fn a_pinned_folder_collapses_to_its_heading_and_stays_collapsed_after_a_restart( fn folders_of_the_same_name_have_buttons_that_tell_them_apart() { let root = TempFolder::new("same-name"); let (a, b) = (root.0.join("work").join("Scans"), root.0.join("home").join("Scans")); - std::fs::create_dir_all(&a).unwrap(); - std::fs::create_dir_all(&b).unwrap(); + // A file in each, so each heading folds (a folder with nothing listed has nothing to fold). + for folder in [&a, &b] { + std::fs::create_dir_all(folder).unwrap(); + std::fs::write(folder.join("scan.pdf"), FIXTURE).unwrap(); + } let (a, b) = (a.to_string_lossy().into_owned(), b.to_string_lossy().into_owned()); let pins = (a.clone(), b.clone()); let mut s = plain(move |app| { diff --git a/crates/ui-egui/tests/it/organize_drag.rs b/crates/ui-egui/tests/it/organize_drag.rs index 35f7987cdb..6233bd708a 100644 --- a/crates/ui-egui/tests/it/organize_drag.rs +++ b/crates/ui-egui/tests/it/organize_drag.rs @@ -60,8 +60,14 @@ fn page_texts(app: &PdfCraftApp) -> Vec { .collect() } +/// Organize copies pages as a file manager copies files: Option on macOS, Ctrl elsewhere. fn copy_modifier(_h: &Harness<'static, PdfCraftApp>, copying: bool) -> Modifiers { - if copying { Modifiers::ALT } else { Modifiers::NONE } + match (copying, cfg!(target_os = "macos")) { + (false, _) => Modifiers::NONE, + (true, true) => Modifiers::ALT, + // Ctrl as a keyboard sends it off macOS: the command key too. + (true, false) => Modifiers { ctrl: true, command: true, ..Modifiers::NONE }, + } } fn start_drag(h: &mut Harness<'static, PdfCraftApp>, copying: bool) -> (Pos2, Modifiers) {