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)
This commit is contained in:
Dylan M. Taylor
2026-11-18 16:15:25 -05:00
parent ca985dfc7e
commit a7e04adab1
9 changed files with 1077 additions and 3878 deletions
-344
View File
@@ -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<String>,
}
/// 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<Claim>; 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<String>) {
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<Claim>; LAYERS.len()], tool: QuickTool) -> Option<Claim> {
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<String> {
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<QuickTool> {
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<Claim> {
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<CursorIcon>, claims: &mut PageCursor, tool: QuickTool) -> (CursorIcon, Option<String>) {
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");
}
}
File diff suppressed because it is too large Load Diff
-173
View File
@@ -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<Event>, 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));
});
}
}
+407
View File
@@ -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<u64> {
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<PartRef> {
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<usize>)> {
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<CursorIcon>,
tip: Option<String>,
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<HitShape>, 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<String>) -> 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<PagePress>,
/// 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<Owner>,
/// 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<Owner>,
report: Report,
}
/// What `update` read, for `finish`.
#[derive(Debug, Default)]
struct Report {
press: Option<PagePress>,
key: Option<(Owner, Intent)>,
hovered: Option<Owner>,
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<Owner>) -> 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<Intent> {
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<PartRef> = 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 }
}
}
-150
View File
@@ -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<Pos2>,
/// 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<Pos2>,
/// This frame's primary presses and releases of a press the pages hold, in order.
pub edges: Vec<Edge>,
/// 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<Pos2>,
/// 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<Pos2> {
self.pos.filter(|p| r.contains(*p))
}
/// Where this frame's first primary press was.
pub(crate) fn pressed(&self) -> Option<Pos2> {
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<Pos2> {
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<Modifiers> {
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<Pos2> {
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<Edge> {
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;
@@ -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<Event>, 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<Event>, 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<Event> = (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<Event> = (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<String>) -> Vec<(&'static str, Option<String>, 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<String> = 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<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");
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<String>, 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<String> {
misuses_in(page_module_uses(names), allowed, why, unused)
}
/// [`misuses`], of what was `found`.
fn misuses_in(found: Vec<(&str, Option<String>, usize, String)>, allowed: &[(&str, &str, &str)], why: &str, unused: &str) -> Vec<String> {
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::<Vec<_>>().join("/");
let source = std::fs::read_to_string(&path).expect("source file");
let marks = PAGE_MODULE_MARKS.iter().filter(|mark| source.contains(**mark)).collect::<Vec<_>>();
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<String> {
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<String> {
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<Hit> {").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<String> {
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::<Vec<_>>().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"));
}
-355
View File
@@ -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<ObjectTarget>),
/// 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<String>,
/// 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<Item = Hit>, tool: QuickTool) -> Option<Hit> {
hits.into_iter().filter(|h| h.layer.reached_by(tool)).fold(None, |best: Option<Hit>, 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<Owner> {
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<Owner>,
}
/// The press the pages hold, from its frame until the button is up.
#[derive(Debug, Default)]
pub(crate) struct PageRouter {
capture: Option<Capture>,
/// A press is held, and the page it began on (`None`: off the pages, between them or beside one).
began: Option<Option<usize>>,
}
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<Item = Hit>, tool: QuickTool) {
if self.began != Some(None) {
return;
}
let hits: Vec<Hit> = 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<Owner> {
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));
}
}
+559
View File
@@ -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<String, String>,
/// 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<DocTexts<'a>>,
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<dyn CanvasTool + 'a>),
/// 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<ToolKey>,
}
/// 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<usize>,
/// The Crop tool's drawn rectangle, which the page body turns into the crop edit.
pub(crate) crop: Option<CropResult>,
/// Fill & Sign asked for a signature (`false`) or initials (`true`) before it can place one.
pub(crate) open_signature: Option<bool>,
/// Fill & Sign refused a click, and why.
pub(crate) refused: Option<String>,
edit: Option<Edit>,
camera_page: Option<usize>,
sign_drawn: Option<(usize, [f64; 4])>,
redaction: Option<RedactResult>,
presenter_keys: Vec<ToolKey>,
/// The quick tool, when it selects text.
text_tool: Option<QuickTool>,
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<PickedImage>,
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<FillOutcome>`);
// 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<FillOutcome>,
) -> 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<FillOutcome>, 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<Edit>)` carries no page, which `fill_signature_page` needs
// (production set the clicked page); assumed `Signature(Box<Edit>, 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<ToolRegion> {
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<ToolAccess> {
self.tool().access(cx)
}
fn command_form(&self) -> ToolPath {
self.tool().command_form()
}
}
File diff suppressed because it is too large Load Diff