diff --git a/crates/pages/src/ui/view.rs b/crates/pages/src/ui/view.rs index c37d6f9cec..af07140226 100644 --- a/crates/pages/src/ui/view.rs +++ b/crates/pages/src/ui/view.rs @@ -32,7 +32,7 @@ use craft_behavior::kurbo::{Point, Rect as DocRect, Size}; use craft_behavior::{Axis, CanvasView, MoveMods, NavMove, PressPhase, WheelNotch, ZoomLadder}; use craft_ui::canvas::{ BodyKeys, Canvas, CanvasOutput, CanvasScrollbars, NavigationOptions, PageFrame, PageKey, Pasteboard, PasteboardOutput, Snap, ToolPass, - ToolRegion, canvas_space, tool_pass, + ToolRegion, canvas_space, pixel_aligned, tool_pass, }; use craft_ui::contract::{Bind, BodyCx, Held, Props as _, Show as _, ShowContainer as _}; use craft_ui::primitives::EditorPurpose; @@ -316,7 +316,9 @@ impl PageViewOutput { /// `Priority::VISIBLE`, one row either side at `Priority::NEAR`; a page larger than the texture side adds a /// second picture of the part in view. Sharp renders wait while a zoom gesture or ease runs. A page scrolled /// further than [`picture_reach`](Self::picture_reach) from the view gives its picture back. -/// - Layout: a scale the fit or the app changes keeps the page at the top of the view in place. +/// - Layout: a scale the fit or the app changes keeps the page at the top of the view in place. A zoom about the +/// pointer keeps the point under it in place relative to the page there (or, in a gap, the nearest page), and one +/// that does not ease draws its new layout, reflowed, in the pass it happens, so the next pass moves nothing. /// - Scrolling: the canvas folds in the wheel (the wheel scrolls, Shift or Ctrl/Cmd + wheel scrolls sideways, Alt + /// wheel and a pinch zoom about the pointer, as [`NavigationOptions`] say) and the view commands; the view /// reads the result back into its state. [`CanvasScrollbars`] land in their own pass. Not continuous, a page @@ -713,6 +715,8 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState> let fixed = (target.center - given.center) * (given.zoom * target.zoom / (target.zoom - given.zoom)); let pointer = rect.center() + Vec2::new(fixed.x as f32, fixed.y as f32); geo = zoom_about(build, &mut state, &geo, rect, pointer, target.zoom / given.zoom); + let (xs, ys) = (offset_range(geo.doc.x0, geo.doc.x1, vw), offset_range(geo.doc.y0, geo.doc.y1, vh)); + state.offset = (state.offset.0.clamp(xs.0, xs.1), state.offset.1.clamp(ys.0, ys.1)); want = state.offset; } else { // The canvas was given the view the pass started with, so its change of it is the pan; the state's offset @@ -728,6 +732,20 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState> if wheel_left == 0.0 { mem.overshoot = 0.0; } + // A zoom that does not ease draws the layout it made in its own pass, through the view of the anchored offset: the + // pages reflow and the point under the pointer stays in the pass the zoom happens, and the next pass, given that + // view, moves nothing. (Drawing the layout the pass started with, scaled, put the reflow and the spacing that does + // not scale one pass late.) An ease draws the layout it started from, scaled, until it lands. + let (drawn, drawn_frame, shown) = if zooming && !space.easing() { + let frame = Frame::of(&geo); + let mut view = frame.view(rect, state.offset, geo.scale / SCREEN_POINTS_PER_POINT); + // As the canvas places a given view: in its own rect (inside the rulers), about the same centre. + view.rect = target.rect; + let view = if shown == target { view } else { pixel_aligned(view, ui.ctx().pixels_per_point()) }; + (Arc::clone(&geo), frame, view) + } else { + (drawn, drawn_frame, shown) + }; let keys = KeyMoves::of(space.keys(), &state, &geo, rect); want.0 += keys.pan.0; want.1 = if keys.to_end { f64::INFINITY } else { want.1 + keys.pan.1 }; @@ -1118,12 +1136,14 @@ fn zoom_about(build: &Geometry, state: &mut PageViewState, old: &Placed, rect: R state.fit = Fit::None; state.zoom = (state.zoom * delta).clamp(*ZOOM_RANGE.start(), *ZOOM_RANGE.end()); let new = build.of(state); - let (x, y) = match crate::layout::page_at(&old.layout, at) { - Some(page) => { + // The page under the pointer, or in a gap (between columns, rows or pages) the nearest: the point keeps its place + // relative to that page, outside it too, since the gaps keep their size and the pages may reflow. + let (x, y) = match crate::layout::page_at(&old.layout, at).or_else(|| nearest_page(&old.layout, at)) { + Some(page) if page < new.layout.rects.len() => { let (before, after) = (old.layout.rects[page], new.layout.rects[page]); (after.x0 + (at.x - before.x0) / before.width() * after.width(), after.y0 + (at.y - before.y0) / before.height() * after.height()) } - None => { + _ => { let ratio = new.scale / old.scale; (at.x * ratio, at.y * ratio) } @@ -1132,6 +1152,17 @@ fn zoom_about(build: &Geometry, state: &mut PageViewState, old: &Placed, rect: R new } +/// The page whose shown band lies nearest `p` (content coordinates); the earlier page on a tie, `None` with no pages. +fn nearest_page(layout: &PagedLayout, p: Point) -> Option { + let distance = |page: usize| { + let band = band_rect(layout, page); + let dx = (band.x0 - p.x).max(p.x - band.x1).max(0.0); + let dy = (band.y0 - p.y).max(p.y - band.y1).max(0.0); + dx.hypot(dy) + }; + (0..layout.rects.len().min(layout.bands.len())).min_by(|&a, &b| distance(a).total_cmp(&distance(b))) +} + /// The pages one row either side of what shows: the neighbouring rows, or the neighbouring row of a single shown /// row. fn near_pages(placed: &Placed, continuous: bool, visible: &Range, count: usize, options: &LayoutOptions) -> Vec { diff --git a/crates/pages/tests/it/views.rs b/crates/pages/tests/it/views.rs index 032ee24622..61b1a9cd58 100644 --- a/crates/pages/tests/it/views.rs +++ b/crates/pages/tests/it/views.rs @@ -145,6 +145,117 @@ fn pages_scrolled_out_of_reach_give_their_pictures_back() { assert!(held > 0 && held <= drawn + 2, "{held} pictures held with no reach, {drawn} pages drawn"); } +/// What a pass of the zoom rig showed: the area the pages show in, the pages drawn and the screen points per page point. +#[derive(Clone)] +struct ZoomSeen { + area: egui::Rect, + pages: Vec<(usize, egui::Rect)>, + scale: f64, +} + +impl ZoomSeen { + /// Pages across: those level with the first page drawn. + fn columns(&self) -> usize { + self.pages.first().map_or(0, |(_, first)| self.pages.iter().filter(|(_, r)| (r.top() - first.top()).abs() < 1.0).count()) + } + + fn rect(&self, page: usize) -> Option { + self.pages.iter().find(|(p, _)| *p == page).map(|(_, r)| *r) + } +} + +/// WordCraft's Ctrl + wheel zoom out (#1340): the point under the pointer stays where it is in every frame, the +/// pages reflow into rows in the frame of the notch that makes room for them, and a frame without input moves +/// nothing. Pointer in the middle of the area inside the rulers, many pages down, a notch every 8 frames; the pages +/// pass through a gutter between columns under the pointer on the way. +#[trial] +fn a_ctrl_wheel_zoom_keeps_the_point_under_the_pointer_and_settles_in_its_own_frame() { + let state = Rc::new(RefCell::new(state_with(|s| { + s.fit = Fit::None; + s.zoom = 1.0; + s.display = PageDisplay::Columns; + }))); + let seen = Rc::new(RefCell::new(ZoomSeen { area: egui::Rect::NOTHING, pages: Vec::new(), scale: 0.0 })); + let (kept, shown) = (Rc::clone(&state), Rc::clone(&seen)); + let pages = DemoPages::new(200); + let mut navigation = craft_ui::canvas::NavigationOptions::default(); + navigation.wheel = craft_ui::canvas::WheelScheme::Document; + let mut fixture = Fixture::new(move |ui| { + let mut now = kept.borrow().clone(); + let mut area = egui::Rect::NOTHING; + let out = PageView::new("Pages", &pages, &mut now, PAPER) + .options(LayoutOptions::WORD) + .navigation(navigation) + .rulers(true) + .show(ui, |_, body| area = body.view.rect); + let scale = out.pages.first().map_or(0.0, |p| p.scale); + *shown.borrow_mut() = ZoomSeen { area, pages: out.pages.iter().map(|p| (p.page, p.rect)).collect(), scale }; + *kept.borrow_mut() = now; + }); + fixture.ctx().options_mut(|options| options.input_options.zoom_modifier = Modifiers::NONE); + fixture.room(vec2(1280.0, 760.0)); + fixture.settle(); + // Far enough down that zooming out never meets the top of the document, whose clamp would move the place. + state.borrow_mut().offset.1 = 40.4 * 1056.0; + fixture.settle(); + let pointer = seen.borrow().area.center(); + fixture.frame(vec![egui::Event::PointerMoved(pointer)]).settle(); + let start = seen.borrow().clone(); + let (page, _) = *start + .pages + .iter() + .min_by(|(_, a), (_, b)| a.distance_to_pos(pointer).total_cmp(&b.distance_to_pos(pointer))) + .expect("pages show"); + assert!(page >= 30, "many pages down: page {page}"); + let under = |seen: &ZoomSeen| seen.rect(page).map(|r| (pointer - r.min) / seen.scale as f32); + let at = under(&start).expect("the page shows"); + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + fixture.frame(vec![egui::Event::ModifiersChanged(ctrl)]); + let mut last = seen.borrow().clone(); + for n in 0..40 { + let notch = n % 8 == 0; + let events = if notch { + vec![egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + modifiers: ctrl, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }] + } else { + Vec::new() + }; + fixture.frame(events); + let now = seen.borrow().clone(); + let here = under(&now).unwrap_or_else(|| panic!("frame {n}: page {page} shows")); + let off = (here - at) * now.scale as f32; + // Across, the place holds while the pages stay one a row; in rows they fit the window side by side. + let across = now.columns() > start.columns() || off.x.abs() < 2.0; + assert!( + across && off.y.abs() < 2.0, + "frame {n} at scale {:.3}: {here:?} on page {page}, was {at:?}; {:?} after {:?}", + now.scale, + now.pages, + last.pages + ); + if !notch { + assert_eq!(now.columns(), last.columns(), "frame {n}: the pages reflow only in a notch's frame"); + assert_eq!(now.pages, last.pages, "frame {n}: a frame without input moves nothing"); + } + last = now; + } + assert!(last.scale < start.scale * 0.6, "zoomed out: {} -> {}", start.scale, last.scale); + assert!( + last.columns() > start.columns(), + "the pages reflowed into rows on the way: {} to {} at {} in {:?}: {:?}", + start.columns(), + last.columns(), + last.scale, + last.area, + last.pages + ); +} + /// A wheel step of `lines` over the middle of the room. fn wheel(fixture: &mut Fixture, lines: f32) { let middle = pos2(450.0, 300.0);