mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 04:27:49 +00:00
Merge branch 'red/fu-canvas' into area/ribbon-fw
This commit is contained in:
@@ -61,4 +61,4 @@ pub use text_selection::{
|
||||
pub use thumbnails::{
|
||||
PageThumbnails, PageThumbnailsOutput, THUMBNAIL_ZOOM, ThumbnailEvent, ThumbnailMarks, ThumbnailSection, ThumbnailWords, moved_page,
|
||||
};
|
||||
pub use view::{PageBody, PageSource, PageView, PageViewOutput, PageViewState, PageViewWords, PlacedPage};
|
||||
pub use view::{PageBody, PageRegion, PageSnap, PageSource, PageView, PageViewOutput, PageViewState, PageViewWords, PlacedPage};
|
||||
|
||||
@@ -14,14 +14,14 @@ use craft_text::ui::DocUnit;
|
||||
use craft_text::ui::ruler::{RulerValues, TabAlign, TextRuler, TextRulerOutput, nudge_size, ruler_text, snap_step, snap_stop};
|
||||
use craft_ui::canvas::{RulerTick, Rulers, TickRule};
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, Common, Component, Cx, Focus as _, Input, MeasureCx, Name, Numeric, Outcome, NoValue, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _,
|
||||
Access, Bind, Common, Component, Cx, Focus as _, IdSource, Input, MeasureCx, Name, Numeric, Outcome, NoValue, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _,
|
||||
Role, Show as _, Styled as _, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth, TextRun, Tick, TickEdge, TickRank};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::focus::{ActivateKeys, FocusShape, KeyUse};
|
||||
use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, TextLook, TypeRole};
|
||||
use egui::{CornerRadius, Pos2, Rangef, Rect, Response, Ui, Vec2, pos2, vec2};
|
||||
use egui::{AsIdSalt, CornerRadius, IdSalt, Pos2, Rangef, Rect, Response, Ui, Vec2, pos2, vec2};
|
||||
|
||||
use super::margins::{MarginHandles, MarginHandlesOutput, MarginRules, PageEdges};
|
||||
use super::view::PlacedPage;
|
||||
@@ -391,6 +391,8 @@ pub struct PageRulers<'a> {
|
||||
rows: &'a [f32],
|
||||
gutter: f64,
|
||||
mirrored_even: bool,
|
||||
id: IdSource,
|
||||
gaps_draggable: bool,
|
||||
}
|
||||
|
||||
impl<'a> PageRulers<'a> {
|
||||
@@ -410,9 +412,24 @@ impl<'a> PageRulers<'a> {
|
||||
rows: &[],
|
||||
gutter: 0.0,
|
||||
mirrored_even: false,
|
||||
id: IdSource::Auto,
|
||||
gaps_draggable: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Salts the text ruler's id with `salt` (the caret paragraph's key): a new salt is a new ruler, so a drag open on
|
||||
/// the ruler of another paragraph ends with no commit.
|
||||
pub fn id_salt(mut self, salt: impl AsIdSalt) -> Self {
|
||||
self.id = IdSource::Salt(IdSalt::new(salt));
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the column gaps' edges take a drag (the default): [`TextRuler::gaps_draggable`].
|
||||
pub fn gaps_draggable(mut self, on: bool) -> Self {
|
||||
self.gaps_draggable = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// The text column's start and end, points from the page's left. Without it the column is the text area between the
|
||||
/// margins.
|
||||
pub fn column(mut self, column: (f32, f32)) -> Self {
|
||||
@@ -470,7 +487,8 @@ impl<'a> PageRulers<'a> {
|
||||
|
||||
/// Shows the rulers over the canvas at `canvas_rect`.
|
||||
pub fn show_at(self, ui: &mut Ui, canvas_rect: Rect) -> PageRulersOutput {
|
||||
let PageRulers { label, page, mut edges, ruler, column, unit, kind, right_to_left, columns, gaps, rows, gutter, mirrored_even } = self;
|
||||
let PageRulers { label, page, mut edges, ruler, column, unit, kind, right_to_left, columns, gaps, rows, gutter, mirrored_even, id, gaps_draggable } =
|
||||
self;
|
||||
let (words, interface_rtl) = {
|
||||
let env = Env::of(ui);
|
||||
(env.words::<PageRulersWords>(), env.view().direction().is_rtl())
|
||||
@@ -494,10 +512,12 @@ impl<'a> PageRulers<'a> {
|
||||
.unit(unit)
|
||||
.columns(columns)
|
||||
.gaps(gaps)
|
||||
.gaps_draggable(gaps_draggable)
|
||||
.origin(origin)
|
||||
.extent(extent)
|
||||
.scale(scale)
|
||||
.right_to_left(rtl);
|
||||
.right_to_left(rtl)
|
||||
.id_source(id);
|
||||
if let Some(kind) = kind {
|
||||
horizontal = horizontal.kind(kind);
|
||||
}
|
||||
|
||||
+96
-10
@@ -27,8 +27,9 @@ use super::access::AccessDescriber;
|
||||
use crate::layout::{
|
||||
Fit, LayoutOptions, PageDisplay, PageSpacing, PagedLayout, SCREEN_POINTS_PER_POINT, ViewDefaults, ZOOM_RANGE, fit_scale, place_pages, shown_row,
|
||||
};
|
||||
use craft_behavior::geometry::{SnapOptions, SnapTarget, SnapTargets};
|
||||
use craft_behavior::kurbo::{Point, Rect as DocRect, Size};
|
||||
use craft_behavior::{CanvasView, MoveMods, NavMove, PressPhase, WheelNotch, ZoomLadder};
|
||||
use craft_behavior::{Axis, CanvasView, MoveMods, NavMove, PressPhase, WheelNotch, ZoomLadder};
|
||||
use craft_ui::canvas::{
|
||||
BodyKeys, Canvas, CanvasOutput, CanvasScrollbars, NavigationOptions, PageFrame, PageKey, Pasteboard, PasteboardOutput, Snap, ToolPass,
|
||||
ToolRegion, canvas_space, tool_pass,
|
||||
@@ -218,6 +219,45 @@ impl PageBody<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The snapping of the coordinates the pointer sets on the view ([`PageView::snap`]), over targets on the pages in
|
||||
/// each page's own points: the view places them where their page shows in each pass.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct PageSnap {
|
||||
options: SnapOptions,
|
||||
pages: Vec<(usize, Vec<SnapTarget>)>,
|
||||
}
|
||||
|
||||
impl PageSnap {
|
||||
/// Snapping with `options` and no targets yet.
|
||||
pub fn new(options: SnapOptions) -> Self {
|
||||
PageSnap { options, pages: Vec::new() }
|
||||
}
|
||||
|
||||
/// Adds `targets` on page `page`, in the page's own points from its top left corner, their spans included.
|
||||
#[must_use]
|
||||
pub fn page(mut self, page: usize, targets: Vec<SnapTarget>) -> Self {
|
||||
self.pages.push((page, targets));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// An area of a page where the active tool takes a press over the canvas controls ([`PageView::tool_regions`]), in the
|
||||
/// page's own points: the view places it where its page shows in each pass.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct PageRegion {
|
||||
page: usize,
|
||||
points: Vec<Point>,
|
||||
}
|
||||
|
||||
impl PageRegion {
|
||||
/// The polygon with the corners `points` on page `page`, in the page's own points from its top left corner.
|
||||
pub fn polygon(page: usize, points: Vec<Point>) -> Self {
|
||||
PageRegion { page, points }
|
||||
}
|
||||
}
|
||||
|
||||
/// What the view did this pass.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
@@ -285,8 +325,8 @@ pub struct PageView<'a> {
|
||||
describer: Option<&'a dyn AccessDescriber>,
|
||||
paper: DataColor,
|
||||
editor: Option<EditorPurpose>,
|
||||
snap: Option<Snap>,
|
||||
tool_regions: Vec<ToolRegion>,
|
||||
snap: Option<PageSnap>,
|
||||
tool_regions: Vec<PageRegion>,
|
||||
rulers: bool,
|
||||
}
|
||||
|
||||
@@ -345,16 +385,19 @@ impl<'a> PageView<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The snapping of the coordinates the pointer sets on the view, passed to the inner canvas.
|
||||
/// The snapping of the coordinates the pointer sets on the view, with its targets in page points. The view places
|
||||
/// them on the pages that show this pass, drops those of pages outside the shown row and passes the result to the
|
||||
/// inner canvas.
|
||||
#[must_use]
|
||||
pub fn snap(mut self, snap: Option<Snap>) -> Self {
|
||||
pub fn snap(mut self, snap: Option<PageSnap>) -> Self {
|
||||
self.snap = snap;
|
||||
self
|
||||
}
|
||||
|
||||
/// The areas where the active tool takes a press over the canvas controls, passed to the inner canvas.
|
||||
/// The areas where the active tool takes a press over the canvas controls, in page points. The view places them
|
||||
/// as [`snap`](Self::snap)'s targets and passes them to the inner canvas.
|
||||
#[must_use]
|
||||
pub fn tool_regions(mut self, regions: Vec<ToolRegion>) -> Self {
|
||||
pub fn tool_regions(mut self, regions: Vec<PageRegion>) -> Self {
|
||||
self.tool_regions = regions;
|
||||
self
|
||||
}
|
||||
@@ -393,12 +436,14 @@ 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).tool_regions(tool_regions).show_rulers(rulers);
|
||||
// The app's page geometry, in page points, placed where its page shows in this pass's layout.
|
||||
let regions: Vec<ToolRegion> = tool_regions.iter().filter_map(|region| placed_region(region, &geo, &frame)).collect();
|
||||
let mut canvas = Canvas::new(label.clone()).view(given).navigation(navigation).keys_to_body(true).tool_regions(regions).show_rulers(rulers);
|
||||
if let Some(purpose) = editor {
|
||||
canvas = canvas.editor(purpose);
|
||||
}
|
||||
if let Some(snap) = snap {
|
||||
canvas = canvas.snap(snap);
|
||||
if let Some(snap) = &snap {
|
||||
canvas = canvas.snap(placed_snap(snap, &geo, &frame));
|
||||
}
|
||||
if start.continuous {
|
||||
canvas = canvas.document(frame.document(&geo));
|
||||
@@ -547,6 +592,47 @@ impl Frame {
|
||||
fn layout_point(&self, p: Point) -> Point {
|
||||
Point::new(p.x * self.zoom + self.origin.x, p.y * self.zoom + self.origin.y)
|
||||
}
|
||||
|
||||
/// A layout point as a document point.
|
||||
fn document_point(&self, l: Point) -> Point {
|
||||
Point::new((l.x - self.origin.x) / self.zoom, (l.y - self.origin.y) / self.zoom)
|
||||
}
|
||||
}
|
||||
|
||||
/// The document point of `p`, a point of page `page` in the page's own points; `None` for a page outside the row
|
||||
/// `geo` shows.
|
||||
fn page_to_document(geo: &Placed, frame: &Frame, page: usize, p: Point) -> Option<Point> {
|
||||
if !geo.row.contains(&page) {
|
||||
return None;
|
||||
}
|
||||
let origin = geo.layout.rects.get(page)?.origin();
|
||||
Some(frame.document_point(Point::new(origin.x + p.x * geo.scale, origin.y + p.y * geo.scale)))
|
||||
}
|
||||
|
||||
/// The snapping over `snap`'s targets on the pages `geo` shows, in `frame`'s document units.
|
||||
fn placed_snap(snap: &PageSnap, geo: &Placed, frame: &Frame) -> Snap {
|
||||
let mut targets = SnapTargets::new();
|
||||
for (page, list) in &snap.pages {
|
||||
let to_doc = |p: Point| page_to_document(geo, frame, *page, p);
|
||||
for target in list {
|
||||
// A line along Y snaps x and spans y; one along X snaps y and spans x. The mapping is separate per axis.
|
||||
let vertical = target.along == Axis::Y;
|
||||
let across = |v: f64| to_doc(if vertical { Point::new(v, 0.0) } else { Point::new(0.0, v) }).map(|d| if vertical { d.x } else { d.y });
|
||||
let along = |v: f64| to_doc(if vertical { Point::new(0.0, v) } else { Point::new(v, 0.0) }).map(|d| if vertical { d.y } else { d.x });
|
||||
let Some(position) = across(target.position) else { break };
|
||||
let mut placed = *target;
|
||||
placed.position = position;
|
||||
placed.span = target.span.and_then(|(a, b)| Some((along(a)?, along(b)?)));
|
||||
targets.add(placed);
|
||||
}
|
||||
}
|
||||
Snap::new(Arc::new(targets), snap.options)
|
||||
}
|
||||
|
||||
/// `region` on the page it names, in `frame`'s document units; `None` for a page outside the row `geo` shows.
|
||||
fn placed_region(region: &PageRegion, geo: &Placed, frame: &Frame) -> Option<ToolRegion> {
|
||||
let points = region.points.iter().map(|p| page_to_document(geo, frame, region.page, *p)).collect::<Option<Vec<Point>>>()?;
|
||||
Some(ToolRegion::polygon(points))
|
||||
}
|
||||
|
||||
/// One pass of the canvas body: layout, scrolling, zoom and paging folded into the state; the pasteboard, the
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
//! Stories of the page view and its leaves.
|
||||
|
||||
use super::pictures::{PageMetrics, PagePictures};
|
||||
use super::{PageView, PageViewState};
|
||||
use super::{PageSnap, PageSource as _, PageView, PageViewState};
|
||||
use crate::layout::{LayoutOptions, PageDisplay};
|
||||
use crate::ui::fixtures::{DemoPages, PAPER, demo_placed};
|
||||
use craft_behavior::CanvasView;
|
||||
use craft_behavior::kurbo::Point;
|
||||
use craft_ui::canvas::Canvas;
|
||||
use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget};
|
||||
use craft_behavior::kurbo::{Point, Rect as DocRect};
|
||||
use craft_behavior::{Axis, CancelReason, CanvasView};
|
||||
use craft_ui::canvas::{Canvas, CanvasTool, ToolAction, ToolContext, ToolHost, ToolPath, ToolPointer};
|
||||
use craft_ui::contract::{Show as _, ShowContainer as _};
|
||||
use craft_ui::primitives::Draw;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::{Pos2, Ui, Vec2};
|
||||
|
||||
@@ -45,6 +47,60 @@ fn one_page_row(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
view(ui, data, false, |state| state.continuous = false)
|
||||
}
|
||||
|
||||
/// A page margin's inset from each edge, in page points.
|
||||
const MARGIN: f64 = 72.0;
|
||||
|
||||
/// A tool whose drag snaps the point under the pointer as a point-sized box, so the host draws the smart guide it
|
||||
/// snapped to.
|
||||
struct MarginSnapper;
|
||||
|
||||
impl CanvasTool for MarginSnapper {
|
||||
fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction {
|
||||
ToolAction::Claimed
|
||||
}
|
||||
|
||||
fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
if let Some(space) = cx.space() {
|
||||
let at = space.view.to_doc(pointer.pos);
|
||||
let _ = cx.snap_rect(DocRect::from_points(at, at));
|
||||
}
|
||||
}
|
||||
|
||||
fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Command("the Snap to Margins command")
|
||||
}
|
||||
}
|
||||
|
||||
/// Two-up spreads whose page margins are snap targets handed over in page points ([`PageSnap`]): a drag snaps to the
|
||||
/// margins of the page it is over, where that page shows, and the smart guide shows where it snapped.
|
||||
#[story(PageView<'static>, covers = [], drive = Drive::Never)]
|
||||
fn snapped_margins(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let state = data.value("view", PageViewState { display: PageDisplay::TwoUp, ..PageViewState::default() });
|
||||
let pages = DemoPages::new(PAGES);
|
||||
let snap = (0..PAGES).fold(PageSnap::new(SnapOptions::default()), |snap, page| {
|
||||
let size = pages.page_size(page);
|
||||
let margins = vec![
|
||||
SnapTarget::new(Axis::Y, MARGIN, SnapKind::LayerEdge),
|
||||
SnapTarget::new(Axis::Y, size.width - MARGIN, SnapKind::LayerEdge),
|
||||
SnapTarget::new(Axis::X, MARGIN, SnapKind::LayerEdge),
|
||||
SnapTarget::new(Axis::X, size.height - MARGIN, SnapKind::LayerEdge),
|
||||
];
|
||||
snap.page(page, margins)
|
||||
});
|
||||
let out = PageView::new("Pages", &pages, state, PAPER).options(LayoutOptions::ACROBAT).snap(Some(snap)).show(ui, |ui, body| {
|
||||
if let Some(pass) = body.pass {
|
||||
let _ = ToolHost::new().run(ui, pass, &mut MarginSnapper);
|
||||
}
|
||||
});
|
||||
out.canvas.response.into()
|
||||
}
|
||||
|
||||
#[story(PageMetrics, covers = [Default], drive = Drive::Never)]
|
||||
fn page_metrics(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let room = craft_ui::testing::stage(ui);
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
//! The page rulers: ruler numbers keep clear of table column markers, the margin handles stop short of the opposite
|
||||
//! edge and swap sides on a mirrored even page, and a table row grip drags as one gesture.
|
||||
|
||||
use craft_behavior::GesturePhase;
|
||||
use craft_behavior::{EditEvent, GesturePhase};
|
||||
use craft_pages::setup::Margins;
|
||||
use craft_pages::ui::fixtures::demo_placed;
|
||||
use craft_pages::ui::margins::{MIN_TEXT, MarginHandlesWords};
|
||||
use craft_pages::ui::page_rulers::PageRulersWords;
|
||||
use craft_pages::ui::{PageEdges, PageRulers, RowDrag, VerticalRuler};
|
||||
use craft_text::ui::DocUnit;
|
||||
use craft_text::ui::ruler::{RulerValues, TextRulerWords};
|
||||
use craft_text::ui::ruler::{RulerValues, TabAlign, TabLeader, TabStop, TextRulerWords};
|
||||
use craft_ui::contract::{Bind, Role, Show as _};
|
||||
use craft_ui::runtime::env::UnitKind;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers, Rangef, Rect, pos2, vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
/// Where the page's top-left corner sits in the fixture, points.
|
||||
@@ -144,3 +144,56 @@ fn a_row_grip_drag_reports_one_gesture_with_alt_free_and_the_arrow_nudges() {
|
||||
assert_eq!(nudge.phase, GesturePhase::Commit, "a nudge is a lone Commit");
|
||||
assert!(nudge.position > 100.0, "Down moves the border down: {}", nudge.position);
|
||||
}
|
||||
|
||||
/// Where the trial's left tab stop sits, points from the column's start edge.
|
||||
const STOP_AT: f32 = 144.0;
|
||||
|
||||
/// Guards `PageRulers::id_salt`: the caret paragraph's key salts the text ruler, so a new paragraph is a new ruler and
|
||||
/// a stop drag open on the old one commits nothing when its button comes up. The first drag, with the salt kept, is the
|
||||
/// control: it commits once.
|
||||
#[trial]
|
||||
fn a_new_salt_during_a_tab_drag_commits_nothing() {
|
||||
let salt = Rc::new(Cell::new(1u32));
|
||||
let commits = Rc::new(Cell::new(0usize));
|
||||
let mut start = RulerValues::default();
|
||||
start.stops.push(TabStop::new(STOP_AT, TabAlign::Left, TabLeader::None));
|
||||
let values = Rc::new(RefCell::new(start));
|
||||
let (shown_salt, seen, shown_values) = (Rc::clone(&salt), Rc::clone(&commits), Rc::clone(&values));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let full = craft_ui::testing::stage(ui);
|
||||
let page = demo_placed(1, pos2(full.min.x + PAGE_AT.0, full.min.y + PAGE_AT.1)).remove(0);
|
||||
let mut edges = PageEdges::new(Margins::uniform(72.0));
|
||||
let out = PageRulers::new("Rulers", &page, Bind::bound(&mut edges), Bind::bound(&mut *shown_values.borrow_mut()))
|
||||
.id_salt(shown_salt.get())
|
||||
.show_at(ui, full);
|
||||
let committed = out.ruler.edit.events.iter().filter(|event| matches!(event, EditEvent::Commit { .. })).count();
|
||||
seen.set(seen.get() + committed);
|
||||
});
|
||||
fixture.room(vec2(900.0, 600.0));
|
||||
fixture.settle();
|
||||
let left_tab = TextRulerWords::default().left_tab;
|
||||
let stop = |fixture: &Fixture| {
|
||||
fixture
|
||||
.by_role(Role::SLIDER)
|
||||
.into_iter()
|
||||
.find(|target| craft_ui::testing::access::name(fixture.tree(), target.node).is_some_and(|name| name.starts_with(left_tab.as_str())))
|
||||
.expect("the ruler shows the stop")
|
||||
.rect
|
||||
.center()
|
||||
};
|
||||
let by = vec2(40.0, 0.0);
|
||||
|
||||
let at = stop(&fixture);
|
||||
fixture.drag_hold_at(at, by);
|
||||
fixture.release_at(at + by);
|
||||
fixture.settle();
|
||||
assert_eq!(commits.get(), 1, "a stop drag on one paragraph's ruler commits once");
|
||||
|
||||
let at = stop(&fixture);
|
||||
fixture.drag_hold_at(at, by);
|
||||
salt.set(2);
|
||||
fixture.idle(1);
|
||||
fixture.release_at(at + by);
|
||||
fixture.settle();
|
||||
assert_eq!(commits.get(), 1, "the drag open when the paragraph changed commits nothing");
|
||||
}
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
//! The page view and the page preview: the scroll anchor under a zoom change, wheel input at the end of the document,
|
||||
//! the view's page and arrow keys and its zoom commands, and the preview's keys.
|
||||
|
||||
use craft_behavior::geometry::{CropBox, SnapKind, SnapOptions, SnapTarget};
|
||||
use craft_behavior::kurbo;
|
||||
use craft_pages::layout::{Fit, LayoutOptions};
|
||||
use craft_behavior::{Axis, CancelReason, CanvasView};
|
||||
use craft_pages::layout::{Fit, LayoutOptions, PageDisplay};
|
||||
use craft_pages::ui::fixtures::{DemoPages, PAPER};
|
||||
use craft_pages::ui::{PagePreview, PageSource, PageView, PageViewState, PageViewWords, ReadingNav, ReadingState, ReadingView};
|
||||
use craft_ui::contract::{Role, Show as _};
|
||||
use craft_pages::ui::{
|
||||
PagePreview, PageRegion, PageSnap, PageSource, PageView, PageViewState, PageViewWords, PlacedPage, ReadingNav, ReadingState, ReadingView,
|
||||
};
|
||||
use craft_ui::canvas::{CanvasTool, CropOverlay, ToolAction, ToolContext, ToolHost, ToolPath, ToolPointer};
|
||||
use craft_ui::contract::{Bind, Role, Show as _};
|
||||
|
||||
use craft_ui::primitives::EditorPurpose;
|
||||
use craft_ui::primitives::{Draw, EditorPurpose};
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui::testing::{Fixture, pointer, trial};
|
||||
use egui::{Key, Modifiers, pos2, vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
@@ -511,3 +516,134 @@ fn a_view_with_an_editor_purpose_takes_no_plain_keys_for_moving() {
|
||||
let (before, after) = keyed(true);
|
||||
assert_eq!((after.current, after.offset), (before.current, before.offset), "the editor view leaves moving to the app");
|
||||
}
|
||||
|
||||
/// Where a snap line lies on page 2, in that page's own points.
|
||||
const LINE_X: f64 = 120.0;
|
||||
|
||||
/// A tool that snaps the document point under each drag sample and keeps the last one, and counts its presses.
|
||||
#[derive(Default)]
|
||||
struct Snapper {
|
||||
snapped: Option<kurbo::Point>,
|
||||
presses: usize,
|
||||
}
|
||||
|
||||
impl CanvasTool for Snapper {
|
||||
fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction {
|
||||
self.presses += 1;
|
||||
ToolAction::Claimed
|
||||
}
|
||||
|
||||
fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
if let Some(space) = cx.space() {
|
||||
self.snapped = Some(cx.snap(space.view.to_doc(pointer.pos)));
|
||||
}
|
||||
}
|
||||
|
||||
fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Command("the Snap command")
|
||||
}
|
||||
}
|
||||
|
||||
/// A drag a few points beside the snap line at `LINE_X` on page 2, in a view of `state` with the line handed over in
|
||||
/// page points: where the drag snapped to on screen, and where the line shows on page 2.
|
||||
fn drag_beside_the_line_on_page_two(state: PageViewState) -> (f32, f32) {
|
||||
let tool = Rc::new(RefCell::new(Snapper::default()));
|
||||
let two: Rc<Cell<Option<(PlacedPage, CanvasView)>>> = Rc::default();
|
||||
let (shown_tool, seen) = (Rc::clone(&tool), Rc::clone(&two));
|
||||
let pages = DemoPages::new(4);
|
||||
let mut state = state;
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let snap = PageSnap::new(SnapOptions::default()).page(1, vec![SnapTarget::new(Axis::Y, LINE_X, SnapKind::Guide)]);
|
||||
PageView::new("Pages", &pages, &mut state, PAPER).options(LayoutOptions::ACROBAT).snap(Some(snap)).show(ui, |ui, body| {
|
||||
if let Some(page) = body.pages.iter().find(|placed| placed.page == 1) {
|
||||
seen.set(Some((*page, body.view)));
|
||||
}
|
||||
if let Some(pass) = body.pass {
|
||||
let _ = ToolHost::new().run(ui, pass, &mut *shown_tool.borrow_mut());
|
||||
}
|
||||
});
|
||||
});
|
||||
fixture.room(vec2(900.0, 700.0));
|
||||
fixture.settle();
|
||||
let (page, _) = two.get().expect("page 2 shows");
|
||||
let line = page.to_screen(kurbo::Point::new(LINE_X, 200.0));
|
||||
let from = line + vec2(30.0, 0.0);
|
||||
fixture.frame(vec![pointer::moved(from)]);
|
||||
fixture.frame(vec![pointer::press(from)]);
|
||||
for step in 1..=3 {
|
||||
fixture.frame(vec![pointer::moved(from - vec2(9.0 * step as f32, 0.0))]);
|
||||
}
|
||||
let (_, view) = two.get().expect("page 2 shows");
|
||||
let snapped = tool.borrow().snapped.expect("the tool dragged");
|
||||
(view.to_screen(snapped).x, line.x)
|
||||
}
|
||||
|
||||
/// Guards the view's placement of page geometry: a target in page points snaps where its page shows, not at the
|
||||
/// same numbers in document units, in a continuous view and in a two-up spread.
|
||||
#[trial]
|
||||
fn a_snap_target_on_page_two_snaps_a_drag_where_page_two_shows() {
|
||||
let continuous = state_with(|s| {
|
||||
s.fit = Fit::None;
|
||||
s.zoom = 0.4;
|
||||
s.continuous = true;
|
||||
});
|
||||
let spread = state_with(|s| {
|
||||
s.fit = Fit::None;
|
||||
s.zoom = 0.4;
|
||||
s.continuous = false;
|
||||
s.display = PageDisplay::TwoUp;
|
||||
});
|
||||
for (name, state) in [("continuous", continuous), ("two-up", spread)] {
|
||||
let (snapped, line) = drag_beside_the_line_on_page_two(state);
|
||||
assert!((snapped - line).abs() < 0.5, "{name}: the drag snaps onto page 2's line: {snapped} against {line}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Guards the view's placement of tool regions: a region in page points on page 1 takes a press over a canvas
|
||||
/// control there.
|
||||
#[trial]
|
||||
fn a_tool_region_on_page_one_takes_a_press_over_a_canvas_control_there() {
|
||||
let tool = Rc::new(RefCell::new(Snapper::default()));
|
||||
let crop: Rc<RefCell<Option<CropBox>>> = Rc::default();
|
||||
let (shown_tool, shown_crop) = (Rc::clone(&tool), Rc::clone(&crop));
|
||||
let pages = DemoPages::new(2);
|
||||
let mut state = state_with(|s| {
|
||||
s.fit = Fit::None;
|
||||
s.zoom = 0.4;
|
||||
});
|
||||
// The region covers the crop frame's top left corner, at page 1's (100, 80) points.
|
||||
let corner = vec![kurbo::Point::new(80.0, 60.0), kurbo::Point::new(120.0, 60.0), kurbo::Point::new(120.0, 100.0), kurbo::Point::new(80.0, 100.0)];
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let regions = vec![PageRegion::polygon(0, corner.clone())];
|
||||
PageView::new("Pages", &pages, &mut state, PAPER).options(LayoutOptions::ACROBAT).tool_regions(regions).show(ui, |ui, body| {
|
||||
let Some(first) = body.pages.iter().find(|placed| placed.page == 0) else { return };
|
||||
let mut crop = shown_crop.borrow_mut();
|
||||
let frame = crop.get_or_insert_with(|| {
|
||||
let (a, b) = (first.to_doc(&body.view, kurbo::Point::new(100.0, 80.0)), first.to_doc(&body.view, kurbo::Point::new(300.0, 220.0)));
|
||||
CropBox::upright(kurbo::Rect::from_points(a, b))
|
||||
});
|
||||
let _ = CropOverlay::new("Crop", Bind::bound(frame)).show_at(ui, body.rect);
|
||||
if let Some(pass) = body.pass {
|
||||
let _ = ToolHost::new().run(ui, pass, &mut *shown_tool.borrow_mut());
|
||||
}
|
||||
});
|
||||
});
|
||||
fixture.room(vec2(900.0, 700.0));
|
||||
fixture.settle();
|
||||
let start = crop.borrow().as_ref().map(|frame| frame.rect).expect("the crop shows on page 1");
|
||||
let at = fixture.by_label("Crop corner, top left").expect("the crop shows its corners").rect.center();
|
||||
let by = vec2(20.0, 15.0);
|
||||
fixture.frame(vec![pointer::moved(at)]);
|
||||
fixture.frame(vec![pointer::press(at)]);
|
||||
fixture.frame(vec![pointer::moved(at + by * 0.5)]);
|
||||
fixture.frame(vec![pointer::moved(at + by)]);
|
||||
fixture.frame(vec![pointer::release(at + by)]);
|
||||
assert_eq!(tool.borrow().presses, 1, "a press in the region is the tool's");
|
||||
assert_eq!(crop.borrow().as_ref().map(|frame| frame.rect), Some(start), "the corner under the region does not move");
|
||||
}
|
||||
|
||||
@@ -100,12 +100,20 @@ pub struct CommentBalloons<'a> {
|
||||
place: BalloonPlace,
|
||||
width: Option<f32>,
|
||||
now: Option<i64>,
|
||||
read_only: bool,
|
||||
}
|
||||
|
||||
impl<'a> CommentBalloons<'a> {
|
||||
/// Balloons named `label` for `items` on `pages`, with the card state in `state`.
|
||||
pub fn new(label: impl Into<Label>, pages: &'a [PlacedPage], items: &'a [BalloonItem<'a>], state: &'a mut CommentsPanelState) -> Self {
|
||||
CommentBalloons { label: label.into(), pages, items, state, place: BalloonPlace::Column, width: None, now: None }
|
||||
CommentBalloons { label: label.into(), pages, items, state, place: BalloonPlace::Column, width: None, now: None, read_only: false }
|
||||
}
|
||||
|
||||
/// Whether the comments are read only (off by default): every card shows as a locked thread's does, its text
|
||||
/// taking no typing, as the comments panel's rows do while comments cannot change.
|
||||
pub fn read_only(mut self, on: bool) -> Self {
|
||||
self.read_only = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Where the balloons sit.
|
||||
@@ -131,7 +139,7 @@ impl<'a> CommentBalloons<'a> {
|
||||
/// Every card is measured and placed first, so the leaders can be shown beneath the cards; the cards' events
|
||||
/// are applied once all are shown.
|
||||
pub fn show(self, ui: &mut Ui) -> CommentBalloonsOutput {
|
||||
let CommentBalloons { label, pages, items, state, place, width, now } = self;
|
||||
let CommentBalloons { label, pages, items, state, place, width, now, read_only } = self;
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<CommentsWords>();
|
||||
@@ -176,7 +184,7 @@ impl<'a> CommentBalloons<'a> {
|
||||
Some((placed, bottom)) if placed == page.page => bottom + gap,
|
||||
_ => f32::NEG_INFINITY,
|
||||
};
|
||||
let (mut row, thread) = card(item, &words, &*state, now);
|
||||
let (mut row, thread) = card(item, &words, &*state, now, read_only);
|
||||
let height = measure_item(ui, &mut row, SetPosition::new(at).of(count), Proposal::Width(width)).y;
|
||||
let rect = Rect::from_min_size(Pos2::new(x_of(page), anchor.y.max(floor)), vec2(width, height));
|
||||
stacked = Some((page.page, rect.bottom()));
|
||||
@@ -218,8 +226,8 @@ impl<'a> CommentBalloons<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The card of `item` and, for a comment, its thread. A comment's card is the panel's row with the balloon buttons;
|
||||
/// a revision's is the row's note form.
|
||||
/// The card of `item` and, for a comment, its thread. A comment's card is the panel's row with the balloon buttons,
|
||||
/// editable unless the balloons are `read_only` or its thread is locked; a revision's is the row's note form.
|
||||
///
|
||||
/// The thread keeps its own lifetime, apart from the borrow of `state` the row holds, so the caller can change `state`
|
||||
/// once the row is shown.
|
||||
@@ -228,6 +236,7 @@ fn card<'r, 't: 'r>(
|
||||
words: &CommentsWords,
|
||||
state: &'r CommentsPanelState,
|
||||
now: i64,
|
||||
read_only: bool,
|
||||
) -> (CommentRow<'r>, Option<&'t CommentThread>) {
|
||||
match item {
|
||||
BalloonItem::Thread { thread, .. } => {
|
||||
@@ -240,7 +249,7 @@ fn card<'r, 't: 'r>(
|
||||
let row = CommentRow::card(thread, name)
|
||||
.actions(CardActions::Buttons)
|
||||
.body_rows(BODY_ROWS)
|
||||
.state(selected, !thread.locked, now)
|
||||
.state(selected, !read_only && !thread.locked, now)
|
||||
.drafts(editing, if selected { state.reply.as_str() } else { "" });
|
||||
(row, Some(thread))
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ fn beside_page(
|
||||
revisions: &[Revision],
|
||||
selected: Option<u64>,
|
||||
place: BalloonPlace,
|
||||
read_only: bool,
|
||||
) -> StoryOutput {
|
||||
let state = data.value("state", CommentsPanelState { selected: selected.map(ThreadId), ..CommentsPanelState::default() });
|
||||
let (fill, line) = (Color32::WHITE, accent(ui, 1.0));
|
||||
@@ -60,33 +61,41 @@ fn beside_page(
|
||||
items.extend(
|
||||
revisions.iter().enumerate().map(|(at, revision)| BalloonItem::Revision { revision, page: 0, anchor: anchor(threads.len() + at) }),
|
||||
);
|
||||
CommentBalloons::new("Comments", &pages, &items, &mut *state).place(place).now(Some(NOW)).show(ui)
|
||||
CommentBalloons::new("Comments", &pages, &items, &mut *state).place(place).now(Some(NOW)).read_only(read_only).show(ui)
|
||||
})
|
||||
}
|
||||
|
||||
#[story(CommentBalloons<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn balloons_read_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let threads = [thread(1, "Ana", "Locked: nobody edits this.", true), thread(2, "Cy", "So is this one.", true)];
|
||||
beside_page(ui, data, &threads, &[], None, BalloonPlace::Column)
|
||||
beside_page(ui, data, &threads, &[], None, BalloonPlace::Column, false)
|
||||
}
|
||||
|
||||
/// Read-only balloons (`CommentBalloons::read_only`): comments cannot change, so the selected card, its thread not
|
||||
/// locked, shows no reply field and no buttons.
|
||||
#[story(CommentBalloons<'static>, covers = [], drive = Drive::Never)]
|
||||
fn read_only_balloons(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let threads = [thread(1, "Ana", "The margin is too narrow.", false), thread(2, "Cy", "Use the brand colour here.", false)];
|
||||
beside_page(ui, data, &threads, &[], Some(1), BalloonPlace::Column, true)
|
||||
}
|
||||
|
||||
#[story(CommentBalloons<'static>, covers = [], drive = Drive::Never)]
|
||||
fn balloons_selected(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let threads = [thread(1, "Ana", "The margin is too narrow.", false), thread(2, "Cy", "Use the brand colour here.", false)];
|
||||
beside_page(ui, data, &threads, &[], Some(2), BalloonPlace::Column)
|
||||
beside_page(ui, data, &threads, &[], Some(2), BalloonPlace::Column, false)
|
||||
}
|
||||
|
||||
#[story(CommentBalloons<'static>, covers = [], drive = Drive::Never)]
|
||||
fn balloons_long(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let long = "A long comment that runs over many lines of the card. ".repeat(24);
|
||||
let threads = [thread(1, "Ana", &long, false), thread(2, "Cy", "The next card stays in view.", false)];
|
||||
beside_page(ui, data, &threads, &[], None, BalloonPlace::Column)
|
||||
beside_page(ui, data, &threads, &[], None, BalloonPlace::Column, false)
|
||||
}
|
||||
|
||||
#[story(CommentBalloons<'static>, covers = [], drive = Drive::Never)]
|
||||
fn balloons_right_to_left(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let threads = [thread(1, "מיכל", "השוליים צרים מדי בעמוד הזה.", false)];
|
||||
beside_page(ui, data, &threads, &[], None, BalloonPlace::Column)
|
||||
beside_page(ui, data, &threads, &[], None, BalloonPlace::Column, false)
|
||||
}
|
||||
|
||||
#[story(CommentBalloons<'static>, covers = [], drive = Drive::Never)]
|
||||
@@ -97,11 +106,11 @@ fn balloons_revision(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
heading: "Slide 3 changed".into(),
|
||||
details: vec!["Title text changed".into(), "Picture moved".into()],
|
||||
}];
|
||||
beside_page(ui, data, &threads, &revisions, None, BalloonPlace::Column)
|
||||
beside_page(ui, data, &threads, &revisions, None, BalloonPlace::Column, false)
|
||||
}
|
||||
|
||||
#[story(CommentBalloons<'static>, covers = [], drive = Drive::Never)]
|
||||
fn balloons_floating(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let threads = [thread(1, "Ana", "This card floats over the page.", false)];
|
||||
beside_page(ui, data, &threads, &[], None, BalloonPlace::Floating)
|
||||
beside_page(ui, data, &threads, &[], None, BalloonPlace::Floating, false)
|
||||
}
|
||||
|
||||
@@ -39,6 +39,11 @@ struct Shown {
|
||||
|
||||
impl Shown {
|
||||
fn new(threads: Vec<(CommentThread, f32)>, state: CommentsPanelState, place: BalloonPlace, room: Vec2, direction: Direction) -> Shown {
|
||||
Shown::with(threads, state, place, room, direction, false)
|
||||
}
|
||||
|
||||
/// [`Shown::new`] with the balloons `read_only` or not.
|
||||
fn with(threads: Vec<(CommentThread, f32)>, state: CommentsPanelState, place: BalloonPlace, room: Vec2, direction: Direction, read_only: bool) -> Shown {
|
||||
let state = Rc::new(RefCell::new(state));
|
||||
let edits = Rc::new(RefCell::new(Vec::new()));
|
||||
let cards = Rc::new(RefCell::new(Vec::new()));
|
||||
@@ -48,7 +53,7 @@ impl Shown {
|
||||
let items: Vec<BalloonItem<'_>> =
|
||||
threads.iter().map(|(thread, y)| BalloonItem::Thread { thread, page: 0, anchor: Pos2::new(30.0, *y) }).collect();
|
||||
let mut state = shown_state.borrow_mut();
|
||||
let out = CommentBalloons::new("Comments", &pages, &items, &mut state).place(place).now(Some(3_600)).show(ui);
|
||||
let out = CommentBalloons::new("Comments", &pages, &items, &mut state).place(place).now(Some(3_600)).read_only(read_only).show(ui);
|
||||
shown_edits.borrow_mut().extend(out.edits);
|
||||
*shown_cards.borrow_mut() = out.cards;
|
||||
});
|
||||
@@ -122,6 +127,26 @@ fn selecting_a_card_and_posting_a_reply_report_the_matching_edits() {
|
||||
assert!(shown.state.borrow().reply.is_empty(), "a posted reply clears the binding");
|
||||
}
|
||||
|
||||
/// Guards `CommentBalloons::read_only`: while comments cannot change, a selected card takes no typing, as the panel's
|
||||
/// rows do: it shows no reply field, and text typed after a click on it reaches no reply.
|
||||
#[trial]
|
||||
fn a_read_only_card_takes_no_typing() {
|
||||
let threads = vec![(thread(1, "First"), 100.0)];
|
||||
let selected = CommentsPanelState { selected: Some(ThreadId(1)), ..CommentsPanelState::default() };
|
||||
let mut shown = Shown::with(threads, selected, BalloonPlace::Column, room(), Direction::Ltr, true);
|
||||
let words = CommentsWords::default();
|
||||
assert!(shown.fixture.by_label(words.reply.as_str()).is_none(), "a read-only card shows no reply field");
|
||||
let card = shown.card(1);
|
||||
shown.fixture.click_at(card.center()).settle();
|
||||
shown.fixture.type_text("Thanks").settle();
|
||||
assert!(shown.state.borrow().reply.is_empty(), "typing reaches no reply: {:?}", shown.state.borrow().reply);
|
||||
assert!(
|
||||
!shown.edits.borrow().iter().any(|edit| matches!(edit, CommentEdit::Reply { .. })),
|
||||
"no reply is reported: {:?}",
|
||||
shown.edits.borrow()
|
||||
);
|
||||
}
|
||||
|
||||
/// The selected card's buttons: Reply puts the focus in the reply field, Resolve and Reopen report `Resolve`, Delete reports
|
||||
/// `Delete` of the whole thread.
|
||||
#[trial]
|
||||
|
||||
@@ -359,6 +359,10 @@ pub struct TextRuler<'a> {
|
||||
/// The column gaps as (start, end) points from the column's start edge, painted and dragged by their edges.
|
||||
#[prop]
|
||||
gaps: &'a [(f32, f32)],
|
||||
/// Whether the gaps' edges take a drag, with the resize cursor (the default). Off, the gaps are shaded only, with no
|
||||
/// grip: the document's column settings fix them.
|
||||
#[prop]
|
||||
gaps_draggable: bool,
|
||||
/// The screen x where the ruler's zero sits: a page-wide ruler is measured from the page's text origin. Unset, zero
|
||||
/// is the strip's start edge. Given against the screen so the corner square, which only the ruler places, does not
|
||||
/// enter the caller's arithmetic.
|
||||
@@ -396,6 +400,7 @@ impl<'a> TextRuler<'a> {
|
||||
width: if width.is_finite() { width.max(0.0) } else { 0.0 },
|
||||
columns: &[],
|
||||
gaps: &[],
|
||||
gaps_draggable: true,
|
||||
origin: None,
|
||||
extent: None,
|
||||
unit: DocUnit::points(),
|
||||
@@ -554,7 +559,7 @@ impl Component for TextRuler<'_> {
|
||||
.focus_shape(FocusShape::Rect)
|
||||
.value_part();
|
||||
}
|
||||
for (index, gap) in self.gaps.iter().enumerate() {
|
||||
for (index, gap) in self.gaps.iter().enumerate().filter(|_| self.gaps_draggable) {
|
||||
for edge in [GapEdge::End, GapEdge::Start] {
|
||||
cx.part(GAP.at(gap_part(index, edge)), layout.shapes.gap_edge(&layout.g, *gap, edge))
|
||||
.sense(Sense::DRAG)
|
||||
|
||||
@@ -295,6 +295,10 @@ impl TextRuler<'_> {
|
||||
/// step unless Alt is held. An edge stays on its side of the other edge of the gap and within the strip, and a
|
||||
/// press released without a drag reports nothing.
|
||||
fn run_gaps(&mut self, cx: &mut Cx<'_, Self>, g: &super::Geometry, step: f32, held: &mut Held) {
|
||||
// Fixed gaps declared no edge parts.
|
||||
if !self.gaps_draggable {
|
||||
return;
|
||||
}
|
||||
let (lo, hi) = g.span();
|
||||
for (index, gap) in self.gaps.iter().copied().enumerate() {
|
||||
for edge in [GapEdge::End, GapEdge::Start] {
|
||||
|
||||
@@ -111,6 +111,14 @@ fn two_column_gaps(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
TextRuler::new("Ruler", Bind::bound(&mut *values), COLUMN).unit(inches()).gaps(&TWO_GAPS).show(ui).into()
|
||||
}
|
||||
|
||||
/// Fixed column gaps: shaded as on any ruler, with no grip and no resize cursor, where the document's column settings
|
||||
/// fix the gaps.
|
||||
#[story(TextRuler<'static>, covers = [], drive = Drive::Never)]
|
||||
fn fixed_column_gaps(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("values", RulerValues::default());
|
||||
TextRuler::new("Ruler", Bind::bound(&mut *values), COLUMN).unit(inches()).gaps(&TWO_GAPS).gaps_draggable(false).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(TextRuler<'static>, covers = [], drive = Drive::Never)]
|
||||
fn three_column_gaps(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("values", RulerValues::default());
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
//! Stories of the canvas family.
|
||||
|
||||
use super::{Canvas, ContextSource, CropOverlay, MiddleButton, NavigationOptions, NoTool, ToolHost, WheelScheme, tool_pass};
|
||||
use super::{
|
||||
Canvas, CanvasTool, ContextSource, CropOverlay, MiddleButton, NavigationOptions, NoTool, ToolAction, ToolContext, ToolHost, ToolPath,
|
||||
ToolPointer, WheelScheme, tool_pass,
|
||||
};
|
||||
use crate::buttons::Button;
|
||||
use crate::canvas::testing::canvas_story::{StoryDocument, show_document};
|
||||
use crate::contract::{Bind, BodyCx, CanvasGesture, Gap, Sampler as _, Show as _, ShowContainer as _, clicked};
|
||||
use crate::contract::{Bind, BodyCx, CanvasGesture, Gap, Sampler as _, Show as _, ShowContainer as _, clicked, tooltip};
|
||||
use crate::dialog::Dialog;
|
||||
use crate::display::Text;
|
||||
use crate::layout_components::Stack;
|
||||
use crate::primitives::{EditorPurpose, EditorState};
|
||||
use crate::primitives::{Draw, EditorPurpose, EditorState};
|
||||
use crate::runtime::access::Role;
|
||||
use crate::runtime::env::Env;
|
||||
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, pointer, stage, story};
|
||||
use craft_behavior::geometry::CropBox;
|
||||
use craft_behavior::kurbo::{Point, Rect as DocRect};
|
||||
use craft_behavior::{EditorInput, TextPos};
|
||||
use craft_behavior::{CancelReason, EditorInput, TextPos};
|
||||
use egui::{Key, Modifiers, Rect, Ui, vec2};
|
||||
|
||||
/// The zoomed story's zoom, in percent of one device pixel per document pixel.
|
||||
@@ -180,6 +183,54 @@ fn editor_part(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
shown.output.into()
|
||||
}
|
||||
|
||||
/// A tool that asks for a pointer tip on every hover and takes presses, as a document editor's text tool tips a link.
|
||||
struct TippingTool;
|
||||
|
||||
impl CanvasTool for TippingTool {
|
||||
fn hover(&mut self, _: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
cx.tip("Ctrl+click to follow the link");
|
||||
}
|
||||
|
||||
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, _: CancelReason, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Command("the Follow Link command")
|
||||
}
|
||||
}
|
||||
|
||||
/// Rests the pointer on the canvas's centre past the tooltip delay, so the tool's tip shows.
|
||||
fn rest_on_centre(fixture: &mut Fixture) {
|
||||
let Some(at) = canvas_centre(fixture) else { return };
|
||||
fixture.frame(vec![pointer::moved(at)]);
|
||||
fixture.advance(tooltip::DELAY);
|
||||
fixture.settle();
|
||||
}
|
||||
|
||||
/// A tool's pointer tip ([`ToolContext::tip`]): it shows at the pointer after the tooltip delay while the pointer rests
|
||||
/// on the canvas, and a press hides it.
|
||||
#[story(Canvas, covers = [], drive = Drive::Custom(rest_on_centre))]
|
||||
fn tool_tip(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let room = stage(ui);
|
||||
let view = StoryDocument::STANDARD.view(room, ui.pixels_per_point(), 100.0);
|
||||
let shown = Canvas::new("Document").view(view).show_at(ui, room, |ui, body| {
|
||||
show_document(ui, body.rect, &StoryDocument::STANDARD);
|
||||
if let Some(pass) = tool_pass(&body.env) {
|
||||
let _ = ToolHost::new().run(ui, &pass, &mut TippingTool);
|
||||
}
|
||||
});
|
||||
shown.output.into()
|
||||
}
|
||||
|
||||
/// The canvas menu asked for with Shift+F10: the line under the canvas says how the tool host reported the request
|
||||
/// ([`ContextRequest::source`](super::ContextRequest::source)).
|
||||
#[story(Canvas, covers = [], drive = Drive::Custom(press_menu_key))]
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! them to document units with the canvas's view ([`ToolContext::space`]), so it holds no copy of the view.
|
||||
|
||||
use super::{CanvasSpace, MARCH_SECONDS, MARCH_TICK, Snap, ToolPath, march_shift};
|
||||
use crate::contract::{Pattern, PatternKind, PatternProbe};
|
||||
use crate::contract::{Pattern, PatternKind, PatternProbe, Tooltip};
|
||||
use crate::primitives::{ContentPainterCx, Draw};
|
||||
use crate::runtime::env::{Direction, Env, Label, MotionPolicy, PointSize, UnitWords, Units, WordSet, Words};
|
||||
use crate::runtime::motion::loop_phase;
|
||||
@@ -222,6 +222,8 @@ pub(crate) struct ToolRequests {
|
||||
pub(crate) pan: Option<bool>,
|
||||
/// Rows the Show Transformation Values gate never silences, from [`ToolContext::hud`].
|
||||
pub(crate) hud: Option<Vec<(Label, String)>>,
|
||||
/// The pointer tip, from [`ToolContext::tip`].
|
||||
pub(crate) tip: Option<Tooltip>,
|
||||
}
|
||||
|
||||
/// What a tool sees and may ask for during a call.
|
||||
@@ -527,6 +529,14 @@ impl<'a> ToolContext<'a> {
|
||||
self.requests.hud = Some(rows);
|
||||
}
|
||||
|
||||
/// A tip to show at the pointer where it rests (a link's address and the key that follows it), asked from
|
||||
/// [`CanvasTool::hover`]. The host shows it through the framework tooltip, with its look and delay, while no
|
||||
/// gesture runs, and drops it when the pointer leaves the canvas or a press starts. The last request of a pass
|
||||
/// wins, and a hover that asks for none drops the tip.
|
||||
pub fn tip(&mut self, tip: impl Into<Tooltip>) {
|
||||
self.requests.tip = Some(tip.into());
|
||||
}
|
||||
|
||||
/// Asks for another pass (an animation, a held key that repeats).
|
||||
pub fn request_repaint(&mut self) {
|
||||
self.requests.repaint = true;
|
||||
|
||||
@@ -62,7 +62,9 @@
|
||||
//! host ends such keys where it drops injected input (a withdrawal, a focus loss, a cancel, the end of the session).
|
||||
//!
|
||||
//! Readouts: a tool's [`ToolContext::readout`] rows paint only while the root env's `ShowReadouts` holds; its
|
||||
//! [`ToolContext::hud`] rows always paint. A secondary press the tool did not take is reported in
|
||||
//! [`ToolContext::hud`] rows always paint. A tool's [`ToolContext::tip`] from `hover` shows at the pointer through the
|
||||
//! framework tooltip, with its look and delay, while no gesture runs; the pointer leaving or a press drops it, and
|
||||
//! [`ToolHostResponse::tip`] repeats it as data. A secondary press the tool did not take is reported in
|
||||
//! [`ToolHostResponse::context`], and so are a secondary click with the momentary Hand (whose drag pans) and the Menu
|
||||
//! key.
|
||||
//!
|
||||
@@ -91,7 +93,7 @@ use super::zoom_motion::{self, Steer};
|
||||
use super::{CanvasSpace, Snap, ToolPass, context_click};
|
||||
use crate::canvas_controls::paint_lines;
|
||||
use crate::canvas_controls::{SmartGuides, SmartLine};
|
||||
use crate::contract::{Component, Meta as _};
|
||||
use crate::contract::{Component, Meta as _, Tooltip, tooltip};
|
||||
use crate::primitives::{ContentPainterCx, Draw, DrawEnv, PaintRecord};
|
||||
use crate::runtime::access::{self, Name, Role, SubDecl, SubNode};
|
||||
use crate::runtime::commands;
|
||||
@@ -262,6 +264,9 @@ pub struct ToolHostResponse {
|
||||
pub context: Option<ContextRequest>,
|
||||
/// The document distance the view centre moved this pass from a `pan_view`, after the Overscroll clamp.
|
||||
pub pan: Option<ViewPan>,
|
||||
/// The text of the tip the tool asked for at the pointer ([`ToolContext::tip`]) while it stands: the host shows it
|
||||
/// after the tooltip delay; this is the data for automation.
|
||||
pub tip: Option<Label>,
|
||||
}
|
||||
|
||||
/// Where and how the app opens its canvas menu, from [`ToolHostResponse::context`].
|
||||
@@ -357,6 +362,9 @@ struct HostState {
|
||||
time: Option<f64>,
|
||||
/// The open secondary press the tool refused or the momentary Hand took: its release asks for the canvas menu.
|
||||
secondary: Option<SecondaryPress>,
|
||||
/// The tip the tool's last hover asked for: the tool answers again only when the pointer moves, so it stands
|
||||
/// while the pointer rests, until a press, a gesture or the pointer leaving drops it.
|
||||
tip: Option<Tooltip>,
|
||||
}
|
||||
|
||||
fn state_id(canvas: Id) -> Id {
|
||||
@@ -556,6 +564,7 @@ impl<'m> ToolHost<'m> {
|
||||
cancelled: false,
|
||||
ending: None,
|
||||
hover_scrolls: false,
|
||||
hovered: false,
|
||||
};
|
||||
run.call(None, |tool, cx| tool.each_pass(cx));
|
||||
run.hover_scrolls = run.pick_as(None).autoscrolls_on_hover();
|
||||
@@ -570,7 +579,7 @@ impl<'m> ToolHost<'m> {
|
||||
run.keys(&ctx, pass.id, env.direction.is_rtl());
|
||||
run.menu_key();
|
||||
}
|
||||
let Run { mut response, requests, momentary: momentary_tool, .. } = run;
|
||||
let Run { mut response, requests, momentary: momentary_tool, hovered, .. } = run;
|
||||
let before = space.map(|space| space.target());
|
||||
if let Some(past) = response.past_edge {
|
||||
let step = frame_step(input.time - state.time.unwrap_or(input.time));
|
||||
@@ -624,6 +633,17 @@ impl<'m> ToolHost<'m> {
|
||||
}
|
||||
};
|
||||
paint_tool(ui, &env, effective, context());
|
||||
// The tip stands while the pointer rests on the background with no gesture running; each hover answers anew.
|
||||
let resting = matches!(phase, PressPhase::Hover) && state.gesture.is_none() && !disabled;
|
||||
if hovered {
|
||||
state.tip = requests.tip;
|
||||
}
|
||||
if !resting {
|
||||
state.tip = None;
|
||||
}
|
||||
let tip_at = current.filter(|_| resting).map(|pointer| pointer.pos);
|
||||
tooltip::at_pointer(ui, pass.id, state.tip.as_ref(), tip_at, phase.is_press() || state.gesture.is_some());
|
||||
response.tip = state.tip.as_ref().map(|tip| tip.spec().text.clone());
|
||||
if pass.snap.as_ref().is_some_and(|snap| snap.options().smart_guides) {
|
||||
paint_smart_lines(ui, &env, rect, space, &requests.snapped, smart_guide_color);
|
||||
}
|
||||
@@ -922,6 +942,8 @@ struct Run<'a, 't> {
|
||||
ending: Option<GestureId>,
|
||||
/// The tool autoscrolls on hover, in its state after `each_pass`.
|
||||
hover_scrolls: bool,
|
||||
/// The tool had a hover over the canvas this pass: its tip request, or none, replaces the standing tip.
|
||||
hovered: bool,
|
||||
/// The Command stand-in.
|
||||
command: Option<&'a mut (dyn CanvasTool + 't)>,
|
||||
/// The Alt stand-in.
|
||||
@@ -958,6 +980,7 @@ impl<'a, 't: 'a> Run<'a, 't> {
|
||||
self.requests.readout = asked.readout.or(self.requests.readout.take());
|
||||
self.requests.repaint |= asked.repaint;
|
||||
self.requests.hud = asked.hud.or(self.requests.hud.take());
|
||||
self.requests.tip = asked.tip.or(self.requests.tip.take());
|
||||
self.requests.snapped.extend(asked.snapped);
|
||||
self.requests.pan = asked.pan.or(self.requests.pan);
|
||||
if let Some(at) = asked.autoscroll_at {
|
||||
@@ -1206,6 +1229,7 @@ impl<'a, 't: 'a> Run<'a, 't> {
|
||||
|
||||
fn hover(&mut self, pointer: ToolPointer) {
|
||||
self.call(Some(pointer), |tool, cx| tool.hover(&pointer, cx));
|
||||
self.hovered = true;
|
||||
if let Some(past) = self.hover_edge(pointer.pos) {
|
||||
self.response.past_edge = Some(past);
|
||||
}
|
||||
|
||||
@@ -4,9 +4,12 @@
|
||||
use craft_behavior::kurbo::{Point, Size};
|
||||
use craft_behavior::{CanvasView, EditorInput, Proposal, TextPos};
|
||||
use craft_ui::canvas::{Canvas, tool_pass};
|
||||
use craft_ui::contract::ShowContainer as _;
|
||||
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft_ui::primitives::{EditorPurpose, EditorState};
|
||||
use craft_ui::runtime::access::Role;
|
||||
use craft_ui::runtime::focus;
|
||||
use craft_ui::testing::focus::egui_focused;
|
||||
use craft_ui::text::TextField;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Event, Id, ImeEvent, Key, Modifiers, Rect, Vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
@@ -84,3 +87,60 @@ fn a_canvas_editor_takes_focus_on_a_background_press_and_hands_its_inputs_to_the
|
||||
"typed text, a move and a composition reach the body's pass in the order typed, once each: {inputs:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Guards `EditorHandle::report` for an editor whose view describes its text (a page editor): its report has no lines,
|
||||
/// so its caret reaches the input method and no empty text is announced on the canvas's node.
|
||||
#[trial]
|
||||
fn an_editor_report_with_no_lines_reaches_the_input_method_and_publishes_no_text() {
|
||||
let id: Rc<Cell<Option<Id>>> = Rc::default();
|
||||
let shown = Rc::clone(&id);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let view = CanvasView::new(room, Point::new(PAGE.width / 2.0, PAGE.height / 2.0), 1.0);
|
||||
let output = canvas(view).show_at(ui, room, |ui, body| {
|
||||
let Some(pass) = tool_pass(&body.env) else { return };
|
||||
if let Some(editor) = &pass.editor {
|
||||
let caret = Rect::from_min_size(body.rect.min + CARET, Vec2::new(0.0, 16.0));
|
||||
editor.report(ui.ctx(), EditorState::new(caret, &[], TextPos::new(0, 0)));
|
||||
}
|
||||
});
|
||||
shown.set(Some(output.output.response.id));
|
||||
});
|
||||
fixture.room(ROOM);
|
||||
fixture.settle();
|
||||
fixture.click_at((ROOM / 2.0).to_pos2());
|
||||
let canvas_id = id.get().expect("the canvas showed");
|
||||
assert!(fixture.ime().is_some_and(|ime| ime.caret.is_finite()), "the caret reaches the input method");
|
||||
assert_ne!(fixture.tree().value(canvas_id), Some(""), "no empty text is announced on the canvas");
|
||||
assert_eq!(fixture.tree().text_selection(canvas_id), None, "and no caret in it");
|
||||
}
|
||||
|
||||
/// Guards `focus::has` on a canvas: its editor part's widget holds egui focus under its own id, so a query of egui
|
||||
/// focus by the canvas's id would answer no while the canvas has focus.
|
||||
#[trial]
|
||||
fn focus_has_answers_for_a_canvas_whose_editor_part_holds_focus() {
|
||||
let ids: Rc<Cell<Option<(Id, Id)>>> = Rc::default();
|
||||
let shown = Rc::clone(&ids);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut notes = String::new();
|
||||
let field = TextField::new("Notes", Bind::bound(&mut notes)).show(ui).response;
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let view = CanvasView::new(room, Point::new(PAGE.width / 2.0, PAGE.height / 2.0), 1.0);
|
||||
let output = canvas(view).show_at(ui, room, |_, _| {});
|
||||
shown.set(Some((output.output.response.id, field.id)));
|
||||
});
|
||||
fixture.room(ROOM);
|
||||
fixture.settle();
|
||||
let (canvas_id, field_id) = ids.get().expect("the canvas and the field showed");
|
||||
assert!(!focus::has(fixture.ctx(), canvas_id), "nothing has focus yet");
|
||||
|
||||
let canvas_rect = fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas").rect;
|
||||
fixture.click_at(canvas_rect.center());
|
||||
assert!(focus::has(fixture.ctx(), canvas_id), "the canvas has focus while its editor part holds it");
|
||||
assert!(!focus::has(fixture.ctx(), field_id), "the field does not");
|
||||
|
||||
let field_rect = fixture.by_role(Role::TEXT_INPUT).into_iter().next().expect("the field").rect;
|
||||
fixture.click_at(field_rect.center());
|
||||
assert!(focus::has(fixture.ctx(), field_id), "a click on the field moves focus there");
|
||||
assert!(!focus::has(fixture.ctx(), canvas_id), "and the canvas has it no more");
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ use craft_ui::canvas::{
|
||||
NavigationOptions, Snap, StandInKey, ToolAction, ToolClaims, ToolContext, ToolHost, ToolInput, ToolKey, ToolPath, ToolPointer, ToolRegion,
|
||||
canvas_space, tool_pass,
|
||||
};
|
||||
use craft_ui::contract::tooltip::DELAY;
|
||||
use craft_ui::contract::{Bind, Lazy, Sampler as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::dialog::Dialog;
|
||||
use craft_ui::display::Text;
|
||||
@@ -1590,6 +1591,66 @@ fn show_transformation_values_gates_the_readouts_paint_and_never_the_hud() {
|
||||
assert_eq!(readout_during_a_drag(true, Some(false)), (true, true), "a hud paints with Show Transformation Values off");
|
||||
}
|
||||
|
||||
/// The tip [`Tipping`] asks for.
|
||||
const TIP: &str = "Follow the link";
|
||||
|
||||
/// A tool that asks for a tip on every hover and claims every press.
|
||||
struct Tipping;
|
||||
|
||||
impl CanvasTool for Tipping {
|
||||
fn hover(&mut self, _: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
cx.tip(TIP);
|
||||
}
|
||||
|
||||
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, _: CancelReason, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Command("the Follow command")
|
||||
}
|
||||
}
|
||||
|
||||
/// Guards the host's tip rule: the tool answers only when the pointer moves, so the host must keep its tip while the
|
||||
/// pointer rests through the tooltip delay, and drop it at a press.
|
||||
#[trial]
|
||||
fn a_hovering_tools_tip_shows_at_the_pointer_and_a_press_hides_it() {
|
||||
let reported = Rc::new(Cell::new(false));
|
||||
let seen = Rc::clone(&reported);
|
||||
let tool = RefCell::new(Tipping);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let mut reply = None;
|
||||
let _ = Canvas::new("Document").document(DOCUMENT).view(CanvasView::new(room, Point::new(600.0, 450.0), 0.5)).show(ui, |ui, body| {
|
||||
if let Some(pass) = tool_pass(&body.env) {
|
||||
reply = Some(ToolHost::new().run(ui, &pass, &mut *tool.borrow_mut()));
|
||||
}
|
||||
});
|
||||
seen.set(reply.unwrap_or_default().tip.is_some());
|
||||
});
|
||||
fixture.settle();
|
||||
let centre = fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas").center();
|
||||
fixture.frame(vec![pointer::moved(centre)]);
|
||||
fixture.advance(DELAY);
|
||||
fixture.settle();
|
||||
let tip = fixture.texts().iter().find(|run| run.text == TIP).map(|run| run.rect);
|
||||
let tip = tip.expect("the tip shows once the pointer rested for the tooltip delay");
|
||||
assert!(tip.min.y >= centre.y, "the tip hangs below the pointer: {tip:?} for {centre:?}");
|
||||
assert!(reported.get(), "the host reports the standing tip");
|
||||
fixture.frame(vec![pointer::press(centre)]);
|
||||
fixture.settle();
|
||||
assert!(!fixture.texts().iter().any(|run| run.text == TIP), "a press hides the tip");
|
||||
assert!(!reported.get(), "a press drops the tip");
|
||||
}
|
||||
|
||||
/// A tool that keeps the points of its gesture: the press and every drag.
|
||||
#[derive(Default)]
|
||||
struct Trail {
|
||||
|
||||
@@ -126,6 +126,9 @@ impl EditorHandle {
|
||||
|
||||
/// The one editor report path: notes the caret, the composition, the undo state and the surrounding text with the
|
||||
/// IME engine, and returns the text facts when AccessKit reads the part.
|
||||
///
|
||||
/// A report with no lines has no text facts: an editor whose view describes its text (a page editor, through the
|
||||
/// page view's describer) reports its caret to the input method only, and no caret is announced in an empty text.
|
||||
fn note(&self, ctx: &egui::Context, state: EditorState<'_>) -> Option<TextFacts> {
|
||||
let masked = self.purpose == EditorPurpose::Password;
|
||||
if self.focused {
|
||||
@@ -133,7 +136,7 @@ impl EditorHandle {
|
||||
}
|
||||
let surrounding = state.surrounding.as_ref().map(|(epoch, report)| (*epoch, report));
|
||||
ime::note_editor(ctx, self.widget, state.composing, (state.can_undo, state.can_redo), surrounding);
|
||||
if !text_access::exposed(ctx, self.widget) {
|
||||
if state.lines.is_empty() || !text_access::exposed(ctx, self.widget) {
|
||||
return None;
|
||||
}
|
||||
let lines = state
|
||||
|
||||
@@ -178,6 +178,7 @@ pub(crate) fn run(core: &super::CxCore<'_>, input: TipIn<'_>) {
|
||||
wants_input: hovered,
|
||||
pressed: member_pressed.unwrap_or_else(|| core.press.phase.is_press()),
|
||||
subject,
|
||||
describes: subject.is_none().then_some(core.id),
|
||||
};
|
||||
show_tip(call);
|
||||
}
|
||||
@@ -203,6 +204,39 @@ pub fn attach(response: &egui::Response, tooltip: &Tooltip) {
|
||||
wants_input: response.hovered() || response.has_focus(),
|
||||
pressed: crate::runtime::egui::response::is_pressed(response),
|
||||
subject: None,
|
||||
describes: Some(response.id),
|
||||
};
|
||||
show_tip(call);
|
||||
}
|
||||
|
||||
/// Shows `tip` at the pointer for a surface whose tips have no part of their own (a canvas tool's hover tip): the same
|
||||
/// delay, grace, look and hiding as a component's tooltip, placed at the pointer whatever the tip's `at` says.
|
||||
///
|
||||
/// `owner` is the component whose memory keeps the timer. `at` is where the pointer rests in `ui`'s layer, `None` once
|
||||
/// it left; `pressed` is a press or drag that hides the tip. With no tip, a tip shown hides.
|
||||
pub fn at_pointer(ui: &Ui, owner: egui::Id, tip: Option<&Tooltip>, at: Option<egui::Pos2>, pressed: bool) {
|
||||
let ctx = ui.ctx();
|
||||
let env = Env::of(ui);
|
||||
let spec = tip.map(|tip| {
|
||||
let mut spec = tip.spec().clone();
|
||||
spec.at = TooltipAt::Pointer;
|
||||
spec
|
||||
});
|
||||
let text = spec.as_ref().map(|spec| spec_text(&env.view(), spec, true));
|
||||
let call = TipCall {
|
||||
ctx,
|
||||
owner,
|
||||
id: sub(owner, "pointer tip"),
|
||||
env: &env,
|
||||
layer: ui.layer_id(),
|
||||
rect: Rect::from_center_size(at.unwrap_or_default(), Vec2::ZERO),
|
||||
text,
|
||||
rich: None,
|
||||
spec,
|
||||
wants_input: at.is_some(),
|
||||
pressed,
|
||||
subject: None,
|
||||
describes: Some(owner),
|
||||
};
|
||||
show_tip(call);
|
||||
}
|
||||
@@ -225,10 +259,12 @@ struct TipCall<'a> {
|
||||
wants_input: bool,
|
||||
pressed: bool,
|
||||
subject: Option<PartRef>,
|
||||
/// The node the tooltip describes; `None` for a part's tooltip.
|
||||
describes: Option<egui::Id>,
|
||||
}
|
||||
|
||||
fn show_tip(call: TipCall<'_>) {
|
||||
let TipCall { ctx, owner, id, env, layer: rect_layer, rect, text, rich, spec, wants_input, pressed, subject } = call;
|
||||
let TipCall { ctx, owner, id, env, layer: rect_layer, rect, text, rich, spec, wants_input, pressed, subject, describes } = call;
|
||||
let state_id = sub(id, "tip_state");
|
||||
let has_content = text.is_some() || rich.is_some();
|
||||
// A component with no tooltip content and no timer or fading layer left from before has nothing to advance.
|
||||
@@ -298,9 +334,9 @@ fn show_tip(call: TipCall<'_>) {
|
||||
None => {
|
||||
if let Some(text) = &text {
|
||||
let tip = TipText { common: Common::default(), text }.id_salt(tip_id).show(ui);
|
||||
if subject.is_none() {
|
||||
if let Some(node) = describes {
|
||||
// The described control's node was written earlier in the pass; the relation joins it.
|
||||
let patch = LabelPatch::DescribedBy { node: id, label: tip.id };
|
||||
let patch = LabelPatch::DescribedBy { node, label: tip.id };
|
||||
crate::runtime::egui::access::write_label_patch(ctx, &patch);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -572,6 +572,12 @@ pub fn request(ctx: &Context, target: FocusTarget) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether focus is on the component `id` or on one of its parts (a canvas's editor part), from the focus record of
|
||||
/// the stop focus is on. An app asks it of a component it shows, such as whether its document canvas has focus.
|
||||
pub fn has(ctx: &Context, id: Id) -> bool {
|
||||
focused_rec(ctx).is_some_and(|rec| rec.stop.id == id)
|
||||
}
|
||||
|
||||
/// Applies `target` now, for an AccessKit `Focus` action, which moves focus in the pass that carries it.
|
||||
pub(crate) fn request_now(ctx: &Context, target: FocusTarget) {
|
||||
let acts = with(ctx, |state| state.apply_target(target));
|
||||
|
||||
Reference in New Issue
Block a user