diff --git a/Cargo.lock b/Cargo.lock index bffc63c37..0f43f329e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3196,6 +3196,7 @@ version = "0.1.0" dependencies = [ "craft-behavior", "craft-i18n", + "craft-keymap", "craft-text", "craft-theme", "craft-ui", diff --git a/crates/pages/Cargo.toml b/crates/pages/Cargo.toml index 8012afcb8..54c62d6e2 100644 --- a/crates/pages/Cargo.toml +++ b/crates/pages/Cargo.toml @@ -19,7 +19,7 @@ workspace = true [features] default = [] # The page widgets (`craft_pages::ui`), on craft-ui. -ui = ["dep:craft-behavior", "dep:craft-ui", "dep:craft-theme", "dep:egui", "dep:serde_json"] +ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui","dep:craft-theme", "dep:egui", "dep:serde_json"] # The stories and the integration tests (`tests/it`). screen-testing = ["ui", "craft-ui/testing"] @@ -31,6 +31,8 @@ serde = { workspace = true } # `ui::range` keeps a page-range row's value as a dialog's JSON field. serde_json = { workspace = true, optional = true } craft-behavior = { workspace = true, optional = true } +# The arrows the page view reads come with the modifiers held. +craft-keymap = { workspace = true, optional = true } craft-ui = { workspace = true, optional = true } craft-theme = { workspace = true, optional = true } egui = { workspace = true, optional = true } diff --git a/crates/pages/src/ui/view.rs b/crates/pages/src/ui/view.rs index dd546a29e..fa58e560a 100644 --- a/crates/pages/src/ui/view.rs +++ b/crates/pages/src/ui/view.rs @@ -30,9 +30,10 @@ use crate::layout::{ Fit, LayoutOptions, PageDisplay, PageSpacing, PagedLayout, SCREEN_POINTS_PER_POINT, ViewDefaults, ZOOM_RANGE, fit_scale, place_pages, shown_row, }; use craft_behavior::kurbo::{Point, Rect as DocRect, Size}; -use craft_behavior::{CanvasView, MoveMods, NavMove, PressPhase, ZoomLadder}; +use craft_behavior::{CanvasView, NavMove, PressPhase, ZoomLadder}; +use craft_keymap::Mods; use craft_ui::canvas::{ - BodyKeys, Canvas, CanvasOutput, CanvasScrollbars, NavigationOptions, PageBorder, PageFrame, Pasteboard, PasteboardOutput, ToolPass, canvas_space, + BodyKeys, Canvas, CanvasOutput, CanvasScrollbars, CanvasSpace, NavigationOptions, PageBorder, PageFrame, Pasteboard, PasteboardOutput, ToolPass, canvas_space, tool_pass, }; use craft_ui::contract::{Bind, BodyCx, Held, Props as _, Show as _, ShowContainer as _}; @@ -330,7 +331,11 @@ 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, and those of the part /// in view while the view pans too. While the view scrolls, the two rows ahead are asked for instead. -/// - Layout: a scale the fit or the app changes keeps the document point at the centre of the view in place. +/// - Layout: a scale the fit or the app changes keeps the document point at the centre of the view in place; a new +/// room keeps the current page's top where it was. Pages (a page or spread, or a scrolling column) shorter than +/// the view without their margins sit in its middle. +/// - Keys: the arrows go to the app's tool host first ([`PageBody::pass`]); the view moves with those it leaves, in +/// the same pass. /// - 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 @@ -449,9 +454,11 @@ impl<'a> PageView<'a> { let mut seen: Option = None; let mut canvas_body = |ui: &mut Ui, cx: &mut BodyCx<'_>| { let inputs = Inputs { source, describer, build: &build, rect, given, paper, navigation, border, keep }; - let next = run_pass(ui, cx, &mut held, &inputs)?; + let (mut next, pending) = run_pass(ui, cx, &mut held, &inputs)?; let pass = tool_pass(&cx.env); body(ui, &PageBody { rect: cx.rect, pages: &next.pages, view: next.view, pass: pass.as_ref() }); + // The body's tool host took the arrows a tool claims; the view moves with the keys it left. + pending.finish(ui.ctx(), &mut next, &inputs); let decided = next.next.clone(); seen = Some(next); decided @@ -531,7 +538,7 @@ impl Seen { /// A pass whose canvas body did not run (no area). fn empty(view: CanvasView, frame: Frame) -> Seen { Seen { - geo: Arc::new(Placed { layout: PagedLayout::default(), scale: SCREEN_POINTS_PER_POINT, row: 0..0, doc: DocRect::ZERO }), + geo: Arc::new(Placed { layout: PagedLayout::default(), scale: SCREEN_POINTS_PER_POINT, row: 0..0, doc: DocRect::ZERO, pages: DocRect::ZERO }), frame, view, pages: Vec::new(), @@ -601,9 +608,10 @@ impl Frame { } } -/// One pass of the canvas body: layout, scrolling, zoom and paging folded into the state; the pasteboard, the -/// pictures and the scroll bars drawn. -fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState>, inputs: &Inputs<'_>) -> Option { +/// One pass of the canvas body up to the app's body: layout, the wheel, a pinch and a pan folded into the state; the +/// pasteboard, the pictures and the scroll bars drawn. The keys, the turns and the go-to wait for [`Pending::finish`], +/// after the app's body. +fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState>, inputs: &Inputs<'_>) -> Option<(Seen, Pending)> { let Inputs { source, describer, build, rect, given, paper, navigation, border, keep } = *inputs; let mut state = held.read(cx)?; let started = state.clone(); @@ -634,11 +642,18 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState> // A scale the fit (a new viewport or pages) or the app changed keeps the document point at the centre of the // view where it was, unless the app moved the view or asked for a go-to in the same breath. + // A new room (a resized window, a panel opened beside the view) keeps the current page's top where it was instead. let unmoved = mem.offset == Some(state.offset); - if let Some((key, previous)) = previous.filter(|(_, p)| !scale_settled(p.scale, geo.scale)).filter(|_| unmoved && state.go_to.is_none()) - && let Some(offset) = centred_offset(&previous, &geo, state.offset, (key.viewport.width, key.viewport.height), (vw, vh)) - { - state.offset = offset; + if let Some((key, previous)) = previous.filter(|(_, p)| !scale_settled(p.scale, geo.scale)).filter(|_| unmoved && state.go_to.is_none()) { + let room = (key.viewport.width, key.viewport.height); + let centred = centred_offset(&previous, &geo, state.offset, room, (vw, vh)); + let top_kept = |(x, _): (f64, f64)| { + let (before, after) = (previous.layout.rects.get(state.current)?, geo.layout.rects.get(state.current)?); + Some((x, after.y0 - (before.y0 - state.offset.1))) + }; + if let Some(offset) = if room == (vw, vh) { centred } else { centred.and_then(top_kept) } { + state.offset = offset; + } } state.zoom = geo.scale / SCREEN_POINTS_PER_POINT; @@ -661,52 +676,20 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState> want = (state.offset.0 + along_x, state.offset.1 + along_y); } } - let keys = KeyMoves::of(space.keys(), &state, &geo, rect, f64::from(navigation.key_line)); - let mut scrolled = keys.moves() || wheel.is_some_and(|wheel| !zooming && wheel.scroll != Vec2::ZERO); - want.0 += keys.pan.0; - want.1 = if keys.to_end { f64::INFINITY } else { want.1 + keys.pan.1 }; + let mut scrolled = wheel.is_some_and(|wheel| !zooming && wheel.scroll != Vec2::ZERO); - // A key or the app's step turns the page; else, not continuous, the wheel turns it at the row's edge. - // The edge is read at the offset the pass started with, not at `want.1`: the share that pans a long page to - // its edge has not been marked moved yet, and must not also turn. + // Not continuous, the wheel turns the page at the row's edge. The edge is read at the offset the pass started + // with, not at `want.1`: the share that pans a long page to its edge has not been marked moved yet, and must not + // also turn. let wheel_turned = wheel .filter(|_| !state.continuous) .and_then(|wheel| wheel_turn(&wheel, edge_ahead(&geo, state.offset.1, vh, wheel.scroll.y < 0.0), f64::from(navigation.wheel_line))); - let step = state.turn.take(); - let mut go_to = keys.go_to; - if let Some(forward) = keys.turn.or(step).or(wheel_turned) { - let options = build.layout_options(&state); - let row = if state.continuous { shown_row(count, state.current, &options) } else { geo.row.clone() }; - match turned_row(count, &row, &options, forward) { - // A continuous view scrolls to the row, as a go-to of its first page. - Some(next) if state.continuous => go_to = go_to.or(Some(GoTo::Top { page: next, fraction: 0.0 })), - Some(next) => { - state.current = next; - geo = build.of(&state); - state.zoom = geo.scale / SCREEN_POINTS_PER_POINT; - let (lo, hi) = offset_range(geo.doc.y0, geo.doc.y1, vh); - want.1 = if forward { lo } else { hi }; - } - // Past either end there is nowhere to go: the view stays where it was. - None => want.1 = state.offset.1, - } - } // The pasteboard and the pictures are drawn through the view the canvas shows; a zoom still // under way draws the layout the view was made for, scaled. A pointer zoom runs while the canvas zooms this pass // or its eased zoom is still arriving on screen. let ratio = shown.zoom / drawn_frame.zoom; let pointer_zoom = zooming || ratio != 1.0; - - // A key's or the step's go-to replaces a pending one. While a pointer zoom runs, the go-to is placed at the zoom's - // new scale and kept, so the zoom anchors on it; the first pass without one lets it go. - let go_to = go_to.or(state.go_to); - state.go_to = go_to.filter(|_| pointer_zoom); - let went = go_to.is_some(); - if let Some(go_to) = go_to { - geo = place_go_to(build, &mut state, go_to, (vw, vh)); - want = go_to_offset(go_to, &geo, state.continuous, want, (vw, vh), &build.spacing); - } let travel = travel_of(mem.offset, want, wheel.as_ref()); let seen = shown.visible(); @@ -762,9 +745,7 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState> CanvasScrollbars::new(words.scroll_bars.clone(), Bind::given(target), DocRect::from_origin_size(Point::ZERO, document)).show_at(ui, cx.rect); let bar_drag = bars.view.value().is_some(); scrolled |= bar_drag; - if let Some(moved) = bars.view.value() { - want = drawn_frame.offset_of(moved.center, vw, vh); - } + let bar_want = bars.view.value().map(|moved| drawn_frame.offset_of(moved.center, vw, vh)); let bar_shapes = slot.take_after(&ctx); // The part in view waits while the view zooms or moves. @@ -777,28 +758,113 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState> let textures = thumbs.cache().statistics(&ctx) + details.cache().statistics(&ctx); PaintSlot::reserve(&ui.painter_at(cx.rect)).extend(&ctx, bar_shapes); - // The bars' drag landed in `want` above, so it lands in this pass's clamp. - let (xs, ys) = (offset_range(geo.doc.x0, geo.doc.x1, vw), offset_range(geo.doc.y0, geo.doc.y1, vh)); - let offset = (want.0.clamp(xs.0, xs.1), want.1.clamp(ys.0, ys.1)); - state.offset = offset; - if state.continuous && count > 0 && !went && mem.offset.is_some_and(|last| last != offset) { - state.current = page_on_line(&geo.layout, offset.1 + vh / 2.0); - } - mem.offset = Some(offset); - mem.layout = build.cache.borrow().clone(); - let current_changed = state.current != started_on; - Some(Seen { + let seen = Seen { geo: drawn, frame: drawn_frame, view: shown, pages, visible, - current_changed, + current_changed: false, scrolled, pasteboard: Some(pasteboard), textures, - next: Some(Next { started, state, mem, edit: words.edit.as_str().to_owned() }), - }) + next: None, + }; + let pending = + Pending { started, state, mem, geo, want, bar_want, wheel_turned, pointer_zoom, started_on, space, edit: words.edit.as_str().to_owned() }; + Some((seen, pending)) +} + +/// What a pass decides after the app's body ran in it: the keys the body's tool host left, the turns, the go-to and +/// the clamp of the offset. +struct Pending { + started: PageViewState, + state: PageViewState, + mem: Memory, + geo: Arc, + /// The offset the wheel, a pinch and a pan ask for. + want: (f64, f64), + /// The offset a scroll bar's drag or press asks for, which overrides every other move. + bar_want: Option<(f64, f64)>, + wheel_turned: Option, + pointer_zoom: bool, + started_on: usize, + space: CanvasSpace, + edit: String, +} + +impl Pending { + /// Folds the page keys and the arrow nothing in the body took into the state, with the app's step, the wheel's + /// turn and the go-to, clamps the offset, and hands `seen` what the caller stores. + fn finish(self, ctx: &egui::Context, seen: &mut Seen, inputs: &Inputs<'_>) { + let Pending { started, mut state, mut mem, mut geo, mut want, bar_want, wheel_turned, pointer_zoom, started_on, space, edit } = self; + let build = inputs.build; + let (vw, vh) = (build.viewport.width, build.viewport.height); + let count = build.sizes.len(); + let options = build.layout_options(&state); + let keys = KeyMoves::of(space.keys(), space.take_nudge(ctx), &state, &geo, &options, inputs.rect, f64::from(inputs.navigation.key_line)); + seen.scrolled |= keys.moves(); + want.0 += keys.pan.0; + want.1 = if keys.to_end { f64::INFINITY } else { want.1 + keys.pan.1 }; + + // A key or the app's step turns the page; else, not continuous, the wheel turns it at the row's edge. + let step = state.turn.take(); + let mut go_to = keys.go_to; + let before_turn = state.current; + if let Some(forward) = keys.turn.or(step).or(wheel_turned) { + let row = if state.continuous { shown_row(count, state.current, &options) } else { geo.row.clone() }; + match turned_row(count, &row, &options, forward) { + // A continuous view scrolls to the row, as a go-to of its first page. + Some(next) if state.continuous => go_to = go_to.or(Some(GoTo::Top { page: next, fraction: 0.0 })), + Some(next) => { + state.current = next; + geo = build.of(&state); + state.zoom = geo.scale / SCREEN_POINTS_PER_POINT; + let (lo, hi) = geo.y_range(vh); + want.1 = if forward { lo } else { hi }; + } + // Past either end there is nowhere to go: the view stays where it was. + None => want.1 = state.offset.1, + } + } + + // A key's or the step's go-to replaces a pending one. While a pointer zoom runs, the go-to is placed at the + // zoom's new scale and kept, so the zoom anchors on it; the first pass without one lets it go. + let go_to = go_to.or(state.go_to); + state.go_to = go_to.filter(|_| pointer_zoom); + let went = go_to.is_some(); + if let Some(go_to) = go_to { + geo = place_go_to(build, &mut state, go_to, (vw, vh)); + want = go_to_offset(go_to, &geo, state.continuous, want, (vw, vh), &build.spacing); + } + // Turned by Left or Right at an edge, a row wider than the view starts at the edge the reader comes from, so + // the next key scrolls across it rather than turning again. + if let Some(forward) = keys.across.filter(|_| state.current != before_turn) + && let Some(row) = row_rect(&geo, state.current, &options) + && row.width() + 2.0 * build.spacing.side > vw + { + want.0 = if forward { row.x0 - build.spacing.side } else { row.x1 + build.spacing.side - vw }; + } + if let Some(bar) = bar_want { + want = bar; + } + + let (xs, ys) = (offset_range(geo.doc.x0, geo.doc.x1, vw), geo.y_range(vh)); + let offset = (want.0.clamp(xs.0, xs.1), want.1.clamp(ys.0, ys.1)); + state.offset = offset; + if state.continuous && count > 0 && !went && mem.offset.is_some_and(|last| last != offset) { + state.current = page_on_line(&geo.layout, offset.1 + vh / 2.0); + } + mem.offset = Some(offset); + mem.layout = build.cache.borrow().clone(); + seen.current_changed = state.current != started_on; + seen.next = Some(Next { started, state, mem, edit }); + } +} + +/// The page or spread `current` shows in, content coordinates; `None` with no pages. +fn row_rect(geo: &Placed, current: usize, options: &LayoutOptions) -> Option { + shown_row(geo.layout.rects.len(), current, options).filter_map(|page| geo.layout.rects.get(page).copied()).reduce(|a, b| a.union(b)) } /// Which way the view travels this pass along the page column: `1.0` down the document, `-1.0` up, `0.0` still. The @@ -818,7 +884,7 @@ fn travel_of(last: Option<(f64, f64)>, want: (f64, f64), wheel: Option<&craft_be /// The edge of the shown row the view sits at in the direction it would move: `Some(true)` the end, going forward, /// `Some(false)` the start, going back, `None` when the row still has room that way. A row that fits sits at both. fn edge_ahead(geo: &Placed, y: f64, view_height: f64, forward: bool) -> Option { - let (lo, hi) = offset_range(geo.doc.y0, geo.doc.y1, view_height); + let (lo, hi) = geo.y_range(view_height); if forward { (y >= hi - EDGE).then_some(true) } else { (y <= lo + EDGE).then_some(false) } } @@ -892,31 +958,33 @@ craft_ui::words! { } } -/// What this pass's keys ask of the view (plain keys only). +/// What this pass's keys ask of the view. #[derive(Default)] struct KeyMoves { /// Screen points to move the offset. pan: (f64, f64), /// End in a continuous view: the bottom. to_end: bool, - /// Turn to the next (`true`) or previous row when not continuous. + /// Turn to the next (`true`) or previous row or spread. turn: Option, + /// The turn is Right's (`true`) or Left's at the row's edge: a wide row lands at the edge the reader comes from. + across: Option, /// Where to take the view. go_to: Option, } impl KeyMoves { - /// Page Up and Down a screen less a key line (a row when not continuous), Home and End the first and last page, Up - /// and Down a key line (not continuous, a turn once the row is at its edge that way), Left and Right a page when - /// the page fits the width, else a key line sideways. Home and End with Shift or Cmd, and Page Up, Page Down, Up and - /// Down with Shift and Cmd together, go to the first or last page; Alt, and Shift or Cmd alone with the other keys, + /// Page Up and Down a screen less a key line (a row when not continuous, and with Cmd), Home and End the first + /// and last page, Up and Down a key line (not continuous, a turn once the row is at its edge that way), Left and + /// Right a key line sideways while the current page or spread has more to show that way, else a turn of a page or + /// spread; Cmd with Left or Right turns at once. Home and End with Shift or Cmd, and Page Up, Page Down, Up and + /// Down with Shift and Cmd together, go to the first or last page; Alt, and Shift alone with the other keys, /// leave them to nothing. - fn of(keys: BodyKeys, state: &PageViewState, geo: &Placed, rect: Rect, line: f64) -> KeyMoves { + fn of(keys: BodyKeys, nudge: Option<(Vec2, Mods)>, state: &PageViewState, geo: &Placed, options: &LayoutOptions, rect: Rect, line: f64) -> KeyMoves { let last = geo.layout.rects.len().saturating_sub(1); let top = |page: usize| Some(GoTo::Top { page, fraction: 0.0 }); let mut moves = KeyMoves::default(); let end = |forward: bool| if forward && state.continuous { (true, None) } else { (false, top(if forward { last } else { 0 })) }; - let plain = |mods: &MoveMods| !mods.extend && !mods.lead && !mods.fine; let to_end = match keys.page { Some((step @ (NavMove::Start | NavMove::End), mods)) if !mods.fine => Some(step == NavMove::End), Some((step @ (NavMove::PageUp | NavMove::PageDown), mods)) if mods.extend && mods.lead && !mods.fine => Some(step == NavMove::PageDown), @@ -925,10 +993,10 @@ impl KeyMoves { if let Some(forward) = to_end { (moves.to_end, moves.go_to) = end(forward); } - match keys.page.filter(|(_, mods)| plain(mods)).map(|(step, _)| step) { - Some(step @ (NavMove::PageUp | NavMove::PageDown)) => { + match keys.page.filter(|(_, mods)| !mods.extend && !mods.fine) { + Some((step @ (NavMove::PageUp | NavMove::PageDown), mods)) => { let forward = step == NavMove::PageDown; - if state.continuous { + if state.continuous && !mods.lead { // A key line of the last screen stays in view, so the reader keeps their place. let screen = (f64::from(rect.height()) - line).max(line); moves.pan.1 += if forward { screen } else { -screen }; @@ -938,7 +1006,7 @@ impl KeyMoves { } _ => {} } - if let Some((direction, mods)) = keys.nudge + if let Some((direction, mods)) = nudge && direction.y != 0.0 && mods.shift && (mods.cmd || mods.ctrl) @@ -947,18 +1015,19 @@ impl KeyMoves { (moves.to_end, moves.go_to) = end(direction.y > 0.0); return moves; } - let Some((direction, _)) = keys.nudge.filter(|(_, mods)| mods.is_none()) else { return moves }; - if direction.y != 0.0 { + let Some((direction, mods)) = nudge.filter(|(_, mods)| !mods.shift && !mods.alt) else { return moves }; + let lead = mods.cmd || mods.ctrl; + if direction.y != 0.0 && !lead { moves.line_down(direction.y > 0.0, state, geo, rect, line); } else if direction.x != 0.0 { let forward = direction.x > 0.0; - if geo.doc.width() > f64::from(rect.width()) { - moves.pan.0 += if forward { line } else { -line }; - } else if state.continuous { - let next = if forward { state.current + 1 } else { state.current.saturating_sub(1) }; - moves.go_to = top(next.min(last)); - } else { + if lead { moves.turn = Some(forward); + } else if side_edge(geo, state, options, rect, forward) { + moves.turn = Some(forward); + moves.across = Some(forward); + } else { + moves.pan.0 += if forward { line } else { -line }; } } moves @@ -979,6 +1048,17 @@ impl KeyMoves { } } +/// Whether the view shows the edge of the current page or spread to the right (`forward`) or left: the row is shown +/// whole that way, or the content can scroll no farther. The current row decides, not the widest page, so a narrow +/// page beside wide ones turns at once. +fn side_edge(geo: &Placed, state: &PageViewState, options: &LayoutOptions, rect: Rect, forward: bool) -> bool { + let width = f64::from(rect.width()); + let (lo, hi) = offset_range(geo.doc.x0, geo.doc.x1, width); + let x = state.offset.0; + let row = row_rect(geo, state.current, options); + if forward { x >= hi - EDGE || row.is_some_and(|r| r.x1 <= x + width + EDGE) } else { x <= lo + EDGE || row.is_some_and(|r| r.x0 >= x - EDGE) } +} + /// Two scales a pass apart that are the same scale (round trips through the zoom differ in the last bits). fn scale_settled(before: f64, after: f64) -> bool { (before - after).abs() <= before.abs().max(after.abs()) * 1e-9 @@ -992,8 +1072,23 @@ struct Placed { scale: f64, /// The pages that show: all when continuous, else the current page or spread. row: Range, - /// The scroll area in content coordinates: the whole layout, or the shown row with its margins. + /// The scroll area in content coordinates: the pages that show with the margins above and below them. doc: DocRect, + /// The part of the pages that show, without the margins. + pages: DocRect, +} + +impl Placed { + /// The offsets a view `view_height` tall can take down the shown pages: the pages in the view's middle when they + /// fit it without their margins, else anywhere over the scroll area. + fn y_range(&self, view_height: f64) -> (f64, f64) { + if self.pages.height() <= view_height { + let middle = self.pages.y0 - (view_height - self.pages.height()) / 2.0; + (middle, middle) + } else { + offset_range(self.doc.y0, self.doc.y1, view_height) + } + } } /// What a layout is made from, so a pass with the same inputs reuses the last layout. @@ -1081,14 +1176,12 @@ impl Geometry<'_> { } let count = self.sizes.len(); let row = if state.continuous { 0..count } else { shown_row(count, state.current, &options) }; + // The layout is at least the viewport's height; the scroll area is the pages' own, so pages shorter than the + // view sit in its middle. let whole = DocRect::new(0.0, 0.0, layout.size.width, layout.size.height); - let doc = if state.continuous || row.is_empty() { - whole - } else { - let shown = row.clone().map(|p| band_rect(&layout, p)).reduce(|a, b| a.union(b)).unwrap_or(whole); - DocRect::new(0.0, shown.y0 - self.spacing.margin, layout.size.width, shown.y1 + self.spacing.margin) - }; - Placed { layout, scale, row, doc } + let pages = row.clone().map(|p| band_rect(&layout, p)).reduce(|a, b| a.union(b)); + let doc = pages.map_or(whole, |shown| DocRect::new(0.0, shown.y0 - self.spacing.margin, layout.size.width, shown.y1 + self.spacing.margin)); + Placed { layout, scale, row, doc, pages: pages.unwrap_or(whole) } } } diff --git a/crates/pages/tests/it/views.rs b/crates/pages/tests/it/views.rs index 8a4aeedfd..9d9c232fe 100644 --- a/crates/pages/tests/it/views.rs +++ b/crates/pages/tests/it/views.rs @@ -4,14 +4,14 @@ use craft_behavior::{GESTURE_GAP, kurbo}; use craft_pages::layout::{Fit, LayoutOptions, PageDisplay}; use craft_pages::ui::fixtures::{DemoPages, PAPER}; -use craft_pages::ui::{GoTo, PagePreview, PageSource, PageView, PageViewState, PlacedPage, ReadingState, ReadingView}; -use craft_ui::canvas::NavigationOptions; -use craft_ui::contract::{Role, Show as _}; +use craft_pages::ui::{GoTo, PageBody, PagePreview, PageSource, PageView, PageViewState, PlacedPage, ReadingState, ReadingView}; +use craft_ui::canvas::{CanvasTool, NavigationOptions, ToolAction, ToolContext, ToolHost, ToolKey, ToolPath, ToolPointer}; +use craft_ui::contract::{Bind, Role, Show as _}; use craft_ui::primitives::textures::{Revision, TextureState, ThumbRender, ThumbRequest, ThumbSource}; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers, pos2, vec2}; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::ops::Range; use std::rc::Rc; @@ -81,6 +81,17 @@ struct Rig { /// A rig over `source` in a 900 × 600 room, settled when `settle`. fn rig_over(source: impl PageSource + 'static, start: PageViewState, navigation: NavigationOptions, settle: bool) -> Rig { + rig_with(source, start, navigation, settle, |_, _| ()) +} + +/// A rig over `source` whose page body runs `body` (the app's tool host), in a 900 × 600 room, settled when `settle`. +fn rig_with( + source: impl PageSource + 'static, + start: PageViewState, + navigation: NavigationOptions, + settle: bool, + mut body: impl FnMut(&mut egui::Ui, &PageBody<'_>) + 'static, +) -> Rig { let state = Rc::new(RefCell::new(start)); let out: Rc> = Rc::default(); let keep: Rc>> = Rc::default(); @@ -90,7 +101,7 @@ fn rig_over(source: impl PageSource + 'static, start: PageViewState, navigation: let offset = now.offset; let keep = held.borrow().clone(); let shown = - PageView::new("Pages", &source, &mut now, PAPER).options(LayoutOptions::ACROBAT).navigation(navigation).keep(&keep).show(ui, |_, _| ()); + PageView::new("Pages", &source, &mut now, PAPER).options(LayoutOptions::ACROBAT).navigation(navigation).keep(&keep).show(ui, &mut body); let scrolled = seen.borrow().scrolled || shown.scrolled; *seen.borrow_mut() = Out { offset, rects: shown.layout.rects.clone(), pages: shown.pages, visible: shown.visible, view: shown.canvas.response.rect, scrolled }; @@ -132,8 +143,10 @@ fn assert_centre_kept(out: &Out, before: (usize, kurbo::Point), what: &str) { ); } +/// A written zoom keeps the point at the centre; a new room (a panel opened beside the view) refits and keeps the +/// current page's top where it was, as production did. #[trial] -fn a_changed_zoom_keeps_the_point_at_the_centre_in_place() { +fn a_changed_zoom_keeps_the_point_at_the_centre_and_a_new_room_the_current_pages_top() { // The app's zoom. let mut zoomed = rig( 5, @@ -153,13 +166,19 @@ fn a_changed_zoom_keeps_the_point_at_the_centre_in_place() { // A fit over a new room. let mut fitted = rig(5, state_with(|s| s.fit = Fit::Width)); - let third = fitted.out.borrow().rects[2]; - fitted.state.borrow_mut().offset.1 = third.y0 + 0.4 * third.height(); - fitted.fixture.idle(2); - let before = centre_point(&fitted.out.borrow()); + fitted.state.borrow_mut().go_to_fraction(2, 0.2); + fitted.fixture.idle(3); + let below_top = |out: &Out, page: usize| out.rects[page].y0 - out.offset.1; + let (page, before) = (fitted.state.borrow().current, below_top(&fitted.out.borrow(), 2)); + assert_eq!(page, 2, "precondition: the third page is current"); + let scale = fitted.out.borrow().rects[2].height(); fitted.fixture.room(vec2(700.0, 500.0)); fitted.fixture.idle(3); - assert_centre_kept(&fitted.out.borrow(), before, "a fit after a new room"); + let out = fitted.out.borrow(); + assert!(out.rects[2].height() < scale, "precondition: the fit shrank the pages"); + assert_eq!(fitted.state.borrow().current, 2, "the page stays current"); + let after = below_top(&out, 2); + assert!((after - before).abs() < 1.0, "the current page's top stays put: {before} then {after}"); } /// A wheel step of `lines` over the middle of the room. @@ -882,3 +901,185 @@ fn the_view_reports_the_readers_wheel_and_scroll_bar_but_not_a_go_to_or_a_zoom() }); assert!(dragged, "a press on the scroll bar's track is the reader's scroll"); } + +/// A tool that takes the arrows while `takes` holds (a selected picture's nudge), and counts them. +struct Nudges { + takes: Rc>, + taken: Rc>, +} + +impl CanvasTool for Nudges { + fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction { + ToolAction::Claimed + } + + fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn cancel(&mut self, _: craft_behavior::CancelReason, _: &mut ToolContext<'_>) {} + + fn key(&mut self, key: &ToolKey, _: &mut ToolContext<'_>) -> bool { + let take = matches!(key, ToolKey::Nudge { .. }) && self.takes.get(); + if take { + self.taken.set(self.taken.get() + 1); + } + take + } + + fn paint(&self, _: &craft_ui::primitives::Draw<'_>, _: &ToolContext<'_>) {} + + fn command_form(&self) -> ToolPath { + ToolPath::Command("the nudged object's position fields") + } +} + +/// The page view gives the window's arrows to its body's tool host first and turns the page only with what the tool +/// left, in the same pass. The view used to take them before its body ran, so a selected object never moved. +#[trial] +fn an_arrow_the_tool_takes_leaves_the_page_and_one_it_leaves_turns_it() { + let (takes, taken) = (Rc::new(Cell::new(true)), Rc::new(Cell::new(0))); + let mut tool = Nudges { takes: Rc::clone(&takes), taken: Rc::clone(&taken) }; + let start = state_with(|s| { + s.continuous = false; + s.fit = Fit::Page; + }); + let Rig { mut fixture, state, .. } = rig_with(DemoPages::new(5), start, NavigationOptions::default(), true, move |ui, body| { + if let Some(pass) = body.pass { + let reply = ToolHost::new().run(ui, pass, &mut tool); + assert!(reply.view.is_none(), "the tool moves no view"); + } + }); + fixture.key(Key::ArrowRight, Modifiers::NONE); + fixture.idle(2); + assert_eq!(taken.get(), 1, "the tool takes the arrow"); + assert_eq!(state.borrow().current, 0, "an arrow the tool took leaves the page"); + takes.set(false); + fixture.key(Key::ArrowRight, Modifiers::NONE); + fixture.idle(2); + assert_eq!((taken.get(), state.borrow().current), (1, 1), "an arrow the tool leaves turns the page"); +} + +/// Cmd with Page Down turns one page in a scrolling view, where plain Page Down scrolls a screen; Right turns a +/// spread in a scrolling two-page view, not to the other page of the spread already on screen. +#[trial] +fn command_page_down_turns_a_page_and_right_a_spread_in_a_scrolling_view() { + let (mut fixture, state, out) = layout_rig(5, state_with(|s| s.fit = Fit::Page)); + focus_canvas(&mut fixture); + fixture.key(Key::PageDown, Modifiers::COMMAND); + fixture.idle(2); + assert_eq!(state.borrow().current, 1, "Cmd+Page Down turns one page"); + let top = out.borrow().rects[1].y0 - out.borrow().offset.1; + assert!(top >= 0.0 && top < 40.0, "the page's top comes to the view's top: {top}"); + fixture.key(Key::PageUp, Modifiers::COMMAND); + fixture.idle(2); + assert_eq!(state.borrow().current, 0, "Cmd+Page Up turns back"); + + let (mut fixture, state, _) = layout_rig( + 6, + state_with(|s| { + s.fit = Fit::Page; + s.display = PageDisplay::TwoUp; + }), + ); + focus_canvas(&mut fixture); + fixture.key(Key::ArrowRight, Modifiers::NONE); + fixture.idle(2); + assert_eq!(state.borrow().current, 2, "Right moves a spread"); +} + +/// Right on a page wider than the view scrolls it a line, turns at its right edge, and the next page comes from its +/// left edge, so Right scrolls across it rather than turning again. The view used to scroll the wide layout for ever. +#[trial] +fn right_scrolls_a_page_wider_than_the_view_then_turns_at_its_edge() { + let (mut fixture, state, out) = layout_rig( + 3, + state_with(|s| { + s.continuous = false; + s.fit = Fit::None; + s.zoom = 3.0; + }), + ); + focus_canvas(&mut fixture); + let start = state.borrow().offset.0; + fixture.key(Key::ArrowRight, Modifiers::NONE); + fixture.idle(2); + assert_eq!(state.borrow().current, 0, "Right scrolls the wide page"); + assert!(state.borrow().offset.0 > start, "the page moved left"); + let mut presses = 1; + while state.borrow().current == 0 { + fixture.key(Key::ArrowRight, Modifiers::NONE); + fixture.idle(2); + presses += 1; + assert!(presses < 300, "Right never reached the page's edge"); + } + assert!(presses > 3, "Right scrolled across the page before turning ({presses} presses)"); + let shown = out.borrow(); + let (left, view) = (shown.rects[1].x0 - shown.offset.0, f64::from(shown.view.width())); + assert!(left >= 0.0 && shown.rects[1].x1 - shown.offset.0 > view, "the next page shows from its left edge: {left}"); +} + +/// Pages shorter than the view sit in its middle, a page or the column of a scrolling view, and so does a page that +/// fits only without its margins. The scroll area used to be at least the view's height, from the top. +#[trial] +fn pages_shorter_than_the_view_sit_in_its_middle() { + let middle = |out: &Out, rows: Range| { + let column = rows.map(|page| out.rects[page]).reduce(|a, b| a.union(b)).expect("pages"); + let (top, bottom) = (column.y0 - out.offset.1, column.y1 - out.offset.1); + let view = f64::from(out.view.height()); + assert!(bottom - top < view, "precondition: {top}..{bottom} is shorter than {view}"); + assert!((top - (view - bottom)).abs() < 1.0, "{top}..{bottom} sits in the middle of {view}"); + }; + let small = |continuous: bool, zoom: f64| { + state_with(|s| { + s.continuous = continuous; + s.fit = Fit::None; + s.zoom = zoom; + }) + }; + let (_, _, out) = layout_rig(1, small(false, 0.25)); + middle(&out.borrow(), 0..1); + let (_, _, out) = layout_rig(2, small(true, 0.25)); + middle(&out.borrow(), 0..2); + + // A page that fits the view only without its margins shows whole, in the middle. + let height = out.borrow().rects[0].height(); + let room = f64::from(out.borrow().view.height()); + let (_, _, out) = layout_rig(1, small(false, 0.25 * (room - 8.0) / height)); + middle(&out.borrow(), 0..1); +} + +/// The reader's wheel over the pages scrolls the view and reports it while a field above the view (a find bar's +/// query) has the focus. +#[trial] +fn the_wheel_over_the_pages_scrolls_and_reports_it_while_a_field_beside_them_has_the_focus() { + let state = Rc::new(RefCell::new(state_with(|s| s.fit = Fit::Width))); + let scrolled = Rc::new(Cell::new(false)); + let (kept, seen) = (Rc::clone(&state), Rc::clone(&scrolled)); + let source = DemoPages::new(5); + let mut query = String::new(); + let mut fixture = Fixture::new(move |ui| { + craft_ui::text::TextField::new("Find", Bind::bound(&mut query)).show(ui); + let mut now = kept.borrow().clone(); + let shown = PageView::new("Pages", &source, &mut now, PAPER).show(ui, |_, _| ()); + seen.set(seen.get() || shown.scrolled); + *kept.borrow_mut() = now; + }); + fixture.room(vec2(900.0, 600.0)); + fixture.settle(); + fixture.key(Key::Tab, Modifiers::NONE); + assert!(fixture.focused_role().is_some_and(|role| role.text), "precondition: the field has the focus"); + let before = state.borrow().offset.1; + fixture.frame(vec![egui::Event::PointerMoved(pos2(450.0, 350.0))]); + scrolled.set(false); + fixture.frame(vec![egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -20.0), + modifiers: Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }]); + fixture.idle(4); + assert!(state.borrow().offset.1 > before, "the wheel scrolls the pages"); + assert!(scrolled.get(), "the view reports the reader's scroll"); +} diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index a1ee92911..985c8718c 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -200,9 +200,10 @@ pub struct Canvas<'a> { /// Whether the rulers show along the top and left edges (View > Rulers): the view lies inside them. #[prop] show_rulers: bool, - /// Whether the canvas leaves Page Up, Page Down, Home, End and the arrows to its body: it applies no page keys - /// and gives no tool or session control the arrows, and its body reads them in [`CanvasSpace::keys`]. For a - /// body that pages its document itself (a page view). + /// Whether the canvas leaves Page Up, Page Down, Home, End and the arrows to its body: it applies no page keys, + /// which its body reads in [`CanvasSpace::keys`], and the arrows reach the body's tool host and session controls + /// first, then the body with [`CanvasSpace::take_nudge`], in the same pass. For a body that pages its document + /// itself (a page view). #[prop] keys_to_body: bool, /// The rulers' units and zero point, published to the body in its [`CanvasSpace`]. @@ -543,7 +544,8 @@ impl<'a> Canvas<'a> { jumped = true; } // Page Up and Down, Home and End scroll the view as in Photoshop; the arrows are the tool's nudges. A canvas - // that leaves its keys to its body hands both to it. + // that leaves its keys to its body hands it the page keys; the arrows stay routed, for the body's tool host + // first and then the body (`CanvasSpace::take_nudge`). let mut keys = BodyKeys::default(); let mut moves = Vec::new(); while let Some(mv) = cx.intents().take_move() { @@ -558,17 +560,6 @@ impl<'a> Canvas<'a> { jumped |= key.apply(&mut view, document); } } - if self.keys_to_body { - // With nothing focused the window's arrows are the canvas's too: no tool here takes them. - keys.nudge = cx.intents().take_nudge().or_else(|| { - let mut nudge = None; - crate::runtime::keys::with_window_intents(&ctx, false, |window| { - nudge = window.take_nudge(); - nudge.is_some() - }); - nudge - }); - } // A pan or a scroll takes over from an ease, here or in a tool. let mut steer = motion.steer.take(); if let Some(ease) = self.ease { diff --git a/crates/ui-canvas/src/canvas/space.rs b/crates/ui-canvas/src/canvas/space.rs index 2830eec46..8d8231fcb 100644 --- a/crates/ui-canvas/src/canvas/space.rs +++ b/crates/ui-canvas/src/canvas/space.rs @@ -225,11 +225,31 @@ impl CanvasSpace { self.easing } - /// The page and arrow keys the canvas left to its body in this pass ([`Canvas::keys_to_body`](super::Canvas)). + /// The page keys the canvas left to its body in this pass ([`Canvas::keys_to_body`](super::Canvas)). pub fn keys(&self) -> BodyKeys { self.keys } + /// Takes this pass's arrow that nothing in the canvas's body took: the one routed to the focused canvas, or, with + /// nothing in the window focused, the window's. A body that pages its document itself + /// ([`Canvas::keys_to_body`](super::Canvas)) runs its tool host and controls first, which take the arrows a tool + /// or a session claims, and moves its view with what is left in the same pass. `None` when the arrow was taken, + /// or there was none; a measuring run reads it without taking it. + pub fn take_nudge(&self, ctx: &egui::Context) -> Option<(Vec2, Mods)> { + let canvas = self.canvas?; + let mut own = crate::runtime::keys::intents_of(ctx, Some(canvas), false); + if let Some(nudge) = own.take_nudge() { + crate::runtime::keys::settle(ctx, Some(canvas), &own); + return Some(nudge); + } + let mut nudge = None; + crate::runtime::keys::with_window_intents(ctx, false, |window| { + nudge = window.take_nudge(); + nudge.is_some() + }); + nudge + } + /// Device pixels per document unit (1 is 100 %) of the view at this scale. pub fn zoom_device(&self) -> f64 { zoom::device(&self.view, self.pixels_per_point) @@ -313,15 +333,14 @@ pub struct BackgroundPress { pub context_key: bool, } -/// The keys a canvas that leaves them to its body took in a pass, one of each kind: a key held down repeats over -/// passes, not within one. +/// The page keys a canvas that leaves them to its body took in a pass: a key held down repeats over passes, not +/// within one. The arrows stay with the body's tool host and controls first; the body takes what they left with +/// [`CanvasSpace::take_nudge`]. #[derive(Clone, Copy, Debug, Default, PartialEq)] #[non_exhaustive] pub struct BodyKeys { /// Page Up, Page Down, Home or End, with the modifiers held. pub page: Option<(NavMove, MoveMods)>, - /// An arrow: a unit direction on screen and the modifiers held. - pub nudge: Option<(Vec2, Mods)>, } impl BackgroundPress { diff --git a/crates/ui-contract/src/contract/steps/sense.rs b/crates/ui-contract/src/contract/steps/sense.rs index 7e659ea03..0652a1f87 100644 --- a/crates/ui-contract/src/contract/steps/sense.rs +++ b/crates/ui-contract/src/contract/steps/sense.rs @@ -8,7 +8,9 @@ use egui::{Context, Id, Rect}; /// Registers a wheel taker for next pass's split (8.6): `sensed`, the taker the wheel bits of the component's sense /// make (`WheelTaker::for_sense`). Every value control is a `WheelTaker::value` taker, in any scope: a wheel gesture it -/// owns ends with a `WheelPhase::End` share. A value control with a text part is a field (`WheelTaker::field`). A value +/// owns ends with a `WheelPhase::End` share. A value control with a text part that steps by the wheel (it senses a +/// wheel axis: a number field) is a field (`WheelTaker::field`), which takes the plain wheel while focused wherever the +/// pointer is; a text field that does not step leaves the wheel over the rest of the window to what is there. A value /// control takes the wheel only while focused or armed, on the axes it senses (the vertical one when it senses none); /// inside a `WheelScope::Free` scope one that senses the wheel takes it without focus. A value control that steps by /// the wheel declares the axis it steps in its sense, so a free scope frees it; one that does not step keeps the @@ -29,7 +31,7 @@ pub(crate) fn register_wheel( if let Some(taker) = taker { wheel::register( ctx, - taker.value(value_control).field(value_control && text).gated(scope == WheelScope::Gated || (value_control && !free && !zone)), + taker.value(value_control).field(value_control && text && sensed.is_some()).gated(scope == WheelScope::Gated || (value_control && !free && !zone)), ); } }