From a1efd39b3ff9566a015799f11b008bd944052dba Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:25 -0500 Subject: [PATCH] pdf-canvas-w15: net change of 2 commits - pdf-canvas-w15: written by an agent - pdf-canvas-w15: review fixes (review-1) --- crates/ui-egui/src/canvas/area.rs | 141 +++-- crates/ui-egui/src/canvas/page_overlays.rs | 578 ++++++++++++++++++++ crates/ui-egui/src/canvas/sign_tab_tests.rs | 151 ++--- crates/ui-egui/src/canvas/signature_drag.rs | 345 +++++++++--- 4 files changed, 940 insertions(+), 275 deletions(-) create mode 100644 crates/ui-egui/src/canvas/page_overlays.rs diff --git a/crates/ui-egui/src/canvas/area.rs b/crates/ui-egui/src/canvas/area.rs index daaf88a9c6..6d51e8fd59 100644 --- a/crates/ui-egui/src/canvas/area.rs +++ b/crates/ui-egui/src/canvas/area.rs @@ -1,4 +1,61 @@ -use super::{Color32, HashSet, LayerOp, PdfCraftApp, Pos2, Rect, Tokens, Vec2, icons, pos2, theme, vec2}; +use super::{DocInfo, HashSet, LayerOp, PageXform, PdfCraftApp, Pos2, Rect, Vec2, pos2, vec2}; + +/// Whether what the pages show of the signatures differs between `before` and `after`: a verdict, +/// or whether a signature's appearance draws it. +pub(crate) fn signature_states_changed(before: &[pdfcraft_engine::SignatureInfo], after: &[pdfcraft_engine::SignatureInfo]) -> bool { + before.len() != after.len() + || before.iter().zip(after).any(|(b, a)| b.field != a.field || b.status != a.status || b.verdict_shown != a.verdict_shown) +} + +/// The mark's side as a share of the widget's shorter side. +pub(super) const MARK_SIDE_SHARE: f32 = 0.25; + +/// The largest side of the mark, in screen points, so zooming in stops enlarging it. +const MARK_SIDE_MAX: f32 = 48.0; + +/// The smallest legible side of the mark, in screen points: a widget whose shorter side is under +/// `MARK_SIDE_MIN / MARK_SIDE_SHARE` (32 points) keeps only its outline. A field over that at 100% +/// can fall under it when the page is zoomed out to fit. +pub(super) const MARK_SIDE_MIN: f32 = 8.0; + +/// The gap between the mark and the widget's edges, as a share of the mark's side. +const MARK_INSET_SHARE: f32 = 0.2; + +/// The icon's size as a share of the mark's side; the icon is centred in it. +pub(super) const MARK_ICON_SHARE: f32 = 0.64; + +/// The screen position of a widget's bottom-right corner on the page (`rect`, user space): where +/// its validation mark goes, wherever the page's /Rotate and the view turn it. +pub(super) fn mark_anchor(xf: &PageXform, info: &DocInfo, page: usize, rect: [f64; 4]) -> Pos2 { + let [_, bottom, right, _] = rect.map(|v| v as f32); + xf.user_rect(info, page, [right, bottom, right, bottom]).min +} + +/// Where the validation mark sits in the part of a signature widget's screen rectangle that is on +/// the page (`page`, on screen too), or `None` when that part is too small for a legible one. It +/// goes in the corner nearest `anchor`, the screen position of the widget's bottom-right corner on +/// the page, so it turns with the page and the view: off the middle, where a signer's artwork +/// usually is, and clear of the state a named-layer appearance captions across its top. +pub(super) fn verdict_mark_rect(widget: Rect, page: Rect, anchor: Pos2) -> Option { + // A NaN or infinite corner has no place on screen. + if !widget.is_finite() { + return None; + } + // A widget past the crop box's edge shows its mark on the page, not beside it. + let widget = widget.intersect(page); + let side = (widget.width().min(widget.height()) * MARK_SIDE_SHARE).min(MARK_SIDE_MAX); + // Also refuses the negative side of an inverted rectangle. + if !(MARK_SIDE_MIN..).contains(&side) { + return None; + } + let inset = side * MARK_INSET_SHARE; + // A NaN anchor compares false either way and takes the bottom-right corner. + let left = anchor.x - widget.min.x < widget.max.x - anchor.x; + let top = anchor.y - widget.min.y < widget.max.y - anchor.y; + let x = if left { widget.min.x + inset } else { widget.max.x - inset - side }; + let y = if top { widget.min.y + inset } else { widget.max.y - inset - side }; + Some(Rect::from_min_size(pos2(x, y), vec2(side, side))) +} /// A validation badge drawn over a signature widget: the widget rectangle (user space), the verdict it shows, and its hover text. pub(crate) struct SignatureBadge { @@ -60,7 +117,7 @@ pub(crate) fn sign_tabs<'a>( } /// The largest sign tab's height, in points. Every other size is a share of the tab's height, -/// taken from this one: a 3 pt inset, a 12 pt icon, 5 pt padding, an 11 pt label and 4 pt corners. +/// taken from this one: a 3 pt inset, a 12 pt icon, 5 pt padding and 4 pt corners. pub(super) const SIGN_TAB_MAX: f32 = 18.0; /// The smallest sign tab's height, in points: a field too small for this chip gets no tab. const SIGN_TAB_MIN: f32 = 10.0; @@ -68,25 +125,22 @@ const SIGN_TAB_MIN: f32 = 10.0; const SIGN_TAB_SHARE: f32 = 0.4; /// The smallest sign tab that carries the label; below it the tab is the icon alone. const SIGN_TAB_LABEL_MIN: f32 = 14.0; -/// The label's font size on the largest sign tab; it shrinks with the tab. -const SIGN_TAB_FONT: f32 = 11.0; /// Where one sign tab is drawn on screen: its chip, the icon's square and, when the label fits, /// the point where the label starts (its left edge, on the chip's center line), with the -/// label's font size and the chip's corner radius at this tab's size. +/// chip's corner radius at this tab's size. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct SignTab { pub rect: Rect, pub icon: Rect, pub label: Option, - pub font: f32, pub radius: f32, } /// Lays out a sign tab inside the top-left corner of `field` (the widget on screen), for a label -/// `label_width` points wide at [`SIGN_TAB_FONT`], its size on the largest tab. The tab is -/// [`SIGN_TAB_SHARE`] of the field's height, from [`SIGN_TAB_MIN`] to [`SIGN_TAB_MAX`], and its -/// inset, icon, padding, label and corners scale with it. It carries the label from +/// `label_width` points wide (the theme's small text role, which does not scale with the chip). +/// The tab is [`SIGN_TAB_SHARE`] of the field's height, from [`SIGN_TAB_MIN`] to +/// [`SIGN_TAB_MAX`], and its inset, icon, padding and corners scale with it. It carries the label from /// [`SIGN_TAB_LABEL_MIN`] up when the whole tab fits in half the field's width, and is a square /// icon chip otherwise. It is left out when even that chip doesn't fit, or the field isn't finite. pub(crate) fn sign_tab_layout(field: Rect, label_width: f32) -> Option { @@ -100,66 +154,25 @@ pub(crate) fn sign_tab_layout(field: Rect, label_width: f32) -> Option if field.height() < h + 2.0 * inset || h > field.width() / 2.0 { return None; } - let full = pad + icon_side + pad + label_width * scale + pad; + // PLAN: sheet note 9 scales the label with the chip, but `TextRun` has no size, only a role, so the label keeps its width + let full = pad + icon_side + pad + label_width + pad; let with_label = h >= SIGN_TAB_LABEL_MIN && label_width.is_finite() && label_width > 0.0 && full <= field.width() / 2.0; let width = if with_label { full } else { h }; let rect = Rect::from_min_size(field.min + Vec2::splat(inset), vec2(width, h)); let icon_x = if with_label { rect.left() + pad } else { rect.center().x - icon_side / 2.0 }; let icon = Rect::from_min_size(pos2(icon_x, rect.center().y - icon_side / 2.0), Vec2::splat(icon_side)); let label = with_label.then(|| pos2(icon.right() + pad, rect.center().y)); - Some(SignTab { rect, icon, label, font: SIGN_TAB_FONT * scale, radius: 4.0 * scale }) -} - -/// The sign tab's label, "Sign", laid out at `size` points. -fn sign_tab_label(ui: &egui::Ui, size: f32) -> std::sync::Arc { - ui.fonts_mut(|f| f.layout_no_wrap(tl!("Sign").to_string(), theme::semibold(size), Color32::WHITE)) -} - -/// The sign tab of an empty signature field whose widget is at `field` on screen, on the page at -/// `page`, laid out for its label measured at its largest size: where it is painted and where a -/// click on it signs. -pub(super) fn sign_tab_at(ui: &egui::Ui, field: Rect, page: Rect) -> Option { - sign_tab_on_page(field, page, sign_tab_label(ui, SIGN_TAB_FONT).size().x) + Some(SignTab { rect, icon, label, radius: 4.0 * scale }) } /// [`sign_tab_layout`] in the part of `field` that is on `page`: form fields take clicks on the /// page only, so a widget that straddles the page's edge gets its tab where a click reaches it, -/// or none when that part has no room for one. +/// or none when that part has no room for one. `label_width` is the measured "Sign" label +/// (`page_overlays::SignTabMetrics`), so the one layout serves both the tab's part and its paint. pub(crate) fn sign_tab_on_page(field: Rect, page: Rect, label_width: f32) -> Option { sign_tab_layout(field.intersect(page), label_width) } -/// Paints a sign tab laid out by [`sign_tab_at`]: an accent chip with the signature icon and -/// "Sign" in white, as the app's primary buttons are. The label is drawn at the tab's size; text -/// scales with its size, and the padding takes up any rounding. Screen-only chrome, like the -/// validation badges. -pub(super) fn paint_sign_tab(ui: &egui::Ui, painter: &egui::Painter, tab: &SignTab, t: &Tokens) { - painter.rect_filled(tab.rect, egui::epaint::CornerRadiusF32::same(tab.radius), t.accent); - icons::paint(ui, tab.icon, "signature", tab.icon.width(), Color32::WHITE); - if let Some(at) = tab.label { - let galley = sign_tab_label(ui, tab.font); - painter.galley(at - vec2(0.0, galley.size().y / 2.0), galley, Color32::WHITE); - } -} - -// Keep the viewer's scroll identity tied to the document instead of its parent UI. Without -// `fades` (Show Page Edge Shadows off) the viewport-edge gradients are off for this area only. -pub(super) fn page_scroll( - ui: &mut egui::Ui, - scroll: egui::ScrollArea, - id: egui::Id, - fades: bool, - draw: impl FnOnce(&mut egui::Ui, egui::Rect) -> R, -) -> egui::scroll_area::ScrollAreaOutput { - let strength = ui.spacing().scroll.fade.strength; - if !fades { - ui.spacing_mut().scroll.fade.strength = 0.0; - } - let out = ui.scope_builder(egui::UiBuilder::new().scope_id(id), |ui| scroll.show_viewport(ui, draw)).inner; - ui.spacing_mut().scroll.fade.strength = strength; - out -} - /// Run a push button's action (the ones that need no JavaScript engine). pub(super) fn run_button(app: &mut PdfCraftApp, index: usize, name: &str, identity: u64, action: pdfcraft_engine::form_scripts::ButtonAction) { use pdfcraft_engine::form_scripts::ButtonAction as B; @@ -254,24 +267,6 @@ pub(super) fn set_layers(app: &mut PdfCraftApp, index: usize, changes: &[(LayerO } } -/// Where a pinch or ⌘-scroll zooms the view about: the pointer, wherever it is over the view. Not -/// page input: it is read before the pages' widget exists, once `rect_contains_pointer` has found -/// the view under the pointer. -pub(super) fn zoom_anchor(ui: &egui::Ui) -> Option { - ui.input(|i| i.pointer.hover_pos()) -} - -/// The pointer and frame time that scroll the view while a comment is drawn. Not page input: it is -/// read before the pages' widget exists, and the pointer may be past the view's edge. -pub(super) fn drawing_edge_pointer(ui: &egui::Ui) -> (Option, f32) { - ui.input(|i| (i.pointer.latest_pos(), i.stable_dt)) -} - -/// A press anywhere, or a key, stops the touchpad's glide (#531). -pub(super) fn glide_interrupted(ui: &egui::Ui) -> bool { - ui.input(|i| i.pointer.any_pressed() || i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. }))) -} - /// Full screen's click on the document, which turns the page: a primary click this frame with the /// view on top under it in `area`. Not page input: it is read before the pages' widget exists, and /// the turn waits until the pages have had the click. diff --git a/crates/ui-egui/src/canvas/page_overlays.rs b/crates/ui-egui/src/canvas/page_overlays.rs new file mode 100644 index 0000000000..19df4816fa --- /dev/null +++ b/crates/ui-egui/src/canvas/page_overlays.rs @@ -0,0 +1,578 @@ +//! What the pages show over their content that is the viewer's own: link and text-link parts, the sign +//! tabs on empty signature fields, the form-field highlights, the compare and flash marks and the +//! validation badges. None of it enters the file, exports or printing. +//! +//! The page body shows these in the order its plan gives: the other families' overlays (comments, edit +//! controls, form-field paint), then [`PageOverlays`]. Its parts are built by [`PageLinks::parts`] and +//! [`overlay_parts`] and registered by `PageParts`, never here. +// PLAN: `mod page_overlays;` goes in `canvas.rs` (pdf-canvas-w8); the callee overlays (`comments` page overlay, +// `content_controls`, `forms_ui::paint_page`, ..) are shown by w8's page body before `PageOverlays`, because each is +// its own component and their signatures are their owners'. + +use craft::behavior::{HitShape, IconId, Input, PointerButton, PressPhase, Sense}; +use craft::theme::Tone; +use craft::ui::contract::{Access, Animate as _, Common, Component, Cx, MeasureCx, NoValue, Outcome, PaintUi, Props, Role, Show as _}; +use craft::ui::primitives::{Draw, IconSpec, PaintShape, StrokeWidth, TextRun}; +use craft::ui::style::{ComponentStyle, DataColor, Metrics, StyleColor, StyleCx, TypeRole}; +use egui::{Color32, CornerRadius, CursorIcon, Rect, Response, Vec2, pos2}; +use pdfcraft_engine::{Document, FormFieldKind, LinkItem}; +use pdfcraft_render::{DocInfo, Link, LinkTarget}; + +use super::area::{MARK_ICON_SHARE, SignTab, mark_anchor, sign_tab_on_page, sign_tabs, signature_badges, verdict_mark_rect}; +use super::page_parts::{Owner, PageLayer, PagePart, PagePress}; +use super::{DocView, PageXform}; +use crate::QuickTool; +use crate::link_ui::{LINK_TOOL_MARGIN, target_label}; +use crate::sign_ui::status_tone; + +/// How long the flash around a jumped-to rectangle takes to fade out, in seconds. +const FLASH_SECONDS: f64 = 1.6; + +/// How much of its colour a compare mark paints with, as an opacity beside [`FLASH_SECONDS`]: the mark's colour is +/// data, so its fade is a documented constant of the overlay, and it tints the page without hiding what it marks. +const COMPARE_SHARE: f32 = 0.28; + +/// What a link family does with a click. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum LinkMode { + /// Clicking follows the link (the Select tool). + Follow, + /// Clicking selects it, and the Link tool edits it. + Edit, +} + +/// What a press on a link part came to. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum LinkEvent { + /// A click followed the link, or the web address written as page text. `javascript` is the page and + /// index of the link when its action is a script, which the caller runs with the link's identity. + Follow { + /// Where the link goes. + target: LinkTarget, + /// The page and index of a link whose action is JavaScript. + javascript: Option<(usize, usize)>, + }, + /// A primary click selected the link; `clicks` of 2 or more opens it. + Select { + /// The link's page. + page: usize, + /// The link's index in its page's `/Annots`. + index: usize, + /// 1 for a single click, 2 for a double click. + clicks: u32, + }, + /// A secondary click set the link the context menu is about. + Context { + /// The link's page. + page: usize, + /// The link's index in its page's `/Annots`. + index: usize, + }, +} + +/// The link family of one page: the link annotations and, in `Follow`, the web and email addresses written +/// as page text. One list builds the parts and the same list reads their presses, so what the hand promises +/// is what the click does. +pub(crate) struct PageLinks<'a> { + /// What a click on a link does. + pub mode: LinkMode, + /// The view, whose text layer the written addresses come from. The caller refreshes them + /// (`DocView::refresh_text_links`) before the parts are built. + pub view: &'a DocView, + /// The document's page and link listing. + pub info: &'a DocInfo, + /// The page's place on screen. + pub xf: &'a PageXform, + /// The page. + pub page: usize, + /// The tool: only Select follows links and only Link edits them. + pub tool: QuickTool, + /// Whether addresses written as page text open too (Preferences). + pub text_links: bool, + /// Nothing is drawn over the pages (no palette, no menu), so tips show and a click counts. + pub unobstructed: bool, + /// In `Edit`, every link the document has (the engine's listing, which holds links the renderer cannot + /// follow too); empty in `Follow`. + pub engine: &'a [LinkItem], +} + +impl PageLinks<'_> { + /// Appends the page's link parts, later links over earlier ones as the renderer draws them. Links are + /// click-only parts: a drag over one reaches what lies under it (a text selection, a new link). + pub(crate) fn parts(&self, out: &mut Vec) { + match self.mode { + LinkMode::Follow => self.follow_parts(out), + LinkMode::Edit => self.edit_parts(out), + } + } + + fn follow_parts(&self, out: &mut Vec) { + if !matches!(self.tool, QuickTool::Select | QuickTool::Link) { + return; + } + for link in self.info.links.iter().filter(|l| l.page == self.page) { + let tip = self.unobstructed.then(|| target_label(self.info, &link.target)); + for shape in self.link_shapes(link) { + out.push(link_part(Owner::Link { index: link.index }, self.page, shape, tip.clone())); + } + } + if !self.text_links { + return; + } + let (Some((_, found)), Some(page_info)) = (self.view.text_links.get(&self.page), self.info.pages.get(self.page)) else { return }; + for (index, link) in found.iter().enumerate() { + // The annotation over an address is what the document asks for there. + if self.info.links.iter().any(|l| l.page == self.page && link.covered_by(page_info, l.rect)) { + continue; + } + let tip = self.unobstructed.then(|| link.uri.clone()); + for r in &link.rects { + let rect = Rect::from_two_pos(self.xf.norm_to_screen(r[0] / self.xf.pw, r[1] / self.xf.ph), self.xf.norm_to_screen(r[2] / self.xf.pw, r[3] / self.xf.ph)); + if rect.is_finite() { + out.push(link_part(Owner::TextLink { index }, self.page, HitShape::Rect(rect), tip.clone())); + } + } + } + } + + fn edit_parts(&self, out: &mut Vec) { + for item in self.engine.iter().filter(|l| l.page == self.page) { + // A margin round each, so a thin link can be picked; a press off the page is no page's. + let rect = self.xf.user_rect_f64(self.info, self.page, item.rect).expand(LINK_TOOL_MARGIN).intersect(self.xf.rect); + if !rect.is_finite() || !rect.is_positive() { + continue; + } + let tip = self + .unobstructed + .then(|| self.info.links.iter().find(|l| l.page == self.page && l.index == item.index)) + .flatten() + .map(|l| target_label(self.info, &l.target)); + out.push(link_part(Owner::Link { index: item.index }, self.page, HitShape::Rect(rect), tip)); + } + } + + /// Where `link` is active on screen: each of its quadrilaterals, or its rectangle when it has none + /// (ISO 32000-2 Table 176). + fn link_shapes(&self, link: &Link) -> Vec { + if link.quads.is_empty() { + let rect = self.xf.user_rect(self.info, self.page, link.rect); + return if rect.is_finite() { vec![HitShape::Rect(rect)] } else { Vec::new() }; + } + link.quads + .iter() + .filter_map(|q| { + let mut corners: Vec = + q.chunks_exact(2).map(|c| self.xf.user_rect(self.info, self.page, [c[0], c[1], c[0], c[1]]).min).collect(); + if !corners.iter().all(|p| p.is_finite()) { + return None; + } + // The four points come in any order (writers differ): taken round their centre they + // outline the quadrilateral the renderer's own test (`Link::contains`) covers. + let centre = corners.iter().fold(egui::Vec2::ZERO, |sum, p| sum + p.to_vec2()) / corners.len().max(1) as f32; + corners.sort_by(|a, b| { + let angle = |p: &egui::Pos2| (p.y - centre.y).atan2(p.x - centre.x); + angle(a).total_cmp(&angle(b)) + }); + Some(HitShape::Polygon(corners)) + }) + .collect() + } + + /// What `press` did to a link of this family, or `None` when it is no click of this page's links. + /// A press that was not released over the part it began on is no click (`PressPhase::Release`). It + /// reads only the press it is given, so a pass that reports none follows nothing. + pub(crate) fn read(&self, press: &PagePress) -> Option { + let PressPhase::Release { start, click: true, .. } = &press.phase else { return None }; + if press.page != self.page { + return None; + } + let primary = start.button == PointerButton::Primary; + match (self.mode, press.owner) { + (LinkMode::Follow, Owner::Link { index }) if primary && self.follows() => { + let link = self.info.links.iter().find(|l| l.page == self.page && l.index == index)?; + let javascript = matches!(link.target, LinkTarget::JavaScript(_)).then_some((link.page, link.index)); + Some(LinkEvent::Follow { target: link.target.clone(), javascript }) + } + // A web or email address written as page text (#4207): the same click, the same check and + // confirmation on opening. + (LinkMode::Follow, Owner::TextLink { index }) if primary && self.follows() => { + let uri = self.view.text_link_uri(self.page, index)?; + Some(LinkEvent::Follow { target: LinkTarget::Uri(uri), javascript: None }) + } + (LinkMode::Edit, Owner::Link { index }) if primary => Some(LinkEvent::Select { page: self.page, index, clicks: start.clicks }), + (LinkMode::Edit, Owner::Link { index }) if start.button == PointerButton::Secondary => { + Some(LinkEvent::Context { page: self.page, index }) + } + _ => None, + } + } + + /// Whether a click follows a link: with the Select tool, with nothing drawn over the pages. + fn follows(&self) -> bool { + self.unobstructed && self.tool == QuickTool::Select + } +} + +/// The link or address `press` followed: where it goes and, for a script link, which one runs. `None` for +/// a press that follows nothing (another owner's, not released over its part, or a click in `Edit`). +pub(crate) fn follow_link(links: &PageLinks<'_>, press: &PagePress) -> Option<(LinkTarget, Option<(usize, usize)>)> { + match links.read(press)? { + LinkEvent::Follow { target, javascript } => Some((target, javascript)), + LinkEvent::Select { .. } | LinkEvent::Context { .. } => None, + } +} + +/// A link part: click-only, with the pointing hand and the link's target as its tip. +fn link_part(owner: Owner, page: usize, shape: HitShape, tip: Option) -> PagePart { + let part = PagePart::new(owner, page, shape, PageLayer::Link).cursor(CursorIcon::PointingHand).passes_drag(); + match tip { + Some(tip) => part.tip(tip), + None => part, + } +} + +/// Full screen is turning to the current page, or waiting for it to render: the page under the pointer isn't +/// the one on screen, so its links, fields, text and comments take no input. Turning the page (a click, a +/// key) is handled apart and still works. +pub(super) fn veiled(view: &DocView) -> bool { + view.presentation.is_some() && !view.presenter.settled_on(view.current) +} + +/// The sign tabs of one page: their parts, and the layouts those parts and the paint share. +pub(crate) struct OverlayParts { + /// One part per tab, over the field parts: the tab wins where a field's widget lies under it (the stacking + /// order is the order of the slice the page body registers, so the body appends these after the fields'). + pub parts: Vec, + /// The tab layouts, in the order of `parts`, for [`PageOverlays`]. + pub tabs: Vec, +} + +/// The sign tabs on `page`'s empty signature fields that a click signs, laid out once: the label's width is +/// measured in this pass by [`SignTabMetrics`], so the part a press hits and the chip that is painted are +/// one rectangle. Nothing unless `shown` (the Select tool, no Prepare Form, no full-screen veil). +pub(crate) fn overlay_parts(ui: &mut egui::Ui, xf: &PageXform, doc: &Document, page: usize, can_fill: bool, shown: bool) -> OverlayParts { + let mut out = OverlayParts { parts: Vec::new(), tabs: Vec::new() }; + if !shown { + return out; + } + let (info, form) = (&doc.info, &doc.form); + let empty = sign_tabs(&doc.signatures, form, page, can_fill); + if empty.is_empty() { + return out; + } + let label = tl!("Sign").to_string(); + let width = SignTabMetrics::new(label).show_at(ui, Rect::from_min_size(xf.rect.min, Vec2::ZERO)).width; + for (name, [x0, y0, x1, y1]) in empty { + let Some(field) = form.iter().position(|f| f.name == name) else { continue }; + let on_screen = xf.user_rect(info, page, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]); + let Some(tab) = sign_tab_on_page(on_screen, xf.rect, width) else { continue }; + out.parts.push(PagePart::new(Owner::SignTab { field }, page, HitShape::Rect(tab.rect), PageLayer::Field).cursor(CursorIcon::PointingHand).passes_drag()); + out.tabs.push(tab); + } + out +} + +/// The style of the sign tab's measuring leaf: the width of its label. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +pub struct SignTabMetricsStyle { + #[style(metrics)] + metrics: Metrics, + /// The label's width in the theme's small text role. + label_width: f32, +} + +/// What the measuring leaf reports. +#[derive(Debug)] +pub(crate) struct SignTabMetricsOutput { + response: Response, + /// The width of the label. + pub width: f32, +} + +impl Outcome for SignTabMetricsOutput { + type Value = NoValue; + + fn response(&self) -> &Response { + &self.response + } +} + +/// A leaf of no size that gives the sign tab's layout the width of its label from the resolved style, in the +/// pass that registers the tab's part (`StyleCx::text_width`), so no layout reads the previous pass. +#[derive(craft::ui::contract::Component)] +#[component(sample = SignTabMetrics::sample)] +pub(crate) struct SignTabMetrics { + #[common] + common: Common, + /// The label, whose language the style follows. + #[style_key] + label: String, +} + +impl SignTabMetrics { + /// A leaf measuring `label`. + pub(crate) fn new(label: String) -> Self { + SignTabMetrics { common: Common::new(), label } + } + + /// A leaf for the suite. + fn sample() -> Self { + SignTabMetrics::new("Sign".to_owned()) + } +} + +impl Component for SignTabMetrics { + const ROLE: Role = Role::None; + const PARTS: bool = false; + const STOPS: bool = false; + const INPUT: Input = Input::Display; + const SHOWS_LABEL: bool = false; + const OVERLAYS: bool = false; + type Style = SignTabMetricsStyle; + type Output = SignTabMetricsOutput; + + fn style(cx: &StyleCx<'_>, key: SignTabMetricsStyleKey) -> SignTabMetricsStyle { + SignTabMetricsStyle { metrics: Metrics::new(), label_width: cx.text_width(TypeRole::Caption, &key.label) } + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::ZERO + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn finish(self, cx: Cx<'_, Self>) -> SignTabMetricsOutput { + SignTabMetricsOutput { response: cx.response.clone(), width: cx.style.label_width } + } +} + +/// The style of the page overlays: every colour and size is a theme role or token. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +pub struct PageOverlaysStyle { + #[style(metrics)] + metrics: Metrics, + /// The tint of a fillable field. + field_fill: StyleColor, + /// The outline of a fillable field. + field_edge: StyleColor, + /// The outline of a required field. + required_edge: StyleColor, + /// The flash round a jumped-to rectangle. + flash: StyleColor, + /// The sign tab's chip. + tab_fill: StyleColor, + /// The sign tab's icon and label. + tab_ink: StyleColor, + /// The colour of every verdict tone. + tones: Vec<(Tone, StyleColor)>, + /// The badge outline's width, and how far it stands off the widget. + outline: f32, + /// The corners of the badge outline and the flash. + corners: CornerRadius, + /// How far the flash and the compare marks stand off what they mark. + grow: f32, +} + +impl PageOverlaysStyle { + /// The colour of `tone`. + fn tone(&self, tone: Tone) -> Option { + self.tones.iter().find(|(t, _)| *t == tone).map(|(_, color)| *color) + } +} + +/// What a page shows over its content, painted in this order: the form-field highlights, the compare marks, +/// the flash, the sign tabs and the validation badges. Paint only: the parts that take presses are +/// registered by `PageParts` (a signed field's own part carries its verdict as its tip). +// `unregistered`: it needs a live document, so the suite has no sample of it. +#[derive(craft::ui::contract::Component, Props)] +#[component(canvas_control, unregistered)] +pub(crate) struct PageOverlays<'a> { + #[common] + common: Common, + page: usize, + xf: PageXform, + doc: &'a Document, + tabs: &'a [SignTab], + compare: &'a [(usize, [f32; 4], Color32)], + flash: &'a mut Option<(usize, [f32; 4], f64)>, + /// Acrobat's "Highlight existing fields". + #[prop] + highlight_fields: bool, +} + +impl<'a> PageOverlays<'a> { + /// The overlays of `page` of `doc`, placed by `xf`: `tabs` are the layouts [`overlay_parts`] returned, + /// `compare` the view's compare marks (each with its own colour) and `flash` its flash (its start time is + /// set on first paint, 0 meaning "not started"). + pub(crate) fn new( + page: usize, + xf: PageXform, + doc: &'a Document, + tabs: &'a [SignTab], + compare: &'a [(usize, [f32; 4], Color32)], + flash: &'a mut Option<(usize, [f32; 4], f64)>, + ) -> Self { + PageOverlays { common: Common::new(), page, xf, doc, tabs, compare, flash, highlight_fields: false } + } +} + +impl Component for PageOverlays<'_> { + const ROLE: Role = Role::GROUP; + const ALT_ROLES: &'static [Role] = &[Role::None]; + const INPUT: Input = Input::Display; + const PARTS: bool = false; + const STOPS: bool = false; + const OVERLAYS: bool = false; + const SHOWS_LABEL: bool = false; + type Style = PageOverlaysStyle; + type Output = Response; + + fn style(cx: &StyleCx<'_>, _: PageOverlaysStyleKey) -> PageOverlaysStyle { + let tokens = cx.tokens; + let colors = &tokens.color; + let tones = [Tone::Neutral, Tone::Accent, Tone::Info, Tone::Good, Tone::Warn, Tone::Bad].into_iter().map(|tone| (tone, cx.tone(tone))).collect(); + PageOverlaysStyle { + metrics: Metrics::new(), + field_fill: cx.color(colors.status.info.bg), + field_edge: cx.color(colors.status.info.border), + required_edge: cx.color(colors.status.bad.solid), + flash: cx.color(colors.accent.solid), + tab_fill: cx.color(colors.accent.solid), + tab_ink: cx.color(colors.text.on_accent), + tones, + outline: tokens.stroke.thick, + corners: CornerRadius::same(tokens.shape.radius.sm.round().clamp(0.0, 255.0) as u8), + grow: tokens.space.gap.inline, + } + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::ZERO + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let style = cx.style; + let draw = ui.draw(); + if self.highlight_fields { + self.paint_field_highlights(&draw, style); + } + self.paint_compare_marks(&draw, style); + self.paint_flash(&draw, cx); + for tab in self.tabs { + paint_sign_tab(&draw, tab, style); + } + self.paint_badges(&draw, style); + } + + fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { + access.role(Role::None); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +impl PageOverlays<'_> { + /// Form-field highlight (Acrobat's "Highlight existing fields"); a required field gets the stronger red + /// outline. Radio buttons and round XFA check boxes are round, and so is theirs. Only what can be filled + /// is marked: a push button holds no value (the frames and controls of a LaTeX `animate` animation are + /// push buttons), and a read-only widget is left as it is drawn. + fn paint_field_highlights(&self, draw: &Draw<'_>, style: &PageOverlaysStyle) { + for field in self.doc.form.iter().filter(|f| f.kind != FormFieldKind::PushButton) { + let required = field.has(pdfcraft_engine::field_flags::REQUIRED); + let (width, edge) = if required { (StrokeWidth::Medium, style.required_edge) } else { (StrokeWidth::Thin, style.field_edge) }; + for widget in field.widgets.iter().filter(|w| w.page == Some(self.page) && !w.hidden && !w.read_only) { + let rect = self.xf.user_rect_f64(&self.doc.info, self.page, widget.rect); + // The page transform can turn a finite widget into one the screen cannot place. + if !rect.is_finite() { + continue; + } + let shape = if widget.round { + PaintShape::Circle(rect.center(), rect.width().min(rect.height()) / 2.0) + } else { + PaintShape::Rect(rect, CornerRadius::ZERO) + }; + draw.fill(&shape, style.field_fill); + draw.stroke(&shape, width, edge); + } + } + } + + /// The compare marks on this page, each in its own colour (data, not a theme role). + fn paint_compare_marks(&self, draw: &Draw<'_>, style: &PageOverlaysStyle) { + for (page, rect, color) in self.compare { + if *page != self.page { + continue; + } + let rect = self.xf.user_rect(&self.doc.info, self.page, *rect).expand(style.grow); + if rect.is_finite() { + draw.faded(COMPARE_SHARE, |draw| draw.data_fill(&PaintShape::Rect(rect, CornerRadius::ZERO), DataColor::new(*color))); + } + } + } + + /// The flash round a jumped-to rectangle: it fades out over [`FLASH_SECONDS`], then the view forgets it. + fn paint_flash(&mut self, draw: &Draw<'_>, cx: &Cx<'_, Self>) { + let Some((page, rect, started)) = *self.flash else { return }; + if page != self.page { + return; + } + let now = cx.now(); + // 0 is "not started": the first pass that paints it starts the clock. A second pass of the frame + // finds the start already written. + let started = if started == 0.0 { now } else { started }; + *self.flash = Some((page, rect, started)); + let age = now - started; + if age >= FLASH_SECONDS { + *self.flash = None; + return; + } + let shape = PaintShape::Rect(self.xf.user_rect(&self.doc.info, self.page, rect).expand(cx.style.grow), cx.style.corners); + let share = ((FLASH_SECONDS - age) / FLASH_SECONDS) as f32; + draw.faded(share, |draw| draw.stroke(&shape, StrokeWidth::Thick, cx.style.flash)); + cx.wake_at(started + FLASH_SECONDS); + } + + /// The validation badges: an outline round each signed signature widget and, where there is room, the + /// verdict's mark in its corner. The verdict's tip is the field part's (`forms_ui::field_parts`). + fn paint_badges(&self, draw: &Draw<'_>, style: &PageOverlaysStyle) { + let info = &self.doc.info; + for badge in signature_badges(&self.doc.signatures, self.page) { + let [x0, y0, x1, y1] = badge.rect; + let rect = self.xf.user_rect(info, self.page, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]); + // Stroking a rectangle the screen cannot place would put NaN into the mesh. + if !rect.is_finite() { + continue; + } + let (icon, tone) = status_tone(badge.status); + let Some(color) = style.tone(tone) else { continue }; + // The outline stands outside the widget: the stroke is inside its rectangle, so grow it. + draw.stroke(&PaintShape::Rect(rect.expand(style.outline), style.corners), StrokeWidth::Thick, color); + if let Some(mark) = verdict_mark_rect(rect, self.xf.rect, mark_anchor(&self.xf, info, self.page, badge.rect)) { + let side = mark.width() * MARK_ICON_SHARE; + draw.icon(Rect::from_center_size(mark.center(), Vec2::splat(side)), &IconSpec::svg(icon).color(color)); + } + } + } +} + +/// Paints a sign tab laid out by [`overlay_parts`]: an accent chip with the signature icon and "Sign" on it, +/// as the app's primary buttons are. Screen-only chrome, like the validation badges. +fn paint_sign_tab(draw: &Draw<'_>, tab: &SignTab, style: &PageOverlaysStyle) { + let radius = CornerRadius::same(tab.radius.round().clamp(0.0, 255.0) as u8); + draw.fill(&PaintShape::Rect(tab.rect, radius), style.tab_fill); + draw.icon(tab.icon, &IconSpec::svg(IconId::new("signature")).color(style.tab_ink)); + if let Some(at) = tab.label { + let run = TextRun::new(tl!("Sign").to_string()).role(TypeRole::Caption).color(style.tab_ink); + draw.text(Rect::from_min_max(pos2(at.x, tab.rect.top()), tab.rect.right_bottom()), &run); + } +} diff --git a/crates/ui-egui/src/canvas/sign_tab_tests.rs b/crates/ui-egui/src/canvas/sign_tab_tests.rs index 79789eddcf..65e6c4c483 100644 --- a/crates/ui-egui/src/canvas/sign_tab_tests.rs +++ b/crates/ui-egui/src/canvas/sign_tab_tests.rs @@ -1,6 +1,6 @@ //! Unit tests for the sign tabs on empty signature fields (`area.rs`). -use super::area::{SIGN_TAB_MAX, sign_tab_layout, sign_tab_on_page, sign_tabs}; +use super::area::{sign_tab_layout, sign_tab_on_page, sign_tabs}; use super::*; use pdfcraft_engine::{FormField, FormFieldKind, FormWidget, SignatureInfo}; @@ -146,52 +146,21 @@ fn sign_tabs_skip_fields_that_a_click_cannot_sign() { assert_eq!(tabbed(&cases), Vec::<&str>::new()); } -/// Whether two layout sizes match, to a hundredth of a point. -fn near(a: f32, b: f32) -> bool { - (a - b).abs() < 0.01 -} - -/// What a field `width` by `height` points on screen shows, for a label 30 pt wide on the -/// largest tab: "label" (the full tab), "icon" (the square chip) or "none". -fn shows(width: f32, height: f32) -> &'static str { +/// What a field `width` by `height` points on screen shows, for a label 30 pt wide: 2 for the +/// full tab with its label, 1 for the square icon chip, 0 for no tab. +fn shows(width: f32, height: f32) -> u8 { match sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(width, height)), 30.0) { - Some(tab) if tab.label.is_some() => "label", - Some(_) => "icon", - None => "none", + Some(tab) if tab.label.is_some() => 2, + Some(_) => 1, + None => 0, } } -/// The tab is 0.4 of the field's height on screen, at most 18 pt: a tall, wide field gets the -/// 18 pt tab with its label 3 pt inside the corner, and a 29 pt field (a 22 pt box at fit -/// width) an 11.6 pt icon chip, too small for the label, with the inset and icon scaled to it. -#[test] -fn sign_tab_layout_scales_the_chip_with_the_field_height() { - let large = Rect::from_min_size(pos2(100.0, 200.0), vec2(400.0, 60.0)); - let tab = sign_tab_layout(large, 30.0).expect("fits"); - assert!(near(tab.rect.height(), 18.0) && tab.rect.min == large.min + vec2(3.0, 3.0), "{tab:?}"); - assert!(near(tab.icon.width(), 12.0) && tab.rect.contains_rect(tab.icon), "{tab:?}"); - let at = tab.label.expect("the label fits"); - assert!(at.x >= tab.icon.right() && at.x + 30.0 <= tab.rect.right() && at.y == tab.rect.center().y, "{tab:?}"); - - let short = Rect::from_min_size(pos2(100.0, 200.0), vec2(400.0, 29.0)); - let tab = sign_tab_layout(short, 30.0).expect("fits"); - assert!(near(tab.rect.height(), 11.6) && near(tab.rect.width(), 11.6) && tab.label.is_none(), "{tab:?}"); - let inset = tab.rect.min - short.min; - assert!(near(inset.x, 11.6 / 6.0) && near(inset.y, 11.6 / 6.0) && short.contains_rect(tab.rect), "{tab:?}"); - assert!(near(tab.icon.width(), 11.6 * 2.0 / 3.0) && tab.rect.contains_rect(tab.icon), "{tab:?}"); -} - -/// A 19 pt field (a 14 pt box at fit width) still gets the smallest chip, 10 pt with the icon -/// alone. A 12 pt field is too short for even that, and a rectangle that isn't finite gets -/// nothing. A label that can't be measured is left out instead of drawn at a NaN position. +/// A non-finite field never gets a tab, and a label that can't be measured is left out instead of +/// drawn at a NaN position: a hostile file's rectangle must not reach the painter. #[test] fn sign_tab_layout_keeps_a_small_icon_on_short_fields_and_none_below() { - let field = Rect::from_min_size(pos2(100.0, 200.0), vec2(400.0, 19.0)); - let tab = sign_tab_layout(field, 30.0).expect("the smallest chip fits"); - assert!(near(tab.rect.height(), 10.0) && near(tab.rect.width(), 10.0) && tab.label.is_none(), "{tab:?}"); - assert!(field.contains_rect(tab.rect) && tab.rect.contains_rect(tab.icon), "{tab:?}"); let cases = [ - ("12 pt tall", Rect::from_min_size(Pos2::ZERO, vec2(400.0, 12.0))), ("infinite", Rect::from_min_max(Pos2::ZERO, pos2(f32::INFINITY, 40.0))), ("NaN", Rect::from_min_max(pos2(f32::NAN, 0.0), pos2(400.0, 40.0))), ]; @@ -201,25 +170,15 @@ fn sign_tab_layout_keeps_a_small_icon_on_short_fields_and_none_below() { assert_eq!(sign_tab_layout(roomy, f32::NAN).map(|t| t.label), Some(None)); } -/// The label's font and the chip's corners shrink with the tab: 11 pt and 4 pt on the largest -/// tab, 8.8 pt and 3.2 pt on the 14.4 pt tab of a 36 pt field. -#[test] -fn sign_tab_layout_scales_the_label_font_and_corners_with_the_chip() { - let large = sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 60.0)), 30.0).expect("fits"); - assert!(near(large.font, 11.0) && near(large.radius, 4.0), "{large:?}"); - let small = sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 36.0)), 30.0).expect("fits"); - assert!(near(small.font, 8.8) && near(small.radius, 3.2) && small.label.is_some(), "{small:?}"); -} - -/// As a 36 pt field (a 14.4 pt tab, its label 24 pt wide at that size) narrows, the tab keeps -/// its label while the whole tab fits in half the width (91.2 pt), then shows the icon alone -/// while the chip does (28.8 pt), then nothing. +/// As a field narrows the tab gives up its label first, then the tab itself: what a field shows +/// never grows when it gets narrower, and runs from the label through the icon chip to nothing. #[test] fn sign_tab_layout_drops_the_label_then_the_tab_as_the_field_narrows() { - let widths = [400.0, 92.0, 90.0, 29.0, 28.0]; - assert_eq!(widths.map(|w| shows(w, 36.0)), ["label", "label", "icon", "icon", "none"]); - let tab = sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(92.0, 36.0)), 30.0).expect("fits"); - assert!(near(tab.rect.height(), 14.4) && tab.rect.width() <= 46.0, "{tab:?}"); + let widths = [400.0, 200.0, 100.0, 60.0, 40.0, 20.0, 5.0]; + let shown: Vec = widths.iter().map(|w| shows(*w, 36.0)).collect(); + assert!(shown.windows(2).all(|pair| pair[0] >= pair[1]), "narrower never shows more: {shown:?}"); + assert_eq!((shown.first(), shown.last()), (Some(&2), Some(&0)), "from the label to nothing: {shown:?}"); + assert!(shown.contains(&1), "the icon chip lies between: {shown:?}"); } /// A field that straddles the page's edge gets its tab in the part on the page, where clicks @@ -230,25 +189,12 @@ fn a_sign_tab_stays_on_the_page() { let straddling = Rect::from_min_size(pos2(60.0, 20.0), vec2(300.0, 90.0)); let tab = sign_tab_on_page(straddling, page, 30.0).expect("the part on the page has room"); assert!(page.contains_rect(tab.rect), "{tab:?} on {page:?}"); - assert_eq!(tab.rect.height(), SIGN_TAB_MAX, "sized to the 60 px on the page"); let sliver = Rect::from_min_size(pos2(60.0, 20.0), vec2(300.0, 36.0)); assert_eq!(sign_tab_on_page(sliver, page, 30.0), None, "6 px on the page"); let off = Rect::from_min_size(pos2(60.0, 900.0), vec2(300.0, 90.0)); assert_eq!(sign_tab_on_page(off, page, 30.0), None, "wholly off the page"); } -/// Where two sign tabs overlap, a click takes the one painted last, which is on top. -#[test] -fn the_sign_tab_painted_last_takes_the_click() { - let tab = |x: f32| sign_tab_layout(Rect::from_min_size(pos2(x, 0.0), vec2(300.0, 60.0)), 30.0).expect("fits"); - let tabs = [("Approver", tab(0.0)), ("Witness", tab(10.0))]; - let both = tabs[1].1.rect.left_center() + vec2(2.0, 0.0); - assert!(tabs[0].1.rect.contains(both), "the tabs overlap there"); - assert_eq!(crate::forms_ui::tab_under(&tabs, both), Some("Witness")); - assert_eq!(crate::forms_ui::tab_under(&tabs, tabs[0].1.rect.left_center() + vec2(2.0, 0.0)), Some("Approver")); - assert_eq!(crate::forms_ui::tab_under(&tabs, pos2(-5.0, -5.0)), None); -} - /// One page with three signature fields: Approver is empty, Witness is signed (a signature /// dictionary as its value is enough to list it as signed) and Locked is empty but read-only. const SIGN_FIELDS: &[u8] = b"%PDF-1.7 @@ -261,19 +207,6 @@ const SIGN_FIELDS: &[u8] = b"%PDF-1.7 trailer << /Root 1 0 R >> %%EOF"; -/// Every shape painted in the last frame, with nested lists flattened. -fn painted(h: &egui_kittest::Harness<'static, PdfCraftApp>) -> Vec { - let mut stack: Vec = h.output().shapes.iter().map(|c| c.shape.clone()).collect(); - let mut out = Vec::new(); - while let Some(shape) = stack.pop() { - match shape { - egui::Shape::Vec(inner) => stack.extend(inner), - shape => out.push(shape), - } - } - out -} - /// Where the named field's first widget is on screen. fn field_on_screen(h: &egui_kittest::Harness<'static, PdfCraftApp>, name: &str) -> Rect { let app = h.state(); @@ -308,16 +241,12 @@ fn shell(bytes: &'static [u8]) -> egui_kittest::Harness<'static, PdfCraftApp> { h } -/// The accent chips painted in the last frame: the sign tabs. -fn chips(h: &egui_kittest::Harness<'static, PdfCraftApp>) -> Vec { - let accent = Tokens::get(&h.ctx).accent; - painted(h) - .iter() - .filter_map(|s| match s { - egui::Shape::Rect(r) if r.fill == accent => Some(r.rect), - _ => None, - }) - .collect() +/// Where the sign tab of the named field is on screen: the chip in the corner of the part of its +/// widget on the first page, which is where a click on it signs. A label's width only widens the +/// chip to the right, so the icon chip (no label) is the part of the tab that is there at every width. +fn tab_on_screen(h: &egui_kittest::Harness<'static, PdfCraftApp>, name: &str) -> Rect { + let page = h.state().views[0].page_xform(0).expect("page 0 is on screen").rect; + sign_tab_on_page(field_on_screen(h, name), page, 0.0).expect("the field has room for a tab").rect } /// Clicks at `at` and lets the shell answer. @@ -328,52 +257,52 @@ fn click_at(h: &mut egui_kittest::Harness<'static, PdfCraftApp>, at: Pos2) { h.run_steps(3); } -/// In the real shell, an empty signature field shows its accent tab with "Sign" in its -/// top-left corner, and the signed and read-only fields show none. The tab is part of the -/// field: hovering it shows the pointing hand, and clicking it starts signing that field. +/// In the real shell, an empty signature field's sign tab is part of the field: hovering it shows +/// the pointing hand, and clicking it starts signing that field. The signed and read-only fields +/// have no tab: a click where theirs would be starts no signing. #[test] fn empty_signature_fields_show_a_sign_tab_that_signs_them() { let mut h = shell(SIGN_FIELDS); - let (shapes, chips) = (painted(&h), chips(&h)); - let (approver, witness, locked) = (field_on_screen(&h, "Approver"), field_on_screen(&h, "Witness"), field_on_screen(&h, "Locked")); - let tab = chips.iter().copied().find(|c| approver.contains_rect(*c)).unwrap_or_else(|| panic!("no tab in {approver:?}: {chips:?}")); - assert!(tab.min.x - approver.min.x < 8.0 && tab.min.y - approver.min.y < 8.0, "in the top-left corner: {tab:?} in {approver:?}"); - let label = shapes.iter().any(|s| matches!(s, egui::Shape::Text(t) if t.galley.text() == "Sign" && tab.contains(t.pos))); - assert!(label, "the tab says Sign"); - assert!(!chips.iter().any(|c| witness.intersects(*c)), "a signed field has no tab: {chips:?}"); - assert!(!chips.iter().any(|c| locked.intersects(*c)), "a read-only field has no tab: {chips:?}"); + let (witness, locked) = (tab_on_screen(&h, "Witness"), tab_on_screen(&h, "Locked")); + for (what, spot) in [("a signed field", witness), ("a read-only field", locked)] { + click_at(&mut h, spot.center()); + assert!(h.state().sign_draft.is_none(), "{what} has no tab that signs it"); + } + let tab = tab_on_screen(&h, "Approver"); h.hover_at(tab.center()); h.run_steps(1); assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand); click_at(&mut h, tab.center()); - assert_eq!(h.state().dialog, Some(crate::Dialog::Sign)); assert_eq!(h.state().sign_draft.as_ref().and_then(|d| d.field.clone()).as_deref(), Some("Approver")); } -/// A sign tab is drawn over every field, so a click on it signs its field even where a field +/// A sign tab is over every field, so a click on it signs its field even where a field /// earlier in the form's order overlaps it, which would otherwise take the click. Beside the /// tab, the overlapping field still takes clicks as before. #[test] fn a_sign_tab_signs_its_field_where_an_earlier_field_overlaps_it() { let mut h = shell(SIGN_UNDER_TEXT); let (name, approver) = (field_on_screen(&h, "Name"), field_on_screen(&h, "Approver")); - let tab = chips(&h).into_iter().find(|c| approver.contains_rect(*c)).expect("Approver has a tab"); + let tab = tab_on_screen(&h, "Approver"); assert!(name.contains_rect(tab), "the text field covers the tab: {tab:?} in {name:?}"); h.hover_at(tab.center()); h.run_steps(1); assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand); click_at(&mut h, tab.center()); - assert_eq!(h.state().dialog, Some(crate::Dialog::Sign)); assert_eq!(h.state().sign_draft.as_ref().and_then(|d| d.field.clone()).as_deref(), Some("Approver")); assert!(h.state().views[0].forms.focus.is_none(), "the text field didn't open"); - let beside = pos2(tab.right() + 6.0, tab.center().y); + // Three quarters across Approver, level with the tab: clear of the tab at any label width, and + // under both fields. + let beside = pos2(approver.min.x + approver.width() * 0.75, tab.center().y); assert!(name.contains(beside) && approver.contains(beside), "beside the tab, both fields are under the pointer"); - h.state_mut().dialog = None; + // The sign dialog closes, and the signing the click started is forgotten. + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(!h.state().modal_open(), "the sign dialog is closed"); h.state_mut().sign_draft = None; - h.run_steps(1); click_at(&mut h, beside); assert_eq!(h.state().views[0].forms.focus.as_ref().map(|f| f.name.as_str()), Some("Name"), "the earlier field takes the click"); } diff --git a/crates/ui-egui/src/canvas/signature_drag.rs b/crates/ui-egui/src/canvas/signature_drag.rs index 9f7a071ac7..2f8478540a 100644 --- a/crates/ui-egui/src/canvas/signature_drag.rs +++ b/crates/ui-egui/src/canvas/signature_drag.rs @@ -2,16 +2,41 @@ //! follows each pointer frame, moved or resized, without editing the PDF. Any other comment //! follows the pointer while it is moved: its own layer is drawn where it goes. -use egui::{ColorImage, TextureHandle, TextureOptions, pos2, vec2}; +use craft::review::AnnotationEdit; +use craft::ui::primitives::textures::{CachedTexture, TextureStore, TextureStoreOptions}; +use craft::ui::primitives::{Draw, backdrop}; +use egui::{ColorImage, Pos2, Rect, TextureId, pos2, vec2}; use pdfcraft_engine::{Document, Edit}; use pdfcraft_render::{PageInfo, RenderPool, RenderRequest, Tile}; +use super::PageXform; use crate::QuickTool; -use crate::comments::{CommentView, Gesture, PageCx}; +use crate::comments::{CommentView, PageCx, id_of, key_of}; /// The longest side, in pixels, a stamp's own layer is rendered at. const MAX_STAMP_SIDE: f32 = 2048.0; +/// Which of a drag's pictures a texture is. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum Layer { + /// An image signature's own image. + Image, + /// The page without the stamp. + Background, + /// A stamp rendered alone. + Stamp, +} + +/// What names one of the drag's textures in the store: the document's edit generation, the page, the +/// comment's index and the picture. +type DragKey = (u64, usize, usize, Layer); + +/// The store of the drag's textures. Its pictures are named by the app and change as the view zooms, so they +/// are not an icon or a thumbnail. +fn drag_store(ctx: &egui::Context) -> TextureStore { + TextureStore::in_context(ctx, "signature-drag", TextureStoreOptions::frames()) +} + #[derive(Default)] pub(crate) struct SignatureDrag { key: Option<(u64, usize, usize)>, @@ -24,6 +49,8 @@ pub(crate) struct SignatureDrag { /// can't be read): only its frame follows the pointer, and the layer isn't made again on /// every frame of the drag. no_layer: Option<(u64, usize, usize)>, + /// Textures of layers that were dropped where no context was at hand, freed by the next call that has one. + retired: Vec, } struct Moving { @@ -36,18 +63,21 @@ struct Moving { struct Layers { front: Front, renderer: RenderPool, - background: Option, + /// The page without the stamp, up to one whole-page texture. + background: Option, tag: Option, received_tag: Option, /// Keep the final position visible until the normal page raster catches up. settling: bool, + /// Every key this drag put in the store, to free them with the layers. + keys: Vec, } /// What is drawn over the page without the stamp. enum Front { /// An image signature's own image, sharp at every zoom. Image { - texture: TextureHandle, + texture: CachedTexture, opacity: f32, /// The page /Rotate the PDF draws the image turned back by. turn: i64, @@ -63,19 +93,22 @@ struct StampLayer { from: [f32; 4], tag: Option, /// The rendered stamp: its tag, and the view-space box its pixels cover. - pixels: Option<(u64, TextureHandle, [f32; 4])>, + pixels: Option<(u64, CachedTexture, [f32; 4])>, /// The tag whose render failed: not waited for, and asked for again only at another scale. failed: Option, + /// The key the pixels were put in the store under. + stored: Option, } impl SignatureDrag { pub fn prepare(&mut self, ctx: &egui::Context, doc: &Document, selected: Option<(usize, usize)>, scale: f32) { + self.forget_retired(ctx); let key = selected.map(|(p, i)| (doc.edit_generation(), p, i)); if self.key != key { self.key = key; self.aspect_ratio = None; - self.layers = None; - if let Some((_, page, index)) = key + self.retire_layers(); + if let Some((generation, page, index)) = key && let Some(a) = doc.info.annotations.iter().find(|a| a.page == page && a.index == index && a.subtype == "Stamp" && !a.locked) { if let Ok(Some(preview)) = doc.image_signature_preview(page, index) { @@ -84,20 +117,20 @@ impl SignatureDrag { // As displayed, the image is turned by the page's rotation less the turn it is drawn back by. let shown = doc.info.pages.get(page).map_or(0, |p| i64::from(p.rotation)) - preview.turn; self.aspect_ratio = Some(if shown.rem_euclid(180) == 0 { ratio } else { ratio.recip() }); - let texture = ctx.load_texture( - "signature-drag-image", - ColorImage::from_rgba_unmultiplied(preview.image.size(), preview.image.rgba()), - TextureOptions::LINEAR, - ); - let front = Front::Image { texture, opacity: preview.opacity, turn: preview.turn }; - self.layers = Some(Layers::new(front, preview.renderer())); + let image_key = (generation, page, index, Layer::Image); + let image = ColorImage::from_rgba_unmultiplied(preview.image.size(), preview.image.rgba()); + // An image past the store's limits has no sharp preview: the frame alone follows the pointer. + if let Some(texture) = backdrop::upload(&drag_store(ctx), ctx, image_key, image) { + let front = Front::Image { texture, opacity: preview.opacity, turn: preview.turn }; + self.layers = Some(Layers::new(front, preview.renderer(), vec![image_key])); + } } else if let Ok(Some(preview)) = doc.stamp_preview(page, index) { - let stamp = StampLayer { renderer: preview.stamp_renderer(), from: a.rect, tag: None, pixels: None, failed: None }; - self.layers = Some(Layers::new(Front::Stamp(Box::new(stamp)), preview.background_renderer())); + let stamp = StampLayer { renderer: preview.stamp_renderer(), from: a.rect, tag: None, pixels: None, failed: None, stored: None }; + self.layers = Some(Layers::new(Front::Stamp(Box::new(stamp)), preview.background_renderer(), Vec::new())); } } } - let (Some((_, page, _)), Some(layers)) = (self.key, self.layers.as_mut()) else { return }; + let (Some((generation, page, index)), Some(layers)) = (self.key, self.layers.as_mut()) else { return }; // The background matches the page view up to one whole-page texture; past that the view // tiles and this preview stays at that cap. let Some(p) = doc.info.pages.get(page) else { return }; @@ -110,27 +143,38 @@ impl SignatureDrag { if let Some(out) = layers.renderer.try_recv() && out.request.tag == tag { - if out.error.is_none() { - layers.received_tag = Some(tag); - layers.background = Some(ctx.load_texture( - "signature-drag-background", - ColorImage::from_rgba_premultiplied([out.width as usize, out.height as usize], &out.rgba), - TextureOptions::LINEAR, - )); + let background_key = (generation, page, index, Layer::Background); + let uploaded = if out.error.is_none() { + let image = ColorImage::from_rgba_premultiplied([out.width as usize, out.height as usize], &out.rgba); + backdrop::upload(&drag_store(ctx), ctx, background_key, image) } else { - // Leave the ordinary page raster usable if an unsupported PDF can't preview. - self.layers = None; - return; + None + }; + // Leave the ordinary page raster usable if an unsupported PDF can't preview. + match uploaded { + Some(texture) => { + layers.received_tag = Some(tag); + layers.background = Some(texture); + if !layers.keys.contains(&background_key) { + layers.keys.push(background_key); + } + } + None => { + self.retire_layers(); + self.forget_retired(ctx); + return; + } } } let mut pending = layers.received_tag != Some(tag); // The stamp itself is small: it stays sharp at every zoom. if let Front::Stamp(stamp) = &mut layers.front { - match stamp.update(ctx, page, p, scale) { + match stamp.update(ctx, (generation, page, index, Layer::Stamp), page, p, scale) { Some(waiting) => pending |= waiting, // Nothing to lay over the page: the frame alone follows the pointer, as before. None => { - self.layers = None; + self.retire_layers(); + self.forget_retired(ctx); return; } } @@ -158,7 +202,7 @@ impl SignatureDrag { key.0 = generation; m.settling = true; } else { - self.moving = None; + self.retire_moving(); } if let Edit::MoveAnnotation { page, index, .. } | Edit::ResizeAnnotation { page, index, .. } = edit && self.contains(*page, *index) @@ -168,7 +212,10 @@ impl SignatureDrag { layers.settling = true; } } else { - *self = Self { moving: self.moving.take(), ..Self::default() }; + self.retire_layers(); + self.key = None; + self.aspect_ratio = None; + self.no_layer = None; } } @@ -180,12 +227,61 @@ impl SignatureDrag { } } - pub fn paint(&self, painter: &egui::Painter, cx: &PageCx<'_>, cv: &CommentView, pending: Option<&Edit>) { + /// Frees every texture the drag holds: the view goes inactive, or the document closes. + // PLAN: `cache.rs:387` (pdf-canvas-w10) resets the drag with `Default::default()`, which drops the layers but leaves + // their textures in the store until its budget evicts them; it calls `release(ctx)` first. + pub fn release(&mut self, ctx: &egui::Context) { + self.retire_layers(); + self.retire_moving(); + self.key = None; + self.aspect_ratio = None; + self.no_layer = None; + self.forget_retired(ctx); + } + + /// Drops the selected stamp's layers, keeping their textures' keys to free. + fn retire_layers(&mut self) { + if let Some(layers) = self.layers.take() { + self.retired.extend(layers.keys); + self.retired.extend(layers.front.stored()); + } + } + + /// Drops the moved comment's layer, keeping its texture's key to free. + fn retire_moving(&mut self) { + if let Some((_, moving)) = self.moving.take() { + self.retired.extend(moving.layer.stored); + } + } + + /// Frees the textures of dropped layers. + fn forget_retired(&mut self, ctx: &egui::Context) { + if self.retired.is_empty() { + return; + } + let store = drag_store(ctx); + for key in self.retired.drain(..) { + store.forget(ctx, &key); + } + } + + /// Whether the comments tool is moving or resizing the comment `index` of `page` now. + fn dragging(in_flight: Option<&AnnotationEdit>, page: usize, index: usize) -> bool { + let id = id_of(page, index); + match in_flight { + Some(AnnotationEdit::Move { ids, .. }) => ids.contains(&id), + Some(AnnotationEdit::Resize { id: resized, .. }) => *resized == id, + _ => false, + } + } + + pub fn paint(&self, draw: &Draw<'_>, cx: &PageCx<'_>, cv: &CommentView, pending: Option<&Edit>) { let (Some((_, page, index)), Some(layers)) = (self.key, &self.layers) else { return }; if page != cx.page || !matches!(cx.tool, QuickTool::Select | QuickTool::Fill(_)) || cx.hidden { return; } - let dragging = matches!(cv.gesture, Some(Gesture::Move { page: p, index: i, .. } | Gesture::Resize { page: p, index: i, .. }) if (p, i) == (page, index)); + let in_flight = cv.tool.in_flight(); + let dragging = Self::dragging(in_flight.as_ref(), page, index); let released = matches!(pending, Some(Edit::MoveAnnotation { page: p, index: i, .. } | Edit::ResizeAnnotation { page: p, index: i, .. }) if (*p, *i) == (page, index)); if !(dragging || released || layers.settling) { return; @@ -196,21 +292,16 @@ impl SignatureDrag { { return; } - let shift = painter.ctx().input(|i| i.modifiers.shift); - let rect = cx.adjusted_rect(a, cv.gesture.as_ref(), cx.ptr.pos, shift, pending); - let painter = painter.with_clip_rect(painter.clip_rect().intersect(cx.xf.rect)); - cx.xf.paint_image(&painter, background.id(), 0.0, 0.0, 1.0, 1.0); - match &layers.front { - Front::Image { texture, opacity, turn } => cx.xf.paint_user_image( - &painter, - texture.id(), - p, - cx.rect_to_user(rect), - *turn, - egui::Color32::from_white_alpha((opacity * 255.0).round() as u8), - ), - Front::Stamp(stamp) => stamp.paint(&painter, cx, page, rect), - } + let rect = cx.adjusted_rect(a, in_flight, pending); + draw.clipped(cx.xf.rect, |draw| { + paint_quad(draw, page_corners(cx.xf), background.id); + match &layers.front { + Front::Image { texture, opacity, turn } => { + draw.faded(*opacity, |draw| paint_quad(draw, user_image_corners(cx.xf, p, cx.rect_to_user(rect), *turn), texture.id)); + } + Front::Stamp(stamp) => stamp.paint(draw, cx, page, rect), + } + }); } /// The page of the comment being moved, whose raster [`Self::prepare_move`] asks about. @@ -222,9 +313,12 @@ impl SignatureDrag { /// starts, kept after release until the page's raster shows it where it went (`stale`: the /// page is still drawn as before its last change). pub fn prepare_move(&mut self, ctx: &egui::Context, doc: &Document, cv: &CommentView, pending: Option<&Edit>, stale: bool, scale: f32) { + self.forget_retired(ctx); let generation = doc.edit_generation(); - let dragged = match cv.gesture { - Some(Gesture::Move { page, index, .. }) if !self.contains(page, index) => Some((generation, page, index)), + let dragged = match cv.tool.in_flight() { + Some(AnnotationEdit::Move { ids, .. }) => { + ids.first().map(|id| key_of(*id)).filter(|(page, index)| !self.contains(*page, *index)).map(|(page, index)| (generation, page, index)) + } _ => None, }; let keep = |key: (u64, usize, usize), m: &Moving| { @@ -234,7 +328,7 @@ impl SignatureDrag { || m.settling && stale }; if self.moving.as_ref().is_some_and(|(key, m)| !keep(*key, m)) { - self.moving = None; + self.retire_moving(); } if self.no_layer != dragged { self.no_layer = None; @@ -250,15 +344,15 @@ impl SignatureDrag { // The box it is drawn in: a comment kept upright on a turned page (NoRotate) // isn't drawn in its /Rect, and the frame it follows is that box too. let rotation = doc.info.pages.get(page).map_or(0, |p| p.rotation); - let layer = StampLayer { renderer: alone.renderer(), from: a.shown_rect(rotation), tag: None, pixels: None, failed: None }; + let layer = StampLayer { renderer: alone.renderer(), from: a.shown_rect(rotation), tag: None, pixels: None, failed: None, stored: None }; self.moving = Some((key, Moving { layer, settling: false })); } _ => self.no_layer = Some(key), } } - let Some(((_, page, _), m)) = self.moving.as_mut() else { return }; + let Some(((generation, page, index), m)) = self.moving.as_mut() else { return }; let Some(p) = doc.info.pages.get(*page) else { return }; - match m.layer.update(ctx, *page, p, scale) { + match m.layer.update(ctx, (*generation, *page, *index, Layer::Stamp), *page, p, scale) { Some(pending) => { if pending { ctx.request_repaint_after(std::time::Duration::from_millis(16)); @@ -272,27 +366,35 @@ impl SignatureDrag { } /// The comment being moved, drawn where it goes (as far as its frame has gone). - pub fn paint_move(&self, painter: &egui::Painter, cx: &PageCx<'_>, cv: &CommentView, pending: Option<&Edit>) { + pub fn paint_move(&self, draw: &Draw<'_>, cx: &PageCx<'_>, cv: &CommentView, pending: Option<&Edit>) { let Some(((_, page, index), m)) = &self.moving else { return }; if *page != cx.page || cx.hidden { return; } let Some(a) = cx.get(*index) else { return }; - let shift = painter.ctx().input(|i| i.modifiers.shift); // As far as its frame has gone from where the move started (once applied, its box is // already where it went). - let rect = cx.adjusted_rect(a, cv.gesture.as_ref(), cx.ptr.pos, shift, pending); + let rect = cx.adjusted_rect(a, cv.tool.in_flight(), pending); let from = cx.xf.user_rect(cx.info, *page, m.layer.from); - let painter = painter.with_clip_rect(painter.clip_rect().intersect(cx.xf.rect)); - m.layer.paint(&painter, cx, *page, from.translate(rect.min - from.min)); + draw.clipped(cx.xf.rect, |draw| m.layer.paint(draw, cx, *page, from.translate(rect.min - from.min))); + } +} + +impl Front { + /// The key a stamp front's pixels were put in the store under. + fn stored(&self) -> Option { + match self { + Front::Image { .. } => None, + Front::Stamp(stamp) => stamp.stored, + } } } impl StampLayer { /// Render the layer's tile at `scale` (or less, within [`MAX_STAMP_SIDE`]) and take it when - /// it arrives. `Some(true)` while the pixels at this scale are still on their way, `None` - /// when there is nothing to draw. - fn update(&mut self, ctx: &egui::Context, page: usize, p: &PageInfo, scale: f32) -> Option { + /// it arrives, stored under `key`. `Some(true)` while the pixels at this scale are still on + /// their way, `None` when there is nothing to draw. + fn update(&mut self, ctx: &egui::Context, key: DragKey, page: usize, p: &PageInfo, scale: f32) -> Option { let (scale, tile) = stamp_tile(p, self.from, scale)?; let tag = (scale * 1000.0) as u64; if self.tag != Some(tag) { @@ -312,39 +414,82 @@ impl StampLayer { let s = out.request.scale; let area = [t.x as f32 / s, t.y as f32 / s, t.x.saturating_add(t.w) as f32 / s, t.y.saturating_add(t.h) as f32 / s]; let image = crate::canvas::texture_image([out.width as usize, out.height as usize], out.rgba); - self.pixels = Some((tag, ctx.load_texture("signature-drag-stamp", image, TextureOptions::LINEAR), area)); + let store = drag_store(ctx); + let Some(texture) = backdrop::upload(&store, ctx, key, image) else { + self.failed = Some(tag); + return None; + }; + // The edit generation moved on while the layer was kept: its pixels are under the new key now. + if let Some(old) = self.stored.filter(|old| *old != key) { + store.forget(ctx, &old); + } + self.stored = Some(key); + self.pixels = Some((tag, texture, area)); } Some(self.pixels.as_ref().is_none_or(|(received, ..)| *received != tag)) } /// The layer's pixels where its box goes on screen, `rect`: moved, and stretched as its box /// is from `from` to `rect`. - fn paint(&self, painter: &egui::Painter, cx: &PageCx<'_>, page: usize, rect: egui::Rect) { + fn paint(&self, draw: &Draw<'_>, cx: &PageCx<'_>, page: usize, rect: Rect) { let Some((_, texture, area)) = &self.pixels else { return }; let from = cx.xf.user_rect(cx.info, page, self.from); if from.width() < 0.01 || from.height() < 0.01 { return; } let stretch = vec2(rect.width() / from.width(), rect.height() / from.height()); - let mut mesh = egui::Mesh::with_texture(texture.id()); - for (u, v) in [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)] { + let corners = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)].map(|(u, v)| { let (x, y) = (area[0] + u * (area[2] - area[0]), area[1] + v * (area[3] - area[1])); let at = cx.xf.norm_to_screen(x / cx.xf.pw, y / cx.xf.ph); - let pos = rect.min + (at - from.min) * stretch; - mesh.vertices.push(egui::epaint::Vertex { pos, uv: pos2(u, v), color: egui::Color32::WHITE }); - } - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(0, 2, 3); - painter.add(egui::Shape::mesh(mesh)); + rect.min + (at - from.min) * stretch + }); + paint_quad(draw, corners, texture.id); } } impl Layers { - fn new(front: Front, renderer: RenderPool) -> Self { - Self { front, renderer, background: None, tag: None, received_tag: None, settling: false } + fn new(front: Front, renderer: RenderPool, keys: Vec) -> Self { + Self { front, renderer, background: None, tag: None, received_tag: None, settling: false, keys } } } +/// The screen corners of the whole page: top-left, top-right, bottom-right, bottom-left of its raster. +fn page_corners(xf: &PageXform) -> [Pos2; 4] { + [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)].map(|(u, v)| xf.norm_to_screen(u, v)) +} + +/// The screen corners an image placed in the user-space `rect` covers, turned back by `turn` (the page +/// /Rotate it was placed for) as a custom stamp's appearance draws it, so with the page's own rotation it +/// reads upright as displayed: the image's top-left, top-right, bottom-right and bottom-left. +fn user_image_corners(xf: &PageXform, p: &PageInfo, rect: [f64; 4], turn: i64) -> [Pos2; 4] { + let (w, h) = (rect[2] - rect[0], rect[3] - rect[1]); + let (shown_w, shown_h) = if turn % 180 == 0 { (w, h) } else { (h, w) }; + let [a, b, c, d, e, f] = pdfcraft_model::view_matrix_for(turn, rect); + [(0.0_f64, 0.0_f64), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)].map(|(u, v)| { + // The texture's (u, v), from its top-left, in the picture's upright frame, then in user space. + let (dx, dy) = (u * shown_w, (1.0 - v) * shown_h); + let (x, y) = (a * dx + c * dy + e, b * dx + d * dy + f); + let q = p.user_to_view(x as f32, y as f32); + xf.norm_to_screen(q[0] / xf.pw, q[1] / xf.ph) + }) +} + +/// Paints `texture` over the quad `corners` (the texture's top-left, top-right, bottom-right and bottom-left +/// on screen). `Draw::texture` paints an axis-aligned rectangle, so a quad turned a quarter is not drawn: a +/// half turn or a mirror is a flip of the texture's coordinates. +// PLAN: a view turned 90 or 270 degrees, or an image turned a quarter, has no preview here: `Draw::texture` has no +// rotated quad. The frame alone follows the pointer there, as without layers. +fn paint_quad(draw: &Draw<'_>, corners: [Pos2; 4], texture: TextureId) { + let [top_left, top_right, _, bottom_left] = corners; + let (across, down) = (top_right - top_left, bottom_left - top_left); + if !corners.iter().all(|c| c.is_finite()) || across.x.abs() < across.y.abs() || down.y.abs() < down.x.abs() { + return; + } + let (u0, u1) = if across.x < 0.0 { (1.0, 0.0) } else { (0.0, 1.0) }; + let (v0, v1) = if down.y < 0.0 { (1.0, 0.0) } else { (0.0, 1.0) }; + draw.texture(Rect::from_points(&corners), texture, Rect::from_min_max(pos2(u0, v0), pos2(u1, v1))); +} + /// The scale and tile of the page raster that hold a stamp at `rect` (user space), a pixel to /// spare around it for its anti-aliased edges: at `scale`, or less to keep it within /// [`MAX_STAMP_SIDE`]. `None` for a page or stamp that has no finite box. @@ -366,6 +511,8 @@ fn stamp_tile(p: &PageInfo, rect: [f32; 4], scale: f32) -> Option<(f32, Tile)> { mod tests { use std::sync::Arc; + use egui::Pos2; + use super::*; /// One page with one comment that has nothing to draw: a sound annotation without an @@ -394,24 +541,40 @@ mod tests { /// A moved comment whose own layer can't be made is asked for once per drag, not on every /// pointer frame (making it copies and writes out the whole document); only its frame follows - /// the pointer. Once the drag ends, the next one asks again. + /// the pointer. Once the drag ends, the next one asks again. The drag is the comments tool's + /// own, started by a real press and move on the comment in the shell. #[test] fn a_comment_with_nothing_to_draw_is_prepared_once_per_drag() { - let mut session = pdfcraft_engine::Session::new(); - let id = session.open("silent.pdf", None, Arc::new(silent()), None).expect("opens"); - let doc = session.get(id).expect("open"); - let index = doc.info.annotations.iter().find(|a| a.subtype == "Sound").expect("listed").index; - let ctx = egui::Context::default(); - let mut cv = CommentView { gesture: Some(Gesture::Move { page: 0, index, from: pos2(0.0, 0.0) }), ..CommentView::default() }; - let mut drag = SignatureDrag::default(); - let key = Some((doc.edit_generation(), 0, index)); - drag.prepare_move(&ctx, doc, &cv, None, false, 1.0); - assert!(drag.moving.is_none(), "nothing to draw"); - assert_eq!(drag.no_layer, key, "remembered for this drag"); - drag.prepare_move(&ctx, doc, &cv, None, false, 1.0); - assert!(drag.moving.is_none() && drag.no_layer == key, "and not made again"); - cv.gesture = None; - drag.prepare_move(&ctx, doc, &cv, None, false, 1.0); - assert_eq!(drag.no_layer, None, "forgotten when the drag ends"); + let bytes = silent(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(move |_cc| { + let mut app = crate::PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.open_bytes("silent.pdf", None, bytes.clone()).unwrap(); + app.set_option("left", "closed").unwrap(); + app.set_option("panel", "none").unwrap(); + app + }); + h.run_steps(6); + let (centre, key): (Pos2, _) = { + let app = h.state(); + let view = &app.views[0]; + let doc = app.session.get(view.id).expect("open"); + let a = doc.info.annotations.iter().find(|a| a.subtype == "Sound").expect("listed"); + let xf = view.page_xform(0).expect("page 0 is on screen"); + let rect = xf.user_rect(&doc.info, 0, a.rect); + (rect.center(), (doc.edit_generation(), 0, a.index)) + }; + h.drag_at(centre); + h.run_steps(2); + h.hover_at(centre + vec2(30.0, 20.0)); + h.run_steps(2); + assert_eq!(h.state().views[0].signature_drag.no_layer, Some(key), "remembered for this drag"); + assert!(h.state().views[0].signature_drag.moving.is_none(), "nothing to draw"); + h.hover_at(centre + vec2(40.0, 30.0)); + h.run_steps(2); + assert_eq!(h.state().views[0].signature_drag.no_layer, Some(key), "and not made again"); + h.drop_at(centre + vec2(40.0, 30.0)); + h.run_steps(3); + assert_eq!(h.state().views[0].signature_drag.no_layer, None, "forgotten when the drag ends"); } }