canvas-w5: net change of 2 commits

- canvas-w5: written from its sheet
- canvas-w5: review fixes (review-1)
This commit is contained in:
Martin Ball
2026-11-18 14:03:48 +00:00
parent d45dad938a
commit 59cc1ac191
7 changed files with 388 additions and 49 deletions
+24 -9
View File
@@ -5,7 +5,8 @@
//! geometry and the turning. [`ReadingNav`] is the row of page-turn buttons under the columns.
use craft_behavior::{IconId, Metrics, NavMove, PartKey, PressPhase, Sense};
use craft_ui::buttons::IconButton;
use craft_ui::buttons::{Button, IconButton};
use craft_ui::display::Text;
use craft_ui::contract::{
Access, Animate as _, Common, Component, Cx, DisabledLook, Focus as _, Input, MeasureCx, Name, NoValue, Outcome, PaintUi, PartsCx, Pointer as _,
Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _, clicked, spec,
@@ -14,7 +15,7 @@ use craft_ui::layout_components::Row;
use craft_ui::primitives::textures::{Priority, TextureStoreOptions, ThumbPaint, ThumbRequest, ThumbnailOptions, Thumbnails, texture_side};
use craft_ui::primitives::{PaintShape, ReadingMeasure};
use craft_ui::runtime::commands::FireSource;
use craft_ui::runtime::env::Env;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::focus::{ActivateKeys, KeepKeys, KeyUse};
use craft_ui::style::{ComponentStyle, DataColor, FocusLook, StyleCx, UiTokens};
use egui::{CornerRadius, Pos2, Rect, Response, Ui, Vec2, pos2, vec2};
@@ -60,6 +61,8 @@ craft_ui::words! {
pub struct ReadingViewWords {
previous: "readingView.previous" = "Previous Screen";
next: "readingView.next" = "Next Screen";
/// The position between the page-turn buttons: the screen shown and how many there are.
position: template "readingView.position" = "{n} / {m}";
}
}
@@ -461,10 +464,8 @@ impl Outcome for ReadingNavOutput {
pub struct ReadingNav<'a> {
state: &'a mut ReadingState,
count: usize,
#[allow(dead_code)] // P3(canvas-w5): cv.K16
position: bool,
#[allow(dead_code)] // P3(canvas-w5): cv.K16
action: Option<craft_ui::runtime::env::Label>,
action: Option<Label>,
}
impl<'a> ReadingNav<'a> {
@@ -489,15 +490,29 @@ impl<'a> ReadingNav<'a> {
/// Shows the row.
pub fn show(self, ui: &mut Ui) -> ReadingNavOutput {
let words = Env::of(ui).words::<ReadingViewWords>();
let (column, count) = (self.state.column, self.count);
let ReadingNav { state, count, position, action } = self;
let env = Env::of(ui);
let words = env.words::<ReadingViewWords>();
let column = state.column;
let position = position.then(|| {
let format = env.format();
let (at, total) = (format.integer((column + 1).min(count) as u64), format.integer(count as u64));
Label::from(words.position.fill(&[("n", at.as_str()), ("m", total.as_str())]))
});
let mut by = 0;
let mut acted = false;
let row = Row::new().show(ui, |ui, _| {
let previous = IconButton::new(IconId::new("chevron_left")).label(words.previous.clone()).enabled(column > 0).show(ui);
if let Some(position) = &position {
Text::new(position.clone()).show(ui);
}
let next = IconButton::new(IconId::new("chevron_right")).label(words.next.clone()).enabled(column + 1 < count).show(ui);
if let Some(label) = &action {
acted = clicked(&Button::new(label.clone()).show(ui));
}
by = i32::from(clicked(&next)) - i32::from(clicked(&previous));
});
self.state.turn(by, count);
ReadingNavOutput { response: row.output, turned: by != 0, action: false }
state.turn(by, count);
ReadingNavOutput { response: row.output, turned: by != 0, action: acted }
}
}
+12
View File
@@ -22,3 +22,15 @@ fn reading_nav(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let state = data.value("state", ReadingState { column: 1, ..ReadingState::default() });
ReadingNav::new(state, PAGES).show(ui).into()
}
#[story(ReadingNav<'static>, covers = [], drive = Drive::Never)]
fn with_position(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let state = data.value("state", ReadingState { column: 1, ..ReadingState::default() });
ReadingNav::new(state, PAGES).position(true).show(ui).into()
}
#[story(ReadingNav<'static>, covers = [], drive = Drive::Never)]
fn with_action(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let state = data.value("state", ReadingState { column: 1, ..ReadingState::default() });
ReadingNav::new(state, PAGES).action("Done").show(ui).into()
}
+44 -16
View File
@@ -193,6 +193,7 @@ struct MarkLook {
radius: CornerRadius,
/// How far the current match grows past its glyphs.
current_grow: f32,
/// The accent stroke: the column selection's outline and the underline of spoken text.
column_outline: StyleColor,
}
@@ -210,29 +211,50 @@ impl MarkLook {
}
}
/// Paints the selection and find marks of one placed page: the selection fill, the match fills, the current match
/// grown. The one painter of both: [`TextMarks`] paints the matches and the tool the selection through it.
/// One filled mark, `rect` grown by `grow`: the one fill of every mark.
fn fill_mark(draw: &Draw<'_>, look: &MarkLook, rect: egui::Rect, fill: StyleColor, grow: f32) {
draw.fill(&PaintShape::Rect(rect.expand(grow), look.radius), fill);
}
/// Paints the selection, find and area marks of one placed page: the selection fill, the match fills, the current match
/// grown. The one painter of all: [`TextMarks`] paints the matches and areas and the tool the selection through it.
/// Without `text` (a page whose text is not there, or none at all) only the `areas` paint.
fn paint_marks(
draw: &Draw<'_>,
look: &MarkLook,
placed: &PlacedPage,
text: &dyn PageTextSource,
text: Option<&dyn PageTextSource>,
selection: Option<&TextSelection>,
marks: &[TextMark],
areas: &[MarkArea],
) {
let (top, bottom) = placed.band;
let band = egui::Rect::from_min_max(pos2(placed.rect.min.x, placed.rect.min.y + top), pos2(placed.rect.max.x, placed.rect.min.y + bottom));
let screen = |r: Rect| egui::Rect::from_two_pos(placed.to_screen(Point::new(r.x0, r.y0)), placed.to_screen(Point::new(r.x1, r.y1)));
draw.clipped(band, |draw| {
for mark in marks.iter().filter(|mark| mark.page == placed.page) {
let (fill, grow) = if mark.current { (look.current, look.current_grow) } else { (look.found, 0.0) };
for rect in text.line_rects(mark.glyphs.clone()) {
draw.fill(&PaintShape::Rect(screen(rect).expand(grow), look.radius), fill);
if let Some(text) = text {
for mark in marks.iter().filter(|mark| mark.page == placed.page) {
let (fill, grow) = if mark.current { (look.current, look.current_grow) } else { (look.found, 0.0) };
for rect in text.line_rects(mark.glyphs.clone()) {
fill_mark(draw, look, screen(rect), fill, grow);
}
}
}
if let Some(selection) = selection.filter(|selection| selection.page == placed.page) {
for area in areas.iter().filter(|area| area.page == placed.page) {
let rect = screen(area.rect);
let (fill, grow) = match area.kind {
MarkKind::Selection => (look.selection, 0.0),
MarkKind::Found => (look.found, 0.0),
MarkKind::Current | MarkKind::Spoken => (look.current, look.current_grow),
};
fill_mark(draw, look, rect, fill, grow);
if area.kind == MarkKind::Spoken {
draw.stroke(&PaintShape::Path(vec![pos2(rect.min.x, rect.max.y), rect.max]), StrokeWidth::Thin, look.column_outline);
}
}
if let (Some(text), Some(selection)) = (text, selection.filter(|selection| selection.page == placed.page)) {
for rect in selection.rects(text) {
draw.fill(&PaintShape::Rect(screen(rect), look.radius), look.selection);
fill_mark(draw, look, screen(rect), look.selection, 0.0);
}
}
});
@@ -439,7 +461,7 @@ impl CanvasTool for TextSelectTool<'_> {
let look = MarkLook::of(style);
for placed in self.pages {
let Some(text) = self.texts.page(placed.page) else { continue };
paint_marks(draw, &look, placed, text, self.state.selection.as_ref(), &[]);
paint_marks(draw, &look, placed, Some(text), self.state.selection.as_ref(), &[], &[]);
}
if let (Some((page, _)), Some(TextSelection { page: selected, span: TextSpan::Column { from, to } })) =
(self.state.gesture, self.state.selection)
@@ -535,8 +557,16 @@ pub struct MarkArea {
impl MarkArea {
/// The area `rect` of `page`, marking `kind`.
pub fn new(page: usize, rect: craft_behavior::kurbo::Rect, kind: MarkKind) -> Self {
let _ = (page, rect, kind);
todo!("cv.K17")
MarkArea { page, rect, kind }
}
}
/// No page has text: what [`TextMarks::over`] reads, so only its areas paint.
struct NoTexts;
impl PageTexts for NoTexts {
fn page(&self, _: usize) -> Option<&dyn PageTextSource> {
None
}
}
@@ -548,8 +578,7 @@ impl<'a> TextMarks<'a> {
/// Marks for [`areas`](Self::areas) alone over the placed `pages`, with no text source.
pub fn over(pages: &'a [PlacedPage]) -> Self {
let _ = pages;
todo!("cv.K17")
TextMarks { common: Common::new(), pages, texts: &NoTexts, marks: &[], selection: None, areas: &[] }
}
}
@@ -578,8 +607,7 @@ impl Component for TextMarks<'_> {
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let draw = ui.draw();
for placed in self.pages {
let Some(text) = self.texts.page(placed.page) else { continue };
paint_marks(&draw, &cx.style.look, placed, text, self.selection.as_ref(), self.marks);
paint_marks(&draw, &cx.style.look, placed, self.texts.page(placed.page), self.selection.as_ref(), self.marks, self.areas);
}
}
+17 -2
View File
@@ -5,10 +5,10 @@ use std::ops::Range;
use craft_behavior::kurbo::{Point, Rect};
use craft_ui::canvas::Canvas;
use craft_ui::contract::{Show as _, ShowContainer as _};
use craft_ui::testing::{StoryData, StoryOutput, story};
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::{Pos2, Ui};
use super::{PageTextSource, PageTexts, TextMark, TextMarks, TextSelection, TextSpan};
use super::{MarkArea, MarkKind, PageTextSource, PageTexts, TextMark, TextMarks, TextSelection, TextSpan};
use crate::ui::fixtures::demo_placed;
const LINES: [&str; 3] = ["The quick brown fox", "jumps over the lazy dog", "and keeps running"];
@@ -125,6 +125,21 @@ fn run_selected(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
on_page(ui, &[], Some(TextSelection::new(0, TextSpan::run(4, 26))))
}
#[story(TextMarks<'static>, covers = [], drive = Drive::Never)]
fn areas_of_each_kind(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let pages = demo_placed(1, Pos2::new(24.0, 24.0));
let areas = [
MarkArea::new(0, Rect::new(0.0, 0.0, 90.0, LINE_HEIGHT), MarkKind::Selection),
MarkArea::new(0, Rect::new(0.0, LINE_HEIGHT, 90.0, 2.0 * LINE_HEIGHT), MarkKind::Found),
MarkArea::new(0, Rect::new(0.0, 2.0 * LINE_HEIGHT, 90.0, 3.0 * LINE_HEIGHT), MarkKind::Current),
MarkArea::new(0, Rect::new(0.0, 3.0 * LINE_HEIGHT, 90.0, 4.0 * LINE_HEIGHT), MarkKind::Spoken),
];
let mut control = Some(TextMarks::over(&pages).areas(&areas));
let stage = craft_ui::testing::stage(ui);
let shown = Canvas::new("Page").show_at(ui, stage, |ui, body| control.take().map(|control| control.show_at(ui, body.rect)));
shown.inner.flatten().map(StoryOutput::from).unwrap_or_default()
}
#[story(TextMarks<'static>, covers = [Default])]
fn column_selected(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let (from, to) = (Point::new(15.0, 2.0), Point::new(65.0, 40.0));
+39 -15
View File
@@ -171,14 +171,12 @@ impl PlacedPage {
/// Page point `p` to document coordinates of `view`.
pub fn to_doc(&self, view: &CanvasView, p: Point) -> Point {
let _ = (view, p);
todo!("cv.K19")
view.to_doc(self.to_screen(p))
}
/// Document point `d` of `view` to page coordinates.
pub fn from_doc(&self, view: &CanvasView, d: Point) -> Point {
let _ = (view, d);
todo!("cv.K19")
self.to_page(view.to_screen(d))
}
}
@@ -201,8 +199,22 @@ pub struct PageBody<'b> {
impl PageBody<'_> {
/// The page under document point `d` and the point in its coordinates; the nearest page when `d` is outside all.
pub fn page_at_doc(&self, d: Point) -> Option<(&PlacedPage, Point)> {
let _ = d;
todo!("cv.K19")
let screen = self.view.to_screen(d);
// The squared distance from the point to a page's rectangle; zero inside it. A strictly smaller distance wins,
// so a tie goes to the earlier page.
let distance = |placed: &PlacedPage| {
let dx = (placed.rect.min.x - screen.x).max(0.0).max(screen.x - placed.rect.max.x);
let dy = (placed.rect.min.y - screen.y).max(0.0).max(screen.y - placed.rect.max.y);
f64::from(dx) * f64::from(dx) + f64::from(dy) * f64::from(dy)
};
let mut nearest: Option<(&PlacedPage, f64)> = None;
for placed in self.pages {
let away = distance(placed);
if nearest.is_none_or(|(_, best)| away < best) {
nearest = Some((placed, away));
}
}
nearest.map(|(placed, _)| (placed, placed.from_doc(&self.view, d)))
}
}
@@ -272,13 +284,9 @@ pub struct PageView<'a> {
bodies: Option<&'a [(f64, f64)]>,
describer: Option<&'a dyn AccessDescriber>,
paper: DataColor,
#[allow(dead_code)] // P3(canvas-w5): cv.K14
editor: Option<EditorPurpose>,
#[allow(dead_code)] // P3(canvas-w5): cv.K18
snap: Option<Snap>,
#[allow(dead_code)] // P3(canvas-w5): cv.K18
tool_regions: Vec<ToolRegion>,
#[allow(dead_code)] // P3(canvas-w5): cv.K20
rulers: bool,
}
@@ -372,7 +380,8 @@ impl<'a> PageView<'a> {
}
fn run(self, ui: &mut Ui, rect: Rect, take_room: bool, mut body: impl FnMut(&mut Ui, &PageBody<'_>)) -> PageViewOutput {
let PageView { label, source, state, options, navigation, bodies, describer, paper, .. } = self;
let PageView { label, source, state, options, navigation, bodies, describer, paper, editor, snap, tool_regions, rulers } = self;
let spacing = PageMetrics::new().show_at(ui, Rect::from_min_size(rect.min, Vec2::ZERO)).spacing;
let count = source.page_count();
let sizes: Vec<Size> = (0..count).map(|page| source.page_size(page)).collect();
@@ -384,7 +393,13 @@ impl<'a> PageView<'a> {
let given = frame.view(rect, start.offset, geo.scale / SCREEN_POINTS_PER_POINT);
let mut navigation = navigation;
navigation.overscroll = !start.continuous;
let mut canvas = Canvas::new(label.clone()).view(given).navigation(navigation).keys_to_body(true);
let mut canvas = Canvas::new(label.clone()).view(given).navigation(navigation).keys_to_body(true).tool_regions(tool_regions).show_rulers(rulers);
if let Some(purpose) = editor {
canvas = canvas.editor(purpose);
}
if let Some(snap) = snap {
canvas = canvas.snap(snap);
}
if start.continuous {
canvas = canvas.document(frame.document(&geo));
}
@@ -674,12 +689,21 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState>
// The scroll bars come before the clamp, so a drag of this pass lands in this pass.
let document = drawn_frame.document(&drawn);
let bars =
CanvasScrollbars::new(words.scroll_bars.clone(), Bind::given(shown), DocRect::from_origin_size(Point::ZERO, document)).show_at(ui, cx.rect);
let (xs, ys) = (offset_range(geo.doc.x0, geo.doc.x1, vw), offset_range(geo.doc.y0, geo.doc.y1, vh));
let bars = CanvasScrollbars::new(words.scroll_bars.clone(), Bind::given(shown), DocRect::from_origin_size(Point::ZERO, document));
// The tip names the page at the top of the view the thumb moved to: the bars ask for it once they know the move.
let format = env.format();
let tip = |moved: &CanvasView| {
let top = drawn_frame.offset_of(moved.center, vw, vh).1.clamp(ys.0, ys.1);
let page = if state.continuous { page_on_line(&geo.layout, top) } else { state.current };
let (label, total) = (source.page_label(page), format.integer(count as u64));
Label::from(words.page_of.fill(&[("page", label.as_str()), ("count", total.as_str())]))
};
let bars = if count > 0 { bars.tip(&tip) } else { bars };
let bars = bars.show_at(ui, cx.rect);
if let Some(moved) = bars.view.value() {
want = drawn_frame.offset_of(moved.center, vw, vh);
}
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) {
+10 -5
View File
@@ -14,30 +14,35 @@ use egui::{Pos2, Ui, Vec2};
/// Pages in the story document: enough to scroll.
const PAGES: usize = 6;
fn view(ui: &mut Ui, data: &mut StoryData, change: impl FnOnce(&mut PageViewState)) -> StoryOutput {
fn view(ui: &mut Ui, data: &mut StoryData, rulers: bool, change: impl FnOnce(&mut PageViewState)) -> StoryOutput {
let state = data.value("view", {
let mut state = PageViewState::default();
change(&mut state);
state
});
let pages = DemoPages::new(PAGES);
let out = PageView::new("Pages", &pages, state, PAPER).options(LayoutOptions::ACROBAT).show(ui, |_, _| ());
let out = PageView::new("Pages", &pages, state, PAPER).options(LayoutOptions::ACROBAT).rulers(rulers).show(ui, |_, _| ());
out.canvas.response.into()
}
#[story(PageView<'static>, covers = [], drive = Drive::Never)]
fn continuous(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
view(ui, data, |_| ())
view(ui, data, false, |_| ())
}
#[story(PageView<'static>, covers = [], drive = Drive::Never)]
fn with_rulers(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
view(ui, data, true, |_| ())
}
#[story(PageView<'static>, covers = [], drive = Drive::Never)]
fn spreads(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
view(ui, data, |state| state.display = PageDisplay::TwoUp)
view(ui, data, false, |state| state.display = PageDisplay::TwoUp)
}
#[story(PageView<'static>, covers = [], drive = Drive::Never)]
fn one_page_row(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
view(ui, data, |state| state.continuous = false)
view(ui, data, false, |state| state.continuous = false)
}
#[story(PageMetrics, covers = [Default], drive = Drive::Never)]
+242 -2
View File
@@ -4,12 +4,14 @@
use craft_behavior::kurbo;
use craft_pages::layout::{Fit, LayoutOptions};
use craft_pages::ui::fixtures::{DemoPages, PAPER};
use craft_pages::ui::{PagePreview, PageView, PageViewState, ReadingState, ReadingView};
use craft_pages::ui::{PagePreview, PageSource, PageView, PageViewState, PageViewWords, ReadingNav, ReadingState, ReadingView};
use craft_ui::contract::{Role, Show as _};
use craft_ui::primitives::EditorPurpose;
use craft_ui::runtime::env::Env;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, pos2, vec2};
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
/// The default state with `change` applied.
@@ -262,3 +264,241 @@ fn the_reading_view_turns_on_the_wheel_but_leaves_cmd_or_ctrl_with_the_wheel_to_
wheel_with(&mut fixture, -1.0, Modifiers::NONE);
assert!(state.borrow().column > 0, "the wheel alone turns");
}
/// The page whose tip text (one of `expected`, the words filled for pages 1, 2, ..) is painted in the latest frame.
fn page_tip(fixture: &Fixture, expected: &[String]) -> Option<usize> {
fixture.texts().iter().find_map(|run| expected.iter().position(|text| text.as_str() == &*run.text).map(|at| at + 1))
}
/// The tip named while the vertical thumb is dragged `fraction` of the bar's height from its top, and after the release.
fn tips_around_a_thumb_drag(hide_white_space: bool, fraction: f32) -> (Option<usize>, Option<usize>) {
let pages = DemoPages::new(8);
let bodies = vec![(72.0, 720.0); 8];
let mut state = state_with(|s| s.hide_white_space = hide_white_space);
let expected: Rc<RefCell<Vec<String>>> = Rc::default();
let shared = Rc::clone(&expected);
let mut fixture = Fixture::new(move |ui| {
let env = Env::of(ui);
let words = env.words::<PageViewWords>();
let total = env.format().integer(8);
*shared.borrow_mut() = (1..=8).map(|page| words.page_of.fill(&[("page", page.to_string().as_str()), ("count", total.as_str())])).collect();
let mut view = PageView::new("Pages", &pages, &mut state, PAPER).options(LayoutOptions::ACROBAT);
if hide_white_space {
view = view.bodies(&bodies);
}
view.show(ui, |_, _| ());
});
fixture.room(vec2(900.0, 600.0));
fixture.settle();
let bar = fixture
.by_role(Role::SCROLL_BAR)
.into_iter()
.find(|bar| bar.rect.height() > bar.rect.width())
.expect("the view has a vertical scroll bar");
assert_eq!(page_tip(&fixture, &expected.borrow()), None, "no tip while no thumb drags");
let from = pos2(bar.rect.center().x, bar.rect.min.y + 3.0);
let mut during = None;
fixture.drag_at_pausing(from, vec2(0.0, bar.rect.height() * fraction), |held| during = page_tip(held, &expected.borrow()));
let after = page_tip(&fixture, &expected.borrow());
(during, after)
}
#[trial]
fn a_thumb_drag_names_the_page_at_the_top_of_the_view() {
for hide_white_space in [false, true] {
let (early, early_after) = tips_around_a_thumb_drag(hide_white_space, 0.02);
let (late, late_after) = tips_around_a_thumb_drag(hide_white_space, 1.0);
let (early, late) = (early.expect("the tip shows while the thumb drags"), late.expect("the tip shows while the thumb drags"));
assert!(late > early, "dragging farther names a later page (hide white space {hide_white_space}): {early} then {late}");
assert!(late <= 8, "the tip names a page of the document: {late}");
assert_eq!((early_after, late_after), (None, None), "the tip is gone after the release (hide white space {hide_white_space})");
}
}
/// The height under the columns kept for the page-turn row, screen points.
const NAV_ROW: f32 = 60.0;
/// The rects of the columns' paper and of the row's Next button, for a reading view over `room` above a page-turn row.
fn columns_above_the_nav(room: egui::Vec2) -> (Vec<egui::Rect>, egui::Rect) {
let tall = DemoPages::new(1).page_size(0).height as f32 * ReadingView::screen_scale(1.0);
let pages = DemoPages::new(6);
let mut state = ReadingState::default();
let mut fixture = Fixture::new(move |ui| {
let all = ui.available_rect_before_wrap();
let (view, bar) = all.split_top_bottom_at_y(all.max.y - NAV_ROW);
ReadingView::new("Document", &pages, &mut state, PAPER).show_at(ui, view);
ui.scope_builder(egui::UiBuilder::new().max_rect(bar), |ui| {
ReadingNav::new(&mut state, 6).show(ui);
});
});
fixture.room(room);
fixture.settle();
let papers = fixture.shape_bounds().iter().copied().filter(|rect| (rect.height() - tall).abs() < 1.0).collect();
let next = fixture.by_label("Next Screen").expect("the row has Next").rect;
(papers, next)
}
#[trial]
fn reading_columns_fit_above_the_nav_bar_and_the_viewport_shows_whole_columns() {
let (narrow, narrow_next) = columns_above_the_nav(vec2(900.0, 1400.0));
let (wide, wide_next) = columns_above_the_nav(vec2(1800.0, 1400.0));
assert!(!narrow.is_empty(), "the columns are painted");
for (papers, next) in [(&narrow, narrow_next), (&wide, wide_next)] {
for paper in papers {
assert!(paper.max.y <= next.min.y, "a column ends above the nav row: {paper:?} and {next:?}");
}
}
assert!(wide.len() >= narrow.len(), "a wider room shows at least as many columns: {} then {}", narrow.len(), wide.len());
}
#[trial]
fn the_reading_view_reports_resizing_until_the_size_holds() {
let resized = Rc::new(Cell::new(false));
let seen = Rc::clone(&resized);
let mut state = ReadingState::default();
let pages = DemoPages::new(4);
let mut fixture = Fixture::new(move |ui| {
if ReadingView::new("Document", &pages, &mut state, PAPER).show(ui).resizing {
seen.set(true);
}
});
fixture.room(vec2(900.0, 600.0));
fixture.settle();
resized.set(false);
fixture.idle(2);
assert!(!resized.get(), "a size that holds is not resizing");
fixture.room(vec2(700.0, 500.0));
fixture.idle(1);
assert!(resized.get(), "a changed size is resizing");
resized.set(false);
fixture.idle(3);
assert!(!resized.get(), "resizing ends once the size holds");
}
#[trial]
fn to_doc_and_from_doc_round_trip_and_page_at_doc_takes_the_nearest_page_outside_all() {
#[derive(Default)]
struct Probe {
pages: Vec<usize>,
gap: f32,
round_trip: f64,
hit: Option<(usize, f64)>,
near_first: Option<usize>,
near_second: Option<usize>,
above: Option<usize>,
below: Option<usize>,
}
let probe = Rc::new(RefCell::new(Probe::default()));
let kept = Rc::clone(&probe);
let pages = DemoPages::new(3);
let mut state = state_with(|s| {
s.fit = Fit::None;
s.zoom = 0.2;
});
let mut fixture = Fixture::new(move |ui| {
PageView::new("Pages", &pages, &mut state, PAPER).options(LayoutOptions::ACROBAT).show(ui, |_, body| {
let [first, second, ..] = body.pages else { return };
let last = body.pages[body.pages.len() - 1];
let at = kurbo::Point::new(100.0, 150.0);
let doc = second.to_doc(&body.view, at);
let back = second.from_doc(&body.view, doc);
let gap = second.rect.min.y - first.rect.max.y;
let x = first.rect.center().x;
let page_at = |y: f32| body.page_at_doc(body.view.to_doc(pos2(x, y))).map(|(placed, _)| placed.page);
*kept.borrow_mut() = Probe {
pages: body.pages.iter().map(|placed| placed.page).collect(),
gap,
round_trip: (back.x - at.x).abs().max((back.y - at.y).abs()),
hit: body.page_at_doc(doc).map(|(placed, point)| (placed.page, (point.x - at.x).abs().max((point.y - at.y).abs()))),
near_first: page_at(first.rect.max.y + gap * 0.25),
near_second: page_at(second.rect.min.y - gap * 0.25),
above: page_at(first.rect.min.y - 400.0),
below: page_at(last.rect.max.y + 400.0),
};
});
});
fixture.room(vec2(900.0, 700.0));
fixture.settle();
let probe = probe.borrow();
assert!(probe.pages.len() >= 2, "two pages are in view: {:?}", probe.pages);
assert!(probe.gap > 0.0, "pages are apart: {}", probe.gap);
assert!(probe.round_trip < 1e-3, "to_doc then from_doc returns the page point: {}", probe.round_trip);
let (first, second, last) = (probe.pages[0], probe.pages[1], probe.pages[probe.pages.len() - 1]);
assert_eq!(probe.hit.map(|(page, _)| page), Some(second), "a point on a page finds that page");
assert!(probe.hit.is_some_and(|(_, error)| error < 1e-3), "the page point is the one mapped: {:?}", probe.hit);
assert_eq!(probe.near_first, Some(first), "between pages the nearer page: nearer the first");
assert_eq!(probe.near_second, Some(second), "between pages the nearer page: nearer the second");
assert_eq!(probe.above, Some(first), "above all pages: the first");
assert_eq!(probe.below, Some(last), "below all pages: the last in view");
}
#[trial]
fn a_reading_column_turn_eases_and_lands_exactly_on_the_column_start() {
let state = Rc::new(RefCell::new(ReadingState::default()));
let kept = Rc::clone(&state);
let tall = DemoPages::new(1).page_size(0).height as f32 * ReadingView::screen_scale(1.0);
let pages = DemoPages::new(6);
let mut fixture = Fixture::new(move |ui| {
ReadingView::new("Document", &pages, &mut kept.borrow_mut(), PAPER).show(ui);
});
// Tall enough that the pages' paper is not cut by the room, so each paper's bounds keep the page's height.
fixture.room(vec2(900.0, 1400.0));
fixture.settle();
// The leading edge of the leftmost painted page: with the column at the start, page 0 sits there; once on column 1, page 1 does.
let leading = |fixture: &Fixture| {
fixture.shape_bounds().iter().filter(|rect| (rect.height() - tall).abs() < 1.0).map(|rect| rect.min.x).reduce(f32::min)
};
let start = leading(&fixture).expect("page 0's paper is painted");
state.borrow_mut().turn(1, 6);
let mut seen = Vec::new();
for _ in 0..60 {
fixture.idle(1);
seen.extend(leading(&fixture));
}
assert!(seen.iter().filter(|x| **x < start - 0.5).count() >= 2, "the turn takes several passes, the columns part way between: {seen:?}");
let landed = seen.last().copied().expect("the paper is painted after the turn");
assert!((landed - start).abs() < 1e-3, "the new column lands exactly on the column start: {landed} against {start}");
}
#[trial]
fn a_view_with_an_editor_purpose_takes_no_plain_keys_for_moving() {
/// Page Down, the arrows and End in a focused view with or without an editor purpose: the state before and after.
fn keyed(editor: bool) -> (PageViewState, PageViewState) {
let state = Rc::new(RefCell::new(state_with(|s| s.fit = Fit::Page)));
let kept = Rc::clone(&state);
let pages = DemoPages::new(5);
let mut fixture = Fixture::new(move |ui| {
let mut now = kept.borrow().clone();
let mut view = PageView::new("Pages", &pages, &mut now, PAPER).options(LayoutOptions::ACROBAT);
if editor {
view = view.editor(EditorPurpose::Text);
}
view.show(ui, |_, _| ());
*kept.borrow_mut() = now;
});
fixture.room(vec2(900.0, 600.0));
fixture.settle();
if editor {
for _ in 0..4 {
if fixture.focused().is_some() {
break;
}
fixture.key(Key::Tab, Modifiers::NONE);
}
assert!(fixture.focused().is_some(), "Tab reaches the editor view");
} else {
focus_canvas(&mut fixture);
}
let before = state.borrow().clone();
for key in [Key::PageDown, Key::ArrowDown, Key::ArrowRight, Key::End] {
fixture.key(key, Modifiers::NONE);
fixture.idle(1);
}
let after = state.borrow().clone();
(before, after)
}
let (before, after) = keyed(false);
assert!(after.current != before.current || after.offset != before.offset, "the plain view moves on its keys");
let (before, after) = keyed(true);
assert_eq!((after.current, after.offset), (before.current, before.offset), "the editor view leaves moving to the app");
}