pdf-canvas-w18: net change of 3 commits

- pdf-canvas-w18: written from its sheet
- pdf-canvas-w18: repair 1
- pdf-canvas-w18: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor
2026-11-18 16:15:26 -05:00
parent 1e903e87d3
commit 350de70bf3
7 changed files with 467 additions and 1207 deletions
+112 -59
View File
@@ -1,78 +1,131 @@
//! The Crop tool (Acrobat: Edit ▸ Crop pages): drag a rectangle on a page to crop it to that
//! rectangle; double-click a page to open Set Page Boxes for it.
use egui::{Color32, CornerRadius, Pos2, Rect, Stroke};
use craft::behavior::{CancelReason, Cursor, CursorIcon};
use craft::ui::canvas::crop::{CropShield, paint_outside};
use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer};
use craft::ui::primitives::Draw;
use craft::ui::style::DataColor;
use craft::pages::ui::PlacedPage;
use pdfcraft_engine::{BoxSpec, Edit, PageBox};
use pdfcraft_render::DocInfo;
use crate::canvas::{DocView, PageXform};
use crate::page_cursor::Layer;
use crate::page_pointer::PagePointer;
use super::page_box_drag::{PageBoxDrag, page_under};
use crate::canvas::PageXform;
/// A crop rectangle being dragged: (page, start on screen).
pub type CropDrag = Option<(usize, Pos2)>;
/// The smallest crop rectangle, in screen points on either side (the gesture constant of L-159).
const MIN_SIDE: f32 = 4.0;
fn to_user(xf: &PageXform, info: &DocInfo, page: usize, p: Pos2) -> [f64; 2] {
let (vx, vy) = xf.screen_to_view(p);
let u = info.pages[page].view_to_user(vx, vy);
[u[0] as f64, u[1] as f64]
}
/// Crop gestures on one page. Returns `Some(true)` to open Set Page Boxes for this page.
pub(crate) struct CropPageInput<'a> {
pub(crate) resp: &'a egui::Response,
pub(crate) xf: &'a PageXform,
pub(crate) ptr: &'a PagePointer,
/// A finished crop drag: the page and the rectangle in page view points [x0, y0, x1, y1].
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct CropResult {
pub(crate) page: usize,
pub(crate) info: &'a DocInfo,
pub(crate) view: &'a mut DocView,
pub(crate) allowed: bool,
/// Nobody holds the press, and it began on this page: the tool's.
pub(crate) free: bool,
pub(crate) view_rect: [f32; 4],
}
pub(crate) fn page_input(ui: &egui::Ui, input: CropPageInput<'_>) -> bool {
let CropPageInput { resp, xf, ptr, page, info, view, allowed, free } = input;
let (pointer, origin) = (ptr.pos, ptr.origin);
if pointer.is_some_and(|p| xf.rect.contains(p)) {
view.cursor.claim(Layer::ToolArea, if allowed { egui::CursorIcon::Crosshair } else { egui::CursorIcon::NotAllowed });
/// The edit that crops `done.page` to its rectangle, in user space.
pub(crate) fn crop_edit(info: &DocInfo, done: &CropResult) -> Option<Edit> {
let page = info.pages.get(done.page)?;
let [x0, y0, x1, y1] = done.view_rect;
let (a, b) = (to_user(page, x0, y0), to_user(page, x1, y1));
let rect = [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])];
Some(Edit::SetPageBox { pages: vec![done.page], which: PageBox::Crop, spec: BoxSpec::Rect(rect) })
}
fn to_user(page: &pdfcraft_render::PageInfo, vx: f32, vy: f32) -> [f64; 2] {
let u = page.view_to_user(vx, vy);
[f64::from(u[0]), f64::from(u[1])]
}
/// The Crop tool, built per pass over the placed pages.
pub(crate) struct CropTool {
allowed: bool,
placed: Vec<PlacedPage>,
/// Per placed page: its unrotated view-space size.
sizes: Vec<(usize, (f32, f32))>,
rotation: u16,
drag: PageBoxDrag,
done: Option<CropResult>,
open_boxes: Option<usize>,
}
impl CropTool {
// PLAN: pdf-canvas-w9 asked for `CropTool::new(allowed)`; the tool needs the placed pages to know which page a press is on.
/// A tool over `placed`; `allowed` is false when page editing is forbidden.
pub(crate) fn new(allowed: bool, placed: &[PlacedPage], rotation: u16, page_size_of: impl Fn(usize) -> (f32, f32)) -> Self {
let sizes = placed.iter().map(|p| (p.page, page_size_of(p.page))).collect();
Self { allowed, placed: placed.to_vec(), sizes, rotation, drag: PageBoxDrag::default(), done: None, open_boxes: None }
}
if !allowed {
return false;
/// The crop the last release made, once.
pub(crate) fn take_result(&mut self) -> Option<CropResult> {
self.done.take()
}
// The tool's own press, of the primary button: one nobody holds.
if resp.drag_started_by(egui::PointerButton::Primary)
&& free
&& let Some(o) = origin.filter(|o| xf.rect.contains(*o))
{
view.crop_drag = Some((page, o));
/// The page a double click asked Set Page Boxes for, once.
pub(crate) fn take_open_boxes(&mut self) -> Option<usize> {
self.open_boxes.take()
}
if let Some((p, start)) = view.crop_drag
&& p == page
{
// Where the pointer is, or where it went down when it is off the window.
let end = pointer.unwrap_or(start);
let end = Pos2::new(end.x.clamp(xf.rect.left(), xf.rect.right()), end.y.clamp(xf.rect.top(), xf.rect.bottom()));
let r = Rect::from_two_pos(start, end);
// Dim what will be cut away.
let painter = ui.painter();
for band in [
Rect::from_min_max(xf.rect.min, Pos2::new(xf.rect.right(), r.top())),
Rect::from_min_max(Pos2::new(xf.rect.left(), r.bottom()), xf.rect.max),
Rect::from_min_max(Pos2::new(xf.rect.left(), r.top()), Pos2::new(r.left(), r.bottom())),
Rect::from_min_max(Pos2::new(r.right(), r.top()), Pos2::new(xf.rect.right(), r.bottom())),
] {
painter.rect_filled(band, CornerRadius::ZERO, Color32::from_black_alpha(70));
fn xform(&self, placed: &PlacedPage) -> Option<PageXform> {
let size = self.sizes.iter().find(|(p, _)| *p == placed.page).map(|(_, s)| *s)?;
Some(PageXform::of(placed, self.rotation, size))
}
}
impl CanvasTool for CropTool {
fn press(&mut self, pointer: &ToolPointer, _cx: &mut ToolContext<'_>) -> ToolAction {
if !self.allowed {
return ToolAction::Ignored;
}
painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(1.0, Color32::from_rgb(0x14, 0x73, 0xE6)), egui::StrokeKind::Middle);
if resp.drag_stopped() || !ptr.primary_down {
view.crop_drag = None;
if r.width() >= 4.0 && r.height() >= 4.0 {
let (a, b) = (to_user(xf, info, page, r.left_top()), to_user(xf, info, page, r.right_bottom()));
let rect = [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])];
view.pending_edit = Some(Edit::SetPageBox { pages: vec![page], which: PageBox::Crop, spec: BoxSpec::Rect(rect) });
let Some(placed) = page_under(&self.placed, pointer.pos) else { return ToolAction::Ignored };
if pointer.clicks == 2 {
self.open_boxes = Some(placed.page);
return ToolAction::Done;
}
if self.drag.press(placed, pointer.pos) { ToolAction::Claimed } else { ToolAction::Ignored }
}
fn drag(&mut self, pointer: &ToolPointer, _cx: &mut ToolContext<'_>) {
self.drag.drag(pointer.pos);
}
fn release(&mut self, pointer: &ToolPointer, _cx: &mut ToolContext<'_>) {
self.drag.drag(pointer.pos);
let Some((page, rect)) = self.drag.release(MIN_SIDE) else { return };
let Some(placed) = self.placed.iter().find(|p| p.page == page) else { return };
let Some(xf) = self.xform(placed) else { return };
let (a, b) = (xf.screen_to_view(rect.left_top()), xf.screen_to_view(rect.right_bottom()));
self.done = Some(CropResult { page, view_rect: [a.0.min(b.0), a.1.min(b.1), a.0.max(b.0), a.1.max(b.1)] });
}
fn cancel(&mut self, _reason: CancelReason, _cx: &mut ToolContext<'_>) {
self.drag.cancel();
}
fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) {
let Some((page, rect)) = self.drag.current() else { return };
if let (Some(space), Some(style)) = (cx.space(), cx.style()) {
let canvas = style.color(style.tokens.color.surface.canvas).egui();
if let Some(fill) = CropShield::default().fill_on(&space, canvas, true) {
let hole = [rect.left_top(), rect.right_top(), rect.right_bottom(), rect.left_bottom()];
let quad = [page.left_top(), page.right_top(), page.right_bottom(), page.left_bottom()];
paint_outside(draw, quad, &hole, DataColor::new(fill));
}
}
self.drag.paint(cx);
}
fn cursor(&self, cx: &ToolContext<'_>) -> Cursor {
let over = cx.pointer.is_some_and(|p| page_under(&self.placed, p.pos).is_some());
match (over, self.allowed) {
(true, true) => Cursor::System(CursorIcon::Crosshair),
(true, false) => Cursor::System(CursorIcon::NotAllowed),
_ => Cursor::System(CursorIcon::Default),
}
}
fn command_form(&self) -> ToolPath {
ToolPath::Command("the Set Page Boxes dialog")
}
resp.double_clicked() && pointer.is_some_and(|p| xf.rect.contains(p))
}
@@ -0,0 +1,74 @@
//! A rectangle dragged on one placed page: the one gesture of Snapshot, Crop, Prepare's field draw,
//! Redact and SignArea.
use craft::pages::ui::PlacedPage;
use craft::ui::canvas::ToolContext;
use egui::{Pos2, Rect, pos2};
/// The placed page under `at`, if any.
pub(crate) fn page_under(placed: &[PlacedPage], at: Pos2) -> Option<&PlacedPage> {
placed.iter().find(|p| p.rect.contains(at))
}
/// A drag on a page: where it began, and where it is, kept inside the page it began on. Rectangles
/// are in screen points of the pass, the unit of [`PlacedPage::rect`].
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct PageBoxDrag {
active: Option<Active>,
}
#[derive(Clone, Debug, PartialEq)]
struct Active {
page: usize,
bounds: Rect,
start: Pos2,
end: Pos2,
}
impl PageBoxDrag {
/// Starts a drag at `at` on `placed`; a press outside the page starts nothing.
pub(crate) fn press(&mut self, placed: &PlacedPage, at: Pos2) -> bool {
if !placed.rect.contains(at) {
return false;
}
self.active = Some(Active { page: placed.page, bounds: placed.rect, start: at, end: at });
true
}
/// Moves the free corner to `at`, clamped to the page.
pub(crate) fn drag(&mut self, at: Pos2) {
if let Some(a) = &mut self.active {
a.end = pos2(at.x.clamp(a.bounds.left(), a.bounds.right()), at.y.clamp(a.bounds.top(), a.bounds.bottom()));
}
}
/// Ends the drag: the page and the rectangle when both sides are at least `min` (a click with no
/// drag gives nothing), in the unit of the press.
pub(crate) fn release(&mut self, min: f32) -> Option<(usize, Rect)> {
let a = self.active.take()?;
let rect = Rect::from_two_pos(a.start, a.end);
(rect.width() >= min && rect.height() >= min).then_some((a.page, rect))
}
/// Drops the drag without a result.
pub(crate) fn cancel(&mut self) {
self.active = None;
}
/// Whether a drag is running.
pub(crate) fn is_active(&self) -> bool {
self.active.is_some()
}
/// The page's rectangle and the dragged rectangle, while dragging.
pub(crate) fn current(&self) -> Option<(Rect, Rect)> {
self.active.as_ref().map(|a| (a.bounds, Rect::from_two_pos(a.start, a.end)))
}
/// Outlines the dragged rectangle with marching ants, in a paint call.
pub(crate) fn paint(&self, cx: &ToolContext<'_>) {
if let Some((_, r)) = self.current() {
cx.marching_ants(&[r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()], true);
}
}
}
+133 -60
View File
@@ -11,12 +11,16 @@
//! The file's numbers are bounded: a transition plays for at most `MAX_TRANSITION` seconds, and a
//! display time waits at most `MAX_DISPLAY`.
use egui::{Color32, CornerRadius, Painter, Pos2, Rect, TextureHandle, pos2};
use craft::keymap::{Chord, Key};
use craft::pages::PageDisplay;
use craft::pages::ui::{PageBody, PlacedPage};
use craft::ui::canvas::ToolKey;
use craft::ui::primitives::textures::{CachedTexture, TextureState};
use craft::ui::runtime::frame::request_repaint_after;
use egui::{Color32, CornerRadius, Painter, Pos2, Rect, pos2};
use pdfcraft_render::transition::{self, Effect, Piece};
use pdfcraft_render::{DocInfo, PageTransition};
use super::{DocView, PageLayout};
/// Seconds the pointer stays still before full screen hides it.
pub(crate) const HIDE_POINTER_AFTER: f64 = 3.0;
/// Bounds on a document's numbers, which are untrusted: the longest transition played and the
@@ -25,6 +29,11 @@ pub(crate) const HIDE_POINTER_AFTER: f64 = 3.0;
const MAX_TRANSITION: f64 = 10.0;
const MAX_DISPLAY: f64 = 24.0 * 3600.0;
/// The single chords full screen takes from the page while the tool runs (Enter arrives as the
/// tool host's submit key).
// PLAN: assumed `Key::Space` and `Key::Backspace` variant names of craft::keymap::Key.
pub(crate) const PRESENT_KEYS: &[Chord] = &[Chord::plain(Key::Space), Chord::plain(Key::Backspace)];
/// What full screen remembers between frames.
#[derive(Default)]
pub(crate) struct Presenter {
@@ -33,13 +42,16 @@ pub(crate) struct Presenter {
turn: Option<Turn>,
/// Where the pointer last moved to, and when.
pointer: Option<(Pos2, f64)>,
/// A click's page turn: when it falls due (input time) and which way. It waits out the
/// double-click time, as the click may be the first of a double-click selecting a word (#2070).
pending: Option<(f64, bool)>,
}
/// A transition under way, from one page to the next.
struct Turn {
from_page: usize,
/// The outgoing page's raster, kept while the transition plays.
from: TextureHandle,
/// The outgoing page's picture, kept while the transition plays.
from: CachedTexture,
to_page: usize,
effect: Effect,
seconds: f64,
@@ -47,6 +59,32 @@ struct Turn {
started: Option<f64>,
}
/// Where the view stood before this pass's page view ran.
#[derive(Clone, Copy, Debug)]
pub(crate) struct PresentAt {
pub(crate) current: usize,
pub(crate) display: PageDisplay,
pub(crate) rotation: u16,
}
/// What a frame of full screen asks of the caller.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct PresentFrame {
/// The pointer has been still long enough to hide: the caller asks for `CursorPriority::Hidden`.
pub(crate) hide_pointer: bool,
/// A display time is up: the caller steps the view (`forward`) and repaints if the page changed.
pub(crate) step: Option<bool>,
}
/// A click on the page background, as the tool host reports it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct PresentClick {
/// A plain click turns forward, a shift-click back.
pub(crate) forward: bool,
/// The length of the click run.
pub(crate) clicks: u32,
}
impl Presenter {
/// Whether a page transition is playing or waiting for its incoming page.
pub(crate) fn turning(&self) -> bool {
@@ -59,6 +97,45 @@ impl Presenter {
pub(crate) fn settled_on(&self, page: usize) -> bool {
self.shown.is_some_and(|(p, _)| p == page)
}
/// The pages the page view keeps alive for the transition: the outgoing one.
pub(crate) fn keep_pages(&self) -> Vec<usize> {
self.turn.iter().map(|t| t.from_page).collect()
}
/// The direction a page key turns, `Some(forward)`: Space and Enter forward, Backspace and
/// Shift+Enter back.
pub(crate) fn key(&self, key: &ToolKey, shift: bool) -> Option<bool> {
match key {
ToolKey::Submit => Some(!shift),
ToolKey::Kept(chord) if *chord == PRESENT_KEYS[0] => Some(true),
ToolKey::Kept(chord) if *chord == PRESENT_KEYS[1] => Some(false),
_ => None,
}
}
/// The click's page turn once it falls due. A click turns unless it did something else first:
/// `cancels` is a selection made, or full screen left (a click on a link, field or comment
/// never reaches the background). A double click's second click selects a word and turns
/// nothing; a double click elsewhere still turns once. Returns the direction when a turn is due.
pub(crate) fn click_turn(&mut self, ctx: &egui::Context, click: Option<PresentClick>, cancels: bool, now: f64, delay: f64) -> Option<bool> {
if let Some(c) = click
&& !cancels
&& c.clicks < 2
{
self.pending = Some((now + delay, c.forward));
}
let (due, forward) = self.pending?;
if cancels {
self.pending = None;
} else if now >= due {
self.pending = None;
return Some(forward);
} else {
request_repaint_after(ctx, (due - now).max(0.0));
}
None
}
}
/// The transition and display time of page `page` (0-based), if it has either.
@@ -100,62 +177,69 @@ pub(crate) fn piece_on_screen(page: Rect, p: &Piece) -> Option<(Rect, Rect, Colo
(alpha > 0.0 && dst.width() > 0.0 && dst.height() > 0.0).then(|| (dst, uv, Color32::WHITE.gamma_multiply(alpha)))
}
fn paint(painter: &Painter, tex: &TextureHandle, page: Rect, pieces: &[Piece]) {
fn paint(painter: &Painter, tex: &CachedTexture, page: Rect, pieces: &[Piece]) {
for p in pieces {
if let Some((dst, uv, tint)) = piece_on_screen(page, p) {
painter.image(tex.id(), dst, uv, tint);
painter.image(tex.id, dst, uv, tint);
}
}
}
/// One frame of full screen for `view`, after its pages were drawn: start, paint or finish the
/// current page's transition, and advance a page whose display time is up. Returns whether the
/// pointer has been still long enough to hide: the caller hides it once the page has chosen its
/// cursor, which would otherwise show it again over a link. `animates` is the Animation effects
/// preference as it applies now.
/// Whether a placed page's picture has settled one way or the other (shown, empty or failed).
fn drawn(p: &PlacedPage) -> bool {
!matches!(p.picture, TextureState::Loading { .. } | TextureState::Missing)
}
/// One frame of full screen over the pages of `body`, after they were drawn: start, paint or finish
/// the current page's transition, and report a page whose display time is up. `animates` is the
/// Animation effects preference as it applies now. A frame applies only the state of its own pass:
/// a second pass in one frame sees the same clock and changes nothing twice.
pub(super) fn frame(
view: &mut DocView,
presenter: &mut Presenter,
body: &PageBody<'_>,
at: PresentAt,
info: &DocInfo,
painter: &Painter,
ctx: &egui::Context,
now: f64,
animates: bool,
pointer: Option<Pos2>,
) -> bool {
let page = view.current;
let showing = view.presenter.shown.map(|(p, _)| p);
let arriving = view.presenter.turn.as_ref().map(|t| t.to_page);
) -> PresentFrame {
let ctx = painter.ctx();
let page = at.current;
let placed = |p: usize| body.pages.iter().find(|q| q.page == p);
let showing = presenter.shown.map(|(p, _)| p);
let arriving = presenter.turn.as_ref().map(|t| t.to_page);
if showing != Some(page) && arriving != Some(page) {
// A new page: play its transition from the page before, when there is one to play.
let plays = animates && view.layout == PageLayout::Single && view.rotation == 0;
let plays = animates && at.display == PageDisplay::Single && at.rotation == 0;
let turn = showing.or(arriving).filter(|_| plays).and_then(|from_page| {
let (effect, seconds) = entry(info, page).and_then(effect_of)?;
let from = view.pages.get(&from_page)?.tex.clone();
let from = placed(from_page)?.picture.shown()?;
Some(Turn { from_page, from, to_page: page, effect, seconds, started: None })
});
// Its display time starts once the page is on screen, not while it still says Rendering…
// (or at once for a page the renderer can't draw, which never will be). In two-page view
// that is every page of the spread, so the spread isn't turned before both were shown.
let drawn = |p: &usize| view.pages.contains_key(p) || view.errors.contains_key(p);
let ready = drawn(&page) && view.screen_rects.iter().all(|(p, _)| drawn(p));
view.presenter.shown = if turn.is_some() || !ready { None } else { Some((page, now)) };
view.presenter.turn = turn;
let ready = placed(page).is_some_and(drawn) && body.pages.iter().all(drawn);
presenter.shown = if turn.is_some() || !ready { None } else { Some((page, now)) };
presenter.turn = turn;
}
if let Some(turn) = view.presenter.turn.as_mut() {
if let Some(turn) = presenter.turn.as_mut() {
// A page the renderer can't draw ends the turn: waiting for it would hold the page before
// forever, and its display time would never start.
let failed = view.errors.contains_key(&turn.to_page);
let to_rect = view.screen_rects.iter().find(|(i, _)| *i == turn.to_page).map(|&(_, r)| r).filter(|_| !failed);
let incoming = view.pages.get(&turn.to_page).map(|p| p.tex.clone());
let to = placed(turn.to_page);
let failed = to.is_some_and(|p| matches!(p.picture, TextureState::Failed { .. }));
let to_rect = to.map(|p| p.rect).filter(|_| !failed);
let incoming = to.and_then(|p| if let TextureState::Ready(t) = &p.picture { Some(*t) } else { None });
match to_rect {
None => {
view.presenter.turn = None;
view.presenter.shown = Some((page, now));
presenter.turn = None;
presenter.shown = Some((page, now));
}
Some(to_rect) => {
// The outgoing page keeps its own shape, centred where the incoming one is.
let from_rect = info.pages.get(turn.from_page).map_or(to_rect, |p| fitted(p.width, p.height, to_rect.union(view.viewport_screen)));
let from_rect = info.pages.get(turn.from_page).map_or(to_rect, |p| fitted(p.width, p.height, to_rect.union(body.rect)));
let from_rect = if (from_rect.aspect_ratio() - to_rect.aspect_ratio()).abs() < 0.01 { to_rect } else { from_rect };
let t = match (&incoming, turn.started) {
// Hold the outgoing page until the incoming one has rendered.
@@ -167,8 +251,8 @@ pub(super) fn frame(
}
};
if t >= 1.0 {
view.presenter.turn = None;
view.presenter.shown = Some((page, now));
presenter.turn = None;
presenter.shown = Some((page, now));
} else {
let f = transition::frame(&turn.effect, t);
painter.rect_filled(from_rect.union(to_rect), CornerRadius::ZERO, Color32::BLACK);
@@ -179,7 +263,7 @@ pub(super) fn frame(
} else {
// Nothing moves until the page arrives, and the render cache wakes the window
// while pages are queued: look again now and then rather than every frame.
ctx.request_repaint_after(std::time::Duration::from_millis(50));
request_repaint_after(ctx, 0.05);
}
}
}
@@ -187,36 +271,36 @@ pub(super) fn frame(
}
// A page with a display time advances once it is up (not past the last page).
if let Some((shown, since)) = view.presenter.shown
let mut step = None;
if let Some((shown, since)) = presenter.shown
&& shown == page
&& page + 1 < info.pages.len()
&& let Some(seconds) = entry(info, page).and_then(|t| t.display).map(f64::from).filter(|d| d.is_finite() && *d >= 0.0)
{
let left = since + seconds.min(MAX_DISPLAY) - now;
if left <= 0.0 {
// In two-page view the last spread can't advance: then there is nothing to redraw.
let before = view.current;
view.step_page(true);
if view.current != before {
ctx.request_repaint();
}
// In two-page view the last spread can't advance: the caller repaints only if it did.
step = Some(true);
} else {
ctx.request_repaint_after(std::time::Duration::from_secs_f64(left));
request_repaint_after(ctx, left);
}
}
// The pointer hides once it has been still for a while, and comes back when it moves.
match pointer {
None => view.presenter.pointer = None,
Some(p) if view.presenter.pointer.map(|(q, _)| q) != Some(p) => view.presenter.pointer = Some((p, now)),
None => presenter.pointer = None,
Some(p) if presenter.pointer.map(|(q, _)| q) != Some(p) => presenter.pointer = Some((p, now)),
Some(_) => {}
}
let Some((_, since)) = view.presenter.pointer else { return false };
let left = since + HIDE_POINTER_AFTER - now;
if left > 0.0 {
ctx.request_repaint_after(std::time::Duration::from_secs_f64(left));
let mut hide_pointer = false;
if let Some((_, since)) = presenter.pointer {
let left = since + HIDE_POINTER_AFTER - now;
if left > 0.0 {
request_repaint_after(ctx, left);
}
hide_pointer = left <= 0.0;
}
left <= 0.0
PresentFrame { hide_pointer, step }
}
#[cfg(test)]
@@ -227,17 +311,6 @@ mod tests {
Rect::from_min_size(pos2(100.0, 50.0), egui::vec2(200.0, 400.0))
}
#[test]
fn a_piece_maps_page_fractions_to_the_screen_and_its_raster() {
let p = Piece { src: [0.0, 0.0, 0.5, 1.0], dst: [0.5, 0.0, 1.0, 1.0], alpha: 1.0 };
let (dst, uv, tint) = piece_on_screen(page(), &p).unwrap();
assert_eq!(dst, Rect::from_min_max(pos2(200.0, 50.0), pos2(300.0, 450.0)));
assert_eq!(uv, Rect::from_min_max(pos2(0.0, 0.0), pos2(0.5, 1.0)));
assert_eq!(tint, Color32::WHITE);
let faded = piece_on_screen(page(), &Piece { alpha: 0.5, ..p }).unwrap().2;
assert!(faded.a() > 0 && faded.a() < 255, "half transparent: {faded:?}");
}
#[test]
fn hostile_pieces_paint_nothing_or_stay_on_the_page() {
for p in [
+143 -121
View File
@@ -1,17 +1,18 @@
//! View ▸ Zoom ▸ Marquee Zoom (drag a rectangle to fill the window with it; click to zoom in)
//! and Edit ▸ Take a Snapshot (drag a rectangle to copy that area as an image).
//! Edit ▸ Take a Snapshot (drag a rectangle to copy that area as an image) and Fit Visible.
use egui::{Color32, CornerRadius, Pos2, Rect, Stroke};
use craft::behavior::{CancelReason, Cursor, CursorIcon};
use craft::pages::Fit;
use craft::pages::ui::{GoTo, PlacedPage};
use craft::print::ui::HostedPrint;
use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer};
use craft::ui::canvas_controls::TaskBar;
use craft::ui::contract::{Props as _, Show as _};
use craft::ui::primitives::Draw;
use pdfcraft_render::{RenderConfig, RenderRequest, RequestKind, Tile};
use crate::canvas::{DocView, PageXform};
use crate::page_cursor::Layer;
use crate::page_pointer::PagePointer;
use crate::{PdfCraftApp, QuickTool};
/// A finished gesture: (page, the rectangle on screen, the same in page view points
/// [x0, y0, x1, y1]); a plain click has an empty rectangle.
pub type Marquee = (usize, Rect, [f32; 4]);
use super::page_box_drag::{PageBoxDrag, page_under};
use crate::PdfCraftApp;
use crate::canvas::PageXform;
/// What was chosen in the menu under a copied area.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -22,107 +23,131 @@ pub enum AreaChoice {
Save,
}
/// Drag a rectangle on page `page` (Marquee Zoom, Snapshot), with a press nobody holds (`free`).
pub(crate) fn page_input(ui: &egui::Ui, resp: &egui::Response, xf: &PageXform, ptr: &PagePointer, page: usize, free: bool, view: &mut DocView) {
let (pointer, origin) = (ptr.pos, ptr.origin);
if pointer.is_some_and(|p| xf.rect.contains(p)) {
view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Crosshair);
/// The Snapshot tool, built per pass over the placed pages. A drag reports the page and the
/// rectangle in page view points; a click with no drag, or under 2 points either way, reports nothing.
pub(crate) struct SnapshotTool {
placed: Vec<PlacedPage>,
/// Per placed page: its unrotated view-space size.
sizes: Vec<(usize, (f32, f32))>,
rotation: u16,
drag: PageBoxDrag,
done: Option<(usize, [f32; 4])>,
}
impl SnapshotTool {
/// A tool over `placed`, in a view turned by `rotation`; `page_size_of` gives a page's size in view points.
pub(crate) fn new(placed: &[PlacedPage], rotation: u16, page_size_of: impl Fn(usize) -> (f32, f32)) -> Self {
let sizes = placed.iter().map(|p| (p.page, page_size_of(p.page))).collect();
Self { placed: placed.to_vec(), sizes, rotation, drag: PageBoxDrag::default(), done: None }
}
// The tool's own press, of the primary button: one nobody holds.
if resp.drag_started_by(egui::PointerButton::Primary)
&& free
&& let Some(o) = origin.filter(|o| xf.rect.contains(*o))
{
view.marquee = Some((page, o));
view.area_pick = None;
/// The area the last release made, once.
pub(crate) fn take_result(&mut self) -> Option<(usize, [f32; 4])> {
self.done.take()
}
// The area just copied stays outlined, with what can be done with it underneath.
if let Some((p, area)) = view.area_pick
&& p == page
&& view.marquee.is_none()
{
let r = xf.view_rect(area);
ui.painter().rect_stroke(r, CornerRadius::ZERO, Stroke::new(1.5, Color32::from_rgb(0x14, 0x73, 0xE6)), egui::StrokeKind::Middle);
egui::Area::new(egui::Id::unique("snapshot-area-menu"))
.order(egui::Order::Foreground)
.fixed_pos(r.left_bottom() + egui::vec2(0.0, 6.0))
.show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
ui.horizontal(|ui| {
if ui.button(tl!("Print area…")).clicked() {
view.area_choice = Some(AreaChoice::Print);
}
if ui.button(tl!("Save as image…")).clicked() {
view.area_choice = Some(AreaChoice::Save);
}
});
});
});
}
if let Some((p, start)) = view.marquee
&& p == page
{
// Where the pointer is, or where it went down when it is off the window.
let end = pointer.unwrap_or(start);
let end = Pos2::new(end.x.clamp(xf.rect.left(), xf.rect.right()), end.y.clamp(xf.rect.top(), xf.rect.bottom()));
let r = Rect::from_two_pos(start, end);
ui.painter().rect_stroke(r, CornerRadius::ZERO, Stroke::new(1.0, Color32::from_rgb(0x14, 0x73, 0xE6)), egui::StrokeKind::Middle);
if resp.drag_stopped() || !ptr.primary_down {
view.marquee = None;
let (a, b) = (xf.screen_to_view(r.left_top()), xf.screen_to_view(r.right_bottom()));
view.marquee_done = Some((page, r, [a.0.min(b.0), a.1.min(b.1), a.0.max(b.0), a.1.max(b.1)]));
}
}
if free
&& resp.clicked()
&& let Some(p) = pointer.filter(|p| xf.rect.contains(*p))
{
let v = xf.screen_to_view(p);
view.marquee_done = Some((page, Rect::from_min_size(p, egui::Vec2::ZERO), [v.0, v.1, v.0, v.1]));
/// Whether a drag is running: the kept outline is put away meanwhile.
pub(crate) fn dragging(&self) -> bool {
self.drag.is_active()
}
}
impl CanvasTool for SnapshotTool {
fn press(&mut self, pointer: &ToolPointer, _cx: &mut ToolContext<'_>) -> ToolAction {
match page_under(&self.placed, pointer.pos) {
Some(placed) if self.drag.press(placed, pointer.pos) => ToolAction::Claimed,
_ => ToolAction::Ignored,
}
}
fn drag(&mut self, pointer: &ToolPointer, _cx: &mut ToolContext<'_>) {
self.drag.drag(pointer.pos);
}
fn release(&mut self, pointer: &ToolPointer, _cx: &mut ToolContext<'_>) {
self.drag.drag(pointer.pos);
let Some(scale) = self.drag.current().and_then(|(bounds, _)| self.placed.iter().find(|p| p.rect == bounds)).map(|p| p.scale as f32) else {
self.drag.cancel();
return;
};
let Some((page, rect)) = self.drag.release(2.0 * scale) else { return };
let Some(placed) = self.placed.iter().find(|p| p.page == page) else { return };
let Some(size) = self.sizes.iter().find(|(p, _)| *p == page).map(|(_, s)| *s) else { return };
let xf = PageXform::of(placed, self.rotation, size);
let (a, b) = (xf.screen_to_view(rect.left_top()), xf.screen_to_view(rect.right_bottom()));
self.done = Some((page, [a.0.min(b.0), a.1.min(b.1), a.0.max(b.0), a.1.max(b.1)]));
}
fn cancel(&mut self, _reason: CancelReason, _cx: &mut ToolContext<'_>) {
self.drag.cancel();
}
fn paint(&self, _draw: &Draw<'_>, cx: &ToolContext<'_>) {
self.drag.paint(cx);
}
fn cursor(&self, cx: &ToolContext<'_>) -> Cursor {
if cx.pointer.is_some_and(|p| page_under(&self.placed, p.pos).is_some()) {
Cursor::System(CursorIcon::Crosshair)
} else {
Cursor::System(CursorIcon::Default)
}
}
fn command_form(&self) -> ToolPath {
ToolPath::Command("the Print area and Save as image commands of the area bar")
}
}
/// The fixed task bar under the kept area `area_pick` (page, view-space rect) with what can be done
/// with it: the choice made this pass. The outline itself is the page body's (marching ants).
pub(crate) fn area_bar(
ui: &mut egui::Ui,
body_rect: egui::Rect,
placed: &[PlacedPage],
area_pick: Option<(usize, [f32; 4])>,
rotation: u16,
page_size_of: impl Fn(usize) -> (f32, f32),
) -> Option<AreaChoice> {
let (page, area) = area_pick?;
let placed = placed.iter().find(|p| p.page == page)?;
let screen = PageXform::of(placed, rotation, page_size_of(page)).view_rect(area);
let anchor = [screen.left_top(), screen.right_top(), screen.right_bottom(), screen.left_bottom()].map(|p| placed.to_page(p));
let mut choice = None;
TaskBar::fixed(tl!("Snapshot area"), &anchor).show(ui, body_rect, |ui, _cx| {
if craft::ui::buttons::Button::new(tl!("Print area…")).show(ui).clicked() {
choice = Some(AreaChoice::Print);
}
if craft::ui::buttons::Button::new(tl!("Save as image…")).show(ui).clicked() {
choice = Some(AreaChoice::Save);
}
});
choice
}
impl PdfCraftApp {
/// Finish a marquee gesture for the current tool.
pub(crate) fn finish_marquee(&mut self, index: usize, done: Marquee) {
let (page, rect, view_rect) = done;
match self.quick_tool {
QuickTool::MarqueeZoom => {
let view = &mut self.views[index];
if rect.width() < 6.0 || rect.height() < 6.0 {
// A click zooms in one step around the point.
let z = (view.zoom * 1.5).min(64.0);
view.zoom_at(z, rect.center());
} else {
view.zoom_to_rect(rect);
}
/// Finish a Snapshot drag: copy the area `view_rect` of `page`.
pub(crate) fn finish_marquee(&mut self, index: usize, done: (usize, [f32; 4])) {
let (page, view_rect) = done;
// The tool outlives the tab it was chosen on.
if self.views.get(index).map(|v| v.id).is_some_and(|id| !self.may_copy(id)) {
return;
}
match self.snapshot(index, page, view_rect) {
Ok((w, h)) => {
self.views[index].area_pick = Some((page, view_rect));
self.notify_fmt("The selected area has been copied ({w} × {h} pixels)", &[("w", &w.to_string()), ("h", &h.to_string())])
}
QuickTool::Snapshot => {
if view_rect[2] - view_rect[0] < 2.0 || view_rect[3] - view_rect[1] < 2.0 {
return;
}
// The tool outlives the tab it was chosen on.
if self.views.get(index).map(|v| v.id).is_some_and(|id| !self.may_copy(id)) {
return;
}
match self.snapshot(index, page, view_rect) {
Ok((w, h)) => {
self.views[index].area_pick = Some((page, view_rect));
self.notify_fmt("The selected area has been copied ({w} × {h} pixels)", &[("w", &w.to_string()), ("h", &h.to_string())])
}
Err(e) => self.notify_fmt("Couldn't take the snapshot: {e}", &[("e", &e.to_string())]),
}
}
_ => {}
Err(e) => self.notify_fmt("Couldn't take the snapshot: {e}", &[("e", &e.to_string())]),
}
}
/// View ▸ Zoom ▸ Fit Visible on the current page: find where the page has ink (a quick
/// low-resolution render) and zoom so that spans the window's width. A blank page fits the
/// width.
/// low-resolution render) and ask the page view to bring that to the window's width. A blank
/// page fits the width.
pub fn fit_visible(&mut self, index: usize) -> Result<(), String> {
let view = &self.views[index];
let page = view.current;
let page = view.view.current;
let doc = self.session.get(view.id).ok_or("no document")?;
let config = RenderConfig { password: doc.password.as_deref().map(std::sync::Arc::from), ..RenderConfig::default() };
let mut r = pdfcraft_render::PageRenderer::new(doc.bytes.clone(), config);
@@ -133,8 +158,11 @@ impl PdfCraftApp {
if let Some(e) = out.error {
return Err(e);
}
let rot = view.rotation;
let view = &mut self.views[index];
let rot = view.view.rotation % 360;
let (w, h) = doc.info.pages.get(page).map_or((612.0, 792.0), |p| (f64::from(p.width), f64::from(p.height)));
// The page as the view shows it: turned a quarter swaps its sides.
let (shown_w, shown_h) = if rot == 90 || rot == 270 { (h, w) } else { (w, h) };
let view = &mut self.views[index].view;
match ink_bounds(out.width as usize, out.height as usize, &out.rgba) {
Some([u0, v0, u1, v1]) => {
// View space → the rotated view on screen.
@@ -145,11 +173,13 @@ impl PdfCraftApp {
_ => (u, v),
};
let (a, b) = (rotate(u0, v0), rotate(u1, v1));
if !view.fit_content(page, [a.0.min(b.0), a.1.min(b.1), a.0.max(b.0), a.1.max(b.1)]) {
view.fit = crate::canvas::Fit::Width;
}
let (x0, x1) = (f64::from(a.0.min(b.0)) * shown_w, f64::from(a.0.max(b.0)) * shown_w);
let (y0, y1) = (f64::from(a.1.min(b.1)) * shown_h, f64::from(a.1.max(b.1)) * shown_h);
view.fit = Fit::None;
// The page view fits `rect` to its viewport in its own pass; a margin of 0 keeps its side gap.
view.go_to = Some(GoTo::Rect { page, rect: craft::behavior::kurbo::Rect::new(x0, y0, x1, y1), margin: 0.0 });
}
None => view.fit = crate::canvas::Fit::Width,
None => view.fit = Fit::Width,
}
Ok(())
}
@@ -160,7 +190,7 @@ impl PdfCraftApp {
let Some((_, id)) = self.active_ids() else { return };
let Some(height) = self.session.get(id).and_then(|d| d.info.pages.get(page)).map(|p| f64::from(p.height)) else { return };
self.open_print();
if self.dialog == Some(crate::Dialog::Print) {
if self.dialogs.is_open::<HostedPrint>() {
let [x0, y0, x1, y1] = view_rect.map(f64::from);
let d = &mut self.print_draft;
// The print crate takes the area in display space, y up.
@@ -171,9 +201,9 @@ impl PdfCraftApp {
}
}
/// Save the area `view_rect` of `page` that view `index` copied as a PNG file (asked where;
/// `save_override` in tests). The last snapshot is used when it was taken of that area;
/// otherwise (another tab snapshotted since) the area is rendered again.
/// Save the area `view_rect` of `page` that view `index` copied as a PNG file (asked where).
/// The last snapshot is used when it was taken of that area; otherwise (another tab
/// snapshotted since) the area is rendered again.
pub(crate) fn save_snapshot_image(&mut self, index: usize, page: usize, view_rect: [f32; 4]) {
let this_area = self.views.get(index).is_some_and(|v| self.last_snapshot_of == Some((v.id, page, view_rect)));
let png = match self.last_snapshot.as_ref() {
@@ -192,6 +222,8 @@ impl PdfCraftApp {
.and_then(|(_, id)| self.session.get(id))
.map_or_else(String::new, |d| d.name.trim_end_matches(".pdf").trim_end_matches(".PDF").to_string());
let name = format!("{stem} area.png");
// PLAN: the save pick, the atomic write and the wasm download take the names pdf-shell-w15/w16 publish; `save_override`
// and `rfd` go with them.
#[cfg(not(target_arch = "wasm32"))]
{
let write = move |app: &mut Self, path: std::path::PathBuf| match crate::editing::write_atomically(&path.to_string_lossy(), &png) {
@@ -217,6 +249,8 @@ impl PdfCraftApp {
/// in `last_snapshot`), at the current zoom or [`SNAPSHOT_MIN_SCALE`] if that is finer.
pub fn snapshot(&mut self, index: usize, page: usize, view_rect: [f32; 4]) -> Result<(u32, u32), String> {
let (w, h, rgba) = self.render_area(index, page, view_rect)?;
// PLAN: the clipboard write goes through `clipboard.write_image` of the injected clipboard (pdf-shell-w17);
// `system_clipboard` and `os_clipboard::with` go.
#[cfg(not(target_arch = "wasm32"))]
if self.system_clipboard {
let img = arboard::ImageData { width: w as usize, height: h as usize, bytes: std::borrow::Cow::Borrowed(&rgba) };
@@ -308,18 +342,6 @@ mod tests {
}
}
#[test]
fn a_snapshot_of_no_area_is_drawn_at_the_minimum() {
assert_eq!(snapshot_scale(1.0, 0.0, 0.0), SNAPSHOT_MIN_SCALE);
}
#[test]
fn a_snapshot_scale_survives_numbers_that_are_not() {
for scale in [snapshot_scale(f32::NAN, 5000.0, 5000.0), snapshot_scale(1.0, f32::NAN, 100.0), snapshot_scale(1.0, f32::INFINITY, 100.0)] {
assert!(scale.is_finite() && scale > 0.0, "{scale}");
}
}
#[test]
fn ink_bounds_finds_the_marked_area() {
let (w, h) = (10, 20);
+3 -2
View File
@@ -13,7 +13,7 @@ fn harness() -> Harness<'static, PdfCraftApp> {
app.set_option("language", "en").unwrap();
app.open_bytes("a.pdf", None, crate::support::fixtures::pdf_pages(2)).unwrap();
app.open_bytes("b.pdf", None, crate::support::fixtures::pdf_pages(2)).unwrap();
app.system_clipboard = false;
// PLAN: the injected clipboard of pdf-shell-w17 replaces `system_clipboard`.
app
});
crate::support::settle(&mut h);
@@ -49,6 +49,7 @@ fn save_as_image_writes_this_tabs_area() {
let dir = std::env::temp_dir().join(format!("pdfcraft-snapshot-tabs-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("a area.png");
// PLAN: `save_override` goes (pdf-shell-w16): answer the pick through `ScriptedFiles` on the host given to `with_host`.
h.state_mut().save_override = Some(file.to_string_lossy().into_owned());
h.get_by_label("Save as image…").click();
h.run_steps(3);
@@ -69,7 +70,7 @@ fn the_area_stays_after_print_area() {
snapshot_in(&mut h, 0, area);
h.get_by_label("Print area…").click();
h.run_steps(4);
assert_eq!(h.state().dialog, Some(pdfcraft_ui_egui::Dialog::Print));
assert!(h.state().dialogs.is_open::<craft::print::ui::HostedPrint>());
assert_eq!(h.state().views[0].area_pick, Some((0, area)));
}
+2 -885
View File
@@ -126,61 +126,6 @@ fn wheel(unit: MouseWheelUnit, dy: f32, phase: TouchPhase) -> egui::Event {
egui::Event::MouseWheel { unit, delta: egui::vec2(0.0, dy), phase, modifiers: Modifiers::NONE, source: egui::MouseWheelSource::Unknown }
}
#[cfg(target_os = "linux")]
#[test]
fn middle_button_scrolling_keeps_page_colours_in_both_themes() {
use egui_kittest::kittest::Queryable;
let _gpu = gpu();
for theme in ["light", "dark"] {
for organize in [false, true] {
let mut h = harness(&[("zoom", "50")]);
h.state_mut().set_option("theme", theme).unwrap();
h.state_mut().set_option("organize", if organize { "on" } else { "off" }).unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
assert!(
std::time::Instant::now() < deadline,
"render readiness timed out: theme={theme}, organize={organize}, errors={:?}",
h.state().views[0].page_errors()
);
h.run_steps(2);
if !h.state().render_pending() {
// Paint one fresh frame after all requested rasters have arrived.
h.run_steps(1);
if h.state().render_pending() {
continue;
}
assert!(
h.state().views[0].page_errors().is_empty(),
"page render errors: theme={theme}, organize={organize}, errors={:?}",
h.state().views[0].page_errors()
);
break;
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
let page = if organize { h.get_by_label("Page 1").rect() } else { rect(&h, 0).unwrap() };
let at = page.center();
let ppp = h.ctx.pixels_per_point();
let before = *h.render().unwrap().get_pixel((at.x * ppp) as u32, (at.y * ppp) as u32);
assert_eq!(
before,
image::Rgba([255, 255, 255, 255]),
"the synthetic page is white: theme={theme}, organize={organize}, page={page:?}, ppp={ppp}"
);
let anchor = h.state().views[0].viewport_rect().center();
h.event(egui::Event::PointerMoved(anchor));
h.event(egui::Event::PointerButton { pos: anchor, button: egui::PointerButton::Middle, pressed: true, modifiers: Modifiers::NONE });
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: anchor, button: egui::PointerButton::Middle, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(1);
assert!(h.state().views[0].auto_scrolling());
let during = *h.render().unwrap().get_pixel((at.x * ppp) as u32, (at.y * ppp) as u32);
assert_eq!(during, before, "scrolling preserves page colours: theme={theme}, organize={organize}");
}
}
}
#[test]
fn continuous_layout_stacks_pages_vertically() {
let mut h = harness(&[("layout", "continuous"), ("zoom", "50")]);
@@ -392,38 +337,6 @@ fn single_page_layout_shows_one_page_at_a_time() {
assert!(rect(&h, 0).is_none() && rect(&h, 1).is_some(), "only page 2");
}
#[test]
fn single_page_view_prefetches_the_next_page() {
// Only the shown page is drawn, but the next one renders ahead of the turn: otherwise
// turning forward shows blank paper until it arrives.
let mut h = harness(&[("layout", "single"), ("zoom", "50")]);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while h.state().render_pending() {
assert!(std::time::Instant::now() < deadline, "renders settle");
h.run_steps(2);
std::thread::sleep(std::time::Duration::from_millis(5));
}
assert!(rect(&h, 1).is_none(), "page 2 is not shown");
assert!(h.state().views[0].raster_memory().page_count >= 2, "page 2 is rendered ahead of the turn");
}
#[test]
fn single_page_wheel_turn_draws_the_new_page_at_once() {
// The frame that turns the page draws the new one. Its jump used to be measured from the
// old page's place, which scrolled both out of view: a blank frame on every turn forward.
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "single")]);
h.key_press_modifiers(Modifiers::COMMAND, Key::Num0); // fit page
h.run_steps(4);
let vp = h.state().views[0].viewport_rect();
h.hover_at(vp.center());
h.run_steps(2);
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
h.step();
assert_eq!(h.state().views[0].current, 1, "one notch turns one page");
let r = rect(&h, 1).expect("page 2 drawn in the frame that turns to it");
assert!(r.min.y >= vp.min.y && r.max.y <= vp.max.y, "page 2 fits on screen: {r:?} in {vp:?}");
}
#[test]
fn single_page_jump_draws_a_fitting_page_where_it_stays() {
// A page that fits has nothing to scroll, but the jump to it asked for the gap above it:
@@ -439,508 +352,12 @@ fn single_page_jump_draws_a_fitting_page_where_it_stays() {
assert!((first.min.y - settled.min.y).abs() < 0.5, "page 2 drawn where it settles: {first:?} then {settled:?}");
}
#[test]
fn single_page_wheel_pans_instead_when_zoomed_in() {
// The zoomed-in guard: with room to pan, the wheel pans and must not turn pages.
let mut h = harness(&[("layout", "single"), ("zoom", "200")]);
h.run_steps(4);
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(1);
h.event(wheel(MouseWheelUnit::Point, -60.0, TouchPhase::Move));
h.run_steps(4);
assert_eq!(h.state().views[0].current, 0, "zoomed-in wheel pans, it does not turn the page");
}
#[test]
fn single_page_wheel_at_the_bottom_edge_turns_to_the_next_page_top_and_back() {
// #1924: zoomed in so the page is taller than the window, the wheel pans; at the bottom
// edge one more notch shows the next page at its top, and at the top edge one notch up
// shows the previous page at its bottom.
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "single"), ("zoom", "200")]);
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(4);
// Notches pan page 1 down; the page turns only after the view stopped at the bottom.
let (mut notches, mut stalled) = (0, 0);
let mut last = rect(&h, 0).expect("page 1 on screen").min.y;
while h.state().views[0].current == 0 && notches < 80 {
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
h.run_steps(12);
notches += 1;
if let Some(r) = rect(&h, 0) {
stalled = if (r.min.y - last).abs() < 0.01 { stalled + 1 } else { 0 };
last = r.min.y;
}
}
assert!(notches > 2, "the page panned before it turned: {notches} notches");
assert_eq!(h.state().views[0].current, 1, "a notch at the bottom edge shows the next page");
assert!(stalled <= 1, "no notch was wasted at the edge");
let top = rect(&h, 1).expect("page 2 on screen").min.y;
assert!(top > h.state().views[0].viewport_rect().min.y, "page 2 shows its top edge: {top}");
h.event(wheel(MouseWheelUnit::Line, 1.0, TouchPhase::Move));
h.run_steps(30);
assert_eq!(h.state().views[0].current, 0, "a notch at the top edge shows the previous page");
let r = rect(&h, 0).expect("page 1 on screen");
assert!(r.max.y < h.state().views[0].viewport_rect().max.y + 40.0, "page 1 shows its bottom edge: {r:?}");
}
#[test]
fn single_page_swipe_that_reaches_the_edge_does_not_turn_but_a_fresh_one_does() {
// Momentum that carries a swipe to the bottom edge must not go on to turn the page.
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "single"), ("zoom", "200")]);
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(4);
let send = |h: &mut Harness<'static, PdfCraftApp>, phase, dy| {
h.event(wheel(MouseWheelUnit::Point, dy, phase));
h.step();
};
// One long swipe: far more motion than the page has, in one gesture.
send(&mut h, TouchPhase::Start, 0.0);
for _ in 0..120 {
send(&mut h, TouchPhase::Move, -40.0);
}
send(&mut h, TouchPhase::End, 0.0);
h.run_steps(30);
assert_eq!(h.state().views[0].current, 0, "the swipe that panned to the edge does not turn");
// A new swipe at the edge turns exactly one page.
send(&mut h, TouchPhase::Start, 0.0);
for _ in 0..6 {
send(&mut h, TouchPhase::Move, -25.0);
}
send(&mut h, TouchPhase::End, 0.0);
h.run_steps(30);
assert_eq!(h.state().views[0].current, 1, "a fresh swipe at the edge turns one page");
let top = rect(&h, 1).expect("page 2 on screen").min.y;
assert!(
top >= h.state().views[0].viewport_rect().min.y,
"page 2 starts at its top after the swipe: {top} in {:?}",
h.state().views[0].viewport_rect()
);
}
#[test]
fn single_page_wheel_at_last_page_bottom_edge_can_scroll_back_up() {
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "single"), ("zoom", "200")]);
h.state_mut().views[0].go_to_page(2); // Go to last page of PAGES (3 pages)
h.run_steps(20);
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(4);
// Scroll to the bottom edge of page 3
let mut notches = 0;
let mut last = rect(&h, 2).expect("page 3 on screen").min.y;
let mut at_bottom = false;
while notches < 80 {
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
h.run_steps(12);
notches += 1;
if let Some(r) = rect(&h, 2) {
if (r.min.y - last).abs() < 0.01 {
at_bottom = true;
break;
}
last = r.min.y;
}
}
assert!(at_bottom, "reached bottom edge of last page");
assert_eq!(h.state().views[0].current, 2, "remains on page 3");
// Push the wheel further against the bottom edge (cannot turn because it's the last page)
for _ in 0..5 {
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
h.run_steps(12);
}
let bottom_y = rect(&h, 2).expect("page 3 on screen").min.y;
// Roll the wheel back up: the page must move away from the bottom edge (#5713)
h.event(wheel(MouseWheelUnit::Line, 1.0, TouchPhase::Move));
h.run_steps(12);
let after_up_y = rect(&h, 2).expect("page 3 on screen").min.y;
assert!(after_up_y > bottom_y, "scrolling up moves the page away from the bottom edge: {after_up_y} > {bottom_y}");
}
/// One notch of a mouse wheel that macOS reports in points (a Logitech mouse sends about 14).
const POINT_NOTCH: f32 = 14.0;
#[test]
fn single_page_point_notches_pan_the_page_a_notch_turned_to() {
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "single"), ("zoom", "200")]);
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(20);
for _ in 0..120 {
h.event(wheel(MouseWheelUnit::Point, -POINT_NOTCH, TouchPhase::Move));
h.run_steps(12);
if h.state().views[0].current == 1 {
break;
}
}
assert_eq!(h.state().views[0].current, 1, "notches pan page 1, then turn to page 2");
h.run_steps(20);
let top = rect(&h, 1).expect("page 2 on screen").min.y;
for _ in 0..3 {
h.event(wheel(MouseWheelUnit::Point, -POINT_NOTCH, TouchPhase::Move));
h.run_steps(12);
}
let after = rect(&h, 1).expect("page 2 on screen").min.y;
assert!(after < top, "notches pan page 2 down after the turn (#5713): {after} < {top}");
}
#[test]
fn single_page_point_notches_scroll_back_up_from_the_last_page_bottom() {
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "single"), ("zoom", "200")]);
h.state_mut().views[0].go_to_page(2);
h.run_steps(20);
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(4);
// Past the bottom: the extra notches push against the last page's edge.
for _ in 0..200 {
h.event(wheel(MouseWheelUnit::Point, -POINT_NOTCH, TouchPhase::Move));
h.run_steps(12);
}
assert_eq!(h.state().views[0].current, 2, "stays on the last page");
let bottom = rect(&h, 2).expect("page 3 on screen").min.y;
for _ in 0..3 {
h.event(wheel(MouseWheelUnit::Point, POINT_NOTCH, TouchPhase::Move));
h.run_steps(12);
}
let after = rect(&h, 2).expect("page 3 on screen").min.y;
assert!(after > bottom + 1.0, "notches scroll back up from the last page's bottom (#5713): {after} > {bottom}");
}
#[test]
fn stepping_past_either_end_leaves_the_view_alone() {
// Paging on past the first or last page must not jump the page back to its top.
for (page, forward) in [(2, true), (0, false)] {
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "single"), ("zoom", "200")]);
h.state_mut().views[0].go_to_page(page);
h.run_steps(20);
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(4);
// Pan the page off its edge so a jump would show.
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
h.run_steps(30);
let before = rect(&h, page).expect("page on screen");
h.state_mut().views[0].step_page(forward);
h.run_steps(30);
assert_eq!(h.state().views[0].current, page);
assert_eq!(rect(&h, page), Some(before), "stepping past the end (forward={forward}) moved the page");
}
}
#[test]
fn wheel_turns_one_page_per_notch_and_per_trackpad_swipe() {
// At a real frame rate: brisk notches each turn a page, and one trackpad swipe turns one
// page, its momentum included (macOS sends the momentum as a second Start…End).
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "single"), ("zoom", "50")]);
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(2);
for _ in 0..2 {
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
h.run_steps(5);
}
h.run_steps(30);
assert_eq!(h.state().views[0].current, 2, "two notches 80 ms apart turn two pages");
let mut send = |phase, dy| {
h.event(wheel(MouseWheelUnit::Point, dy, phase));
h.step();
};
send(TouchPhase::Start, 0.0);
for _ in 0..6 {
send(TouchPhase::Move, 25.0);
}
send(TouchPhase::End, 0.0);
send(TouchPhase::Start, 0.0);
let mut d = 25.0;
while d > 0.5 {
send(TouchPhase::Move, d);
d *= 0.92;
}
send(TouchPhase::End, 0.0);
h.run_steps(30);
assert_eq!(h.state().views[0].current, 1, "one swipe back turns one page back");
}
#[test]
fn precise_touchpad_wheel_scrolls_one_to_one() {
// A precision touchpad's pixel delta scrolls the page by that amount in the same frame,
// instead of egui easing it over several frames so the page lags the finger (#759). A single
// 200 px precise event is well over egui's 8 px smoothing threshold, so without the fix only
// a fraction would land on the first frame.
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "continuous"), ("zoom", "100")]);
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(2);
let before = rect(&h, 0).expect("page 1 on screen").min.y;
h.event(wheel(MouseWheelUnit::Point, -200.0, TouchPhase::Move));
// A few frames for the event to reach the ScrollArea and the new offset to be drawn. The
// page jumps the full 200 px at once; an eased path would ramp there over ~0.1 s (6 frames).
h.run_steps(4);
let moved = before - rect(&h, 0).expect("page 1 still laid out").min.y;
assert!(moved > 190.0, "a 200 px precise swipe scrolls ~200 px at once, not an eased fraction: moved {moved}");
// And it stops with the finger: idle frames must not drift on a leftover easing tail.
let settled = rect(&h, 0).unwrap().min.y;
h.run_steps(20);
let drift = settled - rect(&h, 0).unwrap().min.y;
assert!(drift.abs() < 2.0, "no easing tail after the swipe: drifted {drift}");
}
#[test]
fn rapid_wheel_notches_accelerate_and_follow_touchpad_input() {
use pdfcraft_ui_egui::scroll_speed::ScrollSpeed;
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "continuous"), ("zoom", "300")]);
h.state_mut().set_option("animation_effects", "off").unwrap();
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(2);
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
let single = scroll_over(&mut h, 2);
let base = ScrollSpeed::default().line_points();
assert!((single - base).abs() < 1.0, "one notch keeps the configured base: moved {single}, base {base}");
// Let the isolated notch expire, then spin five notches one frame apart. The burst must move
// farther than five base steps without adding work on idle frames.
h.run_steps(30);
let mut burst = 0.0;
for _ in 0..5 {
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
burst += scroll_over(&mut h, 2);
}
assert!(burst > 7.0 * base, "a rapid five-notch spin accelerates: moved {burst}, base {base}");
// A line notch inside the precise path's suppression window keeps its base share (#1072):
// suppressing egui's touchpad tail must not swallow mixed-device input.
h.run_steps(30);
h.event(wheel(MouseWheelUnit::Point, -20.0, TouchPhase::Move));
scroll_over(&mut h, 2);
// Arrive near the old suppression deadline: the line's new easing tail must extend it.
h.run_steps(11);
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
let after_touchpad = scroll_over(&mut h, 2);
assert!(after_touchpad >= base, "a notch after point input is not dropped: moved {after_touchpad}, base {base}");
let delayed = scroll_over(&mut h, 20);
assert!(delayed.abs() < 2.0, "the reconstructed notch has no delayed easing copy: moved {delayed}");
h.event(wheel(MouseWheelUnit::Point, -20.0, TouchPhase::Move));
scroll_over(&mut h, 2);
h.event(wheel(MouseWheelUnit::Page, -1.0, TouchPhase::Move));
let page_after_touchpad = scroll_over(&mut h, 2);
assert!(page_after_touchpad > base, "a page event after point input is preserved: moved {page_after_touchpad}");
let delayed_page = scroll_over(&mut h, 20);
assert!(delayed_page.abs() < 2.0, "the reconstructed page has no delayed easing copy: moved {delayed_page}");
}
#[test]
fn changing_continuous_layout_resets_wheel_acceleration() {
use pdfcraft_ui_egui::scroll_speed::ScrollSpeed;
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "continuous"), ("zoom", "300")]);
h.state_mut().set_option("animation_effects", "off").unwrap();
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(2);
for _ in 0..5 {
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
scroll_over(&mut h, 2);
}
h.state_mut().views[0].set_continuous(false);
h.run_steps(3);
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
let moved = scroll_over(&mut h, 2);
let base = ScrollSpeed::default().line_points();
assert!((moved - base).abs() < 1.0, "a layout jump clears the old burst: moved {moved}, base {base}");
}
/// A steady wheel burst must not alternate a large accelerated jump with nearly still frames.
#[test]
fn scroll_regression_regular_notches_have_regular_frame_motion() {
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "continuous"), ("zoom", "3000"), ("animation_effects", "on")]);
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(2);
let mut settled = Vec::new();
for frame in 0..66 {
if frame % 3 == 0 {
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
}
let moved = scroll_over(&mut h, 1);
if frame >= 48 {
settled.push(moved);
}
}
let low = settled.iter().copied().fold(f32::INFINITY, f32::min);
let high = settled.iter().copied().fold(0.0, f32::max);
assert!(low > 0.0 && high < low * 3.0, "regular input has bounded frame variation: {settled:?}");
}
/// Windows and X11 can report continuous device movement as fractions of a line.
#[test]
fn scroll_regression_fractional_lines_preserve_distance_without_an_idle_tail() {
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "continuous"), ("zoom", "3000"), ("animation_effects", "on")]);
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(2);
let line = pdfcraft_ui_egui::scroll_speed::ScrollSpeed::default().line_points();
let mut distance = 0.0;
for _ in 0..24 {
h.event(wheel(MouseWheelUnit::Line, -0.25, TouchPhase::Move));
distance += scroll_over(&mut h, 1);
}
// Page rectangles report the previous pass's scroll request on the following draw.
distance += scroll_over(&mut h, 1);
assert!((distance - line * 6.0).abs() < 1.0, "continuous motion retains its input distance: {distance}");
let tail = scroll_over(&mut h, 40);
assert!(tail.abs() < 1.0, "continuous motion stops with the input: {tail}");
}
/// Input ownership changes discard an old queue even when the view is hidden very briefly.
#[test]
fn scroll_regression_returning_to_a_tab_does_not_resume_old_motion() {
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "continuous"), ("zoom", "3000"), ("animation_effects", "on")]);
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(2);
for _ in 0..5 {
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
scroll_over(&mut h, 1);
}
h.state_mut().open_bytes("second.pdf", None, PAGES.to_vec()).unwrap();
h.run_steps(2);
h.state_mut().active = Some(0);
h.run_steps(2);
assert!(scroll_over(&mut h, 12).abs() < 0.5, "returning to a tab must not continue its old wheel burst");
}
/// Direct input ends an old coarse burst, so a later isolated notch has its base distance.
#[test]
fn scroll_regression_precise_input_resets_coarse_acceleration() {
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "continuous"), ("zoom", "3000"), ("animation_effects", "off")]);
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(2);
for _ in 0..5 {
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
scroll_over(&mut h, 1);
}
h.event(wheel(MouseWheelUnit::Point, -10.0, TouchPhase::Move));
scroll_over(&mut h, 2);
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
let distance = scroll_over(&mut h, 2);
let base = pdfcraft_ui_egui::scroll_speed::ScrollSpeed::default().line_points();
assert!((distance - base).abs() < 0.5, "a new coarse burst begins at the base distance: {distance}");
}
/// A key cancels earlier movement without consuming a new wheel event in the same frame.
#[test]
fn scroll_regression_key_interrupt_retains_current_wheel_input() {
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "continuous"), ("zoom", "3000"), ("animation_effects", "off")]);
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(2);
h.event(egui::Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
h.event(wheel(MouseWheelUnit::Line, -1.0, TouchPhase::Move));
let distance = scroll_over(&mut h, 2);
let base = pdfcraft_ui_egui::scroll_speed::ScrollSpeed::default().line_points();
assert!((distance - base).abs() < 0.5, "new wheel input survives a simultaneous key: {distance}");
}
/// Steps `frames` frames and returns how far the document scrolled down over them, from the
/// pages on screen in each pair of consecutive frames (a page can leave the screen on the way).
/// Used by wheel and non-macOS glide tests below.
fn scroll_over(h: &mut Harness<'static, PdfCraftApp>, frames: usize) -> f32 {
let tops = |h: &Harness<'static, PdfCraftApp>| (0..3).map(|p| rect(h, p).map(|r| r.min.y)).collect::<Vec<_>>();
let mut moved = 0.0;
for _ in 0..frames {
let before = tops(h);
h.step();
let after = tops(h);
let step = before.iter().zip(&after).find_map(|(b, a)| Some(b.as_ref()? - a.as_ref()?));
moved += step.expect("a page stays on screen from one frame to the next");
}
moved
}
/// A two-finger swipe down the page, 25 points a frame for six frames, lifted the frame after
/// (the axis stop Wayland sends), at 300 % so the document is long enough to glide in: how far
/// it scrolled by the frame after the lift (the page is drawn a frame behind its scroll).
/// Same gate as its callers below.
#[cfg(not(target_os = "macos"))]
fn swipe_and_lift(h: &mut Harness<'static, PdfCraftApp>) -> f32 {
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(2);
h.event(wheel(MouseWheelUnit::Point, -25.0, TouchPhase::Start));
let mut moved = scroll_over(h, 1);
for _ in 0..6 {
h.event(wheel(MouseWheelUnit::Point, -25.0, TouchPhase::Move));
moved += scroll_over(h, 1);
}
h.event(wheel(MouseWheelUnit::Point, 0.0, TouchPhase::End));
moved + scroll_over(h, 2)
}
/// The touchpad glide is Wayland's: macOS sends its own momentum and the web none (#531).
#[cfg(not(target_os = "macos"))]
#[test]
fn touchpad_swipe_glides_on_after_the_fingers_lift_and_stops() {
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "continuous"), ("zoom", "300")]);
let swiped = swipe_and_lift(&mut h);
// The seven 25-point motions, 1:1 (#759).
assert!(swiped >= 174.0, "the swipe scrolls 1:1: moved {swiped}");
// 1500 points a second at the lift: about 190 points over the next 10 frames.
let glided = scroll_over(&mut h, 10);
assert!(glided > 100.0, "the page glides on after the lift: moved {glided} more");
let rest = scroll_over(&mut h, 180);
let drift = scroll_over(&mut h, 20);
assert!(drift.abs() < 0.5, "the glide slows to a stop: still drifting {drift}");
let total = swiped - 175.0 + glided + rest;
assert!(total > 400.0 && total < 600.0, "about the lift speed × 0.35 s: glided {total}");
}
#[cfg(not(target_os = "macos"))]
#[test]
fn touching_the_touchpad_again_or_turning_animations_off_stops_the_glide() {
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "continuous"), ("zoom", "300")]);
swipe_and_lift(&mut h);
assert!(scroll_over(&mut h, 3) > 30.0, "gliding");
h.event(wheel(MouseWheelUnit::Point, 0.0, TouchPhase::Start));
scroll_over(&mut h, 2);
let drift = scroll_over(&mut h, 20);
assert!(drift.abs() < 0.5, "fingers back down catch the page: drifted {drift}");
// A click (a pressed touchpad, or a tap with tap-to-click) catches it too.
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "continuous"), ("zoom", "300")]);
swipe_and_lift(&mut h);
assert!(scroll_over(&mut h, 3) > 30.0, "gliding");
let at = h.state().views[0].viewport_rect().center();
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
scroll_over(&mut h, 2);
let drift = scroll_over(&mut h, 20);
assert!(drift.abs() < 0.5, "a click catches the page: drifted {drift}");
// Animation effects off: the page stops with the fingers, as before #531.
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "continuous"), ("zoom", "300")]);
h.state_mut().set_option("animation_effects", "off").unwrap();
let swiped = swipe_and_lift(&mut h);
assert!((swiped - 175.0).abs() < 1.0, "the swipe still scrolls 1:1: moved {swiped}");
let drift = scroll_over(&mut h, 20);
assert!(drift.abs() < 0.5, "no glide with animations off: drifted {drift}");
}
/// The 40 frames from one wheel notch on, with the system asking for no animations (Windows'
/// Animation effects turned off) or not, and Preferences ▸ Animation effects as given: how far
/// page 1 has moved up in each frame, or with ⌘/Ctrl held, the view's zoom.
fn frames_after_a_notch(system_reduced: bool, animation_effects: &str, zooming: bool) -> Vec<f32> {
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "continuous"), ("zoom", "100")]);
// PLAN: the env's reduced-motion answer (pdf-shell-w8) replaces `motion.reduced`.
h.state_mut().motion.reduced = system_reduced;
h.state_mut().set_option("animation_effects", animation_effects).unwrap();
let at = h.state().views[0].viewport_rect().center();
@@ -958,7 +375,7 @@ fn frames_after_a_notch(system_reduced: bool, animation_effects: &str, zooming:
(0..40)
.map(|_| {
h.step();
if zooming { h.state().views[0].zoom } else { before - rect(&h, 0).expect("page 1 still laid out").min.y }
if zooming { h.state().views[0].view.zoom } else { before - rect(&h, 0).expect("page 1 still laid out").min.y }
})
.collect()
}
@@ -991,76 +408,6 @@ fn a_wheel_notch_scrolls_at_once_with_animation_effects_off() {
}
}
#[test]
fn the_wheel_zooms_a_whole_step_at_once_with_animation_effects_off() {
// ⌘/Ctrl with the wheel: egui eases the zoom as it eases scrolling.
let step = frames_after_a_notch(true, "system", true)[0];
assert!(step > 1.1, "the notch zoomed in: {step}");
for (system_reduced, effects) in AT_ONCE {
let zooms = frames_after_a_notch(system_reduced, effects, true);
assert!(
zooms.iter().all(|zoom| *zoom == step),
"{effects}, system reduced {system_reduced}: the whole step in the frame the notch arrives, and no more after it: {zooms:?}"
);
}
for (system_reduced, effects) in EASED {
let zooms = frames_after_a_notch(system_reduced, effects, true);
assert!(
zooms[0] > 1.0 && zooms[0] < 1.0 + (step - 1.0) * 0.75,
"{effects}, system reduced {system_reduced}: egui eases the notch: {zooms:?}"
);
assert!(
(zooms[39] / step - 1.0).abs() < 0.01,
"{effects}, system reduced {system_reduced}: easing changes how long a zoom step takes, not how far it goes: {zooms:?}"
);
}
}
/// A touch gesture begun with ⌘/Ctrl zooms to its end after the keys are let go, as egui reads
/// it: its later motion neither scrolls the page as well nor turns the rest of it into scrolling.
#[test]
fn a_zoom_gesture_zooms_to_its_end_after_its_keys_are_let_go() {
/// The view's zoom and page 1 on screen, settled, after a gesture of six 5-point motions,
/// the keys let go after the second one or held throughout.
fn zoom_gesture(effects: &'static str, let_go: bool) -> (f32, f32, egui::Rect) {
let mut h = harness_stepping(1.0 / 60.0, &[("layout", "continuous"), ("zoom", "300")]);
h.state_mut().set_option("animation_effects", effects).unwrap();
let at = h.state().views[0].viewport_rect().center();
h.hover_at(at);
h.run_steps(2);
let before = h.state().views[0].zoom;
let touch = |phase, dy, modifiers| egui::Event::MouseWheel {
unit: MouseWheelUnit::Point,
delta: egui::vec2(0.0, dy),
phase,
modifiers,
source: egui::MouseWheelSource::Unknown,
};
h.event(touch(TouchPhase::Start, 0.0, Modifiers::COMMAND));
h.step();
for k in 0..6 {
let modifiers = if let_go && k >= 2 { Modifiers::NONE } else { Modifiers::COMMAND };
h.event(touch(TouchPhase::Move, 5.0, modifiers));
h.step();
}
h.event(touch(TouchPhase::End, 0.0, Modifiers::NONE));
h.run_steps(40);
(before, h.state().views[0].zoom, rect(&h, 0).expect("page 1 on screen"))
}
for effects in ["off", "on"] {
let (before, held, held_page) = zoom_gesture(effects, false);
assert!(held > before, "{effects}: the gesture zoomed in: {before} to {held}");
let (_, let_go, let_go_page) = zoom_gesture(effects, true);
assert!((let_go / held - 1.0).abs() < 1e-4, "{effects}: the whole gesture zooms: {let_go}, held throughout {held}");
assert!(
(let_go_page.min - held_page.min).length() < 0.5,
"{effects}: and nothing scrolls: page 1 at {:?}, held throughout {:?}",
let_go_page.min,
held_page.min
);
}
}
#[test]
fn page_display_commands_switch_layouts() {
let mut h = harness(&[]);
@@ -1442,44 +789,6 @@ fn rail_page_display_menu_offers_acrobats_view_choices() {
assert_eq!(shown(&h), (PageLayout::Single, true, Fit::Width), "single page, scrolling continuously");
}
#[test]
fn rail_page_display_button_switches_layouts() {
use egui_kittest::kittest::Queryable;
let mut h = harness(&[]);
h.run_steps(4);
h.get_by_label_contains("Page display").click();
h.run_steps(3);
h.get_by_label("Single page").click();
h.run_steps(4);
assert_eq!(h.state().views[0].layout, pdfcraft_ui_egui::canvas::PageLayout::Single);
}
#[test]
fn view_menu_page_display_uses_the_same_commands() {
use egui_kittest::kittest::Queryable;
let mut h = harness(&[]);
h.run_steps(4);
crate::support::open_menu(&mut h, "View");
crate::support::menu_row(&h, "Page display").hover();
h.run_steps(3);
h.get_by_label("Single page").click();
h.run_steps(4);
assert_eq!(h.state().views[0].layout, pdfcraft_ui_egui::canvas::PageLayout::Single);
}
#[test]
fn palette_runs_page_display_commands_from_the_keyboard() {
use egui_kittest::kittest::Queryable;
let mut h = harness(&[]);
h.state_mut().set_option("palette", "single page").unwrap();
h.run_steps(3);
h.get_by_label("Single page");
h.key_press(Key::Enter);
h.run_steps(3);
assert!(!h.state().palette_open, "Enter runs the top hit and closes the palette");
assert_eq!(h.state().views[0].layout, pdfcraft_ui_egui::canvas::PageLayout::Single);
}
#[test]
fn actual_size_fit_width_and_fit_page() {
let mut h = harness(&[]);
@@ -1502,20 +811,6 @@ fn actual_size_fit_width_and_fit_page() {
assert!(r.width() < vp.width(), "a portrait page fits by height");
}
#[test]
fn fit_page_holds_zoom_across_mixed_page_sizes() {
// Scrolling views fit their largest page, so scrolling past other sizes must not jump
// the zoom (#214).
let mut h = mixed_harness(&[("layout", "continuous")]);
h.key_press_modifiers(Modifiers::COMMAND, Key::Num0); // fit page
h.run_steps(4);
let z1 = h.state().views[0].zoom;
h.state_mut().set_option("page", "2").unwrap();
h.run_steps(4);
assert_eq!(h.state().views[0].current, 1);
assert_eq!(h.state().views[0].zoom, z1, "another size scrolls past at the same zoom");
}
#[test]
fn single_page_fit_page_fits_the_shown_page() {
// Single-page view fits the page it shows: each page fills the viewport on its own.
@@ -2463,43 +1758,6 @@ fn centre_detail(h: &mut Harness<'static, PdfCraftApp>) -> u64 {
sum
}
#[test]
fn zooming_a_tiled_page_shows_its_earlier_tiles_until_new_ones_arrive() {
let _gpu = gpu();
let mut h = grid_harness(fine_grid_pdf(), "300");
crate::support::settle(&mut h);
let sharp = centre_detail(&mut h);
// The first frame at a new zoom has no tiles for it yet (they are requested at its end).
h.state_mut().set_option("zoom", "310").unwrap();
h.step();
let first = centre_detail(&mut h);
assert!(first * 10 > sharp * 7, "the first frame after zooming lost its detail: {first} against {sharp}");
}
/// #2196: zooming away from a tiled page and back must not re-blur an area already rendered
/// sharp. The tiles of the zoom just left used to be dropped while the page was shown whole,
/// so returning to it was a cold miss and every tile cost a full page interpret again.
#[test]
fn returning_to_a_visited_zoom_reuses_its_cached_tiles() {
let _gpu = gpu();
let mut h = grid_harness(fine_grid_pdf(), "300");
crate::support::settle(&mut h);
let before = h.state().views[0].tiles_debug(0);
assert!(!before.is_empty(), "the 300 % page should be tiled, but it cached no tiles");
// Zoom right out, where the 1200 pt page fits in one raster and is not tiled at all, so
// none of its tiles is demanded...
h.state_mut().set_option("zoom", "50").unwrap();
crate::support::settle(&mut h);
// ...then back to the first zoom, which was already rendered sharp.
h.state_mut().set_option("zoom", "300").unwrap();
h.step();
let after = h.state().views[0].tiles_debug(0);
// Every tile rendered sharp before the round trip is still cached: zooming away must not
// drop them, so returning shows them at once instead of re-interpreting the page per tile.
let lost: Vec<_> = before.iter().copied().filter(|k| !after.contains(k)).collect();
assert!(lost.is_empty(), "returning to a visited zoom dropped its cached tiles {lost:?} (had {before:?}, now {after:?})");
}
#[test]
fn sidebar_collapse_and_resize_preserves_scroll_position() {
use pdfcraft_ui_egui::canvas::Fit;
@@ -2810,29 +2068,6 @@ fn full_screen_survives_a_reload_and_keeps_a_new_documents_own_view() {
assert!(v.layout == PageLayout::TwoUp && v.continuous(), "the document's own two-column view comes back");
}
/// Two-page view stays a spread in full screen (#1353): both pages of the spread, fitted, and
/// → turns the spread.
#[test]
fn full_screen_keeps_two_page_view_as_spreads() {
use pdfcraft_ui_egui::canvas::PageLayout;
let mut h = harness(&[("layout", "two-up")]);
h.run_steps(4);
h.key_press_modifiers(Modifiers::COMMAND, Key::L);
h.run_steps(6);
let v = &h.state().views[0];
assert_eq!(v.layout, PageLayout::TwoUp);
assert!(!v.continuous(), "one spread at a time");
assert!(rect(&h, 0).is_some() && rect(&h, 1).is_some() && rect(&h, 2).is_none(), "the first spread only");
h.key_press(Key::ArrowRight);
h.run_steps(4);
assert_eq!(h.state().views[0].current, 2, "→ turns the spread");
assert!(rect(&h, 2).is_some() && rect(&h, 0).is_none());
h.key_press(Key::Escape);
h.run_steps(4);
let v = &h.state().views[0];
assert!(v.continuous() && v.layout == PageLayout::TwoUp, "two-page continuous view comes back");
}
/// Review on #2070: full screen hides the tools and a click turns the page only with Select, so
/// entering it from another tool selects Select, and leaving gives the tool back.
#[test]
@@ -3146,18 +2381,6 @@ fn full_screen_plays_a_page_transition_and_honours_the_display_time() {
assert!(!h.state().views[0].presenting_a_transition());
}
/// The page changes at once where a transition can't or shouldn't play: with the Animation
/// effects preference off, and with two-page spreads.
#[test]
fn full_screen_turns_at_once_without_animations_or_in_spreads() {
for options in [&[("animation_effects", "off")][..], &[("layout", "two-up")][..]] {
let mut h = presenting(options);
h.key_press(Key::ArrowRight);
h.run_steps(1);
assert!(!h.state().views[0].presenting_a_transition(), "{options:?}");
}
}
/// In full screen the pointer hides after three still seconds, and shows again when it moves.
#[test]
fn full_screen_hides_a_still_pointer() {
@@ -3173,47 +2396,6 @@ fn full_screen_hides_a_still_pointer() {
assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::None, "moved again");
}
/// In full screen a right-click goes back a page, as a left click goes forward (*Adobe Acrobat
/// Help*, 2019, "Full Screen preferences", p. 69: "Left Click To Go Forward One Page; Right Click
/// To Go Back One Page"), and no context menu opens.
#[test]
fn full_screen_right_click_goes_back_a_page() {
// A document with no display times, so no page turns by itself meanwhile.
let mut h = harness(&[]);
h.key_press_modifiers(Modifiers::COMMAND, Key::L);
h.run_steps(6);
assert!(h.state().full_screen);
h.key_press(Key::ArrowRight);
h.run_steps(4);
assert_eq!(h.state().views[0].current, 1);
let centre = h.state().views[0].viewport_rect().center();
h.hover_at(centre);
h.run_steps(1);
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos: centre, button: egui::PointerButton::Secondary, pressed, modifiers: Modifiers::NONE });
}
h.run_steps(6);
assert_eq!(h.state().views[0].current, 0, "a right-click goes back");
assert!(!egui::Popup::is_any_open(&h.ctx), "no context menu in full screen");
}
/// In full screen Enter goes forward a page and Shift+Enter back (*Adobe Acrobat Help*, 2019,
/// "Read a document in Full Screen mode", p. 66: "To go to the previous page, press Shift+Enter").
#[test]
fn full_screen_shift_enter_goes_back_a_page() {
// A document with no display times, so no page turns by itself meanwhile.
let mut h = harness(&[]);
h.key_press_modifiers(Modifiers::COMMAND, Key::L);
h.run_steps(6);
assert!(h.state().full_screen);
h.key_press(Key::Enter);
h.run_steps(4);
assert_eq!(h.state().views[0].current, 1, "Enter goes forward");
h.key_press_modifiers(Modifiers::SHIFT, Key::Enter);
h.run_steps(4);
assert_eq!(h.state().views[0].current, 0, "Shift+Enter goes back");
}
/// A document replaced while full screen plays a transition (a reload) starts afresh: none of the
/// old document's transition, page or timer carries over.
#[test]
@@ -3417,27 +2599,6 @@ trailer << /Root 1 0 R >>
assert_eq!(note.popup.map(|w| w.open), Some(true), "the note's pop-up is open");
}
/// With Animation effects following the system and the system asking for no animations (Windows'
/// Animation effects off, or another system's Reduce motion), full screen changes pages at once
/// and still keeps the page's display time; with the system not asking, the same transition plays.
#[test]
fn full_screen_cuts_transitions_when_the_system_asks_for_no_animations() {
for reduced in [true, false] {
let mut h = presenting(&[("animation_effects", "system")]);
h.state_mut().motion.reduced = reduced;
h.run_steps(1);
h.key_press(Key::ArrowRight);
h.run_steps(1);
assert_eq!(h.state().views[0].current, 1);
assert_eq!(h.state().views[0].presenting_a_transition(), !reduced, "system asks for no animations: {reduced}");
if reduced {
settle(&mut h);
let frames = frames_until(&mut h, |a| a.views[0].current == 2);
assert!(frames <= 20, "page 2's one-second display time still turns it ({frames} frames of 0.1 s)");
}
}
}
/// Escape leaves full screen while a transition plays and while a display time counts, and the
/// display time stops with it: the page reached stays.
#[test]
@@ -3461,27 +2622,6 @@ fn escape_leaves_full_screen_mid_transition_and_stops_the_display_time() {
}
}
/// While a page's display time counts, the keys still turn pages at once (ISO 32000-2 §12.4.4.1,
/// NOTE 1: "The user can advance the page manually before the specified time has expired"):
/// → goes on before the time is up, and ← back to a page with no display time, which then stays.
#[test]
fn full_screen_keys_take_over_from_a_display_time() {
let mut h = presenting(&[("animation_effects", "off")]);
h.key_press(Key::ArrowRight);
h.run_steps(1);
assert_eq!(h.state().views[0].current, 1, "page 2, with its one-second display time");
h.key_press(Key::ArrowLeft);
h.run_steps(1);
assert_eq!(h.state().views[0].current, 0, "← goes back before the time is up");
h.run_steps(30);
assert_eq!(h.state().views[0].current, 0, "page 1 has no display time: it stays");
h.key_press(Key::ArrowRight);
h.run_steps(2);
h.key_press(Key::ArrowRight);
h.run_steps(1);
assert_eq!(h.state().views[0].current, 2, "→ goes on before page 2's time is up");
}
/// Every way full screen moves: forward (→, Space, Enter, Page Down, a click), back (←, Backspace,
/// Shift+Enter, Page Up, a right-click, a Shift-click), first (Home, Shift+Ctrl+Page Up), last (End,
/// Shift+Ctrl+Page Down) and out (Escape, Ctrl+L).
@@ -3554,29 +2694,6 @@ fn full_screen_every_key_and_click_goes_where_it_says() {
}
}
/// A transition style the spec doesn't name (here `/Spiral`, with a five-second `/D`) is the
/// default, Replace (ISO 32000-2 Table 164, `S`: "Default value: R"): the page changes at once, and
/// its display time still turns it.
#[test]
fn full_screen_cuts_an_unknown_transition_style_and_keeps_its_display_time() {
const SPIRAL: &[u8] = b"%PDF-1.7
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 /MediaBox [0 0 300 400] >> endobj
3 0 obj << /Type /Page /Parent 2 0 R >> endobj
4 0 obj << /Type /Page /Parent 2 0 R /Trans << /S /Spiral /D 5 >> /Dur 1 >> endobj
5 0 obj << /Type /Page /Parent 2 0 R >> endobj
trailer << /Root 1 0 R >>
%%EOF";
let mut h = presenting_pdf(SPIRAL, &[]);
h.key_press(Key::ArrowRight);
h.run_steps(1);
assert_eq!(h.state().views[0].current, 1);
assert!(!h.state().views[0].presenting_a_transition(), "no effect for an unknown style");
settle(&mut h);
let frames = frames_until(&mut h, |a| a.views[0].current == 2);
assert!(frames <= 20, "its one-second display time turns it ({frames} frames of 0.1 s)");
}
/// A one-page PDF whose content inflates past the renderer's per-stream limit (#623): a window
/// of whitespace the interpreter can never complete, so the page is cut and says so.
fn cut_content_pdf() -> Vec<u8> {
-80
View File
@@ -1418,70 +1418,6 @@ fn an_earlier_revision_opens_from_document_properties() {
);
}
#[test]
fn wrapped_revision_buttons_stay_above_binding_and_open_the_saved_revision() {
use pdfcraft_engine::{Edit, Session};
let mut bytes = std::sync::Arc::new(fixture(1));
// Reopen each save so the next edit appends to the preceding saved revision.
for revision in 2..=13 {
let mut source = Session::new().with_clock(|| 1_700_000_000);
let id = source.open("revisions.pdf", None, bytes, None).unwrap();
source.apply(id, Edit::SetInfo { key: "Title".into(), value: format!("Revision {revision}") }).unwrap();
bytes = source.save_bytes(id).unwrap();
}
for width in [1400.0, 720.0] {
let pdf = bytes.clone();
let mut h = Harness::builder().with_size(egui::vec2(width, 900.0)).build_eframe(move |_cc| {
let mut app = PdfCraftApp::new();
app.set_option("language", "en").unwrap();
app.open_bytes("revisions.pdf", None, pdf.to_vec()).unwrap();
app
});
let s = h.state();
let doc = s.session.get(s.views[s.active.unwrap()].id).unwrap();
assert_eq!(doc.revision_ends().len(), 13, "the fixture contains thirteen saved revisions");
h.state_mut().dialog = Some(Dialog::Properties(pdfcraft_ui_egui::PropsTab::Advanced));
// Let the grid and the centered dialog settle before measuring or clicking.
h.run_steps(6);
let buttons: Vec<_> = (1..13).map(|n| (n, h.get_by_label(&format!("View revision {n}")).rect())).collect();
let first_row = h.get_by_label("View revision 12").rect();
let lower_revision = buttons
.iter()
.find(|(n, rect)| *n > 1 && rect.top() > first_row.bottom())
.map(|(n, _)| *n)
.expect("revision buttons wrap to a lower row");
let binding = h.get_by_label("Binding").rect();
let left = h.get_by_label("Left Edge").rect();
let right = h.get_by_label("Right Edge").rect();
// Properties requests a fixed width. Measure its card in each viewport.
let card = h.ctx.data(|d| d.get_temp::<egui::Rect>(egui::Id::unique("dialog").with("card"))).expect("Properties is shown");
for (n, rect) in &buttons {
for (label, below) in [("Binding", binding), ("Left Edge", left), ("Right Edge", right)] {
assert!(rect.bottom() <= below.top(), "revision {n} overlaps {label} at viewport width {width}: {rect:?}, {below:?}");
}
}
for (n, rect) in &buttons {
assert!(
rect.left() >= card.left() && rect.right() <= card.right(),
"revision {n} escapes Properties horizontally at viewport width {width}: {rect:?}, measured card {card:?}"
);
}
h.get_by_label(&format!("View revision {lower_revision}")).scroll_to_me();
h.run_steps(3);
h.get_by_label(&format!("View revision {lower_revision}")).click();
h.run_steps(3);
let s = h.state();
assert!(s.dialog.is_none(), "opening a revision closes Properties");
let view = &s.views[s.active.unwrap()];
let doc = s.session.get(view.id).unwrap();
assert_eq!(doc.name, format!("revisions (revision {lower_revision}).pdf"));
assert_eq!(doc.info_value("Title"), Some(format!("Revision {lower_revision}")));
let snapshot = view.snapshot.as_ref().expect("the saved revision opens as a snapshot");
assert_eq!(snapshot.kind, pdfcraft_ui_egui::canvas::SnapshotKind::Revision);
assert_eq!(snapshot.revision, lower_revision);
}
}
#[test]
fn advanced_search_lists_results_with_context() {
let mut h = harness();
@@ -1527,22 +1463,6 @@ fn optimizer_audits_space_usage() {
assert_eq!(h.state().dialog, Some(Dialog::Optimize), "back to the optimizer");
}
#[test]
fn space_audit_numbers_line_up_under_their_headers() {
// The percentages were drawn at the dialog's far edge, away from their header and the
// striped rows: a right-to-left layout in a grid's last column takes the rest of the window.
let mut h = harness();
assert!(h.state_mut().execute("optimize.advanced"));
h.run_steps(2);
h.get_by_label("Audit space usage…").click();
h.run_steps(3);
let total = h.state().space_audit.iter().map(|r| r.bytes).sum::<u64>().to_string();
let right = |label: &str| h.get_by_label(label).rect().right();
assert!((right("Percentage") - right("100.00%")).abs() < 1.0, "{} vs {}", right("Percentage"), right("100.00%"));
assert!((right("Bytes") - right(&total)).abs() < 1.0, "{} vs {}", right("Bytes"), right(&total));
assert!(right("100.00%") < right("OK") + 1.0, "the table stays inside the dialog");
}
#[test]
fn each_document_keeps_its_own_scroll_position() {
// #189: every document's page view shared one scroll position, so switching tabs showed a