From a7e04adab16e670e4769ebc33ca52a85c4671390 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:25 -0500 Subject: [PATCH] pdf-canvas-w9: net change of 5 commits - pdf-canvas-w9: written from its sheet - pdf-canvas-w9: finished by an agent - pdf-canvas-w9: finished by an agent - pdf-canvas-w9: finished by an agent - pdf-canvas-w9: review fixes (review-1) --- crates/ui-egui/src/canvas/page_cursor.rs | 344 ----- crates/ui-egui/src/canvas/page_input.rs | 1177 ----------------- crates/ui-egui/src/canvas/page_keys.rs | 173 --- crates/ui-egui/src/canvas/page_parts.rs | 407 ++++++ crates/ui-egui/src/canvas/page_pointer.rs | 150 --- .../ui-egui/src/canvas/page_pointer/tests.rs | 916 ------------- crates/ui-egui/src/canvas/page_router.rs | 355 ----- crates/ui-egui/src/canvas/page_tools.rs | 559 ++++++++ crates/ui-egui/tests/it/pointer.rs | 874 ++---------- 9 files changed, 1077 insertions(+), 3878 deletions(-) delete mode 100644 crates/ui-egui/src/canvas/page_cursor.rs delete mode 100644 crates/ui-egui/src/canvas/page_input.rs delete mode 100644 crates/ui-egui/src/canvas/page_keys.rs create mode 100644 crates/ui-egui/src/canvas/page_parts.rs delete mode 100644 crates/ui-egui/src/canvas/page_pointer.rs delete mode 100644 crates/ui-egui/src/canvas/page_pointer/tests.rs delete mode 100644 crates/ui-egui/src/canvas/page_router.rs create mode 100644 crates/ui-egui/src/canvas/page_tools.rs diff --git a/crates/ui-egui/src/canvas/page_cursor.rs b/crates/ui-egui/src/canvas/page_cursor.rs deleted file mode 100644 index b820f74d77..0000000000 --- a/crates/ui-egui/src/canvas/page_cursor.rs +++ /dev/null @@ -1,344 +0,0 @@ -//! The cursor the pages show, and the tip beside it, set once a frame. -//! -//! A page module claims the cursor for what it has under the pointer, on a [`Layer`], and never -//! sets egui's cursor itself: where each module set it, the last write of a frame won, so the -//! order of the per-page chain decided the cursor and not what a press there does. A link's hand -//! showed over every tool though only the Select tool follows links, and the I-beam of the text -//! under a comment hid that a drag there moves the comment. `canvas::document_area` sets the -//! cursor once, from the claim on the highest layer the active tool reaches. The tip beside it is -//! that claim's own (a link's target, so only where a press acts on the link: the Select tool -//! follows it, the Link tool edits it), or else what lies under the pointer says (a comment, or a -//! signature's validation badge), with any tool, as Acrobat shows a comment's tooltip. A test in -//! `page_pointer/tests.rs` keeps page modules from setting the cursor. - -use egui::CursorIcon; - -use crate::QuickTool; - -/// What a claim is for, from the bottom up: a claim on a higher layer wins. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub(crate) enum Layer { - /// The page under the active tool: the crosshair it places or draws with, its I-beam or hand. - ToolArea, - /// The page's text, to select; Edit text's paragraphs, and its pictures beneath them. - Text, - /// Links. - Link, - /// Text markup (highlights, underlines…), which lies on the text: under a form field. - Comment, - /// Form fields. - Field, - /// What a drag moves whole: notes, shapes, signatures and Fill & Sign's marks, added text and - /// pictures, the objects selected together, Prepare's fields. - Placed, - /// The grips of the selected item: resize, rewrap, rotate and crop handles, paragraph edges, - /// the frame of the paragraph open for typing. - Handle, - /// An open editor: a paragraph being typed in, a picture being cropped. - Editor, - /// A drag in progress: what is dragged keeps its cursor until the release. - Drag, -} - -/// Every layer, bottom first. -const LAYERS: [Layer; 9] = - [Layer::ToolArea, Layer::Text, Layer::Link, Layer::Comment, Layer::Field, Layer::Placed, Layer::Handle, Layer::Editor, Layer::Drag]; - -impl Layer { - /// Whether a press with `tool` acts on what lies on this layer, so that the layer's claims - /// count. Only the Select tool follows links (the Link tool edits them) and selects text - /// markup: every other tool draws, places or selects text over them. The other layers are - /// claimed only by the modules of the tools that act on them (each module's hit test filters - /// by tool), so they count for every tool. - pub(crate) fn reached_by(self, tool: QuickTool) -> bool { - match self { - Layer::Link => matches!(tool, QuickTool::Select | QuickTool::Link), - Layer::Comment => tool == QuickTool::Select, - Layer::ToolArea | Layer::Text | Layer::Field | Layer::Placed | Layer::Handle | Layer::Editor | Layer::Drag => true, - } - } -} - -/// A claim on the cursor: the icon, and the tip that goes with it (a link's target). -#[derive(Clone, Debug, PartialEq)] -struct Claim { - icon: CursorIcon, - tip: Option, -} - -/// What a description tells about, from the least up: a higher one shows over a lower one. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub(crate) enum Subject { - /// A signature's validation badge: viewer chrome over the signer's own artwork. - SignatureBadge, - /// A comment: who wrote it, and what it says. - Comment, -} - -/// What the page modules claim for the cursor this frame. `canvas::document_area` sets the -/// cursor from it once, after the pages ([`PageCursor::resolve`]). -#[derive(Debug, Default)] -pub(crate) struct PageCursor { - /// The last claim on each layer, bottom layer first. - claims: [Option; LAYERS.len()], - /// What lies under the pointer says ([`PageCursor::describe`]). - description: Option<(Subject, String)>, -} - -impl PageCursor { - /// Shows `icon` while the pointer is over what lies on `layer`, unless the active tool - /// reaches a higher layer that is claimed too. - pub(crate) fn claim(&mut self, layer: Layer, icon: CursorIcon) { - self.claim_with_tip(layer, icon, None); - } - - /// As [`Self::claim`], with `tip` beside the pointer where the claim wins. - pub(crate) fn claim_with_tip(&mut self, layer: Layer, icon: CursorIcon, tip: Option) { - if let Some(slot) = self.claims.get_mut(layer as usize) { - *slot = Some(Claim { icon, tip }); - } - } - - /// Says what lies under the pointer without claiming the cursor: the tip shows with any tool, - /// beside that tool's cursor, as Acrobat shows a comment's tooltip, unless the winning claim - /// has a tip of its own. The description of the highest subject stands, and the last of - /// equals (the topmost of overlapping badges). - pub(crate) fn describe(&mut self, subject: Subject, text: String) { - if self.description.as_ref().is_none_or(|(held, _)| *held <= subject) { - self.description = Some((subject, text)); - } - } - - /// Whether the pointer is over something a press with `tool` acts on in its own right: a - /// link, a comment, a field, or what is placed on the page and its grips and editors. Not the - /// page and its text, nor a drag, whose layer also hides the pointer in full screen. - pub(crate) fn over_object(&self, tool: QuickTool) -> bool { - LAYERS - .into_iter() - .zip(&self.claims) - .any(|(layer, claim)| claim.is_some() && (Layer::Link..Layer::Drag).contains(&layer) && layer.reached_by(tool)) - } - - /// The claim on the highest layer `tool` reaches. - fn winner(claims: [Option; LAYERS.len()], tool: QuickTool) -> Option { - LAYERS.into_iter().zip(claims).rev().find_map(|(layer, claim)| claim.filter(|_| layer.reached_by(tool))) - } - - /// Sets the cursor, once, to the icon of the claim on the highest layer `tool` reaches, and - /// returns the tip: that claim's own, or else the description. With no such claim the cursor - /// is left as it is. The claims are spent: the next frame starts with none. - pub(crate) fn resolve(&mut self, ctx: &egui::Context, tool: QuickTool) -> Option { - let PageCursor { claims, description } = std::mem::take(self); - let winner = Self::winner(claims, tool); - if let Some(w) = &winner { - ctx.set_cursor_icon(w.icon); - } - winner.and_then(|w| w.tip).or(description.map(|(_, text)| text)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::comments::CommentTool; - use crate::fill_sign::FillTool; - use crate::prepare::FieldTool; - - /// One of each tool. The match stops compiling when a tool is added, so that it gets a row - /// in [`Layer::reached_by`]'s tests. - fn tools() -> Vec { - let tools = vec![ - QuickTool::Select, - QuickTool::Hand, - QuickTool::Comment(CommentTool::Rectangle), - QuickTool::Comment(CommentTool::Highlight), - QuickTool::Measure(crate::measure_ui::Tool::Distance), - QuickTool::Crop, - QuickTool::EnhanceCamera, - QuickTool::Fill(FillTool::Signature), - QuickTool::Field(FieldTool::Text), - QuickTool::Redact, - QuickTool::AddText, - QuickTool::EditText, - QuickTool::Stamp(pdfcraft_engine::StampKind::DynApproved), - QuickTool::CustomStamp(0), - QuickTool::Link, - QuickTool::SignArea { certify: false }, - QuickTool::MarqueeZoom, - QuickTool::Snapshot, - QuickTool::ColumnSelect, - ]; - for tool in &tools { - match tool { - QuickTool::Select - | QuickTool::Hand - | QuickTool::Comment(_) - | QuickTool::Measure(_) - | QuickTool::Crop - | QuickTool::EnhanceCamera - | QuickTool::Fill(_) - | QuickTool::Field(_) - | QuickTool::Redact - | QuickTool::AddText - | QuickTool::EditText - | QuickTool::Stamp(_) - | QuickTool::CustomStamp(_) - | QuickTool::Link - | QuickTool::SignArea { .. } - | QuickTool::MarqueeZoom - | QuickTool::Snapshot - | QuickTool::ColumnSelect => {} - } - } - tools - } - - #[test] - fn layers_are_listed_bottom_first_in_their_order() { - for (i, layer) in LAYERS.into_iter().enumerate() { - assert_eq!(layer as usize, i, "{layer:?}"); - } - assert!(LAYERS.windows(2).all(|w| w[0] < w[1])); - } - - #[test] - fn links_count_for_the_select_and_link_tools_only() { - for tool in tools() { - assert_eq!(Layer::Link.reached_by(tool), matches!(tool, QuickTool::Select | QuickTool::Link), "{tool:?}"); - } - } - - #[test] - fn comments_count_for_the_select_tool_only() { - for tool in tools() { - assert_eq!(Layer::Comment.reached_by(tool), tool == QuickTool::Select, "{tool:?}"); - } - } - - #[test] - fn the_other_layers_count_for_every_tool() { - for tool in tools() { - for layer in [Layer::ToolArea, Layer::Text, Layer::Field, Layer::Placed, Layer::Handle, Layer::Editor, Layer::Drag] { - assert!(layer.reached_by(tool), "{layer:?} for {tool:?}"); - } - } - } - - fn claims(claims: &[(Layer, CursorIcon, Option<&str>)]) -> PageCursor { - let mut cursor = PageCursor::default(); - for (layer, icon, tip) in claims { - cursor.claim_with_tip(*layer, *icon, tip.map(str::to_string)); - } - cursor - } - - fn winner(cursor: PageCursor, tool: QuickTool) -> Option { - PageCursor::winner(cursor.claims, tool) - } - - #[test] - fn the_highest_layer_the_tool_reaches_wins_with_its_tip() { - let on_text_under_a_link = [(Layer::Text, CursorIcon::Text, None), (Layer::Link, CursorIcon::PointingHand, Some("https://example.org/"))]; - let select = winner(claims(&on_text_under_a_link), QuickTool::Select); - assert_eq!(select, Some(Claim { icon: CursorIcon::PointingHand, tip: Some("https://example.org/".into()) })); - // A markup tool selects the text there, and the link's tip goes with its hand. - let highlight = winner(claims(&on_text_under_a_link), QuickTool::Comment(CommentTool::Highlight)); - assert_eq!(highlight, Some(Claim { icon: CursorIcon::Text, tip: None })); - // A tool reaching nothing claimed leaves the cursor alone. - assert_eq!(winner(claims(&[(Layer::Link, CursorIcon::PointingHand, None)]), QuickTool::Hand), None); - } - - #[test] - fn a_higher_claim_without_a_tip_hides_a_lower_ones_tip() { - let field_over_a_link = [(Layer::Link, CursorIcon::PointingHand, Some("Go to page 2")), (Layer::Field, CursorIcon::Text, None)]; - assert_eq!(winner(claims(&field_over_a_link), QuickTool::Select), Some(Claim { icon: CursorIcon::Text, tip: None })); - } - - #[test] - fn the_last_claim_on_a_layer_wins() { - let two_links = [(Layer::Link, CursorIcon::PointingHand, Some("first")), (Layer::Link, CursorIcon::PointingHand, Some("second"))]; - assert_eq!(winner(claims(&two_links), QuickTool::Select).and_then(|c| c.tip).as_deref(), Some("second")); - } - - /// Runs one frame that sets the cursor to `before`, if any, then resolves `claims` for - /// `tool`. Returns the frame's cursor and the tip. - fn frame(ctx: &egui::Context, before: Option, claims: &mut PageCursor, tool: QuickTool) -> (CursorIcon, Option) { - let mut tip = None; - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { - if let Some(icon) = before { - ui.ctx().set_cursor_icon(icon); - } - tip = claims.resolve(ui.ctx(), tool); - }); - // An input-only test has no renderer to take the font texture. - output.textures_delta.clear(); - (output.platform_output.cursor_icon, tip) - } - - #[test] - fn resolve_sets_the_winners_cursor_and_spends_the_claims() { - let ctx = egui::Context::default(); - let on_a_link = || claims(&[(Layer::ToolArea, CursorIcon::Crosshair, None), (Layer::Link, CursorIcon::PointingHand, Some("tip"))]); - assert_eq!(frame(&ctx, None, &mut on_a_link(), QuickTool::Select), (CursorIcon::PointingHand, Some("tip".into()))); - let stamp = QuickTool::Stamp(pdfcraft_engine::StampKind::DynApproved); - assert_eq!(frame(&ctx, None, &mut on_a_link(), stamp), (CursorIcon::Crosshair, None), "the stamp's crosshair, and no link tip"); - // Nothing the tool reaches: the cursor stays as the frame set it. - let mut only_a_link = claims(&[(Layer::Link, CursorIcon::PointingHand, Some("tip"))]); - only_a_link.describe(Subject::Comment, "Ana".into()); - assert_eq!(frame(&ctx, Some(CursorIcon::Help), &mut only_a_link, QuickTool::Hand), (CursorIcon::Help, Some("Ana".into()))); - // Resolving spends the claims, reached or not, and the description. - assert_eq!(only_a_link.description, None); - assert_eq!(winner(only_a_link, QuickTool::Select), None); - } - - #[test] - fn a_description_shows_with_any_tool_unless_the_winner_has_a_tip_of_its_own() { - let ctx = egui::Context::default(); - let stamp = QuickTool::Stamp(pdfcraft_engine::StampKind::DynApproved); - let link = (Layer::Link, CursorIcon::PointingHand, Some("https://example.org/")); - let described = |claimed: &[(Layer, CursorIcon, Option<&str>)]| { - let mut cursor = claims(claimed); - cursor.describe(Subject::Comment, "Ana\nCheck this".into()); - cursor - }; - let comment = Some("Ana\nCheck this".to_string()); - // A comment under the stamp's crosshair: the tool's cursor, and what the comment says. - let crosshair = (Layer::ToolArea, CursorIcon::Crosshair, None); - assert_eq!(frame(&ctx, None, &mut described(&[crosshair]), stamp), (CursorIcon::Crosshair, comment.clone())); - // A link the tool follows speaks for itself; one it doesn't keeps its tip to itself. - assert_eq!( - frame(&ctx, None, &mut described(&[crosshair, link]), QuickTool::Select), - (CursorIcon::PointingHand, Some("https://example.org/".into())) - ); - assert_eq!(frame(&ctx, None, &mut described(&[crosshair, link]), stamp), (CursorIcon::Crosshair, comment.clone())); - // A winner without a tip of its own, such as the Select tool's comment claim. - let picked_up = (Layer::Comment, CursorIcon::Move, None); - assert_eq!(frame(&ctx, None, &mut described(&[link, picked_up]), QuickTool::Select), (CursorIcon::Move, comment)); - } - - #[test] - fn a_comment_says_more_than_a_signature_badge_and_the_last_badge_stands() { - let badge_then_comment = { - let mut cursor = PageCursor::default(); - cursor.describe(Subject::SignatureBadge, "Signature is valid".into()); - cursor.describe(Subject::Comment, "Ana".into()); - cursor - }; - let comment_then_badges = { - let mut cursor = PageCursor::default(); - cursor.describe(Subject::Comment, "Ana".into()); - cursor.describe(Subject::SignatureBadge, "Signature is valid".into()); - cursor - }; - let two_badges = { - let mut cursor = PageCursor::default(); - cursor.describe(Subject::SignatureBadge, "Signature is valid".into()); - cursor.describe(Subject::SignatureBadge, "Signature is invalid".into()); - cursor - }; - let said = |cursor: PageCursor| cursor.description.map(|(_, text)| text); - assert_eq!(said(badge_then_comment).as_deref(), Some("Ana")); - assert_eq!(said(comment_then_badges).as_deref(), Some("Ana"), "whichever came first"); - assert_eq!(said(two_badges).as_deref(), Some("Signature is invalid"), "the badge painted last is on top"); - } -} diff --git a/crates/ui-egui/src/canvas/page_input.rs b/crates/ui-egui/src/canvas/page_input.rs deleted file mode 100644 index 5964afa4ed..0000000000 --- a/crates/ui-egui/src/canvas/page_input.rs +++ /dev/null @@ -1,1177 +0,0 @@ -//! Page input: what the tools do with the pointer on one page, what lies under it for the page -//! router, the text layer, and what is drawn over the page after its text. - -use egui::{Color32, CornerRadius, Pos2, Rect, Stroke}; -use pdfcraft_render::{DocInfo, LinkTarget, PageText}; - -use super::area::{SignTab, paint_sign_tab, sign_tab_at, sign_tabs}; -use super::{ - DocView, MARK_ICON_SHARE, PageEnv, PageFrame, PageSlot, PageXform, Selection, Span, cached_edit_images, click_unit, mark_anchor, - signature_badges, start_selection_drag, verdict_mark_rect, -}; -use crate::page_cursor::{Layer, Subject}; -use crate::page_keys::PageKeys; -use crate::page_pointer::PagePointer; -use crate::page_router::{Owner, PagePress, top}; -use crate::{QuickTool, comments, icons}; - -/// What the page's tools did with the pointer this frame. -pub(super) struct PageInput { - /// What the press the pages hold is to this page. - pub(super) press: PagePress, - /// The press's drag is the page's text's: nobody holds it, or its owner lets its drag go (text - /// markup: a click selects it, a drag selects the text under it). - pub(super) text_drag: bool, - /// A tool, a field or a comment took the pointer this frame (its own press, or a gesture of the - /// active tool's): text selection and image pick leave it alone. - pub(super) consumed: bool, - /// Redact or Highlight draws boxes off text. - pub(super) area_tool: bool, - /// What a press under the pointer would take (the top hit there), for hover painting. - pub(super) hover: Option, - /// The press's click came up over what the press began on: a link's or a field's click counts - /// only then, as a button's does. - pub(super) released_over: bool, - /// The sign tabs on empty fields a click would sign, painted over the page. - pub(super) sign_tabs: Vec, -} - -/// Common geometry and pointer state for a tool acting on one page. -#[derive(Clone, Copy)] -pub(crate) struct PageToolContext<'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, - /// This frame's keys as the pages see them. - pub keys: PageKeys, -} - -/// The tools' input on one page. The hits at the press point decide who holds the press, and the -/// modules are told what the press is to this page (`PagePress`): their own, nobody's (the active -/// tool's: `tool_input`, and the tools still called here), or another page's. Edit text's group -/// paints from what lies under the pointer too (`hovered`). Text selection runs after, on what -/// nobody took. -pub(super) fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot) -> PageInput { - let PageEnv { - added, - allowed, - can_fill, - can_modify, - comments_hidden, - doc, - doc_links, - editing_content, - form, - info, - keys, - placing, - prefs, - preparing, - redact_mark, - table_preview, - text_style, - text_links, - tool, - .. - } = frame.env; - let PageSlot { i, xf, .. } = *slot; - let PageFrame { resp, ptr, pointer, .. } = *frame; - let cx = PageToolContext { ui, resp, xf: &xf, ptr, page: i, doc, info, keys }; - let pcx = comments::PageCx { page: i, xf: &xf, ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark, keys }; - let (lines, images) = - if matches!(tool, QuickTool::AddText | QuickTool::EditText) && can_modify { edit_inventory(view, doc, i) } else { Default::default() }; - let field_tool = match tool { - QuickTool::Field(f) => Some(f), - _ => None, - }; - // While a table is being set up, nothing else is drawn or moved. - let prepare_allowed = can_modify && table_preview.is_none() && frame.out.open_table.is_none(); - // An empty field a click would sign carries a small tab saying so, shown only while - // a click on the field signs it (the Select tool, not while preparing a form). The tab - // is drawn over every field, so a click on it signs its field (`forms_ui::hit`). - let tabs = page_sign_tabs(ui, doc, form, info, slot, can_fill, tool == QuickTool::Select && !preparing); - let hits = PageHits { - page: i, - xf: &xf, - info, - tool, - pcx: &pcx, - form, - doc, - can_fill, - can_modify, - editing_content, - preparing, - field_tool, - prepare_allowed, - added, - doc_links, - lines: &lines, - images: &images, - clip: ui.clip_rect(), - text_links, - tabs: &tabs, - }; - if let Some(o) = ptr.pressed() { - // A press with Shift or ⌘ in Edit text is the objects', whatever lies under it - // (`object_ui::modified_hit`): the page's objects are read for it alone. Crop mode holds - // it on its page as any other press, so a modified click away applies the crop rather - // than taking the picture into a group (#6422). - let adds = tool == QuickTool::EditText - && can_modify - && xf.rect.contains(o) - && !hits.cropping(view) - && crate::object_ui::adds(ptr.modifiers) - && !crate::object_ui::menu_open(ui, resp); - let objects = adds.then(|| view.objects.inventory(doc, i)); - let at = hits.at(view, o, objects.as_ref()); - // A press is the page's it lies on, or past its edge the one whose selected picture has its - // rotate knob or a grip there (crop mode's grips too). - let past_edge = |h: &crate::page_router::Hit| { - use crate::page_router::PicturePart; - matches!(h.owner, Owner::Picture { part: PicturePart::Knob | PicturePart::Corner(_) | PicturePart::Crop(_), .. }) - }; - if xf.rect.contains(o) || at.iter().any(past_edge) { - view.router.press(i, at, tool); - } - } - // A drag that the press's owner declines is nobody's once it starts. - if ptr.drag_started { - view.router.drag_began(); - } - // What this page has to do with the press: its owner's, the active tool's, or another page's. - let press = view.router.press_for(i); - // What lies under the pointer before the tools act, on the frames that need it: for a click's - // release, a right-click's tool checks, Fill & Sign's preview, and Edit text's hover outlines. - let editing = matches!(tool, QuickTool::AddText | QuickTool::EditText) && can_modify; - let wants_under = editing || resp.clicked() || resp.secondary_clicked() || matches!(tool, QuickTool::Fill(_)) && !ptr.any_down; - let under = pointer.filter(|p| wants_under && xf.rect.contains(*p)).map(|p| hits.at(view, p, None)).unwrap_or_default(); - let hovered = top(under.iter().cloned(), tool); - // A double-click on the objects selected together is the object's its press was on: the - // double-click leaves the group (`object_ui`), and added text opens for typing, a picture or a - // paragraph is the one taken (the user's ruling). - let press = match press { - PagePress::Mine(Owner::Objects { part: crate::page_router::ObjectsPart::Selection }) if resp.double_clicked() => { - view.router.under_objects().map_or(PagePress::Free, PagePress::Mine) - } - press => press, - }; - let released_over = match press { - PagePress::Mine(owner) if resp.clicked() => under.iter().any(|h| h.owner == owner), - _ => false, - }; - // A right-click while the primary button is held (a comment moved, a box drawn) leaves the - // selections that press acts on alone. egui ends the press's own interaction when any button is - // released, the right-click's own frame included, so the button is what tells. A touch's long - // press, which egui reports as a right-click with the finger still down, opens its menu. - let press_held = ptr.primary_down && !resp.long_touched(); - // A right-click is the page's it lies on, or past its edge the one whose crop grip lies there, - // as a press is (#5835): what a right-click there would go to is asked only off the page. - let right = frame.right_click_on(|p| { - use crate::page_router::PicturePart; - xf.rect.contains(p) || matches!(hits.context_at(view, p, &[]), Some(Owner::Picture { part: PicturePart::Crop(_), .. })) - }); - let context = right.and_then(|p| right_click(&hits, &under, view, p, press_held)); - // Edit text: a right-click on a picture selects it for its menu, and one on anything else on the - // page unselects it. - if right.is_some() && tool == QuickTool::EditText && can_modify && !press_held { - let picture = match context { - Some(Owner::Picture { index, .. }) => Some(index), - _ => None, - }; - crate::edit_text_ui::picture_context(i, picture, view); - } - // A mark already placed takes its own press (comments, below), as does one being moved on this - // page until its move ends; with no button down the Fill & Sign tool's preview hides where a - // press would be taken (a mark, its handles, a Prepare field). - let over_mark = matches!(tool, QuickTool::Fill(_)) - && (matches!(press, PagePress::Mine(_)) || comments::moving_on(view, i) || !ptr.any_down && hovered.is_some()); - tool_input(ui, view, frame, slot, &pcx, press, over_mark); - let on_field = if preparing && !placing { - let o = crate::prepare::page_input(cx, form, field_tool, prepare_allowed, press, view); - frame.out.field_props |= o.properties; - frame.out.field_placed |= o.placed; - frame.out.open_table = frame.out.open_table.or(o.table); - o.consumed || field_tool.is_some() - } else { - tool == QuickTool::Select && !placing && crate::forms_ui::page_input(cx, form, can_fill, press, released_over, view) - }; - // Redact draws boxes off text; so does Highlight (an area highlight, as in Acrobat). - let area_tool = tool == QuickTool::Redact && can_modify || tool == QuickTool::Comment(comments::CommentTool::Highlight) && allowed; - let boxing = area_tool && { - let text = view.page_text(i); - let over_text = |p: Pos2| { - let (vx, vy) = xf.screen_to_view(p); - text.as_ref().is_some_and(|t| t.glyph_at(vx, vy).is_some()) - }; - crate::redact_ui::page_input(cx, tool, over_text, press == PagePress::Free, view) - }; - // Edit text's group: the objects selected together, added content, the paragraphs and the - // pictures, each told what the press is to this page. Edit text ignores input while a dialog, - // the palette, another window or another tab has it (`gate`), as before. - let gate = !(tool == QuickTool::EditText && view.objects.input_blocked()); - if tool == QuickTool::EditText && can_modify && gate { - crate::edit_text_ui::picture_keys(ui.ctx(), keys, view, i, &images, ptr.any_down); - } - let on_objects = tool == QuickTool::EditText && can_modify && crate::object_ui::page_input(cx, press, view); - let picks_up = matches!(tool, QuickTool::Select | QuickTool::AddText | QuickTool::EditText); - let ccx = crate::content_ui::ContentCx { - added, - press, - gate, - picks_up, - adding_text: tool == QuickTool::AddText, - edit_on_click: matches!(tool, QuickTool::AddText | QuickTool::EditText), - style: text_style, - }; - let on_content = !placing && editing_content && can_modify && crate::content_ui::page_input(cx, ccx, view); - // Add text acts on the page's own paragraphs: the one its press was on, until the button is up, - // and the one under the pointer. Edit text boxes every paragraph and picture. - let paragraph = |o: Option| matches!(o, Some(Owner::Paragraph { .. })); - let source = tool == QuickTool::AddText && (paragraph(press.owner()) || paragraph(hovered.as_ref().map(|h| h.owner))); - let on_edit_text = (tool == QuickTool::EditText || source) && can_modify && { - let adding = (tool == QuickTool::AddText).then_some(added.as_slice()); - let pcx = crate::edit_text_ui::ParagraphCx { press, gate, hover: hovered.as_ref(), adding }; - let text_used = crate::edit_text_ui::page_input(cx, &lines, pcx, view); - let image_cx = crate::edit_text_ui::ImageCx { ui, resp, xf: &xf, ptr, page: i, doc, info, press, gate }; - let image_used = crate::edit_text_ui::image_input(&image_cx, &images, view); - text_used || image_used - }; - if tool == QuickTool::EditText { - // A press the objects or added content took leaves the picture unselected; so does one - // while Edit text's input is blocked. Otherwise added content follows the picture selected. - if on_objects || on_content { - if ptr.pressed().is_some() || resp.clicked() || resp.secondary_clicked() { - view.image_selection = None; - } - } else { - crate::content_ui::sync_image_selection(view, i, &images, added); - } - } - let (link_owner, link_context) = (link_of(press.owner()), link_of(context)); - let on_link = tool == QuickTool::Link && can_modify && crate::link_ui::page_input(cx, press == PagePress::Free, link_owner, link_context, view); - if tool == QuickTool::Select - && can_modify - && let Some(index) = link_context - { - view.links.context = Some((i, index)); - } - // Comments, every frame: their own presses, a commenting tool's, and a click elsewhere that - // leaves them unselected. A press nobody holds that another tool took this frame (Prepare's - // selection rectangle, added content) is not also a commenting tool's, as before. - let taken = on_objects || on_edit_text || on_link || on_content || boxing || on_field; - let on_comment = comments::page_input(ui, resp, &pcx, press, taken, view); - let consumed = taken || on_comment; - let hover = pointer.and_then(|p| claim_under(&hits, view, p, frame.env.unobstructed)); - PageInput { - press, - text_drag: !view.router.keeps_drag(), - consumed, - area_tool, - hover, - released_over, - sign_tabs: tabs.into_iter().map(|(_, tab)| tab).collect(), - } -} - -/// The sign tabs on the slot's page, on empty fields a click would sign, each with the field it -/// signs; none unless `shown`. -fn page_sign_tabs<'a>( - ui: &egui::Ui, - doc: &'a pdfcraft_engine::Document, - form: &[pdfcraft_engine::FormField], - info: &DocInfo, - slot: &PageSlot, - can_fill: bool, - shown: bool, -) -> Vec<(&'a str, SignTab)> { - let PageSlot { i, xf, .. } = slot; - let i = *i; - if !shown { - return Vec::new(); - } - sign_tabs(&doc.signatures, form, i, can_fill) - .into_iter() - .filter_map(|(name, [x0, y0, x1, y1])| { - sign_tab_at(ui, xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]), xf.rect).map(|tab| (name, tab)) - }) - .collect() -} - -/// What lies under the pointer at `p`, after the tools act: its top, what a press there would take, -/// for hover painting. With `claim` (nothing drawn over the pages, such as the palette), its cursor -/// and tip too, after the tools claimed theirs (the last claim on a layer stands). -fn claim_under(hits: &PageHits<'_>, view: &mut DocView, p: Pos2, claim: bool) -> Option { - let under = hits.at(view, p, None); - if claim { - for h in &under { - view.cursor.claim_with_tip(h.layer, h.icon, h.tip.clone()); - } - } - top(under, hits.tool) -} - -/// The link `owner` is, by its `/Annots` index. -fn link_of(owner: Option) -> Option { - match owner { - Some(Owner::Link { index }) => Some(index), - _ => None, - } -} - -/// The active tool's own input on page `i`: the one gate for presses nobody holds. Measure, the -/// stamps, Fill & Sign, Sign area, zoom and snapshot, the camera's quadrilateral and crop act only -/// on a press that began on this page and that no hit won (`press` is Free), and keep their cursor -/// and gestures. The camera also drags a corner whose press it holds, and crop's double-click -/// opens Set Page Boxes wherever it is. `over_mark`: with Fill & Sign, a hit holds the press (a -/// mark's, or a Prepare field's), a mark is being moved on this page, or with no button down a press -/// under the pointer would be taken (a mark, its handles, a Prepare field). -fn tool_input( - ui: &egui::Ui, - view: &mut DocView, - frame: &mut PageFrame<'_>, - slot: &PageSlot, - pcx: &comments::PageCx<'_>, - press: PagePress, - over_mark: bool, -) { - let PageEnv { - allowed, - author, - by_line, - can_crop, - can_modify, - custom_line, - custom_stamp, - date_text, - doc, - info, - initials, - keys, - signature, - tool, - units, - fill_text_size, - fill_text_color, - fill_text_border, - .. - } = frame.env; - let PageSlot { i, xf, .. } = *slot; - let PageFrame { resp, ptr, .. } = *frame; - let cx = PageToolContext { ui, resp, xf: &xf, ptr, page: i, doc, info, keys }; - let free = press == PagePress::Free; - if let QuickTool::Measure(measure_tool) = tool { - crate::measure_ui::page_input(ui, crate::measure_ui::Clicks::of(resp, free), doc, view, pcx, measure_tool, units); - } - if let QuickTool::Stamp(kind) = tool - && allowed - && crate::stamps_ui::place(cx, kind, by_line, author, free, view) - { - frame.out.stamp_placed = true; - } - if let Some(cs) = custom_stamp.as_ref() - && allowed - && crate::stamps_ui::place_custom(cx, cs, custom_line, author, free, view) - { - frame.out.stamp_placed = true; - } - if let QuickTool::Fill(ft) = tool - && allowed - && !over_mark - { - let input = crate::fill_sign::PageInput { - tool: ft, - text_size: fill_text_size, - text_color: fill_text_color, - text_border: fill_text_border, - signature: signature.as_ref(), - initials: initials.as_ref(), - preview: frame.signature_preview, - author, - date_text, - }; - match crate::fill_sign::page_input(cx, input, free, view) { - Some(crate::fill_sign::FillAction::Edit(e)) => view.pending_edit = Some(*e), - Some(crate::fill_sign::FillAction::Signature(e)) => { - view.pending_edit = Some(*e); - view.fill_signature_page = Some(i); - } - Some(crate::fill_sign::FillAction::CreateSignature) => frame.out.open_signature = true, - Some(crate::fill_sign::FillAction::CreateInitials) => frame.out.open_initials = true, - Some(crate::fill_sign::FillAction::Refused(why)) => frame.out.refused = Some(why), - None => {} - } - } - if matches!(tool, QuickTool::SignArea { .. }) { - crate::sign_ui::page_input(cx, free, view); - } - if matches!(tool, QuickTool::MarqueeZoom | QuickTool::Snapshot) { - crate::zoom_snap::page_input(ui, resp, &xf, ptr, i, free, view); - } - if tool == QuickTool::EnhanceCamera { - crate::camera_ui::page_input(resp, &xf, ptr, i, view, can_modify, press); - } - if tool == QuickTool::Crop - && crate::crop::page_input(ui, crate::crop::CropPageInput { resp, xf: &xf, ptr, page: i, info, view, allowed: can_crop, free }) - { - view.current = i; - frame.out.open_boxes = true; - } -} - -/// A right-click at `p`: the page's menu opens there, and it goes to what lies on top there -/// ([`PageHits::context_at`]), which the menu then acts on. A comment there is selected, and none -/// elsewhere; a Prepare field is selected; links and Edit text's pictures take theirs from what this -/// returns. -/// `under`: the hits at `p` before the tools act. `press_held`: the primary button is held, and the -/// comment and Prepare selections its press acts on are left alone until its release; links still -/// take theirs, as before. -fn right_click(hits: &PageHits<'_>, under: &[crate::page_router::Hit], view: &mut DocView, p: Pos2, press_held: bool) -> Option { - let context = hits.context_at(view, p, under); - // Delete page, Paste and Copy Image act where the menu opened, whoever takes the right-click. - comments::anchor(hits.pcx, p, view); - // The menu is what the right-click went to (Add text's is the page's), when that is selected: - // under a held press, the selections stay as they are. - view.menu_for = context.filter(|_| !(hits.tool == QuickTool::AddText && hits.can_modify)).map(|o| (hits.page, o)); - if press_held { - return context; - } - // Add text takes every right-click on a page it can change, the Link tool those on a link, and a - // Prepare field tool the whole page, as before: comments see none of them. - let tool_takes_it = match hits.tool { - QuickTool::AddText => hits.can_modify, - QuickTool::Link => hits.can_modify && matches!(context, Some(Owner::Link { .. })), - _ => hits.field_tool.is_some(), - }; - if !tool_takes_it { - let comment = match context { - Some(Owner::Comment { index, .. }) => Some(index), - _ => None, - }; - comments::context(hits.pcx, p, comment, view); - } - if let Some(Owner::PrepareField { field, widget }) = context { - crate::prepare::context(hits.form, field, widget, view); - } - context -} - -/// Edit text's paragraphs and pictures on page `i`, kept while the document is unchanged. -fn edit_inventory( - view: &mut DocView, - doc: &pdfcraft_engine::Document, - i: usize, -) -> (Vec, Vec) { - let generation = doc.edit_generation(); - let lines = match view.edit_lines.get(&i) { - Some((g, l)) if *g == generation => l.clone(), - _ => { - let l = doc.text_blocks(i); - view.edit_lines.insert(i, (generation, l.clone())); - l - } - }; - let images = cached_edit_images(view, doc, i).to_vec(); - (lines, images) -} - -/// What the page modules have under a point on one page, for the page router. -struct PageHits<'a> { - page: usize, - xf: &'a PageXform, - info: &'a DocInfo, - tool: QuickTool, - pcx: &'a comments::PageCx<'a>, - form: &'a [pdfcraft_engine::FormField], - /// Its document: what its scripts show while it is read (`Document::shown_by_scripts`). - doc: &'a pdfcraft_engine::Document, - can_fill: bool, - can_modify: bool, - /// Edit a PDF is open: added text and pictures can be picked up. - editing_content: bool, - preparing: bool, - field_tool: Option, - /// Prepare may draw and move fields (not while a table is being set up). - prepare_allowed: bool, - added: &'a [pdfcraft_engine::Added], - /// The document's links, as the engine lists them (the Link tool edits every one). - doc_links: &'a [pdfcraft_engine::LinkItem], - lines: &'a [pdfcraft_engine::TextBlock], - images: &'a [pdfcraft_engine::PageImage], - /// The pages' visible area (the picture's rotate knob stays inside it). - clip: Rect, - /// Addresses written as plain page text open like links (#4207). - text_links: bool, - /// The sign tabs on empty signature fields, with the field each one signs: drawn over every - /// field, so the pointer on one is on its own field. - tabs: &'a [(&'a str, SignTab)], -} - -impl PageHits<'_> { - /// Edit text's crop mode is on for a picture on this page. - fn cropping(&self, view: &DocView) -> bool { - self.tool == QuickTool::EditText && self.can_modify && view.image_selection.as_ref().is_some_and(|s| s.page == self.page && s.crop.is_some()) - } - - /// The hits at `p`, bottom up ([`Self::hits`]). For a press with Shift or ⌘ in Edit text, the - /// page's `objects` ([`crate::object_ui::ObjectSelection::inventory`]), which take it whole. - fn at(&self, view: &DocView, p: Pos2, objects: Option<&Result, String>>) -> Vec { - self.hits(view, p, false, objects) - } - - /// What a right-click at `p` is on: what lies on top there, as for a press, but with every - /// tool reaching comments, as a comment's menu shows whatever the tool, and a Prepare field - /// whatever the field tool. Links count for the tools that reach them (Select; the Link tool, - /// below). Edit text's paragraphs have no menu, and give way to the picture under them (the - /// user's ruling): with Edit text, a picture under a link or a paragraph takes the right-click. - /// Nor have added content or an open paragraph's frame: those give way to a picture under them, - /// and to nothing else. (Where objects are selected together, the page view unselects the picture - /// a right-click selects, and the menu is the page's.) - /// A highlight over a link is the highlight's ([`comments::context_hit`]). - /// The Link tool edits links and reaches no comment: on a document it can change, its - /// right-click is what its press there would take (`under`, the hits at `p`), when that is - /// anything. - fn context_at(&self, view: &DocView, p: Pos2, under: &[crate::page_router::Hit]) -> Option { - if self.tool == QuickTool::Link - && self.can_modify - && let Some(press) = top(under.iter().cloned(), QuickTool::Link) - { - return Some(press.owner); - } - let reached: Vec<_> = self - .hits(view, p, true, None) - .into_iter() - .filter(|h| (h.layer != Layer::Link || h.layer.reached_by(self.tool)) && !matches!(h.owner, Owner::Paragraph { .. })) - .collect(); - let on_top = top(reached.iter().cloned(), QuickTool::Select)?.owner; - if self.tool == QuickTool::EditText && matches!(on_top, Owner::Added { .. } | Owner::Objects { part: crate::page_router::ObjectsPart::Frame }) - { - let pictures = reached.into_iter().filter(|h| matches!(h.owner, Owner::Picture { .. })); - return Some(top(pictures, QuickTool::Select).map_or(on_top, |h| h.owner)); - } - Some(on_top) - } - - /// The hits at `p`, bottom up: links, comments; Edit text's pictures under its paragraphs (text - /// on top of artwork takes the press), added content, the objects selected together and the - /// open paragraph's frame, the selected picture's grips over them all; the camera tool's corners; - /// then form fields (Prepare's, being moved, over the comments; filled ones under added content - /// and the comments that move). For a press with Shift or ⌘ in Edit text, only the objects - /// (`objects`, the page's); in crop mode, only the picture being cropped, which a right-click - /// reaches only on the crop. - /// For a right-click (`context`), comments by [`comments::context_hit`], and no camera corner (it - /// has no menu). - fn hits( - &self, - view: &DocView, - p: Pos2, - context: bool, - objects: Option<&Result, String>>, - ) -> Vec { - let PageHits { - page, - xf, - info, - tool, - pcx, - form, - doc, - can_fill, - can_modify, - editing_content, - preparing, - field_tool, - prepare_allowed, - added, - doc_links, - lines, - images, - clip, - text_links, - tabs, - } = *self; - // A press with Shift or ⌘ is the objects' (`object_ui::modified_hit`), off crop mode's page. - if let Some(objects) = objects { - return crate::object_ui::modified_hit(view, xf, info, page, objects, clip, p).into_iter().collect(); - } - // Crop mode holds every press on its page (`edit_text_ui::crop_hit`). A right-click is the - // crop's only on the picture being cropped, its box or its grips (#5835), where it keeps crop - // mode and opens no menu; elsewhere it goes to what lies there, as without crop mode. - if self.cropping(view) { - use crate::page_router::{CropPart, PicturePart}; - let crop = crate::edit_text_ui::crop_hit(xf, page, info, images, view, p); - let on_crop = crop.as_ref().is_some_and(|h| !matches!(h.owner, Owner::Picture { part: PicturePart::Crop(CropPart::Page), .. })); - if !context || on_crop { - return crop.into_iter().collect(); - } - } - // A right-click reaches a Prepare field whatever the field tool, and while a table is set up, - // on a document that can be changed. - let (field_tool, prepare_allowed) = if context { (None, can_modify) } else { (field_tool, prepare_allowed) }; - let fields = if preparing { - crate::prepare::hit(xf, info, page, form, field_tool, prepare_allowed, &view.prepare, p) - } else if tool == QuickTool::Select { - crate::forms_ui::hit(xf, info, page, doc, tabs, can_fill, p) - } else { - None - }; - // With Add text, only the paragraphs and pictures not under added content. - let editing = - can_modify && (tool == QuickTool::EditText || tool == QuickTool::AddText && !crate::content_ui::hits_added(xf, info, page, added, p)); - let (pictures, paragraphs, objects, grips) = if editing { - let open = view.line_editor.as_ref().filter(|e| e.page == page); - let frame = open - .filter(|e| !e.has_changes()) - .and_then(|e| lines.get(e.block)) - .map(|l| xf.user_rect(info, page, l.rect.map(|v| v as f32)).expand(2.0)); - // Add text acts on the page's paragraphs only in their boxes, edges included (its click - // there finishes the box being typed and opens the paragraph, `ParagraphCx::adding`): - // not on pictures, nor beside a paragraph, where a click starts a new box. - let edit_text = tool == QuickTool::EditText; - let on_paragraphs = edit_text || crate::edit_text_ui::over_paragraph(xf, info, page, lines, p); - ( - edit_text.then(|| crate::edit_text_ui::picture_hit(xf, page, info, images, view, p)).flatten(), - on_paragraphs.then(|| crate::edit_text_ui::hit(xf, info, page, lines, open.map(|e| e.block), p)).flatten(), - edit_text.then(|| crate::object_ui::hit(view, xf, info, page, frame, p)).flatten(), - edit_text.then(|| crate::edit_text_ui::picture_handle_hit(clip, xf, page, info, images, view, p)).flatten(), - ) - } else { - (None, None, None, None) - }; - // Added text and pictures, over the page's own paragraphs and under the objects selected - // together. - let picks_up = matches!(tool, QuickTool::Select | QuickTool::AddText | QuickTool::EditText); - let added = (editing_content && can_modify && picks_up).then(|| crate::content_ui::hit(xf, info, page, added, view, p)).flatten(); - let corner = (!context && tool == QuickTool::EnhanceCamera && can_modify).then(|| crate::camera_ui::hit(xf, page, view, p)).flatten(); - let link = crate::link_ui::hit(xf, info, page, doc_links, tool, p); - let text_link = (text_links && link.is_none()).then(|| text_link_hit(view, info, xf, page, p)).flatten(); - let on_link = link.is_some() || text_link.is_some(); - let comment = if context { comments::context_hit(pcx, p) } else { comments::hit(pcx, view, p, on_link) }; - [link, text_link, comment, pictures, paragraphs, added, objects, grips, corner, fields].into_iter().flatten().collect() - } -} - -/// The web or email address written as plain text under `p` on `page` (#4207), with no link -/// annotation over it: the same hand and tip (its address) as a link annotation's. -fn text_link_hit(view: &DocView, info: &DocInfo, xf: &PageXform, page: usize, p: Pos2) -> Option { - let (vx, vy) = xf.screen_to_view(p); - let (index, link) = view.text_link_at(info, page, vx, vy)?; - let owner = crate::page_router::Owner::TextLink { index }; - // A drag from the address selects its text, as from any other text: only a click opens it. - Some(crate::page_router::Hit { - tip: Some(link.uri.clone()), - declines_drag: true, - ..crate::page_router::Hit::new(owner, Layer::Link, egui::CursorIcon::PointingHand) - }) -} - -/// Text layer: find matches, selection, I-beam and drag-to-select. -pub(super) fn text_layer(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot, input: &PageInput) { - let PageEnv { selects_text, tool, .. } = frame.env; - let PageSlot { i, r, xf } = *slot; - let PageFrame { resp, ptr, pointer, .. } = *frame; - if let Some(text) = view.texts.get(&i).cloned() { - paint_text_marks(ui, view, &text, i, xf, resp.dragged()); - if selects_text - && !input.consumed - && let Some(p) = pointer.filter(|p| r.contains(*p)) - { - // The I-beam drops where a press would go to a link, an address written as page text - // included (#4207) (ruling E: the tools that select a link's text show it there). - let over_link = input.hover.as_ref().is_some_and(|h| matches!(h.owner, Owner::Link { .. } | Owner::TextLink { .. })); - let pointer = TextPointer { page: i, xf, rect: r, tool, resp, ptr: ptr.clone(), pointer: p, over_link, text_drag: input.text_drag }; - text_pointer_input(ui, view, &text, pointer); - } else if selects_text - && !input.consumed - && input.text_drag - && input.press != PagePress::Elsewhere - && ptr.drag_started - && let (Some(origin), Some(p)) = (ptr.origin, pointer) - { - // A quick drag can leave the page it was pressed on before egui calls it a drag (a - // flick off the bottom of a page, onto the gap or the next page): the press is still - // this page's, so it starts the selection here, for the next page to extend. A press - // something on the page keeps (a link, a comment) selects nothing. - let column = tool == QuickTool::ColumnSelect || ui.input(|input| input.modifiers.alt); - let clicks = selection_click_count(view.clicks, tool); - start_selection_drag(view, i, &text, clicks, column, xf.screen_to_view(origin), xf.screen_to_view(p)); - } - } -} - -fn paint_text_marks(ui: &egui::Ui, view: &DocView, text: &PageText, page: usize, xf: PageXform, dragging: bool) { - let painter = ui.painter(); - let to_screen = |g: [f32; 4]| xf.view_rect(g); - if let Some(find) = &view.find { - for (index, (match_page, range)) in find.matches.iter().enumerate() { - if *match_page != page { - continue; - } - let fill = if find.current == Some(index) { - Color32::from_rgba_unmultiplied(255, 140, 0, 110) - } else { - Color32::from_rgba_unmultiplied(255, 214, 0, 90) - }; - for line_rect in text.line_rects(range.clone()) { - painter.rect_filled(to_screen(line_rect).expand(1.0), CornerRadius::same(2), fill); - } - } - } - if view.all_text { - for line_rect in text.line_rects(0..text.glyphs.len()) { - painter.rect_filled(to_screen(line_rect), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70)); - } - } - if let Some(selection) = view.selection.filter(|selection| selection.pages().contains(&page)) { - for line_rect in selection.rects_on(page, text) { - painter.rect_filled(to_screen(line_rect), CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x3A, 0x7B, 0xF0, 70)); - } - if let Span::Column { rect } = selection.span - && dragging - { - let outline = Stroke::new(1.0, Color32::from_rgb(0x3A, 0x7B, 0xF0)); - painter.rect_stroke(to_screen(rect), CornerRadius::ZERO, outline, egui::StrokeKind::Middle); - } - } -} - -struct TextPointer<'a> { - page: usize, - xf: PageXform, - rect: Rect, - tool: QuickTool, - resp: &'a egui::Response, - ptr: PagePointer, - pointer: Pos2, - /// A press under the pointer would go to a link. - over_link: bool, - /// The press's drag is the page's text's ([`PageInput::text_drag`]). - text_drag: bool, -} - -struct TextGesture<'a> { - page: usize, - xf: PageXform, - rect: Rect, - tool: QuickTool, - ptr: PagePointer, - resp: &'a egui::Response, - pointer: Pos2, - vx: f32, - vy: f32, - over_text: bool, - over_link: bool, - text_drag: bool, - column: bool, -} - -fn text_pointer_input(ui: &mut egui::Ui, view: &mut DocView, text: &PageText, pointer: TextPointer<'_>) { - let TextPointer { page, xf, rect, tool, resp, ptr, pointer: screen_pointer, over_link, text_drag } = pointer; - let (vx, vy) = xf.screen_to_view(screen_pointer); - let over_text = text.glyph_at(vx, vy).is_some(); - let column = tool == QuickTool::ColumnSelect || ui.input(|input| input.modifiers.alt); - let gesture = TextGesture { page, xf, rect, tool, ptr, resp, pointer: screen_pointer, vx, vy, over_text, over_link, text_drag, column }; - update_text_cursor(view, &gesture); - update_selection_on_press(ui, view, text, &gesture); - update_dragged_selection(view, text, &gesture); - finish_text_pointer_gesture(ui, view, text, &gesture); -} - -fn update_text_cursor(view: &mut DocView, gesture: &TextGesture<'_>) { - // A press on a link selects nothing (it is the link's), so no cursor here says it would. - if gesture.column && !gesture.over_link { - view.cursor.claim(Layer::Text, egui::CursorIcon::Crosshair); - } else if gesture.over_text && !gesture.over_link { - view.cursor.claim(Layer::Text, egui::CursorIcon::Text); - } -} - -fn update_selection_on_press(ui: &egui::Ui, view: &mut DocView, text: &PageText, gesture: &TextGesture<'_>) { - // A press held by what keeps its drag (a link, a comment that moves) selects no text; one on - // text markup lets its drag select the text underneath. - let press_here = gesture.ptr.origin.is_some_and(|origin| gesture.rect.contains(origin)); - if gesture.ptr.pressed().is_some() && press_here && gesture.text_drag { - let now = ui.input(|input| input.time); - let (max_delay, max_dist) = ui.ctx().options(|options| (options.input_options.max_double_click_delay, options.input_options.max_click_dist)); - let consecutive = now - view.last_press_time <= max_delay && view.last_press_pos.is_some_and(|pos| pos.distance(gesture.pointer) <= max_dist); - view.clicks = if consecutive { view.clicks.saturating_add(1) } else { 1 }; - view.last_press_time = now; - view.last_press_pos = Some(gesture.pointer); - let clicks = selection_click_count(view.clicks, gesture.tool); - if clicks >= 2 - && gesture.over_text - && let Some((first, last)) = text.nearest(gesture.vx, gesture.vy).and_then(|anchor| click_unit(text, clicks, anchor)) - { - view.selection = Some(Selection::run(gesture.page, first, last)); - } - } - if gesture.ptr.drag_started && press_here && gesture.text_drag { - let origin = gesture.xf.screen_to_view(gesture.ptr.origin.unwrap_or(gesture.pointer)); - let clicks = selection_click_count(view.clicks, gesture.tool); - start_selection_drag(view, gesture.page, text, clicks, gesture.column, origin, (gesture.vx, gesture.vy)); - } -} - -fn selection_click_count(clicks: u32, tool: QuickTool) -> u32 { - if clicks > 2 && tool != QuickTool::Select { 1 } else { clicks } -} - -fn update_dragged_selection(view: &mut DocView, text: &PageText, gesture: &TextGesture<'_>) { - let clicks = selection_click_count(view.clicks, gesture.tool); - // The drag extends the selection on its own page and, for a reading-order selection the drag - // started, on any page the pointer moves on to. Its release frame too: a quick flick back - // onto an earlier page, drawn before the page that started the drag, may be over it only then. - let selecting = view.selection_drag || view.selection_drag_ended; - if (gesture.resp.dragged_by(egui::PointerButton::Primary) || gesture.resp.drag_stopped_by(egui::PointerButton::Primary)) - && let Some(mut selection) = - view.selection.filter(|selection| selection.page == gesture.page || (selecting && matches!(selection.span, Span::Run { .. }))) - { - let hit = text.nearest(gesture.vx, gesture.vy); - match selection.span { - Span::Run { .. } if clicks >= 2 => { - if let Some(hit) = hit { - if selection.page == gesture.page { - // Same page: also select table rows by whole units, as a plain drag does. - extend_by_unit_on_page(&mut selection, text, clicks, hit, gesture.vx); - } else { - extend_by_unit(view, &mut selection, text, clicks, (gesture.page, hit)); - } - } - } - Span::Run { .. } => { - if let Some(hit) = hit { - selection.extend_to_at(gesture.page, hit, Some(gesture.vx).filter(|x| x.is_finite())); - } - } - Span::Column { rect } => selection.span = Span::Column { rect: [rect[0], rect[1], gesture.vx, gesture.vy] }, - } - view.selection = Some(selection); - } - if gesture.resp.drag_stopped() - && view.selection.is_some_and(|selection| { - selection.page == gesture.page && matches!(selection.span, Span::Column { .. }) && selection.text_on(gesture.page, text).is_empty() - }) - { - view.selection = None; - } -} - -/// After a multi-click the drag extends by its unit (#1685), as in Acrobat and browsers: whole -/// words or lines, always keeping the one clicked, which holds the anchor whichever way the drag -/// went. On another page than the one clicked, the clicked unit is read from its own page. -fn extend_by_unit(view: &DocView, selection: &mut Selection, text: &PageText, clicks: u32, (page, hit): (usize, usize)) { - let Span::Run { anchor, .. } = selection.span else { return }; - let start_page = selection.page; - let other = if start_page == page { None } else { view.texts.get(&start_page).cloned() }; - let anchor_text = match other.as_deref() { - Some(t) => t, - None if start_page == page => text, - None => return, - }; - let Some((first, last)) = click_unit(anchor_text, clicks, anchor) else { return }; - let (to_first, to_last) = click_unit(text, clicks, hit).unwrap_or((hit, hit)); - // (page, glyph) pairs compare in reading order. - let (anchor, head) = if (page, to_first) < (start_page, first) { - (last, to_first) - } else if page == start_page { - (first, to_last.max(last)) - } else { - (first, to_last) - }; - selection.span = Span::Run { anchor, head, head_page: page, head_x: None }; -} - -/// After a multi-click, a same-page drag extends by its unit and, over a table, by visual rows -/// (the rest of the first row, the rows between, the start of the last). The page unit (four -/// clicks) is the page's text in reading order, so it has no `head_x`. -fn extend_by_unit_on_page(selection: &mut Selection, text: &PageText, clicks: u32, hit: usize, vx: f32) { - let Span::Run { anchor, head, head_page, head_x } = &mut selection.span else { return }; - let Some((first, last)) = click_unit(text, clicks, *anchor) else { return }; - let (to_first, to_last) = click_unit(text, clicks, hit).unwrap_or((hit, hit)); - *head_x = Some(vx).filter(|x| x.is_finite() && clicks < 4); - let in_order = if to_first < first { (last, to_first) } else { (first, to_last.max(last)) }; - let by_rows = text.row_ends((first, last), (to_first, to_last)); - let rows = head_x.is_some() && text.visual_between(by_rows.0, by_rows.1, *head_x).is_some(); - (*anchor, *head) = if rows { by_rows } else { in_order }; - *head_page = selection.page; -} - -fn finish_text_pointer_gesture(ui: &egui::Ui, view: &mut DocView, text: &PageText, gesture: &TextGesture<'_>) { - let release_clicks = if gesture.resp.triple_clicked() { - view.clicks.max(2).saturating_add(1) - } else if gesture.resp.double_clicked() { - view.clicks.max(2) - } else { - 0 - }; - if release_clicks > 0 { - view.clicks = release_clicks; - } - let clicks = selection_click_count(view.clicks, gesture.tool); - if release_clicks > 0 - && clicks >= 2 - && gesture.over_text - && view.selection.is_none() - && let Some((first, last)) = text.nearest(gesture.vx, gesture.vy).and_then(|anchor| click_unit(text, clicks, anchor)) - { - view.selection = Some(Selection::run(gesture.page, first, last)); - } else if gesture.resp.clicked() && view.clicks < 2 && gesture.text_drag { - // ⇧-click extends a reading-order selection to the click, on its page or another, - // keeping its anchor (#527). Otherwise (no shift, no selection, or a column selection, - // which has no anchor glyph) a click clears the selection. - let shift = ui.input(|input| input.modifiers.shift); - match (view.selection.as_mut().filter(|selection| shift && matches!(selection.span, Span::Run { .. })), text.nearest(gesture.vx, gesture.vy)) - { - (Some(selection), Some(hit)) => { - selection.extend_to_at(gesture.page, hit, Some(gesture.vx).filter(|x| x.is_finite())); - } - _ => view.selection = None, - } - } -} - -/// Full screen is turning to the current page, or waiting for it to render: the page under the -/// pointer isn't the one on screen, so its links, fields, text and comments take no input. -/// Turning the page (a click, a key) is handled apart and still works. -pub(super) fn veiled(view: &DocView) -> bool { - view.presentation.is_some() && !view.presenter.settled_on(view.current) -} - -/// The page and index of `l` when clicking it runs a JavaScript action (#2081). -fn javascript_link(l: &pdfcraft_render::Link) -> Option<(usize, usize)> { - matches!(l.target, LinkTarget::JavaScript(_)).then_some((l.page, l.index)) -} - -/// Everything drawn over the page after its text: pictures, comments, content, links, fields, marks -/// and badges. -pub(super) fn page_overlays(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame<'_>, slot: &PageSlot, input: &PageInput) { - let PageEnv { - added, - allowed, - calc_order, - can_modify, - comments_hidden, - doc, - doc_links, - editing_content, - form, - generation, - info, - keys, - prepare_tab_order, - prefs, - preparing, - redact_mark, - t, - table_preview, - tool, - unobstructed, - .. - } = frame.env; - let PageSlot { i, r, xf } = *slot; - let PageFrame { resp, ptr, pointer, .. } = *frame; - let painter = ui.painter(); - let tool_cx = PageToolContext { ui, resp, xf: &xf, ptr, page: i, doc, info, keys }; - let pcx = comments::PageCx { page: i, xf: &xf, ptr, info, tool, prefs, allowed, hidden: comments_hidden, redact_mark, keys }; - // A press nobody holds picks the picture under it: a link's click follows the link only (ruling - // 5), though its drag or double-click still lets the picked picture go, as does a drag the page - // it is over first sees, whichever page it began on. - let pick_sees = - matches!(input.press, PagePress::Free | PagePress::Mine(Owner::Link { .. })) || input.press == PagePress::Elsewhere && ptr.drag_started; - if tool != QuickTool::Select { - view.pending_pick = None; - } else if pick_sees && !input.consumed { - crate::image_pick::page_input(resp, &xf, i, info, doc, ptr, input.press == PagePress::Free, view); - } else if resp.clicked() || ptr.drag_started { - // Another owner took the press: an earlier click's picture, still being found, isn't picked. - view.pending_pick = None; - } - crate::image_pick::drop_stale(doc, view); - crate::image_pick::paint(painter, &xf, i, info, view); - // A cancelled press ends no selection: no markup or redaction is made from it, nor from a - // page full screen doesn't show yet. - if !view.press_cancelled && !veiled(view) { - comments::page_after_text(resp, &pcx, view); - if tool == QuickTool::Redact && can_modify { - crate::redact_ui::after_text(resp, i, info, view); - } - } - if input.area_tool { - crate::redact_ui::paint(painter, i, view, pointer); - } - comments::paint_page(ui, painter, &pcx, view, input.hover.as_ref()); - if editing_content { - crate::content_ui::paint_page(painter, &xf, i, info, added, view, pointer); - } - if tool == QuickTool::EditText { - crate::object_ui::paint(painter, &xf, i, info, &view.objects); - } - if tool == QuickTool::EnhanceCamera { - crate::camera_ui::paint(painter, &xf, i, view); - } - if tool == QuickTool::Link { - crate::link_ui::paint(painter, &xf, i, info, doc_links, view, pointer); - } - if preparing { - crate::prepare::paint_page(tool_cx, form, prepare_tab_order.unwrap_or_default(), view); - if let Some(preview) = &table_preview { - crate::field_table_ui::paint_preview(painter, &xf, i, preview); - } - if calc_order { - let selected = view.prepare.selected.as_ref().map(|(name, _)| name.as_str()); - if let Some(field) = crate::calc_order_ui::paint_page(tool_cx, form, &view.calc_order, generation, selected) { - frame.calc_hover = Some(field); - } - } - } else { - crate::forms_ui::paint_page(painter, &xf, i, info, form, view, input.hover.as_ref()); - crate::forms_ui::tooltip(resp, form, input.hover.as_ref()); - if let Some(hovered) = crate::forms_ui::hovered(form, input.hover.as_ref()) { - frame.field_hover = Some(hovered); - } - } - - // Form-field highlight (Acrobat's "Highlight existing fields"); required fields get a - // red border. Radio buttons and round XFA check boxes are round, and so is theirs (as - // in Acrobat). Only what can be filled is marked: a read-only widget (its field's, or a - // radio button's own) is left as it is drawn. - paint_field_highlights(painter, &xf, info, form.as_slice(), i, view.highlight_fields); - // Links: the hand and the link's target, which count only for the tools that follow or - // edit links (`Layer::reached_by`). Tips draw above the palette, so none shows while it is - // open, even beside it. A click follows the link its press was on, released over it: one that - // slips off the link first follows nothing, as a button's does. - if unobstructed - && resp.clicked() - && tool == QuickTool::Select - && !input.consumed - && let PagePress::Mine(Owner::Link { index }) = input.press - && input.released_over - && let Some(l) = info.links.iter().find(|l| l.page == i && l.index == index) - { - frame.out.clicked_link = Some(l.target.clone()); - frame.out.javascript_link = javascript_link(l); - } - // A web or email address written as plain text (#4207): the same click as a link annotation, - // and the same check and confirmation on opening. - if unobstructed - && resp.clicked() - && tool == QuickTool::Select - && !input.consumed - && frame.out.clicked_link.is_none() - && let PagePress::Mine(Owner::TextLink { index }) = input.press - && input.released_over - && let Some(uri) = view.text_link_uri(i, index) - { - frame.out.clicked_link = Some(LinkTarget::Uri(uri)); - } - // Comments say what they are with any tool, beside its cursor, as Acrobat's do. - comments::describe(&pcx, view); - for (mp, mr, mc) in &view.compare_marks { - if *mp == i { - let sr = xf.user_rect(info, i, *mr).expand(1.5); - painter.rect_filled(sr, CornerRadius::same(2), mc.gamma_multiply(0.28)); - } - } - if let Some((fp, fr, t0)) = view.flash - && fp == i - { - let now = ui.input(|inp| inp.time); - let t0 = if t0 == 0.0 { now } else { t0 }; - view.flash = Some((fp, fr, t0)); - let age = (now - t0) as f32; - if age < 1.6 { - let a = ((1.6 - age) / 1.6 * 255.0) as u8; - let sr = xf.user_rect(info, i, fr).expand(4.0); - painter.rect_stroke( - sr, - CornerRadius::same(3), - Stroke::new(2.5, Color32::from_rgba_unmultiplied(0x1B, 0x63, 0xE0, a)), - egui::StrokeKind::Outside, - ); - ui.ctx().request_repaint(); - } else { - view.flash = None; - } - } - // The sign tabs (above). Like the validation badges, they never enter the file, - // exports or printing. - for tab in &input.sign_tabs { - paint_sign_tab(ui, painter, tab, t); - } - // Validation badges are viewer chrome over the widget. A recognised named-layer appearance may - // show the verdict in the display copy too; saves retain its original streams. Badges never - // enter document streams, exports or either print path. Their tips show where the comments' - // do (`comments::tips_shown`). - let tips = comments::tips_shown(tool, view); - for badge in signature_badges(&doc.signatures, i) { - let [x0, y0, x1, y1] = badge.rect; - let sr = xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]); - // The page transform can turn a finite widget into one the screen cannot place; stroking - // it would put NaN into the mesh. - if !sr.is_finite() { - continue; - } - let (icon, color) = crate::sign_ui::signature_status_style(badge.status); - painter.rect_stroke(sr, CornerRadius::same(2), Stroke::new(1.5, color), egui::StrokeKind::Outside); - if let Some(mark) = verdict_mark_rect(sr, r, mark_anchor(&xf, info, i, badge.rect)) { - icons::paint(ui, mark, icon, mark.width() * MARK_ICON_SHARE, color); - } - // The whole widget answers the pointer, so a field too small for a mark still says its - // verdict; only where it is on the page, though. Overlapping widgets paint in order, so - // the topmost badge's verdict is the tip; a link's or a comment's tip wins over any badge. - if tips && pointer.is_some_and(|p| sr.expand(2.0).intersect(r).contains(p)) { - view.cursor.describe(Subject::SignatureBadge, crate::i18n::t(badge.summary).to_string()); - } - } -} - -fn paint_field_highlights(painter: &egui::Painter, xf: &PageXform, info: &DocInfo, form: &[pdfcraft_engine::FormField], page: usize, enabled: bool) { - if !enabled { - return; - } - // A push button holds no value, so it is left as drawn (the frames and controls of a LaTeX - // `animate` animation are push buttons). - for field in form.iter().filter(|f| f.kind != pdfcraft_engine::FormFieldKind::PushButton) { - let required = field.has(pdfcraft_engine::field_flags::REQUIRED); - for widget in field.widgets.iter().filter(|widget| widget.page == Some(page) && !widget.hidden && !widget.read_only) { - let rect = widget.rect; - let screen_rect = xf.user_rect(info, page, [rect[0] as f32, rect[1] as f32, rect[2] as f32, rect[3] as f32]); - let tint = Color32::from_rgba_unmultiplied(0x6E, 0x8E, 0xF5, 48); - let (width, color) = if required { (2.0, Color32::from_rgb(0xE3, 0x22, 0x22)) } else { (1.0, Color32::from_rgb(0x6E, 0x8E, 0xF5)) }; - if widget.round { - let radius = screen_rect.width().min(screen_rect.height()) / 2.0; - painter.circle_filled(screen_rect.center(), radius, tint); - painter.circle_stroke(screen_rect.center(), radius - width / 2.0, Stroke::new(width, color)); - } else { - painter.rect_filled(screen_rect, CornerRadius::same(1), tint); - painter.rect_stroke(screen_rect, CornerRadius::same(1), Stroke::new(width, color), egui::StrokeKind::Inside); - } - } - } -} - -/// Escape while the pages hold a press abandons the gesture it drives, whichever tool's: nothing is -/// placed, drawn, moved, resized or opened, and the press is ignored until the button is up. The -/// frame of the release still belongs to the cancelled press. -pub(super) fn cancel_on_escape(ctx: &egui::Context, view: &mut DocView, ptr: &PagePointer) { - // Over once the button is up and its release seen, or when a new press comes (its release and - // the next press can share a frame). - let new_press = matches!(ptr.edges.last(), Some(crate::page_pointer::Edge::Press(_))); - if view.press_cancelled && (new_press || !ptr.any_down && ptr.edges.is_empty()) { - view.press_cancelled = false; - } - if !view.press_cancelled && ptr.origin.is_some() && ptr.primary_down && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) - { - // A text selection being dragged goes with its drag: the markup, redaction or Replace - // Text that its end would make is not made. - if view.selection_drag { - view.clear_selection(); - } - view.cancel_pointer_gestures(); - view.press_cancelled = true; - } -} diff --git a/crates/ui-egui/src/canvas/page_keys.rs b/crates/ui-egui/src/canvas/page_keys.rs deleted file mode 100644 index c70188e6cc..0000000000 --- a/crates/ui-egui/src/canvas/page_keys.rs +++ /dev/null @@ -1,173 +0,0 @@ -//! The keyboard as the pages see it. -//! -//! A dialog, the palette or a menu over the pages has the keys, but the pages are drawn before the -//! dialogs and read egui's keys first. So page modules read keys through [`PageKeys`], which has -//! none while something is over the pages: Delete under the Keyboard shortcuts window deleted the -//! comment selected behind it, and the Escape that closed it deselected the comment too. -//! -//! Each module still asks for itself whether a text field has the keyboard. - -use egui::{Context, Event, Key, Modifiers}; - -/// A frame's Copy, Cut and Paste, as egui delivers them (⌘C, ⌘X, ⌘V, or a menu's). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct Clipboard { - pub copy: bool, - pub cut: bool, - pub paste: bool, -} - -/// One frame's keyboard, as the pages see it: their keys, or none while something is over them. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct PageKeys { - /// A dialog, the palette or a menu is over the pages. - over: bool, -} - -impl PageKeys { - pub(crate) fn new(over: bool) -> Self { - Self { over } - } - - /// The keys once something more is found over the pages this frame. Only ever more covered: a - /// menu that this frame's Escape closes still had that Escape. - #[must_use] - pub(crate) fn also(self, over: bool) -> Self { - Self { over: self.over || over } - } - - /// `key` was pressed for the pages this frame. It stays for whatever reads it next. - pub(crate) fn pressed(self, ctx: &Context, key: Key) -> bool { - !self.over && ctx.input(|i| i.key_pressed(key)) - } - - /// Take `key`, pressed without ⌘ or Ctrl (egui lets an extra Shift or Alt through), for the - /// pages: nothing after reads it. - pub(crate) fn take(self, ctx: &Context, key: Key) -> bool { - !self.over && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, key)) - } - - /// Take the frame's key presses that `take` wants for the pages, each judged by its own - /// modifiers (the frame's can differ when a key is let go in the same frame). `take` says - /// whether it took the press; a press taken is gone for whatever reads keys next. - pub(crate) fn take_presses(self, ctx: &Context, mut take: impl FnMut(Key, Modifiers) -> bool) { - if self.over { - return; - } - ctx.input_mut(|i| { - i.events.retain(|e| match e { - Event::Key { key, pressed: true, modifiers, .. } => !take(*key, *modifiers), - _ => true, - }); - }); - } - - /// The frame's Copy, Cut and Paste for the pages: none while something is over them. They stay - /// for whatever reads them next. - pub(crate) fn clipboard(self, ctx: &Context) -> Clipboard { - if self.over { - return Clipboard::default(); - } - ctx.input(|i| { - let any = |f: fn(&Event) -> bool| i.events.iter().any(f); - Clipboard { copy: any(|e| matches!(e, Event::Copy)), cut: any(|e| matches!(e, Event::Cut)), paste: any(|e| matches!(e, Event::Paste(_))) } - }) - } - - /// Something is over the pages: their keys wait. - pub(crate) fn over(self) -> bool { - self.over - } - - /// `key` is held down. Not the pages' alone: a key let go while something is over them is let - /// go all the same. - pub(crate) fn held(ctx: &Context, key: Key) -> bool { - ctx.input(|i| i.key_down(key)) - } -} - -#[cfg(test)] -mod tests { - use egui::RawInput; - - use super::*; - - fn press(key: Key) -> Event { - Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE } - } - - /// Run one frame with `events`, calling `f` with its context. - fn frame(events: Vec, f: impl FnOnce(&Context)) { - let ctx = Context::default(); - let mut f = Some(f); - let mut output = ctx.run_ui(RawInput { events, ..Default::default() }, |ui| { - if let Some(f) = f.take() { - f(ui.ctx()); - } - }); - // An input-only test has no renderer to take the font texture. - output.textures_delta.clear(); - } - - #[test] - fn something_found_over_the_pages_stays_over_them_for_the_frame() { - assert_eq!(PageKeys::new(false).also(true), PageKeys::new(true)); - assert_eq!(PageKeys::new(true).also(false), PageKeys::new(true)); - assert_eq!(PageKeys::new(false).also(false), PageKeys::new(false)); - } - - #[test] - fn with_something_over_the_pages_they_have_no_keys_and_leave_them_there() { - frame(vec![press(Key::Delete)], |ctx| { - let keys = PageKeys::new(true); - assert!(!keys.pressed(ctx, Key::Delete)); - assert!(!keys.take(ctx, Key::Delete)); - assert!(ctx.input(|i| i.key_pressed(Key::Delete)), "the key stays for the dialog"); - }); - } - - #[test] - fn the_pages_take_the_presses_they_want_with_their_own_modifiers() { - let shifted = Event::Key { key: Key::ArrowLeft, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT }; - frame(vec![press(Key::ArrowRight), shifted, Event::Copy, press(Key::Escape)], |ctx| { - let mut seen = Vec::new(); - PageKeys::new(true).take_presses(ctx, |key, _| { - seen.push(key); - true - }); - assert!(seen.is_empty(), "nothing while something is over the pages"); - PageKeys::new(false).take_presses(ctx, |key, modifiers| { - seen.push(key); - key == Key::ArrowLeft && modifiers.shift - }); - assert_eq!(seen, [Key::ArrowRight, Key::ArrowLeft, Key::Escape]); - assert!(!ctx.input(|i| i.key_pressed(Key::ArrowLeft)), "the press taken is gone"); - assert!(ctx.input(|i| i.key_pressed(Key::ArrowRight) && i.key_pressed(Key::Escape)), "the others stay"); - assert!(ctx.input(|i| i.events.contains(&Event::Copy)), "and so does what isn't a key"); - }); - } - - #[test] - fn the_clipboard_is_the_pages_only_with_nothing_over_them() { - frame(vec![Event::Copy, Event::Paste("text".into())], |ctx| { - assert_eq!(PageKeys::new(true).clipboard(ctx), Clipboard::default()); - assert_eq!(PageKeys::new(false).clipboard(ctx), Clipboard { copy: true, cut: false, paste: true }); - }); - frame(vec![Event::Cut], |ctx| { - assert_eq!(PageKeys::new(true).clipboard(ctx), Clipboard::default()); - assert_eq!(PageKeys::new(false).clipboard(ctx), Clipboard { copy: false, cut: true, paste: false }); - }); - } - - #[test] - fn the_pages_peek_at_a_key_or_take_it() { - frame(vec![press(Key::Delete)], |ctx| { - let keys = PageKeys::new(false); - assert!(keys.pressed(ctx, Key::Delete)); - assert!(keys.pressed(ctx, Key::Delete), "a peek leaves it"); - assert!(keys.take(ctx, Key::Delete)); - assert!(!keys.pressed(ctx, Key::Delete), "a take doesn't"); - assert!(!keys.take(ctx, Key::Escape)); - }); - } -} diff --git a/crates/ui-egui/src/canvas/page_parts.rs b/crates/ui-egui/src/canvas/page_parts.rs new file mode 100644 index 0000000000..1d35112c40 --- /dev/null +++ b/crates/ui-egui/src/canvas/page_parts.rs @@ -0,0 +1,407 @@ +//! What lies on the pages that a press can take: one part per thing a page module offers (a comment, a link, a +//! form field's widget, added content), all registered in the one [`PageParts`] canvas control, so the framework's +//! hit priority ranks them against each other and the press machine holds each press to its release. The tool host +//! shown after it takes every press no part took. + +use craft::behavior::{CursorIcon, HitLevel, HitPriority, HitShape, Input, Intent, Metrics, PartKey, PartRef, PressPhase, Sense}; +use craft::keymap::Mods; +use craft::ui::contract::{ + Common, Component, Cx, Focus as _, MeasureCx, NoValue, Outcome, PartsCx, Pointer as _, Props as _, Role, TooltipAt, TooltipSpec, +}; +use craft::ui::runtime::commands::FireSource; +use craft::ui::runtime::env::Label; +use craft::ui::runtime::focus::KeyUse; +use craft::ui::style::{ComponentStyle, StyleCx}; +use egui::{Rect, Response, Vec2}; + +/// What a part on the pages is: the page module that offered it reads its own presses by it. Each variant names its +/// thing by the numbers the module keeps it by, never by its place in the part list, so a press held across passes +/// keeps naming the same thing while the list changes under it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum Owner { + /// A comment (or a Fill & Sign mark), by its `/Annots` index on its page. + Comment { index: usize }, + /// A link, by its index in its page's `/Annots`. + Link { index: usize }, + /// A web or email address written as plain page text (#4207), by its index among the page's. + TextLink { index: usize }, + /// A form field's widget, by the field's index in the form and the widget's in the field. + Field { field: usize, widget: usize }, + /// Prepare Form: a field's widget, to select and move. + PrepareField { field: usize, widget: usize }, + /// Edit text: a paragraph, by its index among the page's. + Paragraph { block: usize }, + /// Edit text: a picture, by its index among the page's. + Picture { index: usize }, + /// Edit text: the objects selected together. + Objects, + /// Edit text: the frame band of the paragraph open for typing, by the paragraph's index. + Frame { block: usize }, + /// Added text or a picture placed on the page, by its index among the page's. + Added { index: usize }, + /// The sign tab on an empty signature field a click would sign, by the field's index in the form. + SignTab { field: usize }, +} + +const COMMENT: PartKey = PartKey::new("comment"); +const LINK: PartKey = PartKey::new("link"); +const TEXT_LINK: PartKey = PartKey::new("text_link"); +const FIELD: PartKey = PartKey::new("field"); +const PREPARE_FIELD: PartKey = PartKey::new("prepare_field"); +const PARAGRAPH: PartKey = PartKey::new("paragraph"); +const PICTURE: PartKey = PartKey::new("picture"); +const OBJECTS: PartKey = PartKey::new("objects"); +const FRAME: PartKey = PartKey::new("frame"); +const ADDED: PartKey = PartKey::new("added"); +const SIGN_TAB: PartKey = PartKey::new("sign_tab"); + +/// `high` in the upper 32 bits of a part index and `low` in the lower; `None` when either does not fit, so no two +/// things ever share an index. +fn pack(high: usize, low: usize) -> Option { + let (high, low) = (u32::try_from(high).ok()?, u32::try_from(low).ok()?); + Some((u64::from(high) << 32) | u64::from(low)) +} + +/// The two halves [`pack`] put in `index`. +fn unpack(index: u64) -> Option<(usize, usize)> { + let high = usize::try_from(index >> 32).ok()?; + let low = usize::try_from(index & u64::from(u32::MAX)).ok()?; + Some((high, low)) +} + +impl Owner { + /// The part this owner registers as on `page`. Its key is the variant's; its index packs the page in the upper 32 + /// bits and the variant's own number in the lower, except a field widget's, which is `field << 32 | widget` (a + /// widget lies on one page, so the pair alone names it). `None` when a number does not fit in 32 bits: that part + /// is not registered. + pub(crate) fn part_ref(self, page: usize) -> Option { + let (key, index) = match self { + Owner::Comment { index } => (COMMENT, pack(page, index)?), + Owner::Link { index } => (LINK, pack(page, index)?), + Owner::TextLink { index } => (TEXT_LINK, pack(page, index)?), + Owner::Field { field, widget } => (FIELD, pack(field, widget)?), + Owner::PrepareField { field, widget } => (PREPARE_FIELD, pack(field, widget)?), + Owner::Paragraph { block } => (PARAGRAPH, pack(page, block)?), + Owner::Picture { index } => (PICTURE, pack(page, index)?), + Owner::Objects => (OBJECTS, pack(page, 0)?), + Owner::Frame { block } => (FRAME, pack(page, block)?), + Owner::Added { index } => (ADDED, pack(page, index)?), + Owner::SignTab { field } => (SIGN_TAB, pack(page, field)?), + }; + Some(key.at(index)) + } + + /// The owner `part` names, with its page where the index carries one ([`part_ref`](Self::part_ref)): `None` for + /// a field widget's page, which its part does not hold. `None` for a part that is no page part. + // PLAN: decisions.md gives `Option<(Owner, usize)>`, but a field widget's index is `field << 32 | widget` by the same decision and holds no page, so the page is optional. + pub(crate) fn from_part(part: PartRef) -> Option<(Owner, Option)> { + let (high, low) = unpack(part.index?)?; + let paged = |owner: Owner| Some((owner, Some(high))); + match part.key { + COMMENT => paged(Owner::Comment { index: low }), + LINK => paged(Owner::Link { index: low }), + TEXT_LINK => paged(Owner::TextLink { index: low }), + FIELD => Some((Owner::Field { field: high, widget: low }, None)), + PREPARE_FIELD => Some((Owner::PrepareField { field: high, widget: low }, None)), + PARAGRAPH => paged(Owner::Paragraph { block: low }), + PICTURE => paged(Owner::Picture { index: low }), + OBJECTS => paged(Owner::Objects), + FRAME => paged(Owner::Frame { block: low }), + ADDED => paged(Owner::Added { index: low }), + SIGN_TAB => paged(Owner::SignTab { field: low }), + _ => None, + } + } +} + +/// The families of page parts, lowest first: the one table that says which outranks which where parts overlap. +/// Families that take a press while a tool is active outrank the page's own text and pictures; handles and the open +/// editor outrank everything on the page body. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum PageLayer { + /// Edit text's pictures. + Picture, + /// Edit text's paragraphs. + Text, + /// Links and text links. + Link, + /// Comments and Fill & Sign marks. + Comment, + /// Form fields' widgets and the sign tabs over them. + Field, + /// What a tool placed and moves: added content, Prepare's fields, the objects selected together. + Placed, + /// Handles on what is selected, and the frame band of the paragraph open for typing. + Handle, + /// The open editor's own parts. + Editor, +} + +impl PageLayer { + /// The layer's rank in the framework's hit resolution: a higher `(level, sub)` wins where parts overlap. + pub(crate) fn priority(self) -> HitPriority { + let (level, sub) = match self { + PageLayer::Picture => (HitLevel::Body, 0), + PageLayer::Text => (HitLevel::Body, 1), + PageLayer::Link => (HitLevel::Body, 2), + PageLayer::Comment => (HitLevel::Body, 3), + PageLayer::Field => (HitLevel::Body, 4), + PageLayer::Placed => (HitLevel::Body, 5), + PageLayer::Handle => (HitLevel::Handle, 0), + PageLayer::Editor => (HitLevel::Handle, 1), + }; + HitPriority::new(level, sub) + } +} + +/// One thing on a page a press can take: its owner, its page, its shape in screen points and its layer, with what +/// the pointer shows over it. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct PagePart { + /// What the part is. + pub(crate) owner: Owner, + /// The page it lies on. + pub(crate) page: usize, + /// Its shape, in the screen points of the page body. + pub(crate) shape: HitShape, + /// Its family, which ranks it against overlapping parts. + pub(crate) layer: PageLayer, + cursor: Option, + tip: Option, + passes_drag: bool, + focusable: bool, +} + +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, focusable: false } + } + + /// The cursor over the part. + #[must_use] + pub(crate) fn cursor(mut self, cursor: CursorIcon) -> Self { + self.cursor = Some(cursor); + self + } + + /// The tip shown beside the pointer over the part. + #[must_use] + pub(crate) fn tip(mut self, tip: impl Into) -> Self { + self.tip = Some(tip.into()); + self + } + + /// The part only clicks: a drag that starts on it goes to what lies below (text markup selects the text under it, + /// a link with the Link tool lets a new link be drawn over it). + #[must_use] + pub(crate) fn passes_drag(mut self) -> Self { + self.passes_drag = true; + self + } + + /// The part is a Tab stop, in the order the parts are given (a form's fields in the PDF's tab order). + #[must_use] + pub(crate) fn focusable(mut self) -> Self { + self.focusable = true; + self + } + + /// What the part senses: a click, a secondary click and a drag of its own, or a click that passes its drag on. + fn sense(&self) -> Sense { + let drag = if self.passes_drag { Sense::PASSES_DRAG } else { Sense::DRAG }; + Sense::CLICK | Sense::CONTEXT_CLICK | drag + } +} + +/// A press on a page part in this pass, as the press machine reports it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct PagePress { + /// What was pressed. + pub(crate) owner: Owner, + /// The page it lies on. + pub(crate) page: usize, + /// The press's phase in this pass, in screen points; a click's count is its start's `clicks`. + pub(crate) phase: PressPhase, + /// The modifiers held: readers test `cmd` (Cmd on macOS, Ctrl elsewhere) and `shift`. + pub(crate) mods: Mods, +} + +/// The style of the page parts: they paint nothing. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +pub(crate) struct PagePartsStyle { + #[style(metrics)] + metrics: Metrics, +} + +/// What the page parts report this pass. +#[derive(Debug)] +pub(crate) struct PagePartsOutput { + /// The control's response. + pub(crate) response: Response, + /// The press on a part, in the phase this pass reports. + pub(crate) press: Option, + /// A key the focused part was given: a form field's toggle, its arrows, Enter or typed text. + pub(crate) key: Option<(Owner, Intent)>, + /// The part under the pointer this pass. + pub(crate) hovered: Option, + /// The part focus arrived on this pass (Tab, a focus request or a click): a form field opens on it. + pub(crate) focused: Option<(Owner, usize)>, +} + +impl Outcome for PagePartsOutput { + type Value = NoValue; + + fn response(&self) -> &Response { + &self.response + } +} + +/// The parts of the pages, in paint order: each family appends its own after what it paints over, so where parts of +/// one layer overlap the one drawn on top takes the press. A canvas control that paints nothing: show it first in the +/// page body, before the tool host, over the body's rect. +#[derive(Component)] +#[component(canvas_control, sample = PageParts::sample)] +pub(crate) struct PageParts<'a> { + #[common] + common: Common, + parts: &'a [PagePart], + focus: Option, + report: Report, +} + +/// What `update` read, for `finish`. +#[derive(Debug, Default)] +struct Report { + press: Option, + key: Option<(Owner, Intent)>, + hovered: Option, + focused: Option<(Owner, usize)>, +} + +impl<'a> PageParts<'a> { + /// The parts `parts`, given in paint order. + pub(crate) fn new(parts: &'a [PagePart]) -> Self { + PageParts { common: Common::new(), parts, focus: None, report: Report::default() }.label(Label::from(tl!("Page content"))) + } + + /// Moves the focus to `owner`'s part in this pass, when it is a Tab stop and the pages hold the focus or were just + /// pressed. A request: send it in the one pass that asks, never every pass. + #[must_use] + pub(crate) fn focus(mut self, owner: Option) -> Self { + self.focus = owner; + self + } + + /// No parts, for the component suite. + fn sample() -> Self { + PageParts::new(&[]) + } + + /// The part `part` names, among this pass's parts. + fn part_named(&self, part: PartRef) -> Option<&PagePart> { + let (owner, page) = Owner::from_part(part)?; + self.parts.iter().find(|p| p.owner == owner && page.is_none_or(|page| p.page == page)) + } + + /// The key the focused part was given this pass: an activation by the keyboard, Enter, an arrow or typed text, the + /// first of them; a field reads one key per pass. + fn field_key(cx: &mut Cx<'_, Self>, part: PartRef) -> Option { + if cx.part_activated(part) == Some(FireSource::Key) { + return Some(Intent::Activate); + } + let intents = cx.intents(); + if intents.take(Intent::Submit) { + return Some(Intent::Submit); + } + if let Some((mv, mods)) = intents.take_move() { + return Some(Intent::Move(mv, mods)); + } + intents.take_text().map(Intent::Text) + } +} + +impl Component for PageParts<'_> { + const ROLE: Role = Role::GROUP; + const OVERLAYS: bool = false; + const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_moves(); + type Style = PagePartsStyle; + type Output = PagePartsOutput; + + fn style(_: &StyleCx<'_>, _: PagePartsStyleKey) -> PagePartsStyle { + PagePartsStyle { metrics: Metrics::new() } + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::ZERO + } + + /// One part per page part, in the order given, each with that order as its stacking order. A family gives one + /// shape per owner and page; a second shape of the same owner on the same page is not registered, so one press + /// never names two parts. + fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { + let mut declared: Vec = Vec::with_capacity(self.parts.len()); + for (order, part) in self.parts.iter().enumerate() { + let Some(at) = part.owner.part_ref(part.page) else { continue }; + let Ok(order) = u32::try_from(order) else { break }; + if declared.contains(&at) { + continue; + } + declared.push(at); + let mut builder = cx.part(at, part.shape.clone()).sense(part.sense()).priority(part.layer.priority()).stacking(order); + if let Some(cursor) = part.cursor { + builder = builder.cursor(cursor); + } + if let Some(tip) = &part.tip { + builder = builder.tooltip(TooltipSpec::new(Label::from(tip.clone())).at(TooltipAt::Pointer)); + } + if part.focusable { + builder.focusable(); + } else { + builder.pointer_only("the comments, links and fields panels and the selected object's commands reach page content"); + } + } + } + + /// Reads the press, the hover, the focused part's key and the focus that arrived. The press machine reports a + /// press's phases one per pass, so a second pass of a frame reads only its own phase. + fn update(&mut self, cx: &mut Cx<'_, Self>) { + let pressed = self.parts.iter().filter_map(|part| part.owner.part_ref(part.page)).any(|at| { + cx.part_if_declared(at).is_some_and(|result| result.press.phase.is_press()) + }); + if let Some(owner) = self.focus + && (cx.is_focused() || pressed) + && let Some(at) = self.parts.iter().filter(|part| part.focusable && part.owner == owner).find_map(|part| part.owner.part_ref(part.page)) + { + cx.focus_part(at); + } + for part in self.parts { + let Some(at) = part.owner.part_ref(part.page) else { continue }; + let Some(result) = cx.part_if_declared(at) else { continue }; + let (press, hovered) = (result.press, result.hovered); + if hovered && self.report.hovered.is_none() { + self.report.hovered = Some(part.owner); + } + if press.phase.is_press() && self.report.press.is_none() { + self.report.press = Some(PagePress { owner: part.owner, page: part.page, phase: press.phase, mods: press.mods }); + } + } + if let Some(active) = cx.active_part() + && let Some(owner) = self.part_named(active).filter(|part| part.focusable).map(|part| part.owner) + && let Some(intent) = Self::field_key(cx, active) + { + self.report.key = Some((owner, intent)); + } + if let Some(arrived) = cx.focus_arrived() { + self.report.focused = self.part_named(arrived).map(|part| (part.owner, part.page)); + } + } + + fn finish(self, cx: Cx<'_, Self>) -> PagePartsOutput { + let Report { press, key, hovered, focused } = self.report; + PagePartsOutput { response: cx.response.clone(), press, key, hovered, focused } + } +} + + diff --git a/crates/ui-egui/src/canvas/page_pointer.rs b/crates/ui-egui/src/canvas/page_pointer.rs deleted file mode 100644 index f3a1b13647..0000000000 --- a/crates/ui-egui/src/canvas/page_pointer.rs +++ /dev/null @@ -1,150 +0,0 @@ -//! The pointer as the pages see it, read once per frame from the page view's content widget. -//! -//! egui knows what is drawn over the pages (a dialog, a menu, the palette, the quick bar, the -//! chrome over a page scrolled under it) and which widget holds a drag (a panel's tab carried -//! over them), and keeps a press with the widget it began on until release. egui's raw pointer -//! state knows none of that, and its hover position is gone on the frame -//! a touch or a Windows pen lifts: egui-winit sends `PointerGone` with every touch release, and -//! winit reports Windows pen input as touch. So page modules read [`PagePointer`], never egui's -//! pointer positions or button states; a test below keeps it that way. -//! -//! Dialogs are drawn after the pages, so on the frame one opens egui has not met its layer yet: -//! the reading also takes whether one is open. - -use egui::{Event, Modifiers, PointerButton, Pos2, Rect}; - -/// A primary-button press or release, and where it happened. -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) enum Edge { - Press(Pos2), - Release(Pos2), -} - -/// How many of a frame's presses and releases are kept. A frame holds one or two (a click, a -/// double-click in a slow frame), but one after a stall can hold any number. -const MAX_EDGES: usize = 8; - -/// One frame's pointer, as the pages see it. -#[derive(Clone, Debug, Default, PartialEq)] -pub(crate) struct PagePointer { - /// Where the pointer is, while the pages are what egui has under it and no other widget holds - /// a drag (a panel's tab carried over them), or while they hold a press (until the frame of - /// its release, past a page's edge included). With a dialog open only a drag the pages - /// already have keeps it. It is egui's `interact_pos`, which still has the position on the - /// frame a touch lifts. - pub pos: Option, - /// Where the press the pages hold began, also on the frame of its release when the press - /// came in that same frame (egui has forgotten it by then). `None` for a press that began on - /// something else. - pub origin: Option, - /// This frame's primary presses and releases of a press the pages hold, in order. - pub edges: Vec, - /// Where this frame's last primary release of a press the pages hold was: where a click came - /// up, which the pointer may have left by the frame's end. Kept past the cap on `edges`. - pub released: Option, - /// The primary button is down, wherever it was pressed: a gesture ends once it is up. - pub primary_down: bool, - /// Some button is down, wherever it was pressed. - pub any_down: bool, - /// The modifier keys held at this frame's first primary press, or else now: a press with Shift - /// or ⌘ adds to a selection. - pub modifiers: Modifiers, - /// A primary press the pages hold turned into a drag this frame. egui's own `drag_started()` - /// counts every button, so a right-button drag would start what a left-button drag does. - pub drag_started: bool, -} - -impl PagePointer { - /// The pointer for `resp`, the content widget that holds every page, allocated in `ui`, while - /// a dialog is open over the window or not (`modal`). - pub(crate) fn read(ui: &egui::Ui, resp: &egui::Response, modal: bool) -> Self { - let (at, origin, edges, released, primary_down, any_down, modifiers) = ui.input(|i| { - ( - i.pointer.interact_pos(), - i.pointer.press_origin(), - edges(&i.events), - last_release(&i.events), - i.pointer.primary_down(), - i.pointer.any_down(), - press_modifiers(&i.events).unwrap_or(i.modifiers), - ) - }); - // egui's own answer to "do the pages hold a press?": from the press on until the frame - // of its click, release or drag stop. A drag can outlive egui's press while the - // pointer is outside the window. With a dialog open only a drag counts, up to the frame - // it stops: on the frame one opens egui still gives the pages a press that lands under - // it, and its click. - let layer = ui.layer_id(); - let on_top = - |p: &Pos2| !modal && !dragged_elsewhere(ui, resp) && resp.contains_pointer() && ui.ctx().layer_id_at(*p).is_none_or(|l| l == layer); - let press_origin = origin.or_else(|| first_press(&edges)); - let held = - resp.dragged() || resp.drag_stopped() || (!modal && (resp.interact_pointer_pos().is_some() || press_origin.is_some_and(|p| on_top(&p)))); - let pos = at.filter(|p| held || on_top(p)); - if !held { - return Self { pos, origin: None, edges: Vec::new(), released: None, primary_down, any_down, modifiers, drag_started: false }; - } - let drag_started = resp.drag_started_by(PointerButton::Primary); - Self { pos, origin: press_origin, edges, released, primary_down, any_down, modifiers, drag_started } - } - - /// Where the pointer is, when it is inside `r`. - pub(crate) fn within(&self, r: Rect) -> Option { - self.pos.filter(|p| r.contains(*p)) - } - - /// Where this frame's first primary press was. - pub(crate) fn pressed(&self) -> Option { - first_press(&self.edges) - } -} - -/// Whether egui gives the drag to a widget that is not the pages' (a panel's tab, a floating panel's -/// grip): egui hovers nothing else until it stops, though it still reports the pages under the -/// pointer. A widget on the pages (a form field's editor) keeps them. -fn dragged_elsewhere(ui: &egui::Ui, resp: &egui::Response) -> bool { - let ctx = ui.ctx(); - ctx.dragged_id().is_some_and(|id| { - id != resp.id && !ctx.read_response(id).is_some_and(|r| r.layer_id == resp.layer_id && resp.interact_rect.contains_rect(r.interact_rect)) - }) -} - -fn first_press(edges: &[Edge]) -> Option { - edges.iter().find_map(|e| match e { - Edge::Press(p) => Some(*p), - Edge::Release(_) => None, - }) -} - -/// The modifier keys held at the first primary press among `events`. -fn press_modifiers(events: &[Event]) -> Option { - events.iter().find_map(|e| match e { - Event::PointerButton { button: PointerButton::Primary, pressed: true, modifiers, .. } => Some(*modifiers), - _ => None, - }) -} - -/// Where the last primary release among `events` was, however many came before it. -fn last_release(events: &[Event]) -> Option { - events.iter().rev().find_map(|e| match e { - Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, .. } if pos.is_finite() => Some(*pos), - _ => None, - }) -} - -/// The first [`MAX_EDGES`] primary presses and releases among `events`, in order. -fn edges(events: &[Event]) -> Vec { - events - .iter() - .filter_map(|e| match e { - Event::PointerButton { pos, button: PointerButton::Primary, pressed, .. } if pos.is_finite() => { - Some(if *pressed { Edge::Press(*pos) } else { Edge::Release(*pos) }) - } - _ => None, - }) - .take(MAX_EDGES) - .collect() -} - -#[cfg(test)] -mod tests; diff --git a/crates/ui-egui/src/canvas/page_pointer/tests.rs b/crates/ui-egui/src/canvas/page_pointer/tests.rs deleted file mode 100644 index b0bf54e3b8..0000000000 --- a/crates/ui-egui/src/canvas/page_pointer/tests.rs +++ /dev/null @@ -1,916 +0,0 @@ -use super::*; -use egui::{Context, Modifiers, Sense, TouchDeviceId, TouchId, TouchPhase, pos2, vec2}; - -/// The pages' widget: x 0..200, y 0..200 of a 400×400 screen. -const PAGES: Rect = Rect { min: Pos2::ZERO, max: Pos2 { x: 200.0, y: 200.0 } }; -/// An Area drawn over the pages' lower right corner. -const OVER: Rect = Rect { min: Pos2 { x: 120.0, y: 120.0 }, max: Pos2 { x: 260.0, y: 260.0 } }; - -fn button(pos: Pos2, button: PointerButton, pressed: bool) -> Event { - Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE } -} - -fn touch(phase: TouchPhase, pos: Pos2) -> Event { - Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase, pos, force: None } -} - -/// Runs one frame of the pages' widget (and the Area over it, with `area`) and returns what -/// the pages see. -fn frame(ctx: &Context, events: Vec, area: bool) -> PagePointer { - frame_with(ctx, events, area, false) -} - -/// [`frame`], with a dialog open (`modal`) whose layer egui has not met. -fn frame_with(ctx: &Context, events: Vec, area: bool, modal: bool) -> PagePointer { - let mut seen = PagePointer::default(); - let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 400.0))), events, ..Default::default() }; - let mut output = ctx.run_ui(input, |ui| { - let (_, resp) = ui.allocate_exact_size(PAGES.size(), Sense::click_and_drag()); - seen = PagePointer::read(ui, &resp, modal); - if area { - egui::Area::new(egui::Id::unique("over")).fixed_pos(OVER.min).show(ui.ctx(), |ui| { - ui.allocate_exact_size(OVER.size(), Sense::hover()); - }); - } - }); - // An input-only test has no renderer to take the font texture. - output.textures_delta.clear(); - seen -} - -#[test] -fn a_touch_tap_keeps_its_position_on_the_frame_it_lifts() { - let ctx = Context::default(); - let p = pos2(50.0, 60.0); - frame(&ctx, vec![], false); - let down = frame(&ctx, vec![touch(TouchPhase::Start, p), Event::PointerMoved(p), button(p, PointerButton::Primary, true)], false); - assert_eq!((down.pos, down.origin, down.pressed()), (Some(p), Some(p), Some(p))); - // egui-winit ends a touch with the release and `PointerGone` in one frame. - let up = frame(&ctx, vec![touch(TouchPhase::End, p), button(p, PointerButton::Primary, false), Event::PointerGone], false); - assert_eq!(ctx.input(|i| i.pointer.hover_pos()), None, "egui's hover position is gone"); - assert_eq!(up.pos, Some(p), "the pages still know where the finger lifted"); - assert_eq!(up.edges, [Edge::Release(p)]); - assert_eq!(frame(&ctx, vec![], false), PagePointer::default(), "and forget it the frame after"); -} - -/// A click is located where it came up even after a stall's many presses and releases, past the -/// cap on a frame's edges. Read from the edges kept, it was an earlier release's. -#[test] -fn a_frames_last_release_is_kept_past_the_cap_on_its_edges() { - let ctx = Context::default(); - let (p, q) = (pos2(50.0, 60.0), pos2(80.0, 90.0)); - frame(&ctx, vec![Event::PointerMoved(p)], false); - let mut events: Vec = (0..2 * MAX_EDGES).map(|i| button(p, PointerButton::Primary, i % 2 == 0)).collect(); - events.extend([button(q, PointerButton::Primary, true), button(q, PointerButton::Primary, false)]); - let stall = frame(&ctx, events, false); - assert_eq!(stall.edges.len(), MAX_EDGES); - assert_eq!(stall.released, Some(q)); -} - -#[test] -fn a_press_and_release_in_one_frame_keep_the_press() { - let ctx = Context::default(); - let p = pos2(50.0, 60.0); - frame(&ctx, vec![Event::PointerMoved(p)], false); - let click = frame(&ctx, vec![button(p, PointerButton::Primary, true), button(p, PointerButton::Primary, false)], false); - assert_eq!(ctx.input(|i| i.pointer.press_origin()), None, "egui has forgotten the press"); - assert_eq!(click.origin, Some(p)); - assert_eq!(click.edges, [Edge::Press(p), Edge::Release(p)]); -} - -#[test] -fn something_drawn_over_the_pages_hides_the_pointer() { - let ctx = Context::default(); - // The Area and the widget rects egui hit-tests against come from the frame before. - frame(&ctx, vec![], true); - frame(&ctx, vec![], true); - let beside = pos2(100.0, 100.0); - assert_eq!(frame(&ctx, vec![Event::PointerMoved(beside)], true).pos, Some(beside)); - // Inside the Area, and just inside its edge where egui's interact radius still finds the - // pages' widget. - for p in [pos2(160.0, 160.0), pos2(122.0, 150.0)] { - assert_eq!(frame(&ctx, vec![Event::PointerMoved(p)], true).pos, None, "{p:?}"); - } - // Off the pages altogether. - assert_eq!(frame(&ctx, vec![Event::PointerMoved(pos2(300.0, 50.0))], true).pos, None); - // A press on the Area is not the pages' press, though the button is down all the same. - let p = pos2(160.0, 160.0); - let press = frame(&ctx, vec![button(p, PointerButton::Primary, true)], true); - assert_eq!(press, PagePointer { primary_down: true, any_down: true, ..PagePointer::default() }); -} - -#[test] -fn a_press_on_the_pages_keeps_the_pointer_until_its_release() { - let ctx = Context::default(); - frame(&ctx, vec![], true); - frame(&ctx, vec![], true); - let start = pos2(40.0, 40.0); - frame(&ctx, vec![Event::PointerMoved(start), button(start, PointerButton::Primary, true)], true); - // Dragged over the Area and off the pages: still theirs. - for p in [pos2(160.0, 160.0), pos2(300.0, 50.0)] { - let held = frame(&ctx, vec![Event::PointerMoved(p)], true); - assert_eq!((held.pos, held.origin, held.primary_down), (Some(p), Some(start), true), "{p:?}"); - } - let end = pos2(300.0, 60.0); - let up = frame(&ctx, vec![Event::PointerMoved(end), button(end, PointerButton::Primary, false)], true); - assert_eq!((up.pos, up.edges.as_slice()), (Some(end), [Edge::Release(end)].as_slice()), "the release is the pages' too"); - assert!(!up.primary_down && !up.any_down, "and the button is up"); - assert_eq!(frame(&ctx, vec![], true).pos, None, "then off the pages, the pointer is not theirs"); -} - -#[test] -fn a_dialog_hides_the_pointer_and_its_clicks_but_not_a_drag_the_pages_have() { - let ctx = Context::default(); - let p = pos2(50.0, 50.0); - frame(&ctx, vec![Event::PointerMoved(p)], false); - assert_eq!(frame(&ctx, vec![], false).pos, Some(p)); - assert_eq!(frame_with(&ctx, vec![], false, true).pos, None, "no pointer under a dialog, before egui knows its layer too"); - let click = frame_with(&ctx, vec![button(p, PointerButton::Primary, true), button(p, PointerButton::Primary, false)], false, true); - assert_eq!((click.pos, click.origin, click.edges.as_slice()), (None, None, [].as_slice()), "nor a click egui gives the pages then"); - // A drag the pages already have when a dialog opens goes on until its release. - frame(&ctx, vec![button(p, PointerButton::Primary, true)], false); - frame(&ctx, vec![Event::PointerMoved(pos2(80.0, 50.0))], false); - let q = pos2(110.0, 50.0); - let dragging = frame_with(&ctx, vec![Event::PointerMoved(q)], false, true); - assert_eq!((dragging.pos, dragging.origin), (Some(q), Some(p)), "a drag the pages have keeps its pointer under a dialog"); - let up = frame_with(&ctx, vec![button(q, PointerButton::Primary, false)], false, true); - assert_eq!(up.edges.as_slice(), [Edge::Release(q)].as_slice(), "and its release"); -} - -#[test] -fn a_secondary_press_is_some_button_down_but_no_primary_edge() { - let ctx = Context::default(); - let p = pos2(50.0, 60.0); - frame(&ctx, vec![Event::PointerMoved(p)], false); - let right = frame(&ctx, vec![button(p, PointerButton::Secondary, true)], false); - assert_eq!((right.pos, right.any_down, right.primary_down, right.edges.len()), (Some(p), true, false, 0)); -} - -#[test] -fn edges_are_primary_finite_in_order_and_capped() { - let p = pos2(1.0, 2.0); - let q = pos2(3.0, 4.0); - let events = vec![ - button(p, PointerButton::Secondary, true), - button(p, PointerButton::Primary, true), - Event::PointerMoved(q), - button(pos2(f32::NAN, 0.0), PointerButton::Primary, false), - button(q, PointerButton::Primary, false), - ]; - assert_eq!(edges(&events), [Edge::Press(p), Edge::Release(q)]); - let many: Vec = (0..100).map(|i| button(p, PointerButton::Primary, i % 2 == 0)).collect(); - assert_eq!(edges(&many).len(), MAX_EDGES); - assert_eq!(first_press(&[Edge::Release(q), Edge::Press(p), Edge::Press(q)]), Some(p)); -} - -/// The page modules: the per-page chain in `canvas::document_area` and what it calls. -const PAGE_MODULES: [&str; 38] = [ - "canvas.rs", - "canvas/page_input.rs", - "canvas/area.rs", - "canvas/bars.rs", - "canvas/cache.rs", - "canvas/find.rs", - "canvas/navigation.rs", - "canvas/organize.rs", - "canvas/selection.rs", - "canvas/xform.rs", - "canvas/zoom.rs", - "tools/comments.rs", - "tools/comments/composer.rs", - "tools/comments/geometry.rs", - "tools/comments/input.rs", - "tools/comments/menu.rs", - "tools/comments/paint.rs", - "tools/comments/popups.rs", - "tools/comments/state.rs", - "tools/forms_ui.rs", - "tools/prepare.rs", - "tools/fill_sign.rs", - "tools/fill_sign/scan.rs", - "tools/sign_ui.rs", - "canvas/crop.rs", - "canvas/zoom_snap.rs", - "tools/camera_ui.rs", - "tools/measure_ui.rs", - "tools/redact_ui.rs", - "tools/link_ui.rs", - "tools/content_ui.rs", - "tools/edit_text_ui.rs", - "tools/edit_text_ui/image.rs", - "tools/object_ui.rs", - "canvas/image_pick.rs", - "canvas/signature_drag.rs", - "tools/calc_order_ui.rs", - "tools/stamps_ui.rs", -]; - -/// What a file that acts on the pages uses: the pointer, a tool's or the comments' page context, -/// what a press is to a page, the router's hits and owners, or the router itself. Such a file is a -/// page module. One that acts on the pages through the page view's response and a bare point alone -/// would use none of them, and PAGE_MODULES would list it by hand. -const PAGE_MODULE_MARKS: [&str; 6] = ["PagePointer", "PageToolContext", "PageCx", "PagePress", "page_router::", ".router."]; - -/// The router's own files, which define what page modules use. -const ROUTER_FILES: [&str; 3] = ["canvas/page_pointer.rs", "canvas/page_router.rs", "canvas/page_cursor.rs"]; - -/// egui's raw pointer state: where the pointer is, and which buttons are down or went down. -const RAW_READS: [&str; 21] = [ - "hover_pos()", - "interact_pos()", - "latest_pos()", - "press_origin()", - "pointer_hover_pos()", - "pointer_interact_pos()", - "pointer_latest_pos()", - "primary_down()", - "primary_pressed()", - "primary_released()", - "primary_clicked()", - "any_down()", - "any_pressed()", - "any_released()", - "any_click()", - // These take the button, so they match up to the parenthesis. - "button_down(", - "button_pressed(", - "button_released(", - "button_clicked(", - "button_double_clicked(", - "button_triple_clicked(", -]; - -/// Functions in the page modules that are not page input and read egui's pointer state -/// themselves: (file, function, why). -const NOT_PAGE_INPUT: [(&str, &str, &str); 13] = [ - ("canvas/area.rs", "zoom_anchor", "a pinch zooms the whole view, and is read before the pages' widget exists"), - ("canvas/area.rs", "drawing_edge_pointer", "scrolls the view at its edges, read before the pages' widget exists"), - ("canvas/area.rs", "glide_interrupted", "a press anywhere stops the touchpad's glide"), - ("canvas/area.rs", "presentation_click", "full screen's click to turn the page, read before the pages' widget exists"), - ("canvas/bars.rs", "page_size_hint", "the page size hint sits in the view's corner, not on a page"), - ("canvas/organize.rs", "organize_grid", "Organize Pages shows thumbnails, not pages"), - ("tools/comments/popups.rs", "popups", "the comment pop-up windows are Areas of their own over the page"), - ("tools/forms_ui.rs", "overlay", "the field editor is an Area of its own over the page"), - ("tools/forms_ui.rs", "choice_list", "a drop-down's open list is an Area of its own over the page"), - ("tools/forms_ui.rs", "scroll_bar", "the scroll bar of a drop-down's open list, in its Area over the page"), - ("tools/content_ui.rs", "editor", "the added-text editor is an Area of its own over the page"), - ("tools/edit_text_ui.rs", "overlay", "the paragraph editor is an Area of its own over the page"), - ("tools/fill_sign/scan.rs", "scan_tab", "the signature dialog's Scan tab"), -]; - -/// The function a `fn` line declares, laid out as rustfmt does (`pub`, `const` and the like -/// before `fn`). -fn declares(line: &str) -> Option<&str> { - let mut rest = line; - loop { - let before = rest; - // `pub(crate)`, `pub(super)`, `pub(in crate::canvas)` and the like. - if let Some(scoped) = rest.strip_prefix("pub(") { - rest = scoped.split_once(") ").map_or(rest, |(_, after)| after); - } - for prefix in ["pub ", "const ", "async ", "unsafe "] { - rest = rest.strip_prefix(prefix).unwrap_or(rest); - } - if rest == before { - break; - } - } - let rest = rest.strip_prefix("fn ")?; - rest.find(|c: char| !(c.is_alphanumeric() || c == '_')).map(|end| &rest[..end]) -} - -/// egui's drag start, which counts every button: a right-button drag would start what a left one -/// does. Page modules read `PagePointer::drag_started`, the primary button's, or ask for that button -/// (`drag_started_by`). -const ANY_BUTTON_DRAG: [&str; 1] = [".drag_started()"]; - -/// Functions in the page modules that start a drag of a widget of their own, not of the pages: -/// (file, function, why). -const NOT_PAGE_DRAGS: [(&str, &str, &str); 3] = [ - ("canvas/organize.rs", "drag_pages", "Organize Pages drags thumbnails, not pages"), - ("tools/fill_sign.rs", "signature_pad", "the signature dialog's drawing pad"), - ("tools/fill_sign/scan.rs", "scan_tab", "the signature dialog's Scan tab"), -]; - -/// Ways to set egui's cursor. -const CURSOR_WRITES: [&str; 4] = ["set_cursor_icon(", ".cursor_icon = ", "on_hover_cursor(", "on_hover_and_drag_cursor("]; - -/// Functions in the page modules that set a cursor other than the pages': (file, function, why). -const NOT_PAGE_CURSOR: [(&str, &str, &str); 4] = [ - ("tools/fill_sign/scan.rs", "scan_tab", "the signature dialog's Scan tab"), - ("tools/edit_text_ui.rs", "overlay", "the paragraph editor is an Area of its own over the page, drawn after the pages' cursor is set"), - ("tools/calc_order_ui.rs", "panel", "the Calculation order panel, whose rows are dragged to reorder them"), - ( - "tools/comments/popups.rs", - "popups", - "the comment pop-up windows are Areas of their own over the page; their title bars are dragged to move them", - ), -]; - -/// Whether `line` uses `name`, and not a longer name that ends in it (a field, after its `.`, is -/// never part of a longer name). -fn uses(line: &str, name: &str) -> bool { - line.match_indices(name).any(|(at, _)| name.starts_with('.') || !line[..at].ends_with(|c: char| c.is_alphanumeric() || c == '_')) -} - -/// The lines of `source` outside its test modules, numbered from 1. Tests drive egui's input and -/// read its output themselves. A test module (`#[cfg(test)]` then `mod name {`) ends at the first -/// line that is a lone `}`, as rustfmt lays a top-level item out, so the code after a test module -/// in the middle of a file is still read; `#[cfg(test)]` then `mod name;` is one line. -fn outside_test_modules(source: &str) -> Vec<(usize, &str)> { - let mut kept = Vec::new(); - let mut lines = source.lines().enumerate().map(|(n, line)| (n + 1, line)).peekable(); - while let Some((n, line)) = lines.next() { - if line == "#[cfg(test)]" && lines.peek().is_some_and(|(_, next)| next.starts_with("mod ")) { - if lines.next().is_some_and(|(_, module)| module.ends_with('{')) { - lines.by_ref().find(|(_, line)| *line == "}"); - } - continue; - } - kept.push((n, line)); - } - kept -} - -/// The lines of code in `source` outside its test modules, numbered from 1, each with the -/// top-level function or `impl` method it is in; comment lines are left out. A line rustfmt -/// continued (a method chain split as `view` / `.router` / `.owner(i)`) is read with the one it -/// continues, under that one's number. -fn code_lines(source: &str) -> Vec<(usize, Option<&str>, String)> { - let (mut function, mut in_impl) = (None, false); - let mut lines: Vec<(usize, Option<&str>, String)> = Vec::new(); - for (n, line) in outside_test_modules(source) { - if line.starts_with("impl") { - (function, in_impl) = (None, true); - } else if line == "}" { - (function, in_impl) = (None, false); - } else if let Some(name) = declares(line).or_else(|| line.strip_prefix(" ").filter(|_| in_impl).and_then(declares)) { - function = Some(name); - } - if line.trim_start().starts_with("//") { - continue; - } - match lines.last_mut() { - Some((_, _, text)) if line.trim_start().starts_with('.') => text.push_str(line.trim_start()), - _ => lines.push((n, function, line.to_owned())), - } - } - lines -} - -/// Each name `find` finds in a line of the page modules' code (their tests left out), as (file, -/// the top-level function or `impl` method it is in, line, name) ([`code_lines`]). -fn page_module_matches(find: impl Fn(&str) -> Vec) -> Vec<(&'static str, Option, usize, String)> { - let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); - let mut found = Vec::new(); - for file in PAGE_MODULES { - let source = std::fs::read_to_string(src.join(file)).expect("page module").replace("\r\n", "\n"); - for (n, function, text) in code_lines(&source) { - for name in find(&text) { - found.push((file, function.map(str::to_owned), n, name)); - } - } - } - found -} - -/// Each hit test `source` imports under a name that is not a hit test's (`use …::hit as under;`), -/// as (name, alias), from each `use` statement, from its first line to its `;`, wherever it is. -fn aliased_hit_tests(source: &str) -> Vec<(String, String)> { - let mut found = Vec::new(); - let mut statement: Option = None; - for line in source.lines().map(str::trim) { - if statement.is_none() && ["use ", "pub use ", "pub(crate) use ", "pub(super) use "].iter().any(|start| line.starts_with(start)) { - statement = Some(String::new()); - } - let Some(text) = statement.as_mut() else { continue }; - text.push_str(line); - text.push(' '); - if !line.ends_with(';') { - continue; - } - for part in text.split([',', '{', '}', ';']) { - let Some((path, alias)) = part.split_once(" as ") else { continue }; - let (name, alias) = (path.trim().rsplit("::").next().unwrap_or_default(), alias.trim()); - if is_hit_test(name) && !is_hit_test(alias) { - found.push((name.to_owned(), alias.to_owned())); - } - } - statement = None; - } - found -} - -/// Each hit test a page module imports under a name that is not a hit test's, which the checks by -/// name would not see ([`aliased_hit_tests`]). -fn hit_test_aliases() -> Vec { - let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); - let mut found = Vec::new(); - for file in PAGE_MODULES { - let source = std::fs::read_to_string(src.join(file)).expect("page module"); - for (name, alias) in aliased_hit_tests(&source) { - found.push(format!( - "src/{file}: `{name} as {alias}` imports a hit test under another name, which the checks by name miss: name \ - it `hit` or `…_hit`." - )); - } - } - found -} - -/// Each use of one of `names` in the page modules' code (their tests left out). -fn page_module_uses(names: &[&str]) -> Vec<(&'static str, Option, usize, String)> { - page_module_matches(|line| names.iter().filter(|name| uses(line, name)).map(|name| (*name).to_owned()).collect()) -} - -/// Each use of one of `names` in the page modules' code (their tests left out) outside the -/// functions `allowed` to, as "src/file:line: `name` why"; then each allowed function that uses -/// none of them any more, as "src/file: fn function unused". -fn misuses(names: &[&str], allowed: &[(&str, &str, &str)], why: &str, unused: &str) -> Vec { - misuses_in(page_module_uses(names), allowed, why, unused) -} - -/// [`misuses`], of what was `found`. -fn misuses_in(found: Vec<(&str, Option, usize, String)>, allowed: &[(&str, &str, &str)], why: &str, unused: &str) -> Vec { - let mut problems = Vec::new(); - let mut needed = vec![false; allowed.len()]; - for (file, function, n, name) in found { - match allowed.iter().position(|(f, function_name, _)| *f == file && function.as_deref() == Some(*function_name)) { - Some(k) => needed[k] = true, - None => problems.push(format!("src/{file}:{n}: `{name}` {why}")), - } - } - for ((file, name, _), needed) in allowed.iter().zip(needed) { - if !needed { - problems.push(format!("src/{file}: fn {name} {unused}")); - } - } - problems -} - -/// Page modules read the pointer only through `PagePointer`. egui's raw state misses what is -/// drawn over the pages and where a touch lifted, so a raw read in a page module brings back -/// the bugs `PagePointer` fixed: a cursor or a press through a dialog, a tap that does nothing. -#[test] -fn page_modules_read_the_pointer_only_through_page_pointer() { - let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); - let mut problems = misuses( - &RAW_READS, - &NOT_PAGE_INPUT, - "reads egui's pointer state in a page module. Read `PagePointer` (src/canvas/page_pointer.rs) instead: it \ - knows what is drawn over the pages and where a touch lifted. Not page input? Add the function to \ - NOT_PAGE_INPUT there, with why.", - "reads no pointer state any more: remove it from NOT_PAGE_INPUT.", - ); - // A module that acts on the pages is a page module, so it is checked too. - let mut dirs = vec![src.clone()]; - while let Some(dir) = dirs.pop() { - for entry in std::fs::read_dir(dir).expect("source directory") { - let path = entry.expect("source entry").path(); - // Tests drive egui's input themselves, in test modules and in test files. - let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); - if stem == "tests" || stem.ends_with("_tests") { - continue; - } - if path.is_dir() { - dirs.push(path); - continue; - } - if path.extension().is_none_or(|ext| ext != "rs") { - continue; - } - let file = - path.strip_prefix(&src).expect("under src").components().map(|c| c.as_os_str().to_string_lossy()).collect::>().join("/"); - let source = std::fs::read_to_string(&path).expect("source file"); - let marks = PAGE_MODULE_MARKS.iter().filter(|mark| source.contains(**mark)).collect::>(); - if !ROUTER_FILES.contains(&file.as_str()) && !marks.is_empty() && !PAGE_MODULES.contains(&file.as_str()) { - problems.push(format!("src/{file} uses {marks:?}, so it acts on the pages: add it to PAGE_MODULES.")); - } - } - } - problems.extend(misuses( - &ANY_BUTTON_DRAG, - &NOT_PAGE_DRAGS, - "starts a drag with any button: a right-button drag would start what a left one does. Read \ - `PagePointer::drag_started` (the primary button's) instead. A widget of its own, not the pages? Add the \ - function to NOT_PAGE_DRAGS in src/canvas/page_pointer/tests.rs, with why.", - "starts no drag of its own any more: remove it from NOT_PAGE_DRAGS.", - )); - assert!(problems.is_empty(), "{}", problems.join("\n")); -} - -/// Page modules claim the cursor and never set it. Where each set it, the last write of a frame -/// won, so the order of the per-page chain decided the cursor and not what a press does: a -/// link's hand over every tool, the I-beam over a comment that a drag moves. -#[test] -fn page_modules_claim_the_cursor_and_never_set_it() { - let problems = misuses( - &CURSOR_WRITES, - &NOT_PAGE_CURSOR, - "sets the cursor in a page module, where the last write of a frame would win. Claim it instead, on the layer \ - of what is under the pointer (`view.cursor.claim`, src/canvas/page_cursor.rs): `document_area` sets it once, \ - from the claim on the highest layer the active tool reaches. Not the pages' cursor? Add the function to \ - NOT_PAGE_CURSOR in src/canvas/page_pointer/tests.rs, with why.", - "sets no cursor any more: remove it from NOT_PAGE_CURSOR.", - ); - assert!(problems.is_empty(), "{}", problems.join("\n")); -} - -/// What decides, keeps or drops the press the pages hold. -const ROUTER_WRITES: [&str; 10] = [ - "router.begin(", - "router.press(", - "router.drag_began(", - "router.settle(", - "router.cancel(", - "PageRouter::begin(", - "PageRouter::press(", - "PageRouter::drag_began(", - "PageRouter::settle(", - "PageRouter::cancel(", -]; - -/// The functions that decide, keep or drop the press the pages hold: (file, function, why). -const ROUTER_WRITERS: [(&str, &str, &str); 3] = [ - ("canvas/page_input.rs", "page_tool_input", "the hits at the press point decide its owner, once per press, and a declined drag lets it go"), - ("canvas.rs", "draw_pages", "the press is over once the button is up and its release seen, and a new one drops the last owner"), - ("canvas.rs", "cancel_pointer_gestures", "every pointer gesture's cancel: Escape, automation's cancel"), -]; - -/// Ways to make a `Hit`. -const HIT_BUILDS: [&str; 2] = ["Hit::new(", "Hit {"]; - -/// Whether `name` is a hit test's: `hit`, or `…_hit`. -fn is_hit_test(name: &str) -> bool { - name == "hit" || name.ends_with("_hit") -} - -/// The hit tests `line` calls: by path, bare or as a method. -fn hit_test_calls(line: &str) -> Vec { - line.match_indices("hit(") - .filter_map(|(at, _)| { - let end = at + "hit".len(); - let start = line[..end].char_indices().rev().find(|(_, c)| !(c.is_alphanumeric() || *c == '_')).map_or(0, |(i, c)| i + c.len_utf8()); - let (before, name) = (&line[..start], &line[start..end]); - (is_hit_test(name) && !before.ends_with("fn ")).then(|| name.to_owned()) - }) - .collect() -} - -/// The functions that call a hit test: (file, function, why). Hit tests are found by name (a -/// function named `hit` or `…_hit`, called by path, bare or as a method). The comments' point test -/// has a list of its own (`COMMENT_POINT_TESTERS`). Point tests by other names are not seen: what is -/// left of them paints (a picture's hover outline), keeps a behaviour no hit stands for (added -/// text's click with the tools that don't pick it up, crop mode's controls) or tells a tool that a -/// press nobody holds began on its page (the text layer's `press_here`, redaction's). `PageHits::hits` -/// is the one: the hits at the press point decide its owner, and those under the pointer give its -/// cursor, its tip, hover painting and a right-click. -const HIT_TESTERS: [(&str, &str, &str); 1] = [( - "canvas/page_input.rs", - "hits", - "`PageHits::hits`: every module's hits at a point, for the pointer's cursor and tip, a right-click and, once, the press's owner", -)]; - -/// The page view's asks for every module's hits at a point (`PageHits::hits`, and `at` and -/// `context_at`, which wrap it). -const PAGE_HITS_ASKS: [&str; 6] = [".hits(", ".at(", ".context_at(", "PageHits::hits(", "PageHits::at(", "PageHits::context_at("]; - -/// The functions that ask the page view's hits at a point: (file, function, why). `PageHits` is -/// private to `page_input.rs`, so this keeps a new function there from asking; a second ask inside -/// a listed function is for review to catch. The method names are matched in every page module, -/// so an `at` of another type there would need them narrowed. -const PAGE_HITS_ASKERS: [(&str, &str, &str); 5] = [ - ("canvas/page_input.rs", "at", "`PageHits::at`: the hits at a point, as a press there would take them"), - ("canvas/page_input.rs", "context_at", "`PageHits::context_at`: what a right-click at a point is on"), - ( - "canvas/page_input.rs", - "page_tool_input", - "the hits at the press point decide its owner, once per press; those under the pointer before the tools act, once a \ - frame, serve a click's release, a right-click and Fill & Sign's preview", - ), - ("canvas/page_input.rs", "claim_under", "what lies under the pointer after the tools act: its cursor, its tip and hover painting"), - ("canvas/page_input.rs", "right_click", "what a right-click is on"), -]; - -/// The comments' point test, which their hit tests are built on: which comment lies under a point. -const COMMENT_POINT_TESTS: [&str; 2] = [".comment_at(", "PageCx::comment_at("]; - -/// The functions that ask which comment lies under a point: (file, function, why). -const COMMENT_POINT_TESTERS: [(&str, &str, &str); 4] = [ - ("tools/comments/input.rs", "hit", "the comments' hit test"), - ( - "tools/comments/state.rs", - "click_target", - "the comments' hit tests' lookup: a group subordinate (`/RT /Group`, ISO 32000-2 §12.5.6.2) stands for its primary", - ), - ("tools/comments/state.rs", "picked", "which group subordinate a click selected its primary through, when the click is acted on"), - ("tools/comments/paint.rs", "paint_page", "a redaction mark shows its fill under the pointer with every tool, as comments' tips show"), -]; - -/// What reads who holds the press the pages hold. -const ROUTER_READS: [&str; 4] = ["router.press_for(", "router.keeps_drag(", "PageRouter::press_for(", "PageRouter::keeps_drag("]; - -/// The functions that read who holds the press: (file, function, why). The page view asks once per -/// page and tells each module what the press is to its page (`PagePress`): modules never read the -/// router, and outside `canvas` the compiler refuses them (its methods are `pub(in crate::canvas)`). -/// An unused entry fails the test. -const ROUTER_READERS: [(&str, &str, &str); 1] = [( - "canvas/page_input.rs", - "page_tool_input", - "the page view: what the press is to each page (`press_for`), and whether its drag is the text's (`keeps_drag`)", -)]; - -/// Words a page module's functions are not named with: a function that grabs or owns a press decides -/// for itself whether the press is its own, which the page view tells it (`PagePress`). -const PRESS_CLAIMING_WORDS: [&str; 2] = ["grabs", "owns"]; - -/// The function `line` declares, when one of the words of its name is one of -/// [`PRESS_CLAIMING_WORDS`]. -fn press_claiming_fn(line: &str) -> Vec { - declares(line.trim_start()) - .filter(|name| name.split('_').any(|word| PRESS_CLAIMING_WORDS.contains(&word))) - .map(str::to_owned) - .into_iter() - .collect() -} - -/// Whether `line` takes the router whole (`let r = &view.router;`), which the checks by method -/// name would not see through: anything but a method call on it. -fn takes_the_router(line: &str) -> bool { - line.match_indices(".router") - .any(|(at, name)| line[at + name.len()..].chars().next().is_none_or(|c| c != '.' && !(c.is_alphanumeric() || c == '_'))) -} - -/// What ignores the press the pages hold until the button is up. -const PRESS_IGNORES: [&str; 1] = ["press_cancelled = true"]; - -/// The one function that ignores a press until the button is up: (file, function, why). -const PRESS_IGNORERS: [(&str, &str, &str); 1] = - [("canvas/page_input.rs", "cancel_on_escape", "Escape abandons the gesture the press drives, whichever tool's")]; - -/// Page modules act on a press only when the router says it is theirs. The hits at the press -/// point decide its owner once, in one place, and a `Hit` comes only from a module's hit test, -/// so what the cursor promised is what the press does. Where each module tested the press -/// point again, or asked another whether it wanted the press, the answers disagreed: a press on -/// one check box released over the next ticked the second, and a drag could be taken over -/// halfway. Only `PageHits::hits` asks the hit tests. Escape is the one way to -/// drop a press and ignore it until the button is up. -#[test] -fn page_modules_act_on_a_press_only_through_the_router() { - let mut problems = misuses( - &ROUTER_WRITES, - &ROUTER_WRITERS, - "decides, keeps or drops the press the pages hold. Only the hits at the press point decide its owner, once \ - (src/canvas/page_router.rs), and the page view tells each module what the press is to its page (`PagePress`). Drop a press with \ - `DocView::cancel_pointer_gestures`. A new place that must? Add the function to ROUTER_WRITERS in \ - src/canvas/page_pointer/tests.rs, with why.", - "no longer decides, keeps or drops the press: remove it from ROUTER_WRITERS.", - ); - problems.extend(misuses( - &ROUTER_READS, - &ROUTER_READERS, - "reads who holds the press the pages hold. The page view asks the router once per page and tells each module \ - what the press is to its page: take a `PagePress` (src/canvas/page_router.rs) instead. A new place that must? \ - Add the function to ROUTER_READERS in src/canvas/page_pointer/tests.rs, with why.", - "no longer reads who holds the press: remove it from ROUTER_READERS.", - )); - // A router method the lists above don't name yet is the router's all the same: only their - // functions use it. - let known: Vec<&str> = ROUTER_WRITES.iter().chain(ROUTER_READS.iter()).copied().collect(); - let unlisted = page_module_matches(|line| { - let router = uses(line, ".router.") || uses(line, "PageRouter::") || takes_the_router(line); - if router && !known.iter().any(|name| uses(line, name)) { vec!["router".to_owned()] } else { Vec::new() } - }); - problems.extend( - unlisted - .into_iter() - .filter(|(file, function, _, _)| { - !ROUTER_WRITERS.iter().chain(ROUTER_READERS.iter()).any(|(f, name, _)| f == file && function.as_deref() == Some(*name)) - }) - .map(|(file, _, n, _)| { - format!( - "src/{file}:{n}: uses the router by a method ROUTER_WRITES and ROUTER_READS don't name. The page view \ - decides the press and tells each module what it is to its page (`PagePress`): add the method to \ - ROUTER_WRITES or ROUTER_READS in src/canvas/page_pointer/tests.rs, and the function to their lists \ - only if it must." - ) - }), - ); - problems.extend(misuses( - &COMMENT_POINT_TESTS, - &COMMENT_POINT_TESTERS, - "asks which comment lies under a point. The comments' hit tests answer that for a press and a right-click: \ - act on what the page view tells you, rather than testing the point again. A new place that must? Add the \ - function to COMMENT_POINT_TESTERS in src/canvas/page_pointer/tests.rs, with why.", - "no longer asks which comment lies under a point: remove it from COMMENT_POINT_TESTERS.", - )); - problems.extend(misuses( - &PAGE_HITS_ASKS, - &PAGE_HITS_ASKERS, - "asks the page view's hits at a point. The hits at the press point decide its owner once, and those under the \ - pointer are taken once before the tools act and once after: use those (`under`, `PageInput.hover`). A new \ - place that must ask? Add the function to PAGE_HITS_ASKERS in src/canvas/page_pointer/tests.rs, with why.", - "no longer asks the page view's hits: remove it from PAGE_HITS_ASKERS.", - )); - // A module is told what the press is to its page; none decides it for itself. - problems.extend(page_module_matches(press_claiming_fn).into_iter().map(|(file, _, n, name)| { - format!( - "src/{file}:{n}: `fn {name}` decides whether a press is its module's. The page view tells each module what the \ - press is to its page (`PagePress`): act on that, in a function named for what it does." - ) - })); - problems.extend(misuses( - &PRESS_IGNORES, - &PRESS_IGNORERS, - "ignores the press the pages hold. Escape cancels a press, in `cancel_on_escape`: drop a gesture with \ - `DocView::cancel_pointer_gestures` instead.", - "no longer ignores a press: remove it from PRESS_IGNORERS.", - )); - // A hit test is a function named `hit` or `…_hit`: one answer to "what of mine is here?", - // which gives the module's cursor, its tip and its press. - problems.extend(misuses_in( - page_module_matches(hit_test_calls), - &HIT_TESTERS, - "calls a hit test. The hits at the press point decide its owner once, in `PageHits::hits`: act on the press when \ - the page view tells you it is yours (`PagePress::Mine`), rather than testing its point again. What lies under \ - the pointer comes from the page view's own hits: hover painting and tips (`PageInput.hover`), a click released \ - over what it was pressed on (`released_over`). A new place that must ask? Add the function to HIT_TESTERS in \ - src/canvas/page_pointer/tests.rs, with why.", - "calls no hit test any more: remove it from HIT_TESTERS.", - )); - problems.extend(hit_test_aliases()); - let builds = page_module_uses(&HIT_BUILDS); - assert!(!builds.is_empty(), "no page module makes a `Hit` any more: update HIT_BUILDS"); - problems.extend(builds.into_iter().filter(|(_, function, _, _)| !function.as_deref().is_some_and(is_hit_test)).map(|(file, _, n, name)| { - format!( - "src/{file}:{n}: `{name}` makes a hit outside a hit test. A page module answers \"what of mine is \ - here?\" in one function, named `hit` or `…_hit`, so its cursor, its tip and its press agree." - ) - })); - assert!(problems.is_empty(), "{}", problems.join("\n")); -} - -/// A test module in the middle of a file hides only itself from the page guards: the code after -/// it is read too. The guards used to stop at the first test module. -#[test] -fn the_page_guards_read_past_a_test_module_in_the_middle_of_a_file() { - let source = "fn before() {}\n#[cfg(test)]\nmod tests {\n fn inside() {}\n}\n\nfn after() {}\n#[cfg(test)]\nmod more;\nfn last() {}\n"; - let kept: Vec<(usize, &str)> = outside_test_modules(source); - assert_eq!(kept, [(1, "fn before() {}"), (6, ""), (7, "fn after() {}"), (10, "fn last() {}")]); -} - -/// The guard's readers: hit tests by name, the function a line declares, a call rustfmt split, -/// and a hit test imported as another name. -#[test] -fn the_page_guards_read_hit_tests_split_calls_and_aliases() { - assert_eq!(hit_test_calls("let h = crate::forms_ui::hit(xf, p);"), ["hit"]); - assert_eq!(hit_test_calls("cx.comment_hit(p) && picture_hit(p)"), ["comment_hit", "picture_hit"]); - assert!(hit_test_calls("pub(crate) fn hit(xf: &PageXform) -> Option {").is_empty()); - assert!(hit_test_calls("let all = self.hits(view, p, false);").is_empty()); - assert_eq!(declares("pub(crate) const fn crop_hit<'a>(view: &DocView) {"), Some("crop_hit")); - assert_eq!(declares("let hit = 1;"), None); - assert_eq!(press_claiming_fn(" pub(crate) fn fill_grabs(view: &DocView) -> bool {"), ["fill_grabs"]); - assert_eq!(press_claiming_fn("fn owns_press() {"), ["owns_press"]); - assert_eq!(press_claiming_fn(" pub(in crate::canvas) fn link_grabs(view: &DocView) {"), ["link_grabs"]); - assert!(press_claiming_fn("fn dropdowns() {").is_empty(), "a word that ends in one"); - assert_eq!(declares("pub(in crate::canvas) fn drag_began(&mut self) {"), Some("drag_began")); - assert!(takes_the_router("let r = &view.router;") && takes_the_router("keep(view.router, 1)")); - assert!(!takes_the_router("view.router.press_for(i)") && !takes_the_router("view.routers.len()")); - assert!(press_claiming_fn("fn holds(&self, page: usize) -> bool {").is_empty()); - assert!(press_claiming_fn("let grabs = 1;").is_empty()); - let source = "impl PageHits<'_> {\n fn at(&self) {\n self\n .hits(view, p, false)\n }\n}\nfn after() {\n // view.router.owner(0)\n let _ = view\n .router\n .owner(0);\n}\n"; - assert_eq!( - code_lines(source), - [ - (1, None, "impl PageHits<'_> {".to_owned()), - (2, Some("at"), " fn at(&self) {".to_owned()), - (3, Some("at"), " self.hits(view, p, false)".to_owned()), - (5, Some("at"), " }".to_owned()), - (6, None, "}".to_owned()), - (7, Some("after"), "fn after() {".to_owned()), - (9, Some("after"), " let _ = view.router.owner(0);".to_owned()), - (12, None, "}".to_owned()), - ] - ); - let source = - "fn a() {}\n\n#[cfg(any())]\nuse crate::camera_ui::hit as corner_under;\nuse crate::x::{\n hit as x_hit,\n picture_hit as under,\n};\n"; - let aliases: Vec<(String, String)> = [("hit", "corner_under"), ("picture_hit", "under")].map(|(a, b)| (a.to_owned(), b.to_owned())).to_vec(); - assert_eq!(aliased_hit_tests(source), aliases); -} - -/// egui's raw key state: a key pressed, held, let go or taken, and the key, text and clipboard -/// events themselves, however they are imported. -const RAW_KEY_READS: [&str; 17] = [ - "Event::Copy", - "Event::Cut", - "Event::Paste", - "Event::Text", - "Event::{", - "Event::*", - "Event as ", - "InputState::", - "key_pressed(", - "key_released(", - "key_down(", - "keys_down", - "num_presses(", - "consume_key(", - "consume_shortcut(", - "count_and_consume_key(", - "Event::Key", -]; - -/// Functions in the files the key guard scans ([`key_files`]) that read egui's keys themselves: -/// a window's or a field's own keys, which `PageKeys` would hide, and the pages' reads that -/// `PageKeys` can't make (chords that wait for the menu bar instead, Escape ending what the pages -/// hold, any key stopping a glide, the clipboard's hand-off to text fields): (file, function, why). -const NOT_PAGE_KEYS: [(&str, &str, &str); 17] = [ - ( - "app/clipboard.rs", - "clipboard_keys", - "the pages' clipboard: Copy, Cut and Paste (events and chords), which act only when `page_keys.over()` is false, \ - and the pastes it hands on to text fields while something is over the pages", - ), - ( - "app/keys.rs", - "select_all_keys", - "Select all, a chord that waits for a menu of the menu bar as the registered commands' do, and isn't called while something covers the pages", - ), - ("canvas/area.rs", "glide_interrupted", "any key stops the touchpad's glide"), - ("canvas/autoscroll.rs", "update_latched", "Escape ends the middle-button scroll, which holds the whole view"), - ("canvas/autoscroll.rs", "escape", "Escape ends the middle-button scroll, which holds the whole view"), - ("canvas/find.rs", "find_bar", "the Find field's own keys, while it has the focus"), - ( - "canvas/navigation.rs", - "view_chords", - "the view's chords, which wait for a menu of the menu bar as the registered commands' do, and for whatever covers the pages", - ), - ("canvas/page_input.rs", "cancel_on_escape", "Escape cancels a press the pages hold, which goes on under a dialog opened during it"), - ("tools/calc_order_ui.rs", "panel", "the Calculation order panel's own Alt+arrows"), - ("tools/comments/composer.rs", "submit_key", "the comment field's own Enter, while it has the focus (the Comments panel's too)"), - ("tools/field_table_ui.rs", "show", "the Text field table window's own Escape"), - ("tools/field_table_ui.rs", "column_dividers", "the Text field table window's own arrows"), - ("tools/fill_sign.rs", "signature_pad", "the signature dialog's own ⌘Z"), - ("tools/forms_ui.rs", "combo_editor", "the combo box's own Enter, while its field has the focus"), - ("tools/prepare/properties.rs", "body", "the field properties' own Enter, while one of their fields has the focus"), - ("tools/redact_ui.rs", "search_body", "the redaction search field's own Enter, while it has the focus"), - ("tools/sign_ui/dialog.rs", "sign_as", "the signing dialog's own Enter"), -]; - -/// The files whose key reads the key guard checks, relative to `src`: every file under `canvas/` -/// and `tools/` and the canvas's root, whether or not it is a page module yet, the app's own keys -/// and clipboard, and the Pages panel's thumbnails; not their tests, and not `PageKeys` itself. A -/// helper in another file that page code hands egui's input to isn't seen. -fn key_files() -> Vec { - let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); - let mut files = ["canvas.rs", "app/keys.rs", "app/clipboard.rs", "panels/pages.rs"].map(str::to_owned).to_vec(); - let mut dirs = vec![src.join("canvas"), src.join("tools")]; - while let Some(dir) = dirs.pop() { - for entry in std::fs::read_dir(dir).expect("source directory") { - let path = entry.expect("source entry").path(); - let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); - if stem == "tests" || stem.ends_with("_tests") { - continue; - } - if path.is_dir() { - dirs.push(path); - } else if path.extension().is_some_and(|ext| ext == "rs") { - let file = - path.strip_prefix(&src).expect("under src").components().map(|c| c.as_os_str().to_string_lossy()).collect::>().join("/"); - if file != "canvas/page_keys.rs" { - files.push(file); - } - } - } - } - files.sort(); - files -} - -/// Page code reads keys only through `PageKeys`. The pages are drawn before the dialogs and the -/// palette and read egui's keys first, so a raw read acts on what is selected or typed behind -/// whatever is over them: Delete under a dialog deleted the comment selected behind it, and the -/// Escape that closed one threw away the paragraph being typed. -#[test] -fn page_modules_read_keys_only_through_page_keys() { - let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); - let files = key_files(); - let mut found = Vec::new(); - for file in &files { - let source = std::fs::read_to_string(src.join(file)).expect("source file").replace("\r\n", "\n"); - for (n, function, text) in code_lines(&source) { - for name in RAW_KEY_READS.iter().filter(|name| uses(&text, name)) { - found.push((file.as_str(), function.map(str::to_owned), n, (*name).to_owned())); - } - } - } - let problems = misuses_in( - found, - &NOT_PAGE_KEYS, - "reads egui's keys in page code. Read them through `PageKeys` (src/canvas/page_keys.rs) instead: it has none \ - while a dialog, the palette or a menu is over the pages, which read keys before those are drawn. Not the \ - pages' keys? Add the function to NOT_PAGE_KEYS in src/canvas/page_pointer/tests.rs, with why.", - "reads no keys of its own any more: remove it from NOT_PAGE_KEYS.", - ); - assert!(problems.is_empty(), "{}", problems.join("\n")); -} diff --git a/crates/ui-egui/src/canvas/page_router.rs b/crates/ui-egui/src/canvas/page_router.rs deleted file mode 100644 index 5dbe5d4461..0000000000 --- a/crates/ui-egui/src/canvas/page_router.rs +++ /dev/null @@ -1,355 +0,0 @@ -//! Who a press on the pages belongs to. -//! -//! Each page module answers "what of mine is under this point?" in one place, its hit test, and -//! the answer is a [`Hit`]: what is there ([`Owner`]), on which [`Layer`], with which cursor and -//! tip. The pointer's hits set the cursor and the tip; on the frame of a press, the hits at the -//! press point decide who captures it ([`PageRouter::press`]), by the same table: the highest layer -//! the active tool reaches. Until the button is up only the owner acts on the press, its drag and -//! its release, so what the cursor promised is what the press does, and nothing takes a gesture -//! back halfway; an owner that declines the drag (text markup, a link with the Link tool) lets it -//! go as it starts, and the drag is nobody's. Each page is told what it has to do with the press -//! ([`PagePress`]): its owner's, the active tool's, or none of its business. Only the page view -//! reads the router: its methods are `canvas`'s alone. - -use egui::CursorIcon; -use pdfcraft_engine::ObjectTarget; - -use crate::QuickTool; -use crate::page_cursor::Layer; - -/// What a hit is on. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Owner { - /// A comment (or a Fill & Sign mark), by its `/Annots` index, and the part of it. - Comment { index: usize, part: CommentPart }, - /// A link, by its index in its page's `/Annots`. - Link { index: usize }, - /// A web or email address written as plain page text (#4207), by its index among the page's. - TextLink { index: usize }, - /// A form field's widget, by the field's index in the form and the widget's in the field. - Field { field: usize, widget: usize }, - /// Prepare Form: a field's widget, to select and move. - PrepareField { field: usize, widget: usize }, - /// Prepare Form: a corner handle of the selected field, to resize it. - PrepareCorner { left: bool, top: bool }, - /// Edit text: a paragraph, by its index among the page's, and what of it a press takes. - Paragraph { block: usize, part: ParagraphPart }, - /// Edit text: a picture, by its index among the page's, and what of it a press takes. - Picture { index: usize, part: PicturePart }, - /// Edit text: the objects selected together, or the frame of the paragraph open for typing. - Objects { part: ObjectsPart }, - /// Added text or a picture placed on the page, by its index among the page's, and a corner of - /// the selected one (left, top) or the item itself. - Added { index: usize, corner: Option<(bool, bool)> }, - /// Enhance ▸ Camera image: a corner of the quadrilateral (0 left top, then clockwise). - CameraCorner { corner: usize }, -} - -/// The part of a picture a hit is on. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum PicturePart { - /// The picture: a click selects it, a drag moves the selected one. - Body, - /// A picture lying over the selected one, within the selected one's frame: a click selects the - /// one on top, a drag moves the selected one. - OverSelected, - /// A resize grip in `ImageObb::handles` order (four corners and four edge midpoints). - Corner(usize), - /// The selected picture's rotate knob: a drag turns it. - Knob, - /// The picture being cropped, which holds every press on its page. - Crop(CropPart), -} - -/// What of a picture being cropped a hit is on. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum CropPart { - /// A grip of the box kept, in `crop_handles` order (four corners, then the top, right, bottom - /// and left edge midpoints): a drag moves that side or corner. - Grip(usize), - /// The box kept: a drag moves it over the picture. - Keep, - /// The picture outside the box kept, shown or cut away: a press there moves nothing, and a - /// right-click is the crop's, as on the box and its grips (#5835). - Cut, - /// The rest of the page, its Done and Cancel controls among it: a press there is crop mode's, - /// and moves nothing. - Page, -} - -/// What of the objects a hit is on. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum ObjectsPart { - /// The objects selected together: a drag moves them all. - Selection, - /// The frame drawn around the paragraph open for typing: a click selects the box, a drag moves it. - Frame, - /// A press with Shift or ⌘ (Ctrl): it adds the object under it to the objects selected - /// together, or takes it out of them, or on none starts an area selection that adds to them. - Toggle(Option), - /// A press with Shift or ⌘ while text being typed is open (a new box, or a paragraph with - /// changes), which must be finished or discarded first: it is held until the button is up, and - /// selects nothing. - Held, - /// A press with Shift or ⌘ on a page whose objects can't be selected together: it says so. - Refused, -} - -/// The part of a paragraph a hit is on. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum ParagraphPart { - /// The paragraph: a drag moves it, a click opens it for typing. - Body, - /// Its left or right edge (on screen): a drag rewraps it. - Left, - Right, -} - -/// The part of a comment a hit is on. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum CommentPart { - /// The comment itself: a drag moves it, a click selects it. - Body, - /// A resize handle of the selected comment: (-1, 0 or 1) across, then down. - Handle(i8, i8), - /// A point of the selected line, polygon or cloud. - Point(usize), -} - -/// What lies under a point, for one page module. -#[derive(Clone, Debug, PartialEq)] -pub(crate) struct Hit { - pub owner: Owner, - pub layer: Layer, - pub icon: CursorIcon, - /// Beside the pointer where this hit wins (a link's target). - pub tip: Option, - /// A drag from here is not this owner's: a click on a highlight selects it, a drag across it - /// selects the text underneath; with the Link tool, a drag from a link draws a new one. - pub declines_drag: bool, -} - -impl Hit { - pub(crate) fn new(owner: Owner, layer: Layer, icon: CursorIcon) -> Self { - Hit { owner, layer, icon, tip: None, declines_drag: false } - } -} - -/// The hit that wins among `hits` with `tool`: the highest layer the tool reaches, the last of -/// equals (modules are asked bottom up, in paint order). -pub(in crate::canvas) fn top(hits: impl IntoIterator, tool: QuickTool) -> Option { - hits.into_iter().filter(|h| h.layer.reached_by(tool)).fold(None, |best: Option, h| match best { - Some(b) if b.layer > h.layer => Some(b), - _ => Some(h), - }) -} - -/// What one page has to do with the press the pages hold. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum PagePress { - /// The press began on this page, and the owner's hit won it: its module acts on it. Others - /// only let go of their own state (a click on anything but the selected comment unselects it). - Mine(Owner), - /// No button is down, or the press began on this page and nobody's hit won it, or its owner let - /// its drag go ([`PageRouter::drag_began`]): the active tool's. Also every page's while a - /// press the page view does not hold is down (one that began - /// over a panel), and after the press was dropped ([`PageRouter::cancel`]) until the button is - /// up (`Elsewhere` instead when Escape came in the press's own frame; page input skips a - /// cancelled press either way). - Free, - /// The press began on another page, or off the pages (between them, or beside one) where no - /// page has anything under it. - Elsewhere, -} - -impl PagePress { - /// Who holds the press on this page, if anyone. - pub(crate) fn owner(self) -> Option { - match self { - PagePress::Mine(owner) => Some(owner), - PagePress::Free | PagePress::Elsewhere => None, - } - } -} - -/// A press the pages hold, and who it belongs to. -#[derive(Clone, Debug, PartialEq)] -struct Capture { - pub owner: Owner, - pub declines_drag: bool, - /// What lay on top at the press with the objects selected together aside: a double-click on - /// them reaches it. - under_objects: Option, -} - -/// The press the pages hold, from its frame until the button is up. -#[derive(Debug, Default)] -pub(crate) struct PageRouter { - capture: Option, - /// A press is held, and the page it began on (`None`: off the pages, between them or beside one). - began: Option>, -} - -impl PageRouter { - /// A new press on the pages: the last one's owner goes, and until a page claims it the press is - /// between the pages. - pub(in crate::canvas) fn begin(&mut self) { - self.capture = None; - self.began = Some(None); - } - - /// A press on `page`, or past its edge where `hits` are under it (the selected picture's rotate - /// knob): `hits` at the press point decide who it belongs to. A press nobody's hit claims is held - /// by nobody (the page's text, or a tool that acts anywhere on the page). - /// Only a press just begun ([`Self::begin`]) is claimed, by the first page that does: pages - /// that touch (the gaps hidden) can share a row of pixels, and a press there is one page's. - pub(in crate::canvas) fn press(&mut self, page: usize, hits: impl IntoIterator, tool: QuickTool) { - if self.began != Some(None) { - return; - } - let hits: Vec = hits.into_iter().collect(); - let under_objects = top(hits.iter().filter(|h| !matches!(h.owner, Owner::Objects { .. })).cloned(), tool).map(|h| h.owner); - self.capture = top(hits, tool).map(|h| Capture { owner: h.owner, declines_drag: h.declines_drag, under_objects }); - self.began = Some(Some(page)); - } - - /// What `page` has to do with the press the pages hold. - pub(in crate::canvas) fn press_for(&self, page: usize) -> PagePress { - match (self.began, &self.capture) { - (None, _) => PagePress::Free, - (Some(Some(p)), Some(capture)) if p == page => PagePress::Mine(capture.owner), - (Some(Some(p)), None) if p == page => PagePress::Free, - _ => PagePress::Elsewhere, - } - } - - /// What lay on top at the press with the objects selected together aside. - pub(in crate::canvas) fn under_objects(&self) -> Option { - self.capture.as_ref().and_then(|c| c.under_objects) - } - - /// Whether the press is held by someone who keeps its drag: then the page's text is not - /// selected by it. - pub(in crate::canvas) fn keeps_drag(&self) -> bool { - self.capture.as_ref().is_some_and(|c| !c.declines_drag) - } - - /// The press turned into a drag: an owner that declines its drag lets it go, and from then on - /// the press is nobody's (a drag across a highlight selects the text under it; with the Link - /// tool, a drag from a link draws a new one). Its click stayed the owner's. - pub(in crate::canvas) fn drag_began(&mut self) { - if self.capture.as_ref().is_some_and(|c| c.declines_drag) { - self.capture = None; - } - } - - /// The press is over once the button is up and its release has been seen. - pub(in crate::canvas) fn settle(&mut self, any_down: bool, edges: bool) { - if !any_down && !edges { - self.capture = None; - self.began = None; - } - } - - /// Drops the press (Escape, automation's cancel): every page is the active tool's again - /// ([`PagePress::Free`]). Page input skips a press Escape cancelled until the button is up. - pub(in crate::canvas) fn cancel(&mut self) { - self.capture = None; - self.began = None; - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn hit(layer: Layer, index: usize) -> Hit { - Hit::new(Owner::Comment { index, part: CommentPart::Body }, layer, CursorIcon::Move) - } - - #[test] - fn the_highest_reached_layer_wins_and_the_last_of_equals() { - let hits = [hit(Layer::Comment, 0), hit(Layer::Link, 1), hit(Layer::Comment, 2)]; - assert_eq!(top(hits.clone(), QuickTool::Select).map(|h| h.owner), Some(hits[2].owner)); - // A stamp reaches neither links nor comments. - let stamp = QuickTool::Stamp(pdfcraft_engine::StampKind::DynApproved); - assert_eq!(top(hits, stamp), None); - assert_eq!(top([hit(Layer::Placed, 3), hit(Layer::Comment, 4)], stamp).map(|h| h.owner), Some(hit(Layer::Placed, 3).owner)); - } - - #[test] - fn a_press_is_held_until_the_button_is_up_and_its_release_seen() { - let mut r = PageRouter::default(); - r.begin(); - r.press(2, [hit(Layer::Comment, 7)], QuickTool::Select); - assert_eq!(r.press_for(2).owner(), Some(hit(Layer::Comment, 7).owner)); - assert_eq!(r.press_for(1).owner(), None, "only on its page"); - assert!(r.keeps_drag()); - r.settle(false, true); - assert!(r.press_for(2).owner().is_some(), "the release frame still belongs to the press"); - r.settle(false, false); - assert_eq!(r.press_for(2).owner(), None); - r.begin(); - r.press(0, [], QuickTool::Select); - assert_eq!(r.press_for(0).owner(), None, "a press nobody claims is held by nobody"); - assert!(!r.keeps_drag()); - } - - /// A page is told whether the press is its owner's, the active tool's, or another page's. - #[test] - fn each_page_is_told_whether_the_press_is_its_own() { - let mut r = PageRouter::default(); - assert_eq!(r.press_for(3), PagePress::Free, "no button down: every page is the tool's"); - r.begin(); - assert_eq!(r.press_for(0), PagePress::Elsewhere, "a press between the pages is no page's"); - r.press(2, [], QuickTool::Select); - assert_eq!((r.press_for(2), r.press_for(1)), (PagePress::Free, PagePress::Elsewhere), "nobody's, on page 2"); - r.begin(); - r.press(1, [hit(Layer::Comment, 4)], QuickTool::Select); - assert_eq!((r.press_for(1), r.press_for(2)), (PagePress::Mine(hit(Layer::Comment, 4).owner), PagePress::Elsewhere)); - r.settle(false, true); - assert_eq!(r.press_for(2), PagePress::Elsewhere, "until its release has been seen"); - r.settle(false, false); - assert_eq!((r.press_for(1), r.press_for(2)), (PagePress::Free, PagePress::Free)); - r.begin(); - r.cancel(); - // Page input skips a press Escape cancelled until the button is up (`press_cancelled`). - assert_eq!(r.press_for(0), PagePress::Free, "a cancelled press leaves every page to the tool"); - } - - /// Pages that touch (the gaps hidden) can share a row of pixels: a press there is the first - /// page's to claim it, and the next page's claim is ignored. - #[test] - fn a_press_where_two_pages_touch_is_the_first_pages() { - let mut r = PageRouter::default(); - r.begin(); - r.press(0, [hit(Layer::Comment, 1)], QuickTool::Select); - r.press(1, [hit(Layer::Comment, 2)], QuickTool::Select); - assert_eq!((r.press_for(0), r.press_for(1)), (PagePress::Mine(hit(Layer::Comment, 1).owner), PagePress::Elsewhere)); - } - - #[test] - fn a_highlight_lets_its_drag_go_to_the_text() { - let mut r = PageRouter::default(); - r.begin(); - r.press(0, [Hit { declines_drag: true, ..hit(Layer::Comment, 0) }], QuickTool::Select); - assert!(r.press_for(0).owner().is_some() && !r.keeps_drag()); - r.cancel(); - assert_eq!(r.press_for(0).owner(), None); - } - - /// A drag the owner declines is nobody's once it starts, on the page it began on; a drag the - /// owner keeps stays its own. - #[test] - fn a_declined_drag_is_nobodys_once_it_starts() { - let mut r = PageRouter::default(); - r.begin(); - r.press(1, [Hit { declines_drag: true, ..hit(Layer::Comment, 0) }], QuickTool::Select); - r.drag_began(); - assert_eq!((r.press_for(1), r.press_for(0)), (PagePress::Free, PagePress::Elsewhere)); - r.begin(); - r.press(1, [hit(Layer::Comment, 2)], QuickTool::Select); - r.drag_began(); - assert_eq!(r.press_for(1), PagePress::Mine(hit(Layer::Comment, 2).owner)); - } -} diff --git a/crates/ui-egui/src/canvas/page_tools.rs b/crates/ui-egui/src/canvas/page_tools.rs new file mode 100644 index 0000000000..59f467dbe6 --- /dev/null +++ b/crates/ui-egui/src/canvas/page_tools.rs @@ -0,0 +1,559 @@ +//! The tool the pages run: one [`CanvasTool`] per quick tool, built each pass over the page session and handed to +//! the tool host after the page parts, so it takes every press no part took. What a tool finished in the pass (an +//! edit, a drawn rectangle, a page to move the camera quadrilateral to) is read from it after the run +//! ([`PageTool::finish`]) and applied to the session ([`ToolFinish::apply`]). + +use craft::behavior::{CancelReason, Cursor, PointerButton}; +use craft::host::{HostScope, Wake}; +use craft::keymap::Mods; +use craft::pages::ui::{PageTexts, PlacedPage, TextSelectState}; +use craft::review::SavedSignature; +use craft::ui::canvas::{ + CanvasTool, HandTool, NavigationOptions, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer, ToolRegion, + ZoomTool, +}; +use craft::ui::primitives::Draw; +use pdfcraft_engine::{Document, Edit, FormField}; +use pdfcraft_render::DocInfo; + +use super::crop::{CropResult, CropTool}; +use super::page_parts::{Owner, PagePress}; +use super::page_select::PageSelectTool; +use super::selection::DocTexts; +use super::zoom_snap::SnapshotTool; +use super::{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; +use crate::tools::fill_sign::{FillInput, FillOutcome, FillSignTool, TextBorder}; +use crate::tools::link_ui::LinkTool; +use crate::tools::measure_ui::MeasureTool; +use crate::tools::prepare::tool::PrepareTool; +use crate::tools::redact_ui::tool::{RedactResult, RedactTool}; +use crate::tools::sign_ui::tool::SignAreaTool; +use crate::tools::stamps_ui::{CustomStamp, StampChoice, StampTool}; + +/// The Fill & Sign choices the Fill tools read: the text style and the saved signature and initials. +#[derive(Clone, Copy)] +pub(crate) struct FillPrefs<'a> { + /// The size of new text, in points. + pub(crate) text_size: f64, + /// The colour of new text. + pub(crate) text_color: [f64; 3], + /// The border drawn around new text. + pub(crate) text_border: TextBorder, + /// The saved signature, if any. + pub(crate) signature: Option<&'a SavedSignature>, + /// The saved initials, if any. + pub(crate) initials: Option<&'a SavedSignature>, +} + +/// What the page tools read besides the session: the document, the placement of this pass and the app's choices. +/// One per pass; no tool changes it. +// PLAN: the session is not a field (pdf-canvas-w8 assumed `session` here): forms-w5 decided `FillSignTool::new(cx: +// &PageToolCx, input: FillInput<'a>, ..)` with `&'a mut` session fields in `FillInput`, which cannot be borrowed while a +// cx holding the whole `&mut PageSession` is lent; `page_tool` takes the session beside it (pdf-canvas-w8 passes it). +// PLAN: pdf-canvas-w8's literal also fills `sizes`, `can_crop`, `presenting`, `navigation`, `wake` and the stamp and +// Fill & Sign choices (`author`, `date_text`, `fill`, `by_line`, `custom_stamp`), which the arms read as production did. +#[derive(Clone, Copy)] +pub(crate) struct PageToolCx<'a> { + /// The open document. + pub(crate) doc: &'a Document, + /// Its page facts. + pub(crate) info: &'a DocInfo, + /// Its form fields. + pub(crate) form: &'a [FormField], + /// The pages placed this pass. + pub(crate) pages: &'a [PlacedPage], + /// Every page's size in view space, by page index, unturned by the view (`DocView::page_sizes`). + // PLAN: pdf-canvas-w8 passes `&view.page_sizes`; `PageXform::of` and the text layers need each page's size. + pub(crate) sizes: &'a [(f32, f32)], + /// The view's rotation this pass, in degrees. + pub(crate) rotation: u16, + /// The document allows comments. + pub(crate) allowed: bool, + /// The document allows changes. + pub(crate) can_modify: bool, + /// The document allows its pages' boxes to change. + pub(crate) can_crop: bool, + /// Prepare a form is open. + pub(crate) preparing: bool, + /// Full screen shows the pages: the presenter's keys reach it through the running tool. + pub(crate) presenting: bool, + /// The measuring units. + pub(crate) units: crate::units::Unit, + /// The user's navigation choices, which the Hand and Zoom tools read. + pub(crate) navigation: NavigationOptions, + /// The app's Host, which the tools that run background jobs build their queues from (L-135). + pub(crate) host: &'a HostScope, + /// The app's one wake source (L-168), for those queues. + // PLAN: pdf-canvas-w8 passes `&app.wake` (hub-w1's field); its `PageToolCx` literal has no `wake`. + pub(crate) wake: &'a Wake, + /// The comment author, written on stamps and Fill & Sign marks. + pub(crate) author: &'a str, + /// The date as Fill & Sign's date field writes it, or why it cannot. + pub(crate) date_text: &'a Result, + /// The Fill & Sign choices. + pub(crate) fill: FillPrefs<'a>, + /// The by-line of a dynamic stamp. + pub(crate) by_line: &'a str, + /// The custom stamp chosen, and the line filled in for it (#1741). + pub(crate) custom_stamp: Option<(&'a CustomStamp, Option<&'a str>)>, +} + +/// What the page tool borrows for a pass besides the session: the text layers and page transforms it builds from +/// the session and the placement. The caller keeps it beside the tool for the pass and never reads it. +#[derive(Default)] +pub(crate) struct ToolBench<'a> { + texts: Option>, + xforms: Vec<(usize, PageXform)>, +} + +/// The tool a pass runs: the Select tool's text selection, a view tool, or a tool a page module writes. +enum Arm<'a> { + /// Select and Column Select: the text selection and the picture pick. + Select(PageSelectTool<'a>), + /// The Hand tool. + Hand(HandTool), + /// Marquee Zoom: the framework's Zoom tool without scrubbing, so a drag draws the rectangle. + MarqueeZoom(ZoomTool), + /// A tool whose result is all in the session it borrows. + Area(Box), + /// The camera quadrilateral, moved to the page a click went to. + Camera(CameraTool<'a>), + /// A measuring tool, whose finished measurement is an edit. + Measure(MeasureTool<'a>), + /// A stamp, whose placement is an edit. + Stamp(StampTool<'a>), + /// Redact: a text selection or a box, finished into marks. + Redact(RedactTool<'a>), + /// The signature rectangle of Digitally sign. + SignArea(SignAreaTool), + /// Snapshot: the area to copy. + Snapshot(SnapshotTool<'a>), + /// Crop: the rectangle to crop the page to, or a double click for Set Page Boxes. + Crop(CropTool), +} + +/// The page tool of a pass, handed to the tool host: every [`CanvasTool`] method forwards to the arm. +pub(crate) struct PageTool<'a> { + arm: Arm<'a>, + /// The quick tool the pages see (after the placing rule). + tool: QuickTool, + /// The quick tool selects text ([`tool_selects_text`]). + selects_text: bool, + /// The tool host ended a gesture with a release in this pass. + released: bool, + /// Full screen: the presenter's keys the tool took for it in this pass, applied after the run. + presenting: bool, + presenter_keys: Vec, +} + +/// What the page tool finished in a pass. The fields the page body reads are public; the rest are applied to the +/// session by [`apply`](Self::apply). +#[derive(Default)] +pub(crate) struct ToolFinish { + /// The running tool is done and the app goes back to the Select tool (a stamp placed, a crop committed). + pub(crate) back_to_select: bool, + /// A Snapshot area drawn: (page, view-space rect). + pub(crate) snapshot: Option<(usize, [f32; 4])>, + /// The Crop tool's double click: open Set Page Boxes on that page. + pub(crate) open_boxes: Option, + /// The Crop tool's drawn rectangle, which the page body turns into the crop edit. + pub(crate) crop: Option, + /// Fill & Sign asked for a signature (`false`) or initials (`true`) before it can place one. + pub(crate) open_signature: Option, + /// Fill & Sign refused a click, and why. + pub(crate) refused: Option, + edit: Option, + camera_page: Option, + sign_drawn: Option<(usize, [f64; 4])>, + redaction: Option, + presenter_keys: Vec, + /// The quick tool, when it selects text. + text_tool: Option, + text_finished: bool, +} + +/// Whether copied comments hang on the pointer: they take the next click whatever tool is on. +fn placing(session: &PageSession) -> bool { + session.comments.paste.is_some() +} + +/// The tool the pages see: the Select tool while copied comments hang on the pointer, until the bundle is placed or +/// let go, so no form field, added content or field being prepared takes the click either; else `chosen`. +pub(crate) fn seen_tool(session: &PageSession, chosen: QuickTool) -> QuickTool { + if placing(session) { QuickTool::Select } else { chosen } +} + +/// Text selection runs for the Select tool, for the markup tools (highlight…) and Replace Text, for Redact and for +/// Column Select. Every tool is listed, so a new tool must say whether it selects text. +pub(crate) fn tool_selects_text(tool: QuickTool, preparing: bool) -> bool { + match tool { + QuickTool::Comment(t) => t.markup().is_some() || t == comments::CommentTool::ReplaceText, + QuickTool::Select => !preparing, + QuickTool::Redact | QuickTool::ColumnSelect => true, + QuickTool::Hand + | QuickTool::Measure(_) + | QuickTool::Crop + | QuickTool::EnhanceCamera + | QuickTool::Fill(_) + | QuickTool::Field(_) + | QuickTool::AddText + | QuickTool::EditText + | QuickTool::Stamp(_) + | QuickTool::CustomStamp(_) + | QuickTool::Link + | QuickTool::SignArea { .. } + | QuickTool::MarqueeZoom + | QuickTool::Snapshot => false, + } +} + +/// The Select tool's text selection and picture pick over the session's text, borrowing the session's fields one by +/// one so the comments tool can borrow its own beside it. +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, + xforms: &'a [(usize, PageXform)], +) -> PageSelectTool<'a> { + PageSelectTool::new(cx.pages, texts, text, cx.info, pending_pick, picked_image, xforms, cx.doc.edit_generation()) +} + +/// The page tool for `chosen` this pass. The placing rule applies first ([`seen_tool`]); Fill & Sign leaves its +/// click's outcome in `fill`, which the caller applies after the run with [`ToolFinish::apply`]. +// PLAN: the sheet's `page_tool(tool, cx)` cannot lend the per-pass text layers and transforms the tools borrow (they +// would borrow locals of this function) nor Fill & Sign's outcome slot (forms-w5 decided `&'a mut Option`); +// pdf-canvas-w8 owns `bench` and `fill` beside the call, and reads `fill` after the tool is dropped. +pub(crate) fn page_tool<'a>( + chosen: QuickTool, + cx: PageToolCx<'a>, + session: &'a mut PageSession, + bench: &'a mut ToolBench<'a>, + fill: &'a mut Option, +) -> PageTool<'a> { + let tool = seen_tool(session, chosen); + let ToolBench { texts: texts_slot, xforms } = bench; + let sizes = cx.sizes; + let size = move |page: usize| sizes.get(page).copied().unwrap_or_default(); + *xforms = cx.pages.iter().map(|placed| (placed.page, PageXform::of(placed, cx.rotation, size(placed.page)))).collect(); + let xforms: &'a [(usize, PageXform)] = xforms; + let selects_text = tool_selects_text(tool, cx.preparing); + let arm = match tool { + // Prepare a form under the Select tool: the selection rectangle and the moves of fields are Prepare's. + QuickTool::Select if cx.preparing => Arm::Area(Box::new(PrepareTool::new(None, cx.can_modify, cx.form, session))), + 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); + match tool { + QuickTool::ColumnSelect => Arm::Select(select.column(true)), + QuickTool::Redact => { + // PLAN: assumed `RedactTool::new(select, pages, rotation, info, allowed)` (forms-w13 gives no list). + Arm::Redact(RedactTool::new(select, cx.pages, cx.rotation, cx.info, cx.can_modify)) + } + // Select runs the comments tool too: a hanging paste is placed by its press, and a press no comment + // part took goes on to the text. + // PLAN: assumed `CommentsTool::new(&mut AnnotateTool, Option<&mut PastePlacement>, PageMap, &mut bool)` + // and `.text(PageSelectTool)` (comments-w8 names the fields, not the constructor). + _ => { + let view = &mut session.comments; + let map = comments::bridge::PageMap::new(cx.info, cx.pages, cx.rotation); + let annotate = CommentsTool::new(&mut view.tool, view.paste.as_mut(), map, &mut view.tool_done); + let annotate = if selects_text { annotate.text(select) } else { annotate }; + Arm::Area(Box::new(annotate)) + } + } + } + QuickTool::Hand => Arm::Hand(HandTool::new(cx.navigation)), + QuickTool::MarqueeZoom => { + let mut options = cx.navigation; + options.scrubby_zoom = false; + Arm::MarqueeZoom(ZoomTool::new(options)) + } + QuickTool::Measure(t) => { + Arm::Measure(MeasureTool::new(&mut session.measure, cx.doc, cx.pages, cx.info, t, cx.units, cx.host, cx.wake.clone())) + } + QuickTool::Crop => Arm::Crop(CropTool::new(cx.can_crop, cx.pages, cx.rotation, size)), + QuickTool::EnhanceCamera => Arm::Camera(CameraTool::new(cx.can_modify, cx.pages)), + QuickTool::Fill(fill_tool) => { + let input = FillInput { + tool: fill_tool, + text_size: cx.fill.text_size, + text_color: cx.fill.text_color, + text_border: cx.fill.text_border, + signature: cx.fill.signature, + initials: cx.fill.initials, + author: cx.author, + date_text: cx.date_text, + fill_text: &mut session.fill_text, + comments: &mut session.comments, + }; + Arm::Area(Box::new(FillSignTool::new(&cx, input, fill))) + } + QuickTool::Field(field_tool) => { + Arm::Area(Box::new(PrepareTool::new(Some(field_tool), cx.can_modify, cx.form, session))) + } + // PLAN: assumed `AddTextTool::new(session, doc, info)` in `content_ui` (pdf-edit-w7 gives no argument list). + QuickTool::AddText => Arm::Area(Box::new(crate::tools::content_ui::AddTextTool::new(session, cx.doc, cx.info))), + // PLAN: pdf-edit-w10's `EditTextTool::new(view, doc, info)` takes no placed pages, which the review asked to hand over. + QuickTool::EditText => Arm::Area(Box::new(EditTextTool::new(session, cx.doc, cx.info))), + QuickTool::Stamp(kind) => { + Arm::Stamp(StampTool::new(StampChoice::Builtin(kind), cx.by_line.to_owned(), None, cx.author.to_owned(), cx.pages, cx.info)) + } + QuickTool::CustomStamp(_) => match cx.custom_stamp { + Some((stamp, line)) => Arm::Stamp(StampTool::new( + StampChoice::Custom(stamp.clone()), + cx.by_line.to_owned(), + line.map(str::to_owned), + cx.author.to_owned(), + cx.pages, + cx.info, + )), + // The library no longer holds the stamp: no click places one, and a drag pans as the Hand tool's. + None => Arm::Hand(HandTool::new(cx.navigation)), + }, + // PLAN: assumed `LinkTool::new(session, doc, info, can_modify)` (pdf-edit-w11 gives `new(view, ..)`). + QuickTool::Link => Arm::Area(Box::new(LinkTool::new(session, cx.doc, cx.info, cx.can_modify))), + QuickTool::SignArea { certify } => Arm::SignArea(SignAreaTool::new(certify)), + QuickTool::Snapshot => Arm::Snapshot(SnapshotTool::new(cx.pages, cx.rotation, size)), + }; + PageTool { arm, tool, selects_text, released: false, presenting: cx.presenting, presenter_keys: Vec::new() } +} + +impl<'a> PageTool<'a> { + fn tool(&self) -> &(dyn CanvasTool + 'a) { + match &self.arm { + Arm::Select(t) => t, + Arm::Hand(t) => t, + Arm::MarqueeZoom(t) => t, + Arm::Area(t) => &**t, + Arm::Camera(t) => t, + Arm::Measure(t) => t, + Arm::Stamp(t) => t, + Arm::Redact(t) => t, + Arm::SignArea(t) => t, + Arm::Snapshot(t) => t, + Arm::Crop(t) => t, + } + } + + fn tool_mut(&mut self) -> &mut (dyn CanvasTool + 'a) { + match &mut self.arm { + Arm::Select(t) => t, + Arm::Hand(t) => t, + Arm::MarqueeZoom(t) => t, + Arm::Area(t) => &mut **t, + Arm::Camera(t) => t, + Arm::Measure(t) => t, + Arm::Stamp(t) => t, + Arm::Redact(t) => t, + Arm::SignArea(t) => t, + Arm::Snapshot(t) => t, + Arm::Crop(t) => t, + } + } + + /// What the tool finished in this pass, read after the tool host ran it; the tool's borrows of the session end + /// here. + // PLAN: assumed result readers `MeasureTool::take_edit`, `StampTool::take_placed`, `RedactTool::finished`, + // `SignAreaTool::finished` (the owning sheets name the results, not every reader's name). + pub(crate) fn finish(self) -> ToolFinish { + let mut finish = ToolFinish { + presenter_keys: self.presenter_keys, + text_tool: Some(self.tool).filter(|_| self.selects_text), + text_finished: self.released && self.selects_text, + ..ToolFinish::default() + }; + match self.arm { + Arm::Camera(tool) => finish.camera_page = tool.moved_to(), + Arm::Measure(mut tool) => finish.edit = tool.take_edit(), + Arm::Stamp(mut tool) => { + finish.edit = tool.take_placed(); + finish.back_to_select = finish.edit.is_some(); + } + Arm::Redact(mut tool) => finish.redaction = tool.finished(), + Arm::SignArea(mut tool) => finish.sign_drawn = tool.finished(), + Arm::Snapshot(mut tool) => finish.snapshot = tool.take_result(), + Arm::Crop(mut tool) => { + finish.crop = tool.take_result(); + finish.back_to_select = finish.crop.is_some(); + finish.open_boxes = tool.take_open_boxes(); + } + Arm::Select(_) | Arm::Hand(_) | Arm::MarqueeZoom(_) | Arm::Area(_) => {} + } + finish + } +} + +impl ToolFinish { + /// Applies what the tool finished to the session: its edit, the camera quadrilateral's new page, the signature + /// rectangle, the redaction marks, Fill & Sign's `fill` outcome and the presenter's keys; and, under a tool that + /// selects text, the comments' follow-up of the selection on every placed page (comments-w8 decision: every pass, + /// with `finished` only in the pass of the release). + pub(crate) fn apply(&mut self, fill: Option, session: &mut PageSession, cx: &PageToolCx<'_>) { + if let Some(edit) = self.edit.take() { + session.pending_edit = Some(edit); + } + if let Some(page) = self.camera_page.take() + && let Some(placed) = cx.pages.iter().find(|placed| placed.page == page) + { + // PLAN: assumed `camera_ui::page_points` made `pub(crate)` (pdf-print-ocr-w10), the one rule for a placed + // page's size in view points. + let (w, h) = crate::tools::camera_ui::page_points(placed); + session.camera = Some(CameraQuad::inset(page, w, h)); + } + if let Some(drawn) = self.sign_drawn.take() { + session.sign.drawn = Some(drawn); + } + match self.redaction.take() { + Some(RedactResult::Marks(marks, page)) => session.pending_redaction = Some((QuickTool::Redact, marks, page)), + Some(RedactResult::Refused) => session.redaction_refused = true, + None => {} + } + match fill { + Some(FillOutcome::Edit(edit)) => session.pending_edit = Some(*edit), + // PLAN: forms-w5's `FillOutcome::Signature(Box)` carries no page, which `fill_signature_page` needs + // (production set the clicked page); assumed `Signature(Box, usize)`. + Some(FillOutcome::Signature(edit, page)) => { + session.pending_edit = Some(*edit); + session.fill_signature_page = Some(page); + } + Some(FillOutcome::CreateSignature) => self.open_signature = Some(false), + Some(FillOutcome::CreateInitials) => self.open_signature = Some(true), + Some(FillOutcome::Refused(why)) => self.refused = Some(why), + None => {} + } + for key in self.presenter_keys.drain(..) { + // PLAN: assumed `Presenter::key(&mut self, &ToolKey)` (pdf-canvas-w18 names the keys it takes). + session.presenter.key(&key); + } + if let Some(tool @ QuickTool::Comment(_)) = self.text_tool { + for placed in cx.pages { + // PLAN: assumed `comments::PageCx::of(page, info)` for the per-page cx of `page_after_text` (pdf-comments-w8 + // decided `page_after_text(cx: &PageCx, tool, finished, view)` and pdf-comments-w7 rewrites `PageCx`). + let page_cx = comments::PageCx::of(placed.page, cx.info); + comments::page_after_text(&page_cx, tool, self.text_finished, session); + } + } + } +} + +/// A press on an Edit text part: with Shift or Cmd (Ctrl off macOS) held it adds to or takes from the objects +/// selected together first, whatever lies under it; then the objects and the paragraph frame take their own; then +/// each family its own. +// PLAN: pdf-canvas-w8's `route_press` calls this for the Edit text owners under `QuickTool::EditText`; assumed +// `object_ui::modified_press(..) -> bool` (taken) and `objects_press(session, press)` (pdf-edit-w10 decisions). +pub(crate) fn edit_text_press(session: &mut PageSession, doc: &Document, info: &DocInfo, press: &PagePress) { + let Mods { cmd, shift, .. } = press.mods; + if (shift || cmd) && crate::tools::object_ui::modified_press(session, doc, info, press) { + return; + } + match press.owner { + Owner::Objects | Owner::Frame { .. } => crate::tools::object_ui::objects_press(session, press), + Owner::Paragraph { .. } => crate::tools::edit_text_ui::paragraph_press(session, doc, press), + Owner::Added { .. } => crate::tools::content_ui::added_press(session, doc, press), + Owner::Picture { .. } => crate::tools::edit_text_ui::picture_press(session, doc, press), + Owner::Comment { .. } + | Owner::Link { .. } + | Owner::TextLink { .. } + | Owner::Field { .. } + | Owner::PrepareField { .. } + | Owner::SignTab { .. } => {} + } +} + +impl CanvasTool for PageTool<'_> { + fn each_pass(&mut self, cx: &mut ToolContext<'_>) { + self.released = false; + self.tool_mut().each_pass(cx); + } + + fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction { + self.tool_mut().press(pointer, cx) + } + + fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { + self.tool_mut().drag(pointer, cx); + } + + /// Forwards, and notes the release: a text selection ends in this pass ([`ToolFinish::apply`]). + fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { + self.released = true; + self.tool_mut().release(pointer, cx); + } + + fn hover(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) { + self.tool_mut().hover(pointer, cx); + } + + fn cancel(&mut self, reason: CancelReason, cx: &mut ToolContext<'_>) { + self.tool_mut().cancel(reason, cx); + } + + /// The tool's claims; in full screen the presenter's page keys too. + fn claims(&self) -> ToolClaims { + let claims = self.tool().claims(); + if self.presenting { claims.keys(presenter::PRESENT_KEYS) } else { claims } + } + + fn regions(&self) -> Vec { + self.tool().regions() + } + + /// In full screen the presenter's keys and Enter are the presenter's, applied after the run; every other key is + /// the tool's. + fn key(&mut self, key: &ToolKey, cx: &mut ToolContext<'_>) -> bool { + if self.presenting + && match key { + ToolKey::Kept(chord) => presenter::PRESENT_KEYS.contains(chord), + ToolKey::Submit => true, + _ => false, + } + { + self.presenter_keys.push(key.clone()); + return true; + } + self.tool_mut().key(key, cx) + } + + fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) { + self.tool().paint(draw, cx); + } + + fn cursor(&self, cx: &ToolContext<'_>) -> Cursor { + self.tool().cursor(cx) + } + + fn takes(&self, button: PointerButton, mods: Mods) -> bool { + self.tool().takes(button, mods) + } + + fn autoscrolls(&self) -> bool { + self.tool().autoscrolls() + } + + fn autoscrolls_on_hover(&self) -> bool { + self.tool().autoscrolls_on_hover() + } + + fn view_only(&self) -> bool { + self.tool().view_only() + } + + fn takes_every_move(&self) -> bool { + self.tool().takes_every_move() + } + + fn access(&self, cx: &ToolContext<'_>) -> Option { + self.tool().access(cx) + } + + fn command_form(&self) -> ToolPath { + self.tool().command_form() + } +} diff --git a/crates/ui-egui/tests/it/pointer.rs b/crates/ui-egui/tests/it/pointer.rs index 3b3532d98e..f8972b028b 100644 --- a/crates/ui-egui/tests/it/pointer.rs +++ b/crates/ui-egui/tests/it/pointer.rs @@ -1,19 +1,20 @@ -//! What the page's tools see of the pointer. A finger tap, a touch drag and a click whose press -//! and release share a frame act as a mouse click and drag do, and nothing drawn over the page (a -//! dialog, the palette, the quick bar, the chrome over a page scrolled under it) lets the page's -//! cursor, tips or presses through. -//! -//! The ignored tests pin live bugs that later steps of the page pointer router fix: one hit test -//! (step 3), and press-time capture with cancel (step 4). +//! What the page's parts and tools make of the pointer: the cursor and tip over a part promise +//! what a press there does, the part drawn on top takes the press, a click on two touching pages +//! is the first page's, and nothing drawn over the page (a dialog, the palette, the chrome over a +//! page scrolled under it) lets the page's cursor or tips through. +use std::sync::Arc; + +use craft::host::{AppInfo, Host, Wake}; +use craft::platform::clipboard::EventClipboard; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use pdfcraft_engine::StampKind; use pdfcraft_ui_egui::comments::CommentTool; use pdfcraft_ui_egui::fill_sign::FillTool; -use pdfcraft_ui_egui::{Dialog, PdfCraftApp, QuickTool, UnlockPrompt}; +use pdfcraft_ui_egui::{AppServices, PdfCraftApp, QuickTool}; -use crate::support::input::{coalesced_click, double_click, one_frame, touch_drag, touch_tap}; +use crate::support::input::one_frame; /// A PDF of `objects`, numbered from 1 with the catalog first. fn pdf(objects: &[&str]) -> Vec { @@ -148,19 +149,6 @@ fn checkbox_pdf() -> Vec { ]) } -/// A 300×400 page with two unchecked check boxes side by side: `agree` at x 100..120 and -/// `other` at x 120..140, both at y 200..220. -fn two_checkboxes_pdf() -> Vec { - pdf(&[ - "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R] /DA (/ZaDb 0 Tf 0 g) /DR << /Font << /ZaDb 6 0 R >> >> >> >>", - PAGES, - "<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R] >>", - "<< /Type /Annot /Subtype /Widget /FT /Btn /T (agree) /V /Off /AS /Off /Rect [100 200 120 220] /P 3 0 R /F 4 /MK << /CA (4) >> /DA (/ZaDb 11 Tf 0 g) >>", - "<< /Type /Annot /Subtype /Widget /FT /Btn /T (other) /V /Off /AS /Off /Rect [120 200 140 220] /P 3 0 R /F 4 /MK << /CA (4) >> /DA (/ZaDb 11 Tf 0 g) >>", - "<< /Type /Font /Subtype /Type1 /BaseFont /ZapfDingbats >>", - ]) -} - /// The check box `agree` of [`checkbox_pdf`], with a highlight drawn over it. fn highlighted_checkbox_pdf() -> Vec { pdf(&[ @@ -173,21 +161,24 @@ fn highlighted_checkbox_pdf() -> Vec { ]) } -/// A 300×400 page with a push button at x 100..200, y 200..220 whose action opens a web address. -fn button_pdf() -> Vec { - pdf(&[ - "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DA (/Helv 0 Tf 0 g) >> >>", - PAGES, - "<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>", - "<< /Type /Annot /Subtype /Widget /FT /Btn /Ff 65536 /T (web) /Rect [100 200 200 220] /P 3 0 R /A << /S /URI /URI (https://example.org/) >> >>", - ]) +/// The services a pointer test gives the app: no wake-ups, a clipboard fed by paste events (a +/// paste arrives in the pass that reads it, so its pass clock never needs to move) whose copies go +/// nowhere, a recovery folder of the test process's own, and no update source. +// PLAN: assumed `AppServices::new(wake, clipboard, recovery_dir, update_source, intake, watch)` (L-207). +fn services() -> AppServices { + let clipboard = EventClipboard::new(|| 0, |_| Ok(0)); + let recovery = std::env::temp_dir().join(format!("pdfcraft-pointer-{}", std::process::id())); + let (intake, _sender) = craft::platform::open::FileIntake::new(Wake::none()); + let watch = craft::platform::watch::FileWatch::new(Wake::none()).inline(); + AppServices::new(Wake::none(), clipboard, recovery, None, intake, watch) } /// The app with `pdf` open at `zoom` percent and its first frames run. The left panel stays /// open only where a test places the page relative to the window's chrome. fn open(pdf: Vec, zoom: &'static str, left_open: bool) -> Harness<'static, PdfCraftApp> { let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); + let host = Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "test" }).build(); + let mut app = PdfCraftApp::with_host(Arc::new(host), services()); app.set_option("language", "en").unwrap(); app.open_bytes("test.pdf", None, pdf).unwrap(); if !left_open { @@ -422,7 +413,7 @@ fn a_click_on_stacked_comments_selects_the_one_drawn_on_top() { h.run_steps(2); assert!(tip_says(&h, "Top note") && !tip_says(&h, "Bottom note"), "the tip names the comment drawn on top"); mouse_click(&mut h, overlap); - assert_eq!(h.state().views[0].comments.selected, Some((0, 1)), "a click selects it too"); + assert_eq!(h.state().views[0].comments.primary(), Some((0, 1)), "a click selects it too"); } #[test] @@ -494,25 +485,6 @@ fn a_paragraph_edge_resizes_wherever_it_shows_the_resize_cursor() { // --------------------------------------------------------------------------------------------- // Things drawn over the page keep the page's cursor, tips and presses off. -/// Check that the command palette's frame keeps the default cursor over the page while the page beside it -/// still shows the stamp tool. -#[test] -fn stamp_cursor_stays_off_the_command_palette() { - let mut h = open(link_pdf(), "300", false); - stamp_tool(&mut h); - h.state_mut().palette_open = true; - h.run_steps(4); - let palette = h.ctx.memory(|m| m.area_rect(egui::Id::unique("palette"))).expect("palette shown"); - // On the palette's frame margin, where none of its widgets sets a cursor, over the page. - let p = egui::pos2(palette.left() + 4.0, palette.bottom() - 4.0); - assert!(page(&h).contains(p), "the palette must lie over the page here"); - assert_eq!(cursor_at(&mut h, p), egui::CursorIcon::Default); - // The page beside the palette still shows the tool. - let beside = egui::pos2(palette.left() + 4.0, palette.bottom() + 40.0); - assert!(page(&h).contains(beside)); - assert_eq!(cursor_at(&mut h, beside), egui::CursorIcon::Crosshair); -} - /// A link beside the open palette shows no tip: tips draw above the palette. #[test] fn link_tip_stays_off_while_the_palette_is_open() { @@ -535,277 +507,29 @@ fn link_tip_stays_off_while_the_palette_is_open() { h.get_by_label("https://example.org/"); } -/// A panel's resize edge dragged over a link shows neither the link's tip nor its cursor, and the -/// link answers again once the edge is let go. -#[test] -fn a_dragged_panel_edge_passes_over_a_link_without_its_tip() { - use egui::accesskit::Role; - use egui_kittest::kittest::Queryable; - let mut h = open(link_pdf(), "150", false); - h.state_mut().set_option("panel", "comments").unwrap(); - for _ in 0..4 { - h.run_steps(2); - } - let on_link = at(&h, 100.0, 340.0); - assert_eq!(cursor_at(&mut h, on_link), egui::CursorIcon::PointingHand); - h.run_steps(2); - assert!(tip_shown(&h), "the link's tip shows over an uncovered page"); - // Away from the link, then the side panel's resize edge (the rightmost one) is picked up and - // carried over it. - h.hover_at(at(&h, 150.0, 100.0)); - h.run_steps(4); - let tab = h - .get_all_by(|n| n.role() == Role::Splitter && n.label().as_deref() == Some("Resize panels")) - .map(|n| n.rect().center()) - .max_by(|a, b| a.x.total_cmp(&b.x)) - .expect("the side panel has a resize edge") - // The pane's half of the edge: the page, drawn after the panes, takes the other half. - + egui::vec2(2.0, 0.0); - h.hover_at(tab); - h.run_steps(1); - h.drag_at(tab); - h.run_steps(1); - for i in 1..=8 { - h.hover_at(tab + (on_link - tab) * (i as f32 / 8.0)); - h.run_steps(1); - } - for _ in 0..4 { - h.run_steps(2); - assert!(h.ctx.dragged_id().is_some(), "the edge is still being dragged"); - assert!(!tip_shown(&h), "no link tip under a dragged panel edge"); - assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand); - } - // Back to the start and let go there, which leaves the width as it was. - for i in 1..=8 { - h.hover_at(on_link + (tab - on_link) * (i as f32 / 8.0)); - h.run_steps(1); - } - h.drop_at(tab); - h.run_steps(2); - assert!(h.ctx.dragged_id().is_none()); - assert_eq!(cursor_at(&mut h, on_link), egui::CursorIcon::PointingHand, "the link answers again"); - h.run_steps(2); - assert!(tip_shown(&h), "and shows its tip"); -} - -/// Send one wheel event over the page and let its scrolling settle. -fn wheel(h: &mut Harness<'_, PdfCraftApp>, delta: egui::Vec2) { - h.hover_at(egui::pos2(800.0, 500.0)); - h.event(egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta, - modifiers: egui::Modifiers::NONE, - phase: egui::TouchPhase::Move, - source: egui::MouseWheelSource::Unknown, - }); - for _ in 0..10 { - h.run_steps(2); - } -} - -/// Check that the quick bar's frame keeps the default cursor over the page while the page below it still -/// shows the stamp tool. -#[test] -fn stamp_cursor_stays_off_the_quick_bar() { - let mut h = open(link_pdf(), "400", true); - stamp_tool(&mut h); - // Bring the page under the quick bar's left end. - wheel(&mut h, egui::vec2(-200.0, 0.0)); - let bar = h.ctx.memory(|m| m.area_rect(egui::Id::unique("quick-bar"))).expect("quick bar shown"); - // Inside the bar's frame margin: no button there. - let p = egui::pos2(bar.left() + 3.0, bar.bottom() - 3.0); - assert!(page(&h).contains(p), "the quick bar must lie over the page here"); - assert_eq!(cursor_at(&mut h, p), egui::CursorIcon::Default); - let below = egui::pos2(bar.left() + 3.0, bar.bottom() + 20.0); - assert!(page(&h).contains(below)); - assert_eq!(cursor_at(&mut h, below), egui::CursorIcon::Crosshair); -} - -#[test] -fn stamp_cursor_stays_off_the_chrome_above_a_page_scrolled_under_it() { - let mut h = open(link_pdf(), "400", true); - stamp_tool(&mut h); - let top = page(&h).top(); - wheel(&mut h, egui::vec2(0.0, -300.0)); - let page = page(&h); - // Above where the page started (the viewport's top edge, give or take its margin): the - // toolbar, with the page scrolled up under it. Left of the link, which shows the hand. - let x = page.left() + 20.0; - let p = egui::pos2(x, top - 45.0); - assert!(page.contains(p), "the page must extend under the chrome here"); - // The toolbar keeps its own cursor (a button's hand here); the page's is gone. - assert_ne!(cursor_at(&mut h, p), egui::CursorIcon::Crosshair); - assert_eq!(cursor_at(&mut h, egui::pos2(x, top + 40.0)), egui::CursorIcon::Crosshair); -} - /// Whether the page's hover tip was drawn in the last frame. fn tip_shown(h: &Harness<'_, PdfCraftApp>) -> bool { let tip = egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("canvas-hover")); h.ctx.memory(|m| m.areas().is_visible(&tip)) } -/// Opens the Unlock prompt, a dialog with a backdrop over the whole window, from the next frame. -fn open_unlock_prompt(h: &mut Harness<'_, PdfCraftApp>) { - let doc = h.state().views[0].id; - h.state_mut().unlock_prompt = Some(UnlockPrompt { doc, name: "test.pdf".into(), input: String::new(), error: None, then: None }); -} - -/// Check that the link tip and pointing cursor disappear under the Unlock prompt. -#[test] -fn link_tip_stays_under_the_unlock_prompt() { - let mut h = open(link_pdf(), "300", true); - let page = page(&h); - let k = page.width() / 300.0; - // Near the link's top left corner, clear of the prompt's card in the middle of the window. - let on_link = page.min + egui::vec2(55.0 * k, (400.0 - 345.0) * k); - assert_eq!(cursor_at(&mut h, on_link), egui::CursorIcon::PointingHand); - h.run_steps(2); - assert!(tip_shown(&h), "the link's tip shows over an uncovered page"); - - open_unlock_prompt(&mut h); - h.hover_at(on_link + egui::vec2(1.0, 0.0)); - for _ in 0..4 { - h.run_steps(2); - } - let card = h.ctx.memory(|m| m.area_rect(egui::Id::unique("unlock"))); - assert!(card.is_none_or(|c| !c.contains(on_link)), "the point must be on the backdrop, not the card: {card:?}"); - assert!(!tip_shown(&h), "the link's tip must not float over the Unlock prompt"); - assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand); -} - -/// Check that moving onto a link's floating tip still reports the link's pointing-hand cursor. -#[test] -fn the_link_tip_lets_the_pointer_through_to_the_link() { - let mut h = open(link_pdf(), "150", false); - let p = at(&h, 100.0, 340.0); - assert_eq!(cursor_at(&mut h, p), egui::CursorIcon::PointingHand); - let tip = h.ctx.memory(|m| m.area_rect(egui::Id::unique("canvas-hover"))).expect("the link's tip"); - // A quick move lands on the tip, drawn beside where the pointer was, and still on the link. - let onto = tip.min + egui::vec2(6.0, 6.0); - assert!(egui::Rect::from_two_pos(at(&h, 50.0, 350.0), at(&h, 250.0, 300.0)).contains(onto), "the point must be on the link"); - h.hover_at(onto); - h.run_steps(1); - assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand, "the tip must not take the pointer from the link"); -} - -// Dialogs are drawn after the pages, so on the frame one opens egui does not know its layer yet -// and still gives the pages the pointer, and a press there. - -#[test] -fn the_link_tip_stays_under_a_dialog_on_the_frame_it_opens() { - let mut h = open(link_pdf(), "150", false); - let p = at(&h, 100.0, 340.0); - assert_eq!(cursor_at(&mut h, p), egui::CursorIcon::PointingHand); - h.run_steps(2); - assert!(tip_shown(&h), "the link's tip shows over an uncovered page"); - open_unlock_prompt(&mut h); - h.run_steps(1); - assert!(!tip_shown(&h), "the link's tip must not show over the Unlock prompt on the frame it opens"); -} - -#[test] -fn a_click_on_the_frame_a_dialog_opens_places_no_stamp() { - let mut h = open(link_pdf(), "150", false); - stamp_tool(&mut h); - let p = at(&h, 150.0, 150.0); - assert_eq!(cursor_at(&mut h, p), egui::CursorIcon::Crosshair); - open_unlock_prompt(&mut h); - let button = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; - one_frame(&mut h, [button(true), button(false)]); - h.run_steps(4); - assert_eq!(stamps(&h), 0, "a click in the frame the Unlock prompt opens places no stamp under it"); -} - -#[test] -fn a_double_click_on_a_dialog_backdrop_leaves_page_text_alone() { - let mut h = open(text_pdf(), "150", false); - let word = at(&h, 50.0, 303.0); - // The I-beam shows the page's text layer has arrived. - assert_eq!(wait_for_cursor(&mut h, word, |c| c == egui::CursorIcon::Text), egui::CursorIcon::Text, "the page text is live"); - // Control: without a dialog, a double-click there selects the word. - double_click(&mut h, word); - h.run_steps(4); - assert!(h.state().views[0].selected_text().is_some_and(|t| !t.is_empty()), "control: a double-click selects the word"); - // A click on blank page clears it again. - h.run_steps(30); - let p = at(&h, 150.0, 150.0); - mouse_click(&mut h, p); - h.run_steps(30); - assert!(h.state().views[0].selected_text().is_none_or(|t| t.is_empty()), "cleared before the dialog opens"); - h.state_mut().set_option("dialog", "shortcuts").unwrap(); - h.run_steps(6); - assert!(h.state().dialog.is_some(), "a modal dialog is open"); - // On the dialog's backdrop, where the page's first word lies underneath. - double_click(&mut h, word); - h.run_steps(4); - let selected = h.state().views[0].selected_text(); - assert!(selected.as_deref().is_none_or(str::is_empty), "a double-click on a dialog selects nothing on the page under it: {selected:?}"); -} - // --------------------------------------------------------------------------------------------- -// Taps, touch drags and clicks within one frame. On the frame a touch (or a Windows pen) lifts, -// egui-winit has sent `PointerGone`, so there is no hover position; egui still reports the click. +// Clicks on the parts of a page. #[test] fn mouse_click_follows_a_link() { - // Control for the tap below. let mut h = open(link_pdf(), "150", false); let p = at(&h, 150.0, 325.0); mouse_click(&mut h, p); assert!(h.state().pending_link.is_some(), "a click on a link asks to open it"); } -#[test] -fn touch_tap_follows_a_link() { - let mut h = open(link_pdf(), "150", false); - let p = at(&h, 150.0, 325.0); - touch_tap(&mut h, p); - assert!(h.state().pending_link.is_some(), "a tap on a link asks to open it, as a click does"); -} - -#[test] -fn coalesced_click_follows_a_link() { - let mut h = open(link_pdf(), "150", false); - let p = at(&h, 150.0, 325.0); - coalesced_click(&mut h, p); - assert!(h.state().pending_link.is_some(), "a click whose press and release share a frame follows the link"); -} - -#[test] -fn touch_tap_places_a_stamp() { - let mut h = open(link_pdf(), "150", false); - stamp_tool(&mut h); - let p = at(&h, 150.0, 150.0); - touch_tap(&mut h, p); - assert_eq!(stamps(&h), 1, "a tap with the stamp tool places the stamp"); -} - -#[test] -fn coalesced_click_places_a_stamp() { - let mut h = open(link_pdf(), "150", false); - stamp_tool(&mut h); - let p = at(&h, 150.0, 150.0); - coalesced_click(&mut h, p); - assert_eq!(stamps(&h), 1, "a click whose press and release share a frame places the stamp"); -} - /// The value of the field named `name` on the first view's document. fn field_value(h: &Harness<'_, PdfCraftApp>, name: &str) -> Vec { let s = h.state(); s.session.get(s.views[0].id).unwrap().form.iter().find(|f| f.name == name).unwrap().value.clone() } -/// A press belongs to the field it lands on: pressed at the right edge of `agree` and released just -/// over the edge of `other` beside it (a click still, to egui), it ticks neither, as a button -/// pressed and released off itself does nothing. The release used to tick `other`. -#[test] -fn a_press_on_one_check_box_released_over_another_ticks_neither() { - let mut h = open(two_checkboxes_pdf(), "150", false); - let (press, release) = (at(&h, 119.0, 210.0), at(&h, 121.0, 210.0)); - slipping_click(&mut h, press, release); - assert_eq!((field_value(&h, "agree"), field_value(&h, "other")), (Vec::::new(), Vec::new()), "neither box is ticked"); -} - /// A click whose pointer slips from `press` to `release` before the button comes up (a click /// still, to egui, while they are close), in frames of their own as [`mouse_click`] sends them. fn slipping_click(h: &mut Harness<'_, PdfCraftApp>, press: egui::Pos2, release: egui::Pos2) { @@ -817,33 +541,6 @@ fn slipping_click(h: &mut Harness<'_, PdfCraftApp>, press: egui::Pos2, release: h.run_steps(4); } -/// A click follows the link its press was on only when released over it: pressed just inside the -/// link's edge and released just past it, it follows nothing, as a button pressed and released off -/// itself does nothing. The press used to be enough. -#[test] -fn a_press_on_a_link_released_off_it_follows_nothing() { - let mut h = open(link_pdf(), "150", false); - // The link ends at x 250. - let press = at(&h, 249.0, 325.0); - slipping_click(&mut h, press, press + egui::vec2(5.0, 0.0)); - assert_eq!(h.state().pending_link, None, "nothing asks to open the link"); - mouse_click(&mut h, press); - assert!(h.state().pending_link.is_some(), "a click there asks to open it"); -} - -/// The same for a push button: pressed just inside its edge and released just past it, it runs no -/// action. The press used to be enough. -#[test] -fn a_press_on_a_button_released_off_it_runs_nothing() { - let mut h = open(button_pdf(), "150", false); - // The button ends at x 200. - let press = at(&h, 199.0, 210.0); - slipping_click(&mut h, press, press + egui::vec2(5.0, 0.0)); - assert_eq!(h.state().pending_link, None, "the button's action does not run"); - mouse_click(&mut h, press); - assert!(h.state().pending_link.is_some(), "a click there runs it"); -} - /// Text markup lies on the text, under a form field: a click on a check box under a highlight /// ticks the box, and the field's hand shows there. #[test] @@ -853,40 +550,20 @@ fn a_check_box_under_a_highlight_takes_the_click() { assert_eq!(cursor_at(&mut h, p), egui::CursorIcon::PointingHand); mouse_click(&mut h, p); assert_eq!(field_value(&h, "agree"), ["Yes"], "the box is ticked"); - assert_eq!(h.state().views[0].comments.selected, None, "and the highlight is not selected"); + assert_eq!(h.state().views[0].comments.primary(), None, "and the highlight is not selected"); } #[test] fn mouse_click_ticks_a_check_box() { - // Control for the tap below. let mut h = open(checkbox_pdf(), "150", false); let p = at(&h, 110.0, 210.0); mouse_click(&mut h, p); assert_eq!(agree(&h), ["Yes"], "a click ticks the box"); } -#[test] -fn touch_tap_ticks_a_check_box() { - let mut h = open(checkbox_pdf(), "150", false); - let p = at(&h, 110.0, 210.0); - touch_tap(&mut h, p); - assert_eq!(agree(&h), ["Yes"], "a tap ticks the box, as a click does"); -} - -#[test] -fn touch_drag_moves_a_comment_and_leaves_no_gesture_behind() { - let mut h = open(comment_on_text_pdf(), "150", false); - let k = page(&h).width() / 300.0; - let before = square(&h); - // A finger drags the rectangle 30 pt right, from a blank spot inside it. - let from = at(&h, 120.0, 315.0); - touch_drag(&mut h, from, from + egui::vec2(30.0 * k, 0.0)); - let after_touch = square(&h); - assert_ne!(after_touch, before, "the touch drag moves the rectangle"); - // Later, a mouse drag on empty page far below it. - let p = at(&h, 150.0, 100.0); - mouse_drag(&mut h, p, egui::vec2(10.0 * k, 10.0 * k)); - assert_eq!(square(&h), after_touch, "an unrelated drag elsewhere leaves the rectangle where the touch put it"); +/// Whether a signing dialog shows: its title, in the access tree. +fn signing_dialog_shown(h: &Harness<'_, PdfCraftApp>) -> bool { + ["Sign with a Digital ID", "Configure a Digital ID for Signing"].into_iter().any(|title| h.query_by_label(title).is_some()) } // --------------------------------------------------------------------------------------------- @@ -907,9 +584,10 @@ fn escape_cancels_a_signature_rectangle() { // Escape while the button is still held. h.key_press(egui::Key::Escape); h.run_steps(4); - let s = h.state(); - assert_eq!(s.quick_tool, QuickTool::SignArea { certify: false }, "Escape abandons the rectangle; the tool stays"); - assert!(s.dialog.is_none(), "and no signing dialog opens: {:?}", s.dialog); + assert_eq!(h.state().quick_tool, QuickTool::SignArea { certify: false }, "Escape abandons the rectangle; the tool stays"); + h.drop_at(b); + h.run_steps(4); + assert!(!signing_dialog_shown(&h), "and its release opens no signing dialog"); } /// A highlight dragged over the line of [`text_pdf`] at 150 %, from x 45 to x 150, with Escape @@ -963,47 +641,6 @@ fn a_drag_from_beside_the_page_right_after_a_click_leaves_the_comment_alone() { assert_eq!(square(&h), Some(before), "the comment stays where it was"); } -/// Only the primary button draws a signature rectangle: a right-drag opens no signing dialog. -#[test] -fn a_right_drag_draws_no_signature_rectangle() { - let mut h = open(link_pdf(), "150", false); - h.state_mut().quick_tool = QuickTool::SignArea { certify: false }; - h.run_steps(4); - let (a, b) = (at(&h, 60.0, 200.0), at(&h, 200.0, 120.0)); - let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }; - h.hover_at(a); - h.run_steps(1); - h.event(button(a, true)); - h.run_steps(1); - h.hover_at(b); - h.run_steps(2); - h.event(button(b, false)); - h.run_steps(4); - let s = h.state(); - assert_eq!(s.quick_tool, QuickTool::SignArea { certify: false }, "the tool stays: no rectangle was drawn"); - assert!(s.dialog.is_none(), "and no signing dialog opens: {:?}", s.dialog); -} - -/// Escape with the button down drops the press: its release places no stamp, and the next click -/// places one. -#[test] -fn escape_mid_press_keeps_its_release_from_placing_a_stamp() { - let mut h = open(link_pdf(), "150", false); - stamp_tool(&mut h); - let p = at(&h, 150.0, 150.0); - h.hover_at(p); - h.run_steps(1); - h.drag_at(p); - h.run_steps(1); - h.key_press(egui::Key::Escape); - h.run_steps(1); - h.drop_at(p); - h.run_steps(4); - assert_eq!(stamps(&h), 0, "the cancelled press places nothing on release"); - mouse_click(&mut h, p); - assert_eq!(stamps(&h), 1, "the next click places a stamp"); -} - /// Escape mid-drag abandons a crop rectangle: the page keeps its boxes. #[test] fn escape_cancels_a_crop_rectangle() { @@ -1123,9 +760,17 @@ fn a_drag_with_the_link_tool_from_a_link_draws_a_new_link() { link_tool(&mut h); let on_link = at(&h, 150.0, 325.0); mouse_drag(&mut h, on_link, egui::vec2(80.0, 120.0)); + assert!(h.query_by_label("Create Link").is_some(), "Link Properties opens for a new link"); + assert_eq!(confirm_new_link(&mut h), [0, 0], "after OK the page holds its link and the new one"); +} + +/// Clicks OK in the open Link Properties dialog and returns the page of every link the document +/// then holds. +fn confirm_new_link(h: &mut Harness<'_, PdfCraftApp>) -> Vec { + h.get_by_label("OK").click(); + h.run_steps(6); let s = h.state(); - assert_eq!(s.dialog, Some(Dialog::LinkProps)); - assert_eq!(s.link_draft.as_ref().map(|d| d.index), Some(None), "Link Properties opens for a new link"); + s.session.get(s.views[0].id).unwrap().links().iter().map(|link| link.page).collect() } /// With the Select tool a right-click finds a link only where a click follows it: just beside the @@ -1153,7 +798,7 @@ fn a_right_click_on_a_note_over_a_link_opens_the_notes_menu() { let on_note = at(&h, 150.0, 325.0); right_click(&mut h, on_note); let v = &h.state().views[0]; - assert_eq!((v.links.context, v.comments.selected), (None, Some((0, 1))), "the note is selected, not the link"); + assert_eq!((v.links.context, v.comments.primary()), (None, Some((0, 1))), "the note is selected, not the link"); assert!(h.query_by_label("Remove all links").is_none(), "the menu is the note's"); } @@ -1177,7 +822,7 @@ fn a_right_click_on_a_highlight_over_a_link_opens_the_highlights_menu() { let on_both = at(&h, 150.0, 325.0); right_click(&mut h, on_both); let v = &h.state().views[0]; - assert_eq!((v.links.context, v.comments.selected), (None, Some((0, 1))), "the highlight is selected, not the link"); + assert_eq!((v.links.context, v.comments.primary()), (None, Some((0, 1))), "the highlight is selected, not the link"); assert!(h.query_by_label("Remove all links").is_none(), "the menu is the highlight's"); h.key_press(egui::Key::Escape); h.run_steps(3); @@ -1194,7 +839,7 @@ fn a_right_click_on_a_comment_with_a_drawing_tool_opens_its_menu() { h.run_steps(4); let on_comment = at(&h, 100.0, 305.0); right_click(&mut h, on_comment); - assert_eq!(h.state().views[0].comments.selected, Some((0, 0)), "the comment is selected for its menu"); + assert_eq!(h.state().views[0].comments.primary(), Some((0, 0)), "the comment is selected for its menu"); assert!(h.query_all_by_label("Reply").next().is_some(), "and its menu is open"); } @@ -1217,10 +862,10 @@ fn a_click_on_a_form_field_deselects_the_selected_comment() { let mut h = open(comment_and_checkbox_pdf(), "150", false); let comment = at(&h, 200.0, 125.0); mouse_click(&mut h, comment); - assert_eq!(h.state().views[0].comments.selected, Some((0, 1)), "the comment is selected"); + assert_eq!(h.state().views[0].comments.primary(), Some((0, 1)), "the comment is selected"); let check_box = at(&h, 110.0, 210.0); mouse_click(&mut h, check_box); - assert_eq!(h.state().views[0].comments.selected, None, "a click on the check box leaves it unselected"); + assert_eq!(h.state().views[0].comments.primary(), None, "a click on the check box leaves it unselected"); assert_eq!(agree(&h).len(), 1, "and ticks the box"); } @@ -1230,8 +875,8 @@ fn camera_corners(h: &Harness<'_, PdfCraftApp>) -> Option<[[f32; 2]; 4]> { } /// A corner of the camera tool's quadrilateral is a press of its own: Escape in the middle of its -/// drag cancels it, and once the button is up no corner follows the pointer. Today Escape also -/// leaves the camera tool before the pages see it; this holds whatever the order of the keys. +/// drag cancels it, and once the button is up no corner follows the pointer, whatever else Escape +/// does to the tool. #[test] fn escape_mid_corner_drag_leaves_no_corner_following_the_pointer() { let mut h = open(text_pdf(), "150", false); @@ -1258,7 +903,6 @@ fn escape_mid_corner_drag_leaves_no_corner_following_the_pointer() { h.hover_at(corner + egui::vec2(120.0, 90.0)); h.run_steps(3); assert_eq!(camera_corners(&h), after, "no corner follows the pointer once the press is cancelled"); - assert!(h.state().views[0].camera.is_none_or(|q| q.grab.is_none()), "and none is held"); } /// A 300×400 page with a text field `name` (tooltip "Your name") at x 50..250, y 200..220, and a @@ -1304,7 +948,7 @@ fn a_right_click_with_the_link_tool_on_a_note_over_a_link_selects_the_link() { let on_both = at(&h, 150.0, 325.0); right_click(&mut h, on_both); let v = &h.state().views[0]; - assert_eq!((v.links.selected, v.links.context, v.comments.selected), (Some((0, 0)), Some((0, 0)), None), "the link, not the note"); + assert_eq!((v.links.selected, v.links.context, v.comments.primary()), (Some((0, 0)), Some((0, 0)), None), "the link, not the note"); } /// With Add text a right-click leaves comments alone, as before: Add text takes the page's @@ -1317,7 +961,7 @@ fn a_right_click_with_add_text_selects_no_comment() { // Above the line of text the comment covers, where no paragraph is. let on_comment = at(&h, 100.0, 317.0); right_click(&mut h, on_comment); - assert_eq!(h.state().views[0].comments.selected, None, "the comment under the pointer is not selected"); + assert_eq!(h.state().views[0].comments.primary(), None, "the comment under the pointer is not selected"); } /// With the Select tool a right-click finds a link only where a click follows it: a link that @@ -1353,20 +997,6 @@ fn a_right_click_on_a_field_over_a_link_opens_no_link_menu() { assert!(h.query_by_label("Remove all links").is_none()); } -/// While the palette is open, a field beside it still shows its tooltip, as before: the palette -/// keeps the page's own tips away, not egui's tooltip of a field. -#[test] -fn a_fields_tooltip_shows_beside_the_open_palette() { - let mut h = open(commented_text_field_pdf(), "150", false); - h.state_mut().palette_open = true; - h.run_steps(4); - let palette = h.ctx.memory(|m| m.area_rect(egui::Id::unique("palette"))).expect("palette shown"); - let on_field = at(&h, 60.0, 210.0); - assert!(!palette.expand(20.0).contains(on_field), "the field is beside the palette {palette:?}"); - rest_at(&mut h, on_field); - assert!(h.query_all_by_label("Your name").next().is_some(), "the field's tooltip shows"); -} - /// Two blank 300×400 pages. fn two_pages_pdf() -> Vec { pdf(&[ @@ -1413,8 +1043,9 @@ fn a_redaction_box_dragged_off_its_page_is_drawn_on_it() { #[test] fn a_link_rectangle_dragged_off_its_page_is_drawn_on_it() { - let h = drag_seen_only_past_page_ones_edge(|app| app.quick_tool = QuickTool::Link); - assert_eq!(h.state().link_draft.as_ref().map(|d| (d.page, d.index)), Some((0, None)), "a new link on page 1"); + let mut h = drag_seen_only_past_page_ones_edge(|app| app.quick_tool = QuickTool::Link); + assert!(h.query_by_label("Create Link").is_some(), "Link Properties opens for a new link"); + assert_eq!(confirm_new_link(&mut h), [0], "after OK the new link is on page 1"); } #[test] @@ -1432,13 +1063,13 @@ fn a_right_click_with_the_link_tool_on_a_link_keeps_the_selected_comment() { let mut h = open(note_over_link_pdf(), "150", false); let on_note = at(&h, 150.0, 325.0); mouse_click(&mut h, on_note); - assert_eq!(h.state().views[0].comments.selected, Some((0, 1)), "the note is selected"); + assert_eq!(h.state().views[0].comments.primary(), Some((0, 1)), "the note is selected"); link_tool(&mut h); // On the link, away from the note. let on_link = at(&h, 70.0, 325.0); right_click(&mut h, on_link); let v = &h.state().views[0]; - assert_eq!((v.links.context, v.comments.selected), (Some((0, 0)), Some((0, 1))), "the link's menu; the note stays selected"); + assert_eq!((v.links.context, v.comments.primary()), (Some((0, 0)), Some((0, 1))), "the link's menu; the note stays selected"); } /// A 300×400 page with a rectangle comment round the camera tool's first corner (view 15, 20). @@ -1460,115 +1091,7 @@ fn a_right_click_on_a_comment_under_a_camera_corner_opens_the_comments_menu() { h.run_steps(4); let corner = at(&h, 15.0, 380.0); right_click(&mut h, corner); - assert_eq!(h.state().views[0].comments.selected, Some((0, 0)), "the comment is selected for its menu"); -} - -/// A right-button drag from `a` to `b`, in frames of their own. -fn right_drag(h: &mut Harness<'_, PdfCraftApp>, a: egui::Pos2, b: egui::Pos2) { - let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }; - h.hover_at(a); - h.run_steps(1); - h.event(button(a, true)); - h.run_steps(1); - for k in 1..=4 { - h.hover_at(a + (b - a) * (k as f32 / 4.0)); - h.run_steps(1); - } - h.event(button(b, false)); - h.run_steps(3); -} - -// A right-button drag starts nothing a left-button drag does. egui's drag start counts every -// button, and each of these started on it. - -/// With the Rectangle tool, a right-button drag draws no rectangle. -#[test] -fn a_right_button_drag_draws_no_rectangle() { - let mut h = open(text_pdf(), "150", false); - h.state_mut().quick_tool = QuickTool::Comment(CommentTool::Rectangle); - h.run_steps(4); - let (a, b) = (at(&h, 60.0, 150.0), at(&h, 200.0, 80.0)); - right_drag(&mut h, a, b); - let s = h.state(); - assert!(s.session.get(s.views[0].id).unwrap().info.annotations.is_empty(), "no rectangle is drawn"); -} - -/// With Prepare open, a right-button drag around a field selects it by no selection rectangle. -#[test] -fn a_right_button_drag_selects_no_field() { - let mut h = open(comment_and_checkbox_pdf(), "150", false); - assert!(h.state_mut().execute("form.prepare")); - h.run_steps(4); - let (a, b) = (at(&h, 60.0, 250.0), at(&h, 140.0, 180.0)); - right_drag(&mut h, a, b); - assert!(h.state().views[0].prepare.selected.is_none(), "no field is selected"); -} - -/// With the Link tool, a right-button drag draws no link. -#[test] -fn a_right_button_drag_draws_no_link() { - let mut h = open(text_pdf(), "150", false); - link_tool(&mut h); - let (a, b) = (at(&h, 60.0, 150.0), at(&h, 200.0, 80.0)); - right_drag(&mut h, a, b); - assert!(h.state().link_draft.is_none() && h.state().dialog != Some(Dialog::LinkProps), "no link is drawn"); -} - -/// With the camera, a right-button drag on another page leaves the quadrilateral where it is. -#[test] -fn a_right_button_drag_leaves_the_camera_quadrilateral() { - let mut h = open(two_pages_pdf(), "100", false); - h.state_mut().quick_tool = QuickTool::EnhanceCamera; - h.run_steps(4); - assert_eq!(h.state().views[0].camera.as_ref().map(|q| q.page), Some(0)); - let two = h.state().views[0].page_screen_rect(1).expect("page 2 on screen"); - right_drag(&mut h, two.min + egui::vec2(40.0, 40.0), two.min + egui::vec2(120.0, 100.0)); - assert_eq!(h.state().views[0].camera.as_ref().map(|q| q.page), Some(0), "the quadrilateral stays on page 1"); -} - -/// A text selection, then `tool` and a right-button drag across more of the line. The harness, and -/// the text selected before the drag. -fn right_drag_over_a_selection(tool: QuickTool) -> (Harness<'static, PdfCraftApp>, Option) { - let mut h = open(text_pdf(), "150", false); - let (a, b) = (at(&h, 45.0, 303.0), at(&h, 120.0, 303.0)); - assert_eq!(wait_for_cursor(&mut h, a, |c| c == egui::CursorIcon::Text), egui::CursorIcon::Text, "the page's text has arrived"); - mouse_drag(&mut h, a, b - a); - let selected = h.state().views[0].selected_text(); - assert!(selected.is_some(), "some text is selected"); - h.state_mut().quick_tool = tool; - h.run_steps(2); - let (c, d) = (at(&h, 150.0, 303.0), at(&h, 230.0, 303.0)); - right_drag(&mut h, c, d); - (h, selected) -} - -/// With the Select tool, a right-button drag leaves the text selected as it is. It moved the -/// selection's end to the pointer. -#[test] -fn a_right_button_drag_leaves_a_text_selection_alone() { - let (h, selected) = right_drag_over_a_selection(QuickTool::Select); - assert_eq!(h.state().views[0].selected_text(), selected, "the selection stays as it was"); -} - -/// A right-button drag with a markup tool or Redact turns no selection left from another tool into -/// a comment: its end finished the selection whichever button it was. -#[test] -fn a_right_button_drag_makes_no_mark_of_a_text_selection() { - for tool in [QuickTool::Comment(CommentTool::Highlight), QuickTool::Redact] { - let (h, _) = right_drag_over_a_selection(tool); - let s = h.state(); - assert!(s.session.get(s.views[0].id).unwrap().info.annotations.is_empty(), "no mark with {tool:?}"); - } -} - -/// With the Select tool, a right-button drag across text selects none. -#[test] -fn a_right_button_drag_selects_no_text() { - let mut h = open(text_pdf(), "150", false); - let (a, b) = (at(&h, 45.0, 303.0), at(&h, 200.0, 303.0)); - assert_eq!(wait_for_cursor(&mut h, a, |c| c == egui::CursorIcon::Text), egui::CursorIcon::Text, "the page's text has arrived"); - right_drag(&mut h, a, b); - assert!(h.state().views[0].selected_text().is_none(), "no text is selected"); + assert_eq!(h.state().views[0].comments.primary(), Some((0, 0)), "the comment is selected for its menu"); } /// A 300×400 page with a web link along its left edge, x 0..100, y 300..350. @@ -1606,13 +1129,13 @@ fn a_right_click_with_edit_text_on_a_paragraph_under_a_comment_selects_the_comme let on_text = at(&h, 100.0, 303.0); wait_for_cursor(&mut h, on_text, |c| c != egui::CursorIcon::Default); right_click(&mut h, on_text); - assert_eq!(h.state().views[0].comments.selected, Some((0, 0)), "the comment over the paragraph is selected"); + assert_eq!(h.state().views[0].comments.primary(), Some((0, 0)), "the comment over the paragraph is selected"); assert!(h.query_by_label("Properties…").is_some(), "its menu opens"); assert_eq!(h.state().views[0].comments.context_at.map(|(page, _)| page), Some(0), "the menu is anchored on the page"); // The rectangle ends at x 200; the line goes on. let beside = at(&h, 230.0, 303.0); right_click(&mut h, beside); - assert_eq!(h.state().views[0].comments.selected, None, "the paragraph beside the comment leaves it unselected"); + assert_eq!(h.state().views[0].comments.primary(), None, "the paragraph beside the comment leaves it unselected"); } /// With Edit text, a right-click on added text over a comment selects no comment: what has no menu @@ -1628,7 +1151,7 @@ fn a_right_click_with_edit_text_on_added_text_over_a_comment_selects_no_comment( h.run_steps(4); let on_added = at(&h, 150.0, 303.0); right_click(&mut h, on_added); - assert_eq!(h.state().views[0].comments.selected, None, "the comment under the added text is not selected"); + assert_eq!(h.state().views[0].comments.primary(), None, "the comment under the added text is not selected"); } /// With a Prepare field tool a right-click is the tool's, as before: a comment under it is not @@ -1640,7 +1163,7 @@ fn a_right_click_with_a_field_tool_selects_no_comment() { h.run_steps(4); let on_comment = at(&h, 200.0, 125.0); right_click(&mut h, on_comment); - assert_eq!(h.state().views[0].comments.selected, None); + assert_eq!(h.state().views[0].comments.primary(), None); } /// With the Link tool a click that began off the page (in the gutter beside it) is no page's: the @@ -1679,7 +1202,7 @@ fn a_right_click_during_a_comment_move_keeps_the_moved_comment_selected() { h.run_steps(1); h.drop_at(end); h.run_steps(3); - assert_eq!(h.state().views[0].comments.selected, Some((0, 0)), "the moved comment stays selected"); + assert_eq!(h.state().views[0].comments.primary(), Some((0, 0)), "the moved comment stays selected"); } /// A click on added text leaves the selected comment unselected, as a click on a form field does @@ -1698,45 +1221,32 @@ fn a_click_on_added_text_deselects_the_selected_comment() { h.run_steps(3); let on_comment = at(&h, 150.0, 315.0); mouse_click(&mut h, on_comment); - assert_eq!(h.state().views[0].comments.selected, Some((0, 0)), "the comment is selected"); + assert_eq!(h.state().views[0].comments.primary(), Some((0, 0)), "the comment is selected"); let on_added = at(&h, 90.0, 202.0); mouse_click(&mut h, on_added); - assert_eq!(h.state().views[0].comments.selected, None, "a click on the added text leaves it unselected"); + assert_eq!(h.state().views[0].comments.primary(), None, "a click on the added text leaves it unselected"); } -/// A comment gesture left over with no button down (a release the pages never saw) does not keep -/// a right-click from selecting the comment under it. +/// A comment move made halfway and let go beside the page leaves nothing held: the next +/// right-click selects the comment under it, not the one that was being moved. #[test] fn a_right_click_selects_its_comment_though_a_gesture_was_left_over() { let mut h = open(stacked_comments_pdf(), "150", false); - let bottom = at(&h, 60.0, 160.0); - h.state_mut().views[0].comments.gesture = Some(pdfcraft_ui_egui::comments::Gesture::Move { page: 0, index: 0, from: bottom }); - let top = at(&h, 190.0, 290.0); + // "Bottom note" alone, then "Top note" alone. + let (bottom, top) = (at(&h, 60.0, 160.0), at(&h, 190.0, 290.0)); + let beside = page(&h).left_center() - egui::vec2(20.0, 0.0); + h.hover_at(bottom); + h.run_steps(1); + h.drag_at(bottom); + h.run_steps(1); + h.hover_at(bottom + egui::vec2(0.0, 20.0)); + h.run_steps(1); + h.hover_at(beside); + h.run_steps(1); + h.drop_at(beside); + h.run_steps(3); right_click(&mut h, top); - assert_eq!(h.state().views[0].comments.selected, Some((0, 1)), "the note under the right-click is selected"); -} - -/// A comment's move ends once its button is up, though the pages missed its release, and applies -/// nothing: where it came up is not known, and the pointer has moved on. A drag elsewhere later moves -/// nothing either. The move waited for the next drag's end on the page, and took the comment there. -#[test] -fn a_comment_move_whose_release_the_pages_missed_ends_once_the_button_is_up() { - let mut h = open(stacked_comments_pdf(), "150", false); - let rect = |h: &Harness<'_, PdfCraftApp>| { - let s = h.state(); - s.session.get(s.views[0].id).unwrap().info.annotations.iter().find(|a| a.index == 0).map(|a| a.rect) - }; - let before = rect(&h); - let bottom = at(&h, 60.0, 160.0); - h.state_mut().views[0].comments.gesture = Some(pdfcraft_ui_egui::comments::Gesture::Move { page: 0, index: 0, from: bottom }); - let elsewhere = at(&h, 250.0, 100.0); - h.hover_at(elsewhere); - h.run_steps(2); - assert!(h.state().views[0].comments.gesture.is_none(), "the move is over"); - assert_eq!(rect(&h), before, "and moved nothing to where the pointer turned up"); - let blank = at(&h, 250.0, 60.0); - mouse_drag(&mut h, blank, egui::vec2(30.0, 0.0)); - assert_eq!(rect(&h), before, "nothing moved the comment"); + assert_eq!(h.state().views[0].comments.primary(), Some((0, 1)), "the note under the right-click is selected"); } /// A click that began off the page (in the gutter beside it) is no page's: the selected comment @@ -1746,10 +1256,10 @@ fn a_click_that_began_off_the_page_keeps_the_selected_comment() { let mut h = open(stacked_comments_pdf(), "150", false); let bottom = at(&h, 60.0, 160.0); mouse_click(&mut h, bottom); - assert_eq!(h.state().views[0].comments.selected, Some((0, 0)), "the note is selected"); + assert_eq!(h.state().views[0].comments.primary(), Some((0, 0)), "the note is selected"); let left = page(&h).min.x; slipping_click(&mut h, egui::pos2(left - 2.0, bottom.y), egui::pos2(left + 3.0, bottom.y)); - assert_eq!(h.state().views[0].comments.selected, Some((0, 0)), "a click that began off the page leaves it selected"); + assert_eq!(h.state().views[0].comments.primary(), Some((0, 0)), "a click that began off the page leaves it selected"); } /// A touch's long press on a comment selects it for its menu, as a right-click does: egui reports @@ -1763,7 +1273,7 @@ fn a_long_press_on_a_comment_selects_it_for_its_menu() { one_frame(&mut h, [touch(egui::TouchPhase::Start, top), egui::Event::PointerMoved(top), button(top, true)]); // Held still, past egui's long-press time. h.run_steps(6); - assert_eq!(h.state().views[0].comments.selected, Some((0, 1)), "the note under the finger is selected"); + assert_eq!(h.state().views[0].comments.primary(), Some((0, 1)), "the note under the finger is selected"); one_frame(&mut h, [touch(egui::TouchPhase::End, top), button(top, false), egui::Event::PointerGone]); h.run_steps(2); } @@ -1823,10 +1333,10 @@ fn a_right_click_with_edit_text_on_added_text_unselects_the_comment() { })); h.state_mut().quick_tool = QuickTool::EditText; h.run_steps(4); - h.state_mut().views[0].comments.selected = Some((0, 0)); + h.state_mut().views[0].comments.select_only((0, 0)); let on_added = at(&h, 90.0, 202.0); right_click(&mut h, on_added); - assert_eq!(h.state().views[0].comments.selected, None); + assert_eq!(h.state().views[0].comments.primary(), None); } /// Two pages with their gaps hidden, after `tool` set the tool up, and a point on the row of pixels @@ -1916,7 +1426,7 @@ fn a_right_click_with_the_button_held_opens_the_selected_comments_menu() { let edge = at(&h, 30.0, 303.0); wait_for_cursor(&mut h, edge, |c| c != egui::CursorIcon::Default); mouse_click(&mut h, edge); - assert_eq!(h.state().views[0].comments.selected, Some((0, 0)), "the comment is selected"); + assert_eq!(h.state().views[0].comments.primary(), Some((0, 0)), "the comment is selected"); h.hover_at(edge); h.run_steps(1); h.drag_at(edge); @@ -1929,7 +1439,7 @@ fn a_right_click_with_the_button_held_opens_the_selected_comments_menu() { } h.run_steps(3); assert!(h.query_by_label("Properties…").is_some(), "the comment's menu"); - assert_eq!(h.state().views[0].comments.selected, Some((0, 0)), "the selection stays"); + assert_eq!(h.state().views[0].comments.primary(), Some((0, 0)), "the selection stays"); h.drop_at(moved); h.run_steps(2); } @@ -2104,9 +1614,9 @@ fn a_note_tool_click_on_added_text_starts_no_note() { assert!(h.state().views[0].comments.composer.is_none(), "no note is started"); } -/// With Fill & Sign, a mark being moved on the page keeps the page's presses, as before: a press held -/// through its move and released places no new mark. (A move left over once the button is up ends: -/// `a_comment_move_whose_release_the_pages_missed_ends_once_the_button_is_up`.) +/// With Fill & Sign, a mark being moved on the page keeps the page's presses, as before: a press +/// held through the mark's move and released places no new mark, though it is a Fill click where +/// it comes up. #[test] fn a_fill_and_sign_click_places_nothing_while_a_mark_is_moved() { let mut h = open(comment_on_text_pdf(), "150", false); @@ -2117,13 +1627,17 @@ fn a_fill_and_sign_click_places_nothing_while_a_mark_is_moved() { s.session.get(s.views[0].id).unwrap().info.annotations.len() }; let before = marks(&h); - let blank = at(&h, 150.0, 100.0); - h.hover_at(blank); + // Inside the rectangle, where no text lies: the mark takes the press. + let mark = at(&h, 120.0, 315.0); + let k = page(&h).width() / 300.0; + h.hover_at(mark); h.run_steps(1); - h.drag_at(blank); + h.drag_at(mark); h.run_steps(1); - h.state_mut().views[0].comments.gesture = Some(pdfcraft_ui_egui::comments::Gesture::Move { page: 0, index: 0, from: blank }); - h.drop_at(blank); + let to = mark + egui::vec2(20.0 * k, 0.0); + h.hover_at(to); + h.run_steps(2); + h.drop_at(to); h.run_steps(4); assert_eq!(marks(&h), before, "no mark is placed"); } @@ -2161,9 +1675,9 @@ fn two_pages_and_a_comment_pdf() -> Vec { #[test] fn a_right_click_between_the_pages_opens_the_page_menu_not_the_selected_comments() { let mut h = open(two_pages_and_a_comment_pdf(), "100", false); - h.state_mut().views[0].comments.selected = Some((0, 0)); + h.state_mut().views[0].comments.select_only((0, 0)); h.run_steps(2); - assert_eq!(h.state().views[0].comments.selected, Some((0, 0)), "the comment is selected"); + assert_eq!(h.state().views[0].comments.primary(), Some((0, 0)), "the comment is selected"); let (one, two) = { let v = &h.state().views[0]; (v.page_screen_rect(0).expect("page 1 on screen"), v.page_screen_rect(1).expect("page 2 on screen")) @@ -2171,7 +1685,7 @@ fn a_right_click_between_the_pages_opens_the_page_menu_not_the_selected_comments let gap = egui::pos2(one.center().x, (one.max.y + two.min.y) / 2.0); assert!(!one.contains(gap) && !two.contains(gap), "between the pages: {one:?} {two:?}"); right_click(&mut h, gap); - assert_eq!(h.state().views[0].comments.selected, None); + assert_eq!(h.state().views[0].comments.primary(), None); assert!(h.query_by_label("Rotate view counterclockwise").is_some(), "the page menu opens"); assert!(h.query_by_label("Reply").is_none(), "not the comment's"); } @@ -2182,19 +1696,21 @@ fn a_right_click_between_the_pages_opens_the_page_menu_not_the_selected_comments /// centred the image on page 1's point, which on page 2 lies at its foot. #[test] fn paste_from_a_right_click_where_two_pages_touch_keeps_to_the_first_page() { - let (mut h, seam) = touching_pages(|app| { - app.system_clipboard = false; - app.quick_tool = QuickTool::EditText; - }); - let clip = || pdfcraft_ui_egui::Clip::Image { width: 60, height: 40, rgba: [50u8, 150, 250, 255].repeat(60 * 40) }; - h.state_mut().clipboard_override = Some(clip()); + let (mut h, seam) = touching_pages(|app| app.quick_tool = QuickTool::EditText); + // A picture reaches the clipboard as the platform's paste of it, in the frame that pastes. + let picture = || { + let image = egui::ColorImage::from_rgba_unmultiplied([60, 40], &[50u8, 150, 250, 255].repeat(60 * 40)); + egui::Event::PasteImage(Arc::new(image)) + }; + h.event(picture()); + h.run_steps(1); assert!(h.state_mut().paste_image_at(1, [100.0, 400.0]), "a picture across page 2's top edge"); - h.state_mut().clipboard_override = Some(clip()); h.state_mut().views[0].image_selection = None; h.run_steps(4); right_click(&mut h, seam); assert_eq!(h.state().views[0].comments.context_at.map(|(page, _)| page), Some(0), "page 1 takes the right-click"); assert!(h.state().views[0].image_selection.is_none(), "page 2's picture is not selected for its menu"); + h.event(picture()); h.get_by_label_contains("Paste").click(); h.run_steps(3); let images = |page| { @@ -2241,114 +1757,6 @@ fn a_camera_click_released_off_its_page_moves_nothing() { assert_eq!(h.state().views[0].camera.map(|q| q.page), Some(0)); } -/// Delete and Escape with a dialog open are the dialog's: the link selected behind it with the Link -/// tool stays and stays selected. Delete removed it, and Escape deselected it as it closed the -/// dialog. -#[test] -fn delete_and_escape_under_a_dialog_leave_the_selected_link() { - for key in [egui::Key::Delete, egui::Key::Escape] { - let mut h = open(link_pdf(), "150", false); - link_tool(&mut h); - let on_link = at(&h, 150.0, 325.0); - mouse_click(&mut h, on_link); - assert_eq!(h.state().views[0].links.selected, Some((0, 0))); - h.state_mut().dialog = Some(Dialog::Shortcuts); - h.run_steps(3); - h.key_press(key); - h.run_steps(3); - let s = h.state(); - assert_eq!(s.session.get(s.views[0].id).unwrap().links().len(), 1, "{key:?} under a dialog deletes nothing"); - assert_eq!(s.views[0].links.selected, Some((0, 0)), "{key:?}: still selected"); - assert_eq!(s.dialog.is_none(), key == egui::Key::Escape, "{key:?}: only Escape closes it"); - } -} - -/// Escape with a dialog open over Edit text objects that an area selected closes the dialog, and -/// the objects stay selected: Delete then removes them. Escape went to the objects instead, and the -/// dialog stayed open. -#[test] -fn escape_under_a_dialog_closes_it_over_selected_edit_text_objects() { - let mut h = open(bottom_line_pages_pdf(), "100", false); - h.state_mut().views[0].show_page_gaps = false; - h.state_mut().quick_tool = QuickTool::EditText; - h.run_steps(4); - let (one, two) = { - let v = &h.state().views[0]; - (v.page_screen_rect(0).expect("page 1 on screen"), v.page_screen_rect(1).expect("page 2 on screen")) - }; - mouse_click(&mut h, egui::pos2(one.min.x + 60.0, one.max.y - 8.0)); - mouse_drag(&mut h, egui::pos2(one.min.x + 60.0, two.min.y + 3.0), egui::vec2(200.0, 30.0)); - let blocks = |h: &Harness<'_, PdfCraftApp>| { - let s = h.state(); - s.session.get(s.views[0].id).unwrap().text_blocks(1).len() - }; - assert_eq!(blocks(&h), 1, "page 2's line is there"); - h.state_mut().dialog = Some(Dialog::Shortcuts); - h.run_steps(3); - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert!(h.state().dialog.is_none(), "Escape closes the dialog"); - h.key_press(egui::Key::Delete); - h.run_steps(4); - assert_eq!(blocks(&h), 0, "the objects stayed selected: Delete removes them"); -} - -/// With a menu of the menu bar open, V and H are the menu's: the tool stays. V picked Select. -#[test] -fn the_tool_letters_with_a_menu_open_leave_the_tool() { - for letter in [egui::Key::V, egui::Key::H] { - let mut h = open(link_pdf(), "150", false); - link_tool(&mut h); - crate::support::open_menu(&mut h, "Edit"); - h.key_press(letter); - h.run_steps(3); - assert_eq!(h.state().quick_tool, QuickTool::Link, "{letter:?} with a menu open"); - } -} - -/// With a menu of the menu bar open, Delete leaves Edit text objects that an area selected: the key -/// is the menu's. It deleted them. -#[test] -fn delete_with_a_menu_open_leaves_selected_edit_text_objects() { - let mut h = open(bottom_line_pages_pdf(), "100", false); - h.state_mut().views[0].show_page_gaps = false; - h.state_mut().quick_tool = QuickTool::EditText; - h.run_steps(4); - let (one, two) = { - let v = &h.state().views[0]; - (v.page_screen_rect(0).expect("page 1 on screen"), v.page_screen_rect(1).expect("page 2 on screen")) - }; - mouse_click(&mut h, egui::pos2(one.min.x + 60.0, one.max.y - 8.0)); - mouse_drag(&mut h, egui::pos2(one.min.x + 60.0, two.min.y + 3.0), egui::vec2(200.0, 30.0)); - let blocks = |h: &Harness<'_, PdfCraftApp>| { - let s = h.state(); - s.session.get(s.views[0].id).unwrap().text_blocks(1).len() - }; - assert_eq!(blocks(&h), 1, "page 2's line is there"); - crate::support::open_menu(&mut h, "View"); - h.key_press(egui::Key::Delete); - h.run_steps(4); - assert_eq!(blocks(&h), 1, "Delete with a menu open deletes nothing"); - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert!(!egui::Popup::is_any_open(&h.ctx), "Escape closed the menu"); - h.key_press(egui::Key::Delete); - h.run_steps(4); - assert_eq!(blocks(&h), 0, "the objects stayed selected, and Delete with the menu closed removes them"); -} - -/// With a menu of the menu bar open, End is the menu's: the view stays on its page. It went to the -/// last page. -#[test] -fn end_with_a_menu_open_turns_no_page() { - let mut h = open(bottom_line_pages_pdf(), "100", false); - let current = h.state().views[0].current; - crate::support::open_menu(&mut h, "View"); - h.key_press(egui::Key::End); - h.run_steps(4); - assert_eq!(h.state().views[0].current, current, "End with a menu open turns no page"); -} - /// With a menu of the menu bar open, Delete leaves the picture selected with Edit text: the key is /// the menu's. It deleted the picture. #[test] @@ -2365,63 +1773,3 @@ fn delete_with_a_menu_open_leaves_the_selected_picture() { assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), None, "nothing was deleted"); assert!(s.views[0].image_selection.is_some(), "and the picture is still selected"); } - -/// The Hotbar tools window, left open when full screen hides it, holds no keys there: the arrows -/// still turn the page. It held every page key until the window was drawn again. -#[test] -fn a_hotbar_window_hidden_by_full_screen_holds_no_keys() { - let mut h = open(bottom_line_pages_pdf(), "100", false); - h.get_by_label("Hotbar settings").click(); - h.run_steps(3); - assert!(h.state_mut().execute("view.full_screen")); - h.run_steps(4); - assert!(h.state().full_screen, "full screen"); - let before = h.state().views[0].current; - h.key_press(egui::Key::ArrowRight); - h.run_steps(4); - assert_eq!(h.state().views[0].current, before + 1, "→ turns the page"); -} - -/// Full screen entered as a native menu's click is, between passes, closes the Hotbar tools window -/// on the pass it hides it: → on that pass turns the page. The window, drawn on the pass before, -/// held it. -#[test] -fn full_screen_from_a_native_menu_with_the_hotbar_window_open_leaves_the_keys_to_the_page() { - let mut h = open(bottom_line_pages_pdf(), "100", false); - h.get_by_label("Hotbar settings").click(); - h.run_steps(3); - assert!(h.query_by_label("Close menu").is_some(), "the Hotbar tools window is open"); - let before = h.state().views[0].current; - assert!(h.state_mut().execute("view.full_screen")); - h.key_press(egui::Key::ArrowRight); - h.run_steps(4); - assert!(h.state().full_screen, "full screen"); - assert_eq!(h.state().views[0].current, before + 1, "→ turns the page"); -} - -/// With a menu of the menu bar open, the view's chords wait, as the registered commands' do: ⌘= -/// zooms nothing. It zoomed the view behind the menu. -#[test] -fn a_view_chord_with_a_menu_open_waits() { - // (A chord on the OCR Verify screen: comments::chords_on_the_ocr_verify_screen_leave_the_hidden_page.) - let mut h = open(bottom_line_pages_pdf(), "100", false); - let before = h.state().views[0].zoom; - crate::support::open_menu(&mut h, "View"); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Equals); - h.run_steps(3); - assert_eq!(h.state().views[0].zoom, before, "⌘= with a menu open zooms nothing"); -} - -/// In Organize Pages, a Cut with a menu of the menu bar open is the menu's: the pages stay. It cut -/// the current page. -#[test] -fn a_cut_with_a_menu_open_leaves_organize_pages_alone() { - let mut h = open(bottom_line_pages_pdf(), "100", false); - h.state_mut().views[0].organize = true; - h.run_steps(4); - crate::support::open_menu(&mut h, "View"); - h.event(egui::Event::Cut); - h.run_steps(4); - let s = h.state(); - assert_eq!(s.session.get(s.views[0].id).unwrap().info.pages.len(), 2, "no page was cut"); -}