pdf-canvas-w5: net change of 3 commits

- pdf-canvas-w5: written from its sheet
- pdf-canvas-w5: repair 1
- pdf-canvas-w5: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor
2026-11-18 05:02:30 -05:00
parent b6304e0b25
commit 0c629580c6
4 changed files with 523 additions and 97 deletions
+171 -91
View File
@@ -50,7 +50,7 @@ pub trait PageTextSource {
}
}
/// What is selected on one page.
/// What a selection covers: a run from its page on to any other, or a column on its page.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum TextSpan {
@@ -77,13 +77,8 @@ pub enum TextSpan {
}
impl TextSpan {
/// A run from the glyph `anchor` to the glyph `head`.
pub fn run(anchor: usize, head: usize) -> Self {
TextSpan::Run { anchor, head, head_page: 0, end_x: None } // P3(pdf-canvas-w5): CV-C24
}
/// A run from the glyph `anchor` on the selection's page to the glyph `head` on page `head_page`.
pub fn run_to(anchor: usize, head_page: usize, head: usize) -> Self {
pub fn run(anchor: usize, head_page: usize, head: usize) -> Self {
TextSpan::Run { anchor, head, head_page, end_x: None }
}
@@ -93,68 +88,107 @@ impl TextSpan {
}
}
/// A text selection on one page.
/// A text selection: a run in reading order from its page on to any other, or a column on its page.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct TextSelection {
/// Page index, 0-based.
/// Page index, 0-based: where the selection started.
pub page: usize,
/// The selected glyphs on that page.
/// The selected glyphs.
pub span: TextSpan,
}
impl TextSelection {
/// The selection `span` on page `page`.
/// The selection `span`, started on page `page`.
pub fn new(page: usize, span: TextSpan) -> Self {
TextSelection { page, span }
}
/// The selection as rectangles, one per line piece (for highlighting and markup quads).
// pdfcraft: crates/ui-egui/src/canvas/selection.rs:29 `Selection::rects`.
pub fn rects(&self, text: &dyn PageTextSource) -> Vec<Rect> {
match self.span {
TextSpan::Run { anchor, head, .. } => text.line_rects(run_range(anchor, head)),
TextSpan::Column { from, to } => {
let glyphs = text.glyphs_in(Rect::from_points(from, to));
runs(&glyphs).into_iter().flat_map(|run| text.line_rects(run)).collect()
}
}
/// A run's ends as `(page, glyph)`, anchor then head; `None` for a column.
fn run_ends(&self) -> Option<((usize, usize), (usize, usize))> {
let TextSpan::Run { anchor, head, head_page, .. } = self.span else { return None };
Some(((self.page, anchor), (head_page, head)))
}
/// A run's ends in reading order, first then last: `(page, glyph)` pairs compare in reading order.
fn reading_order(&self) -> Option<((usize, usize), (usize, usize))> {
let (anchor, head) = self.run_ends()?;
Some(if anchor <= head { (anchor, head) } else { (head, anchor) })
}
/// The pages the selection covers, from its first to its last.
pub fn pages(&self) -> RangeInclusive<usize> {
todo!("CV-C24")
match self.reading_order() {
Some(((first, _), (last, _))) => first..=last,
None => self.page..=self.page,
}
}
/// The glyphs of the selection on `page`; `None` when it covers nothing there.
/// The glyphs of the selection on `page`: the rest of its first page, every page between whole, its last page up
/// to its last glyph, whichever way the drag went. `None` when it covers nothing there, and for a column, whose
/// glyphs are not one range ([`rects_on`](Self::rects_on) and [`text`](Self::text) read it).
pub fn glyphs_on(&self, page: usize, text: &dyn PageTextSource) -> Option<Range<usize>> {
let _ = (page, text);
todo!("CV-C24")
let ((first_page, first), (last_page, last)) = self.reading_order()?;
if !(first_page..=last_page).contains(&page) {
return None;
}
// The indices may be stale (the page's text was read again) or hostile: every one is clamped to the page.
let count = text.glyph_count();
let start = if page == first_page { first.min(count) } else { 0 };
let end = if page == last_page { last.saturating_add(1).min(count) } else { count };
Some(start..end).filter(|glyphs| !glyphs.is_empty())
}
/// The selection on `page` as rectangles, one per line piece.
/// The selection on `page` as rectangles, one per line piece (for highlighting and markup quads).
// pdfcraft: crates/ui-egui/src/canvas/selection.rs:29 `Selection::rects`.
pub fn rects_on(&self, page: usize, text: &dyn PageTextSource) -> Vec<Rect> {
let _ = (page, text);
todo!("CV-C24")
match self.span {
TextSpan::Column { from, to } if page == self.page => glyph_rects(text, &text.glyphs_in(Rect::from_points(from, to))),
TextSpan::Column { .. } => Vec::new(),
TextSpan::Run { .. } => match self.rows_on(page, text) {
Some(rows) => glyph_rects(text, &rows),
None => self.glyphs_on(page, text).map(|glyphs| text.line_rects(glyphs)).unwrap_or_default(),
},
}
}
/// The selected text, as Copy puts it on the clipboard; `None` while a covered page is unread.
/// The glyphs a one-page run released past its row's last glyph selects by rows, when the page says so.
fn rows_on(&self, page: usize, text: &dyn PageTextSource) -> Option<Vec<usize>> {
let TextSpan::Run { anchor, head, end_x: Some(end_x), .. } = self.span else { return None };
let ((first, _), (last, _)) = self.reading_order()?;
(first == page && last == page).then(|| text.rows_between(anchor, head, end_x)).flatten()
}
/// The selected text on `page`, one of the pages the selection covers.
fn text_on(&self, page: usize, text: &dyn PageTextSource) -> String {
match self.span {
TextSpan::Column { from, to } => text.column_text(&text.glyphs_in(Rect::from_points(from, to))),
TextSpan::Run { .. } => match self.rows_on(page, text) {
Some(rows) => text.column_text(&rows),
None => self.glyphs_on(page, text).map(|glyphs| text.text_of(glyphs)).unwrap_or_default(),
},
}
}
/// The selected text, as Copy puts it on the clipboard: the covered pages' parts joined with newlines. `None`
/// while a covered page is unread ([`unread_pages`](Self::unread_pages) says which).
// pdfcraft: crates/ui-egui/src/canvas/selection.rs:37 `Selection::text`.
pub fn text(&self, texts: &dyn PageTexts) -> Option<String> {
let text = texts.page(self.page)?; // P3(pdf-canvas-w5): CV-C24, the first page only
Some(match self.span {
TextSpan::Run { anchor, head, .. } => text.text_of(run_range(anchor, head)),
TextSpan::Column { from, to } => text.column_text(&text.glyphs_in(Rect::from_points(from, to))),
})
let parts = self.pages().map(|page| texts.page(page).map(|text| self.text_on(page, text))).collect::<Option<Vec<_>>>()?;
Some(parts.into_iter().filter(|part| !part.is_empty()).collect::<Vec<_>>().join("\n"))
}
/// The covered pages whose text is not read yet.
pub fn unread_pages(&self, texts: &dyn PageTexts) -> Vec<usize> {
let _ = texts;
todo!("CV-C24")
self.pages().filter(|&page| texts.page(page).is_none()).collect()
}
}
/// One rectangle per line piece of `glyphs`, taken as runs of consecutive indices.
fn glyph_rects(text: &dyn PageTextSource, glyphs: &[usize]) -> Vec<Rect> {
runs(glyphs).into_iter().flat_map(|run| text.line_rects(run)).collect()
}
/// The glyphs of a run, both ends included.
fn run_range(anchor: usize, head: usize) -> Range<usize> {
anchor.min(head)..anchor.max(head).saturating_add(1)
@@ -165,8 +199,8 @@ fn runs(glyphs: &[usize]) -> Vec<Range<usize>> {
let mut runs: Vec<Range<usize>> = Vec::new();
for &glyph in glyphs {
match runs.last_mut() {
Some(run) if run.end == glyph => run.end += 1,
_ => runs.push(glyph..glyph + 1),
Some(run) if run.end == glyph => run.end = run.end.saturating_add(1),
_ => runs.push(glyph..glyph.saturating_add(1)),
}
}
runs
@@ -216,7 +250,8 @@ pub trait PageTexts {
pub struct TextSelectState {
/// The selection, if any.
pub selection: Option<TextSelection>,
/// The drag in progress: the page and where it started (glyph, or page point for a column).
/// The drag in progress: the selection's page and where it started (a run from the anchor to the pressed glyph,
/// or the column's first corner).
gesture: Option<(usize, TextSpan)>,
/// The press's click count, and the selection from before the gesture (Esc brings it back).
clicks: u32,
@@ -269,8 +304,8 @@ fn paint_marks(
draw.fill(&PaintShape::Rect(screen(rect).expand(grow), look.radius), fill);
}
}
if let Some(selection) = selection.filter(|selection| selection.page == placed.page) {
for rect in selection.rects(text) {
if let Some(selection) = selection {
for rect in selection.rects_on(placed.page, text) {
draw.fill(&PaintShape::Rect(screen(rect), look.radius), look.selection);
}
}
@@ -280,14 +315,16 @@ fn paint_marks(
/// Acrobat's Select tool on the page view, a craft-ui [`CanvasTool`] the app runs in its `ToolHost` over the page
/// view's canvas; built per pass over the pass's placed pages and the app's [`TextSelectState`].
///
/// - Press and drag with the primary button selects ([`TextSpan::Run`], anchored at the press's glyph); with Alt held
/// (or [`column`](Self::column) on: the Column Select tool) it selects a column, its rectangle outlined while
/// dragging. The press's click count is [`ToolPointer::clicks`]: 2 the word, 3 the line, 4 the page
/// ([`click_unit`]). The cursor is the I-beam over glyphs, the arrow elsewhere. A press off any glyph clears the
/// - Press and drag with the primary button selects ([`TextSpan::Run`], anchored at the press's glyph, its head on
/// whichever page the pointer is over); with Alt held (or [`column`](Self::column) on: the Column Select tool) it
/// selects a column on the pressed page, its rectangle outlined while dragging. The press's click count is
/// [`ToolPointer::clicks`]: 2 the word, 3 the line, 4 the page ([`click_unit`]); dragging after 2 or 3 extends by
/// whole units onto other pages too, the page unit stays on its page. Shift-click extends the run from its anchor
/// onto any page. The cursor is the I-beam over glyphs, the arrow elsewhere. A press off any glyph clears the
/// selection.
/// - Keys while the canvas has the keyboard: Shift with the arrows extends a run by a glyph (Shift and Alt by a word;
/// left and right swap in a right-to-left interface), Escape clears. Select
/// All and Copy are the app's commands (they read [`TextSelection::text`]).
/// - Keys while the canvas has the keyboard: Shift with the arrows moves a run's head on its page by a glyph (Shift
/// and Alt by a word; left and right swap in a right-to-left interface), Escape clears. Select All and Copy are the
/// app's commands (they read [`TextSelection::text`]).
/// - Its command form is the app's Select All command: the tool selects, so it is not freehand.
/// - The selection is reported to assistive technology through the page view's accessibility bridge.
pub struct TextSelectTool<'a> {
@@ -336,6 +373,47 @@ impl<'a> TextSelectTool<'a> {
self.state.clicks = 0;
self.state.before = None;
}
/// The run a 2-, 3- or 4-click drag selects from the unit pressed (around glyph `origin` on `page`) to glyph `hit`
/// on `head_page`: whole units both ways in `(page, glyph)` order; the four-click page unit stays on its page.
/// `None` for a single-click drag, or when the pressed glyph has no unit.
fn unit_run(&self, page: usize, origin: usize, head_page: usize, hit: usize) -> Option<TextSpan> {
let clicks = self.state.clicks;
if clicks < 2 {
return None;
}
let unit = click_unit(self.texts.page(page)?, clicks, origin).filter(|unit| !unit.is_empty())?;
if clicks >= 4 {
return Some(TextSpan::run(unit.start, page, unit.end - 1));
}
let reached = self
.texts
.page(head_page)
.and_then(|text| click_unit(text, clicks, hit))
.filter(|unit| !unit.is_empty())
.unwrap_or(hit..hit.saturating_add(1));
Some(if (head_page, reached.start) < (page, unit.start) {
TextSpan::run(unit.end - 1, head_page, reached.start)
} else if head_page == page {
TextSpan::run(unit.start, page, (reached.end - 1).max(unit.end - 1))
} else {
TextSpan::run(unit.start, head_page, reached.end - 1)
})
}
/// Where a single-click drag that stayed on its page was released, in page points, when no glyph's box holds the
/// release point: the end [`PageTextSource::rows_between`] reads. `None` for a click (the head never left the
/// pressed glyph), a unit drag, a column and a run across pages.
fn released_past_row(&self, pointer: &ToolPointer) -> Option<f64> {
let (page, TextSpan::Run { head: pressed, head_page: pressed_page, .. }) = self.state.gesture? else { return None };
let ((selected, _), head) = self.state.selection?.run_ends()?;
if self.state.clicks != 1 || selected != page || head.0 != page || head == (pressed_page, pressed) {
return None;
}
let placed = self.page_at(pointer.pos).filter(|placed| placed.page == page)?;
let at = placed.to_page(pointer.pos);
self.texts.page(page)?.glyph_box_at(at).is_none().then_some(at.x)
}
}
// pdfcraft: crates/ui-egui/src/canvas.rs:1470 `text_layer`, :1547 `text_pointer_input`.
@@ -362,13 +440,13 @@ impl CanvasTool for TextSelectTool<'_> {
self.set(None);
return ToolAction::Done;
};
let at = placed.to_page(pointer.pos);
let (page, at) = (placed.page, placed.to_page(pointer.pos));
let before = self.state.selection;
if self.column || pointer.mods.alt {
self.state.gesture = Some((placed.page, TextSpan::Column { from: at, to: at }));
self.state.gesture = Some((page, TextSpan::column(at, at)));
self.state.clicks = 1;
self.state.before = before;
self.set(Some(TextSelection { page: placed.page, span: TextSpan::Column { from: at, to: at } }));
self.set(Some(TextSelection::new(page, TextSpan::column(at, at))));
return ToolAction::Claimed;
}
let Some(glyph) = text.glyph_at(at) else {
@@ -376,24 +454,30 @@ impl CanvasTool for TextSelectTool<'_> {
return ToolAction::Done;
};
let clicks = pointer.clicks.max(1);
let extended = before.filter(|selection| pointer.mods.shift && clicks < 2 && selection.page == placed.page);
let (span, start) = match (clicks, extended) {
let extended = before.filter(|_| pointer.mods.shift && clicks < 2).and_then(|selection| selection.run_ends());
let (selection, start) = match (clicks, extended) {
(2.., _) => match click_unit(text, clicks, glyph).filter(|unit| !unit.is_empty()) {
Some(unit) => (TextSpan::run_to(unit.start, placed.page, unit.end - 1), TextSpan::run_to(glyph, placed.page, glyph)),
Some(unit) => {
(TextSelection::new(page, TextSpan::run(unit.start, page, unit.end - 1)), TextSelection::new(page, TextSpan::run(glyph, page, glyph)))
}
None => {
self.set(None);
return ToolAction::Done;
}
},
(_, Some(TextSelection { span: TextSpan::Run { anchor, .. }, .. })) => {
(TextSpan::run_to(anchor, placed.page, glyph), TextSpan::run_to(anchor, placed.page, anchor))
(_, Some(((from, anchor), _))) => {
let run = TextSelection::new(from, TextSpan::run(anchor, page, glyph));
(run, run)
}
_ => {
let run = TextSelection::new(page, TextSpan::run(glyph, page, glyph));
(run, run)
}
_ => (TextSpan::run_to(glyph, placed.page, glyph), TextSpan::run_to(glyph, placed.page, glyph)),
};
self.state.gesture = Some((placed.page, start));
self.state.gesture = Some((start.page, start.span));
self.state.clicks = clicks;
self.state.before = before;
self.set(Some(TextSelection { page: placed.page, span }));
self.set(Some(selection));
ToolAction::Claimed
}
@@ -401,37 +485,35 @@ impl CanvasTool for TextSelectTool<'_> {
let (pages, texts) = (self.pages, self.texts);
let Some((page, start)) = self.state.gesture else { return };
let Some(selection) = self.state.selection.filter(|selection| selection.page == page) else { return };
let (Some(placed), Some(text)) = (pages.iter().find(|placed| placed.page == page), texts.page(page)) else { return };
let at = placed.to_page(pointer.pos);
let span = match (selection.span, start) {
(TextSpan::Column { from, .. }, _) => TextSpan::Column { from, to: at },
(TextSpan::Run { anchor, .. }, TextSpan::Run { anchor: origin, .. }) => {
let Some(hit) = text.glyph_at(at) else { return };
let clicks = self.state.clicks;
match click_unit(text, clicks, origin).filter(|unit| !unit.is_empty()) {
Some(unit) if clicks >= 2 => {
let reached = click_unit(text, clicks, hit).filter(|unit| !unit.is_empty()).unwrap_or(hit..hit + 1);
if reached.start < unit.start {
TextSpan::run_to(unit.end - 1, page, reached.start)
} else {
TextSpan::run_to(unit.start, page, (reached.end - 1).max(unit.end - 1))
}
}
_ => TextSpan::run_to(anchor, page, hit),
}
(TextSpan::Column { from, .. }, _) => {
let Some(placed) = pages.iter().find(|placed| placed.page == page) else { return };
TextSpan::column(from, placed.to_page(pointer.pos))
}
(span, _) => span,
(TextSpan::Run { anchor, .. }, TextSpan::Run { anchor: origin, .. }) => {
// The head follows the pointer onto whichever page it is over; off every page, or over a page whose
// text is not read yet, the selection keeps its last value.
let Some(placed) = self.page_at(pointer.pos) else { return };
let Some(hit) = texts.page(placed.page).and_then(|text| text.glyph_at(placed.to_page(pointer.pos))) else { return };
self.unit_run(page, origin, placed.page, hit).unwrap_or(TextSpan::run(anchor, placed.page, hit))
}
_ => return,
};
self.set(Some(TextSelection { page, span }));
self.set(Some(TextSelection::new(page, span)));
}
fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
self.drag(pointer, cx);
if let Some(selection) = self.state.selection
&& matches!(selection.span, TextSpan::Column { .. })
&& selection.text(self.texts).is_none_or(|text| text.is_empty())
{
self.set(None);
let end_x = self.released_past_row(pointer);
let selection = self.state.selection;
match selection {
Some(selection @ TextSelection { span: TextSpan::Column { .. }, .. }) if selection.text(self.texts).is_none_or(|text| text.is_empty()) => {
self.set(None);
}
Some(TextSelection { page, span: TextSpan::Run { anchor, head, head_page, .. } }) if end_x.is_some() => {
self.set(Some(TextSelection::new(page, TextSpan::Run { anchor, head, head_page, end_x })));
}
_ => {}
}
self.end_gesture();
}
@@ -452,8 +534,9 @@ impl CanvasTool for TextSelectTool<'_> {
true
}
ToolKey::Nudge { direction, mods, .. } if mods.shift => {
let TextSpan::Run { anchor, head, .. } = selection.span else { return false };
let Some(text) = self.texts.page(selection.page) else { return false };
// The head moves on its own page and stops at that page's first and last glyph.
let Some(((_, anchor), (head_page, head))) = selection.run_ends() else { return false };
let Some(text) = self.texts.page(head_page) else { return false };
let count = text.glyph_count();
let vertical = direction.y != 0.0;
let forward = if vertical { direction.y > 0.0 } else { (direction.x > 0.0) != cx.direction().is_rtl() };
@@ -462,14 +545,11 @@ impl CanvasTool for TextSelectTool<'_> {
} else if mods.alt {
word_step(text, head, forward, count)
} else if forward {
head + 1
head.saturating_add(1)
} else {
head.saturating_sub(1)
};
self.set(Some(TextSelection {
page: selection.page,
span: TextSpan::run_to(anchor, selection.page, moved.min(count.saturating_sub(1))),
}));
self.set(Some(TextSelection::new(selection.page, TextSpan::run(anchor, head_page, moved.min(count.saturating_sub(1))))));
true
}
_ => false,
@@ -501,7 +581,7 @@ impl CanvasTool for TextSelectTool<'_> {
/// The head one word on from `head`, or back.
fn word_step(text: &dyn PageTextSource, head: usize, forward: bool, count: usize) -> usize {
if forward {
(head + 1..count).find_map(|glyph| text.word_at(glyph).map(|word| word.end - 1).filter(|end| *end > head)).unwrap_or(head)
(head.saturating_add(1)..count).find_map(|glyph| text.word_at(glyph).map(|word| word.end - 1).filter(|end| *end > head)).unwrap_or(head)
} else {
(0..head).rev().find_map(|glyph| text.word_at(glyph).map(|word| word.start).filter(|start| *start < head)).unwrap_or(head)
}
+20 -6
View File
@@ -99,9 +99,17 @@ impl PageTexts for Lines {
}
}
/// Shows `marks` and `selection` over one page placed at the canvas's top left.
fn on_page(ui: &mut Ui, marks: &[TextMark], selection: Option<TextSelection>) -> StoryOutput {
let pages = demo_placed(1, Pos2::new(24.0, 24.0));
/// How far below the first page's place the last page starts when a story shows several, so the crossing onto it
/// shows.
const LAST_PAGE_TOP: f32 = 96.0;
/// Shows `marks` and `selection` over `count` pages from the canvas's top left; with more than one, the pages rise
/// until the last starts [`LAST_PAGE_TOP`] lower, so the end of the page before it and its start both show.
fn on_page(ui: &mut Ui, count: usize, marks: &[TextMark], selection: Option<TextSelection>) -> StoryOutput {
let origin = Pos2::new(24.0, 24.0);
let last_top = demo_placed(count, origin).last().map_or(origin.y, |last| last.rect.min.y);
let rise = (last_top - origin.y - LAST_PAGE_TOP).max(0.0);
let pages = demo_placed(count, Pos2::new(origin.x, origin.y - rise));
let lines = Lines;
let mut control = Some(TextMarks::new(&pages, &lines, marks));
let stage = craft_ui::testing::stage(ui);
@@ -117,16 +125,22 @@ fn on_page(ui: &mut Ui, marks: &[TextMark], selection: Option<TextSelection>) ->
#[story(TextMarks<'static>, covers = [Default])]
fn find_marks(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let marks = [TextMark::new(0, 4..9, false), TextMark::new(0, 38..42, true), TextMark::new(0, 60..63, false)];
on_page(ui, &marks, None)
on_page(ui, 1, &marks, None)
}
#[story(TextMarks<'static>, covers = [Default])]
fn run_selected(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
on_page(ui, &[], Some(TextSelection::new(0, TextSpan::run(4, 26))))
on_page(ui, 1, &[], Some(TextSelection::new(0, TextSpan::run(4, 0, 26))))
}
/// A run from the last line of the first page onto the first line of the second.
#[story(TextMarks<'static>, covers = [Default])]
fn across_two_pages(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
on_page(ui, 2, &[], Some(TextSelection::new(0, TextSpan::run(40, 1, 12))))
}
#[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));
on_page(ui, &[], Some(TextSelection::new(0, TextSpan::column(from, to))))
on_page(ui, 1, &[], Some(TextSelection::new(0, TextSpan::column(from, to))))
}
+2
View File
@@ -3,6 +3,8 @@
mod range;
mod setup;
mod size_picker;
mod text_select;
mod text_tables;
mod thumbnails;
mod views;
+330
View File
@@ -0,0 +1,330 @@
//! The Select tool on a canvas of placed pages: runs dragged across pages, click units and their drags, and Shift-click,
//! through the canvas's tool host and the fixture's pointer.
use std::cell::RefCell;
use std::ops::Range;
use std::rc::Rc;
use craft_behavior::kurbo::{Point, Rect};
use craft_pages::ui::fixtures::demo_placed;
use craft_pages::ui::{PageTextSource, PageTexts, PlacedPage, TextSelectState, TextSelectTool, TextSelection, TextSpan};
use craft_ui::canvas::{Canvas, ToolHost, tool_pass};
use craft_ui::contract::ShowContainer as _;
use craft_ui::testing::{Fixture, pointer, trial};
use egui::{Modifiers, Pos2, vec2};
const GLYPH_WIDTH: f64 = 10.0;
const LINE_HEIGHT: f64 = 14.0;
const PAGES: usize = 3;
/// Lines of fixed-width glyphs at the top of a page.
struct Grid {
lines: &'static [&'static str],
}
impl Grid {
fn ranges(&self) -> Vec<Range<usize>> {
let mut start = 0;
self.lines
.iter()
.map(|line| {
let range = start..start + line.chars().count();
start = range.end;
range
})
.collect()
}
fn chars(&self) -> Vec<char> {
self.lines.concat().chars().collect()
}
fn line_of(&self, glyph: usize) -> Option<(usize, Range<usize>)> {
self.ranges().into_iter().enumerate().find(|(_, range)| range.contains(&glyph))
}
fn box_of(&self, glyph: usize) -> Option<Rect> {
let (line, range) = self.line_of(glyph)?;
let column = (glyph - range.start) as f64;
Some(Rect::new(column * GLYPH_WIDTH, line as f64 * LINE_HEIGHT, (column + 1.0) * GLYPH_WIDTH, (line + 1) as f64 * LINE_HEIGHT))
}
/// The parts of `glyphs` on each line, one string per line that has any.
fn rows(&self, glyphs: impl Fn(usize) -> bool) -> String {
let chars = self.chars();
let rows: Vec<String> =
self.ranges().into_iter().map(|range| range.filter(|&glyph| glyphs(glyph)).map(|glyph| chars[glyph]).collect()).collect();
rows.into_iter().filter(|row: &String| !row.is_empty()).collect::<Vec<_>>().join("\n")
}
}
impl PageTextSource for Grid {
fn glyph_count(&self) -> usize {
self.ranges().last().map_or(0, |range| range.end)
}
fn glyph_at(&self, p: Point) -> Option<usize> {
if p.y < 0.0 {
return None;
}
let range = self.ranges().into_iter().nth((p.y / LINE_HEIGHT) as usize)?;
let column = ((p.x / GLYPH_WIDTH).max(0.0) as usize).min(range.len().checked_sub(1)?);
Some(range.start + column)
}
fn glyph_box_at(&self, p: Point) -> Option<usize> {
(0..self.glyph_count()).find(|&glyph| self.box_of(glyph).is_some_and(|rect| rect.contains(p)))
}
fn line_rects(&self, glyphs: Range<usize>) -> Vec<Rect> {
self.ranges()
.into_iter()
.filter_map(|range| {
let (start, end) = (glyphs.start.max(range.start), glyphs.end.min(range.end));
if start >= end {
return None;
}
Some(self.box_of(start)?.union(self.box_of(end - 1)?))
})
.collect()
}
fn glyphs_in(&self, rect: Rect) -> Vec<usize> {
(0..self.glyph_count()).filter(|&glyph| self.box_of(glyph).is_some_and(|glyph| rect.contains(glyph.center()))).collect()
}
fn word_at(&self, glyph: usize) -> Option<Range<usize>> {
let chars = self.chars();
let (_, line) = self.line_of(glyph)?;
let word = |at: usize| chars[at] != ' ';
if !word(glyph) {
return None;
}
let start = (line.start..glyph).rev().take_while(|&at| word(at)).last().unwrap_or(glyph);
let end = (glyph..line.end).take_while(|&at| word(at)).last().unwrap_or(glyph) + 1;
Some(start..end)
}
fn line_at(&self, glyph: usize) -> Option<Range<usize>> {
self.line_of(glyph).map(|(_, range)| range)
}
fn text_of(&self, glyphs: Range<usize>) -> String {
self.rows(|glyph| glyphs.contains(&glyph))
}
fn column_text(&self, glyphs: &[usize]) -> String {
self.rows(|glyph| glyphs.contains(&glyph))
}
}
/// The document's pages, `None` where the text is not read yet.
struct Doc(Vec<Option<Grid>>);
impl PageTexts for Doc {
fn page(&self, page: usize) -> Option<&dyn PageTextSource> {
self.0.get(page)?.as_ref().map(|grid| grid as &dyn PageTextSource)
}
}
/// Three pages of text; the middle one unread unless `middle_read`.
fn doc(middle_read: bool) -> Rc<Doc> {
Rc::new(Doc(vec![
Some(Grid { lines: &["one two three", "four five six"] }),
middle_read.then_some(Grid { lines: &["seven eight", "nine ten"] }),
Some(Grid { lines: &["eleven twelve", "thirteen"] }),
]))
}
/// The selection's glyphs on each page.
fn glyphs(selection: &TextSelection, doc: &Doc) -> Vec<Option<Range<usize>>> {
(0..PAGES).map(|page| doc.page(page).and_then(|text| selection.glyphs_on(page, text))).collect()
}
struct Shown {
state: TextSelectState,
placed: Vec<PlacedPage>,
}
/// A canvas showing three placed pages, the Select tool run on its tool pass as an app runs it.
struct Rig {
fixture: Fixture,
shown: Rc<RefCell<Shown>>,
}
impl Rig {
fn new(doc: Rc<Doc>) -> Self {
let shown = Rc::new(RefCell::new(Shown { state: TextSelectState::default(), placed: Vec::new() }));
let seen = Rc::clone(&shown);
let mut fixture = Fixture::new(move |ui| {
let mut guard = seen.borrow_mut();
let Shown { state, placed } = &mut *guard;
let texts: &dyn PageTexts = &*doc;
let _ = Canvas::new("Pages").show(ui, |ui, body| {
*placed = demo_placed(PAGES, body.rect.min + vec2(20.0, 20.0));
if let Some(pass) = tool_pass(&body.env) {
let _ = ToolHost::new().run(ui, &pass, &mut TextSelectTool::new(placed.as_slice(), texts, &mut *state));
}
});
});
fixture.room(vec2(700.0, 1760.0));
fixture.settle();
Rig { fixture, shown }
}
/// The screen point in the middle of glyph `column` of line `line` on page `page`.
fn at(&self, page: usize, line: usize, column: usize) -> Pos2 {
let shown = self.shown.borrow();
let placed = shown.placed.get(page).expect("the page is placed");
placed.to_screen(Point::new((column as f64 + 0.5) * GLYPH_WIDTH, (line as f64 + 0.5) * LINE_HEIGHT))
}
fn selection(&self) -> TextSelection {
self.shown.borrow().state.selection.expect("a selection")
}
/// Presses `clicks` times at `at` (one click run: the same point, a frame apart), holds the last press, drags to
/// `to` in four steps and releases.
fn click_drag(&mut self, at: Pos2, clicks: usize, to: Pos2) {
self.fixture.frame(vec![pointer::moved(at)]);
for _ in 1..clicks {
self.fixture.frame(vec![pointer::press(at)]);
self.fixture.frame(vec![pointer::release(at)]);
}
self.fixture.frame(vec![pointer::press(at)]);
for step in 1..=4 {
self.fixture.frame(vec![pointer::moved(at + (to - at) * (step as f32 / 4.0))]);
}
self.fixture.frame(vec![pointer::release(to)]);
self.fixture.frame(Vec::new());
}
fn drag(&mut self, from: Pos2, to: Pos2) {
self.click_drag(from, 1, to);
}
fn click(&mut self, at: Pos2) {
self.fixture.frame(vec![pointer::moved(at)]);
self.fixture.frame(vec![pointer::press(at)]);
self.fixture.frame(vec![pointer::release(at)]);
self.fixture.frame(Vec::new());
}
/// Waits past the double-click time, so the next press starts a new click run.
fn pause(&mut self) {
self.fixture.advance(2.0);
self.fixture.frame(Vec::new());
}
}
/// A run dragged from page 0 to page 2 takes the rest of page 0, page 1 whole and page 2 up to the head, whichever way
/// it was dragged; its text waits for an unread middle page; stale and hostile indices are clamped to each page.
#[trial]
fn a_run_dragged_across_pages_takes_the_rest_of_the_first_the_middle_whole_and_the_start_of_the_last() {
let read = doc(true);
let mut rig = Rig::new(Rc::clone(&read));
// "five" on page 0's second line (glyph 18), to the "e" of "twelve" on page 2 (glyph 9).
let (five, twelve) = (rig.at(0, 1, 5), rig.at(2, 0, 9));
let whole = "five six\nseven eight\nnine ten\neleven twe";
rig.drag(five, twelve);
let forward = rig.selection();
assert_eq!(forward.page, 0, "the selection starts where the drag did");
assert!(matches!(forward.span, TextSpan::Run { anchor: 18, head: 9, head_page: 2, end_x: None, .. }), "{forward:?}");
assert_eq!(forward.pages(), 0..=2);
assert_eq!(glyphs(&forward, &read), [Some(18..26), Some(0..19), Some(0..10)]);
assert_eq!(forward.text(&*read).as_deref(), Some(whole));
rig.pause();
rig.drag(twelve, five);
let back = rig.selection();
assert_eq!(back.page, 2);
assert!(matches!(back.span, TextSpan::Run { anchor: 9, head: 18, head_page: 0, .. }), "{back:?}");
assert_eq!(back.pages(), 0..=2);
assert_eq!(glyphs(&back, &read), glyphs(&forward, &read), "the same glyphs in reading order");
assert_eq!(back.text(&*read).as_deref(), Some(whole));
// The middle page not read yet: the drag still reaches page 2, and Copy waits for page 1.
let unread = doc(false);
let mut rig = Rig::new(Rc::clone(&unread));
rig.drag(five, twelve);
let waiting = rig.selection();
assert_eq!(waiting.pages(), 0..=2);
assert_eq!(glyphs(&waiting, &unread), [Some(18..26), None, Some(0..10)]);
assert_eq!(waiting.text(&*unread), None);
assert_eq!(waiting.unread_pages(&*unread), vec![1]);
assert_eq!(forward.unread_pages(&*read), Vec::<usize>::new());
// Hostile and stale indices: clamped to each page's glyphs, nothing past the end.
let hostile = TextSelection::new(0, TextSpan::run(usize::MAX, 2, usize::MAX));
assert_eq!(glyphs(&hostile, &read), [None, Some(0..19), Some(0..21)]);
assert_eq!(hostile.text(&*read).as_deref(), Some("seven eight\nnine ten\neleven twelve\nthirteen"));
let stale = TextSelection::new(1, TextSpan::run(30, 1, 40));
assert_eq!(glyphs(&stale, &read), [None, None, None]);
assert_eq!(stale.text(&*read).as_deref(), Some(""));
let past_end = TextSelection::new(1, TextSpan::run(3, 1, 400));
assert_eq!(glyphs(&past_end, &read), [None, Some(3..19), None]);
}
/// Quick clicks select the word, the line and the page on the press; a 2- or 3-click drag extends by whole units onto
/// other pages both ways, the page unit stays on its page; Shift-click extends a run from its anchor onto any page.
#[trial]
fn click_units_and_their_drags_and_shift_click_extend_a_run() {
let doc = doc(true);
let mut rig = Rig::new(Rc::clone(&doc));
let text = |rig: &Rig| rig.selection().text(&*doc).expect("every page is read");
// The "w" of "two" on page 0: each press of the run selects before its release.
let two = rig.at(0, 0, 5);
rig.fixture.frame(vec![pointer::moved(two)]);
for (clicks, selected) in [(1, "w"), (2, "two"), (3, "one two three"), (4, "one two three\nfour five six")] {
rig.fixture.frame(vec![pointer::press(two)]);
assert_eq!(text(&rig), selected, "{clicks} quick clicks, on the press");
rig.fixture.frame(vec![pointer::release(two)]);
}
rig.fixture.frame(Vec::new());
// A double-click on "eight" (page 1) dragged onto "thirteen" (page 2): whole words, anchored at the word's start.
rig.pause();
rig.click_drag(rig.at(1, 0, 7), 2, rig.at(2, 1, 2));
let words = rig.selection();
assert_eq!(words.page, 1);
assert!(matches!(words.span, TextSpan::Run { anchor: 6, head: 20, head_page: 2, end_x: None, .. }), "{words:?}");
assert_eq!(text(&rig), "eight\nnine ten\neleven twelve\nthirteen");
// Dragged back onto "one" (page 0): anchored at the word's end, the head at the reached word's start.
rig.pause();
rig.click_drag(rig.at(1, 0, 7), 2, rig.at(0, 0, 1));
let back = rig.selection();
assert!(matches!(back.span, TextSpan::Run { anchor: 10, head: 0, head_page: 0, .. }), "{back:?}");
assert_eq!(glyphs(&back, &doc), [Some(0..26), Some(0..11), None]);
assert_eq!(text(&rig), "one two three\nfour five six\nseven eight");
// A triple-click on page 0's first line dragged onto page 1's first: whole lines.
rig.pause();
rig.click_drag(rig.at(0, 0, 1), 3, rig.at(1, 0, 2));
assert_eq!(glyphs(&rig.selection(), &doc), [Some(0..26), Some(0..11), None]);
// Four clicks on page 1 dragged onto page 2: the page unit stays on its page.
rig.pause();
rig.click_drag(rig.at(1, 0, 2), 4, rig.at(2, 0, 2));
assert_eq!(rig.selection().pages(), 1..=1);
assert_eq!(text(&rig), "seven eight\nnine ten");
// A run on page 0 from "five", then Shift-clicks: onto page 2, and back before the anchor on page 0.
rig.pause();
rig.drag(rig.at(0, 1, 5), rig.at(0, 1, 7));
assert_eq!(text(&rig), "fiv");
rig.pause();
rig.fixture.hold(Modifiers::SHIFT);
rig.click(rig.at(2, 0, 9));
let extended = rig.selection();
assert_eq!(extended.page, 0, "Shift-click keeps the anchor's page");
assert!(matches!(extended.span, TextSpan::Run { anchor: 18, head: 9, head_page: 2, .. }), "{extended:?}");
assert_eq!(text(&rig), "five six\nseven eight\nnine ten\neleven twe");
rig.pause();
rig.click(rig.at(0, 0, 1));
rig.fixture.hold(Modifiers::NONE);
assert_eq!(rig.selection().pages(), 0..=0);
assert_eq!(text(&rig), "ne two three\nfour f");
}