pdf-canvas-w3: net change of 2 commits

- pdf-canvas-w3: written from its sheet
- pdf-canvas-w3: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor
2026-11-18 05:02:29 -05:00
parent 5bd3eb6976
commit ff5f067baa
11 changed files with 398 additions and 79 deletions
+21 -4
View File
@@ -237,6 +237,12 @@ impl<O> Shape<O> {
self
}
/// The shape's stacking order among shapes of its priority: the higher order wins before the nearest centre.
pub const fn stacking(mut self, order: u32) -> Self {
self.stacking = order;
self
}
/// The shape lies in the body layer's space.
pub const fn local(mut self, local: bool) -> Self {
self.local = local;
@@ -276,8 +282,8 @@ pub struct Winner<O> {
pub local: bool,
}
/// The winner among `shapes` at `point`: stack position first, then level, sub-level, the nearest centre, the last
/// registered. A press considers only shapes that sense a click or a drag.
/// The winner among `shapes` at `point`: stack position first, then level, sub-level, stacking order, the nearest
/// centre, the last registered. A press considers only shapes that sense a click or a drag.
pub fn resolve<O: Copy>(shapes: &[Shape<O>], point: Pos2, what: ResolveFor) -> Option<Winner<O>> {
resolve_mapped(shapes, point, what, |_| point)
}
@@ -292,8 +298,8 @@ pub fn resolve_mapped<O: Copy>(shapes: &[Shape<O>], point: Pos2, what: ResolveFo
.filter(|(_, shape)| what == ResolveFor::Hover || shape.sense.takes_press())
.filter(|(_, shape)| shape.hits(at(shape)))
.max_by(|(ia, a), (ib, b)| {
(a.position, a.priority.level, a.priority.sub)
.cmp(&(b.position, b.priority.level, b.priority.sub))
(a.position, a.priority.level, a.priority.sub, a.stacking)
.cmp(&(b.position, b.priority.level, b.priority.sub, b.stacking))
.then_with(|| distance(b).partial_cmp(&distance(a)).unwrap_or(Ordering::Equal))
.then(ia.cmp(ib))
})
@@ -333,4 +339,15 @@ mod tests {
let tie = [shape(big(), Sense::CLICK, 1, 0, HitLevel::Body, 0), shape(big(), Sense::CLICK, 2, 0, HitLevel::Body, 0)];
assert_eq!(owner(&tie), Some(2));
}
#[test]
fn stacked_parts_of_one_priority_rank_by_their_order_before_the_nearest_centre() {
let at = pos2(50.0, 50.0);
let owner = |shapes: &[Shape<u8>]| resolve(shapes, at, ResolveFor::Press).map(|w| w.owner);
let near = || shape(rect(40.0, 40.0, 20.0, 20.0), Sense::CLICK, 1, 0, HitLevel::Body, 0);
let far = || shape(rect(0.0, 0.0, 200.0, 200.0), Sense::CLICK, 2, 0, HitLevel::Body, 0);
assert_eq!(owner(&[far(), near()]), Some(1), "unstacked, the nearer centre wins");
assert_eq!(owner(&[far().stacking(1), near()]), Some(2), "the higher stacking order wins though the press is nearer the other's centre");
assert_eq!(owner(&[near().stacking(1), far().stacking(1)]), Some(1), "one order: the nearest centre decides");
}
}
+14
View File
@@ -275,6 +275,20 @@ mod tests {
assert_eq!(neither.bottom(), BOUNDS.bottom(), "fits neither way: slides up to stay inside");
}
#[test]
fn an_overlay_with_no_room_on_its_side_opens_on_the_other() {
let size = Vec2::new(200.0, 80.0);
let low = rect(300.0, 540.0, 100.0, 30.0);
let placed = place(&PlaceRequest::new(low, size, BOUNDS).side(Side::Below).gap(4.0));
assert_eq!(placed.side, Side::Above, "no room below the anchor: {placed:?}");
assert!(placed.rect.bottom() <= low.top(), "above the anchor: {placed:?}");
assert!(BOUNDS.contains_rect(placed.rect), "{placed:?}");
let high = rect(300.0, 100.0, 100.0, 30.0);
let placed = place(&PlaceRequest::new(high, size, BOUNDS).side(Side::Below).gap(4.0));
assert_eq!(placed.side, Side::Below, "room below: {placed:?}");
assert!(placed.rect.top() >= high.bottom(), "below the anchor: {placed:?}");
}
#[test]
fn an_overlay_at_least_as_wide_as_its_anchor_takes_that_width_below_it_but_not_beside_it() {
let field = rect(100.0, 100.0, 300.0, 24.0);
+111 -7
View File
@@ -474,6 +474,11 @@ struct Open<T> {
dragging: bool,
/// Moved past slop on a target that senses no drag: the click is gone and nothing starts.
abandoned: bool,
/// Moved past slop in this pass on a target that clicks and passes its drag (`Sense::PASSES_DRAG`), with the
/// pointer at the pass's end: no click and no drag until [`PressMachine::hand_over`] gives the press its new
/// target. The next pass abandons a press no shape took.
passing: Option<Pos2>,
/// A pass reported the press: later passes within slop report `Held`, not `Down`.
reported: bool,
/// A pass reported the drag's start: later passes report `Drag`.
@@ -485,14 +490,14 @@ struct Open<T> {
}
impl<T> Open<T> {
/// A phase before the release is still to be reported.
/// A phase before the release is still to be reported, or the press waits for its hand-over.
fn owes_phase(&self) -> bool {
!self.reported || (self.dragging && !self.drag_reported)
!self.reported || (self.dragging && !self.drag_reported) || self.passing.is_some()
}
/// A release now is a click.
fn clicks(&self) -> bool {
!self.dragging && !self.abandoned && self.sense.contains(Sense::CLICK)
!self.dragging && !self.abandoned && self.passing.is_none() && self.sense.contains(Sense::CLICK)
}
}
@@ -541,6 +546,14 @@ impl<T: Copy> PressMachine<T> {
let mut pos = input.pos;
let mut released: Option<(T, PressStart, Pos2, bool, bool)> = None;
let mut cancelled: Option<(T, PressStart, PressCancel)> = None;
// A press passed in the last pass that no shape took is abandoned; that pass reported its `Down`.
if let Some(open) = &mut self.open
&& open.passing.is_some()
{
open.passing = None;
open.abandoned = true;
open.reported = true;
}
if let Some(open) = self.open
&& let Some((at, click)) = open.released_at
&& !open.owes_phase()
@@ -560,10 +573,13 @@ impl<T: Copy> PressMachine<T> {
&& open.released_at.is_none()
&& !open.dragging
&& !open.abandoned
&& open.passing.is_none()
&& at.distance(open.start.origin) > input.slop
{
if open.sense.contains(Sense::DRAG) {
open.dragging = true;
} else if open.sense.contains(Sense::CLICK | Sense::PASSES_DRAG) {
open.passing = Some(at);
} else {
open.abandoned = true;
}
@@ -610,6 +626,7 @@ impl<T: Copy> PressMachine<T> {
start: PressStart::new(at, button, time, clicks),
dragging: false,
abandoned: false,
passing: None,
reported: false,
drag_reported: false,
released_at: None,
@@ -649,6 +666,9 @@ impl<T: Copy> PressMachine<T> {
};
}
let Some(open) = self.open.as_mut() else { return PressStep::default() };
if let Some(at) = &mut open.passing {
*at = pos;
}
let phase = if !open.reported {
PressPhase::Down { start: open.start }
} else if open.dragging && !open.drag_reported {
@@ -659,16 +679,32 @@ impl<T: Copy> PressMachine<T> {
} else {
PressPhase::Held { start: open.start, pos }
};
open.reported = true;
PressStep { target: Some(open.target), phase: Some(phase), dragging: open.drag_reported, activated: None, passes: None }
// A passing press owes its `Down` to the shape `hand_over` gives it when this pass is its first.
if open.passing.is_none() {
open.reported = true;
}
let passes = open.passing.map(|_| open.start);
PressStep { target: Some(open.target), phase: Some(phase), dragging: open.drag_reported, activated: None, passes }
}
/// Makes `target` the open press's target in the pass that reported `passes`, dragging from the same
/// `PressStart`. It returns the `DragStart` step when an earlier pass reported the press, and the `Down` step
/// (the `DragStart` follows in the next pass) when the move past slop came in the pass of the press itself.
/// `None` when no press passes in this pass or `sense` has no `DRAG`; the next pass abandons the press.
pub fn hand_over(&mut self, target: T, sense: Sense) -> Option<PressStep<T>> {
let _ = (target, sense);
todo!("CV-C12")
let open = self.open.as_mut().filter(|open| !open.abandoned && sense.contains(Sense::DRAG))?;
let at = open.passing.take()?;
open.target = target;
open.sense = sense;
open.dragging = true;
let phase = if open.reported {
open.drag_reported = true;
PressPhase::DragStart { start: open.start, pos: at }
} else {
open.reported = true;
PressPhase::Down { start: open.start }
};
Some(PressStep { target: Some(target), phase: Some(phase), dragging: open.drag_reported, activated: None, passes: None })
}
}
@@ -770,4 +806,72 @@ mod tests {
let passes: [&[PointerEvent]; 5] = [&[press(0.0, 1.0)], &[up, second], &[far, up], &[], &[]];
assert_eq!(phases(&passes, Sense::CLICK | Sense::DRAG), "D R! D S R");
}
const PASSES: Sense = Sense::CLICK.union(Sense::PASSES_DRAG);
/// One pass with the button held at its end, over a root whose press winner is target 1 and passes its drag.
fn passing_pass(machine: &mut PressMachine<u8>, events: &[PointerEvent]) -> PressStep<u8> {
machine.step(PassInput::new(events, SLOP, pos2(0.0, 0.0), true), |_| Some((1, PASSES)))
}
fn moved(x: f32) -> PointerEvent {
PointerEvent::Moved { at: pos2(x, 0.0), sample: None }
}
fn up(x: f32) -> PointerEvent {
PointerEvent::released(pos2(x, 0.0))
}
#[test]
fn a_drag_past_slop_on_a_part_that_passes_it_goes_to_the_shape_below() {
let origin = pos2(0.0, 0.0);
assert_eq!(phases(&[&[press(0.0, 1.0)], &[up(SLOP / 2.0)]], PASSES), "D R!", "within slop the press is the shape's click");
// The press was reported in an earlier pass: the shape below drags from the pass of the move.
let mut machine = PressMachine::new();
let down = passing_pass(&mut machine, &[press(0.0, 1.0)]);
assert!(matches!(down.phase, Some(PressPhase::Down { .. })) && down.passes.is_none(), "{down:?}");
assert!(machine.hand_over(2, Sense::DRAG).is_none(), "a press within slop passes nothing");
let passed = passing_pass(&mut machine, &[moved(40.0)]);
assert_eq!(passed.passes.map(|start| start.origin), Some(origin), "{passed:?}");
let handed = machine.hand_over(2, Sense::DRAG).expect("the shape below takes the drag");
assert_eq!(handed.target, Some(2));
assert!(
matches!(handed.phase, Some(PressPhase::DragStart { start, pos }) if start.origin == origin && pos == pos2(40.0, 0.0)),
"{:?}",
handed.phase
);
let drag = passing_pass(&mut machine, &[moved(60.0)]);
assert_eq!(drag.target, Some(2));
assert!(matches!(drag.phase, Some(PressPhase::Drag { .. })), "{:?}", drag.phase);
let end = passing_pass(&mut machine, &[up(60.0)]);
assert_eq!(end.target, Some(2));
assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase);
assert_eq!(end.activated, None, "a passed press is no click");
// The move past slop came in the press's own pass: the shape below gets the Down, its DragStart next pass,
// and a release in between waits for it.
let mut machine = PressMachine::new();
let first = passing_pass(&mut machine, &[press(0.0, 1.0), moved(40.0)]);
assert!(matches!(first.phase, Some(PressPhase::Down { .. })) && first.passes.is_some(), "{first:?}");
let handed = machine.hand_over(2, Sense::DRAG).expect("the shape below takes the drag");
assert_eq!(handed.target, Some(2));
assert!(matches!(handed.phase, Some(PressPhase::Down { start }) if start.origin == origin), "{:?}", handed.phase);
let start = passing_pass(&mut machine, &[up(40.0)]);
assert_eq!(start.target, Some(2));
assert!(matches!(start.phase, Some(PressPhase::DragStart { .. })), "{:?}", start.phase);
assert!(machine.release_held(), "the release waits for the owed DragStart");
let end = passing_pass(&mut machine, &[]);
assert_eq!(end.target, Some(2));
assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase);
// No shape took the passed press: it is abandoned, and its release is no click.
let mut machine = PressMachine::new();
let _ = passing_pass(&mut machine, &[press(0.0, 1.0)]);
assert!(passing_pass(&mut machine, &[moved(40.0)]).passes.is_some());
let end = passing_pass(&mut machine, &[up(40.0)]);
assert_eq!(end.target, Some(1));
assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase);
assert_eq!(end.activated, None);
}
}
+3 -2
View File
@@ -50,8 +50,9 @@ bitflags! {
/// with `DRAG` by a part whose click does nothing a drag could be mistaken for (a transform box's handles).
/// The component begins the gesture from `PressPhase::Held`.
const FOLLOWS_IN_SLOP = 65536;
/// A shape that clicks and passes its drag: within slop the press stays its click; past slop the drag goes to
/// the shape below it that senses a drag.
/// A press on this shape that moves past slop is not the shape's: the press passes to the shape ranked under
/// it that senses a drag, with its start. Released within slop it is the shape's click. Declared with `CLICK`,
/// without `DRAG`.
const PASSES_DRAG = 131072;
}
}
@@ -1,4 +1,5 @@
//! `TaskBar`: the contextual task bar over a canvas, hung below its anchor until the user moves it.
//! `TaskBar`: the contextual task bar over a canvas: hung below its anchor until the user moves it, fixed beside its
//! anchor, or fixed at the canvas view's top edge.
#[cfg(feature = "testing")]
mod stories;
@@ -20,7 +21,7 @@ use crate::style::{ComponentStyle, StyleCx, SurfaceKind};
use craft_behavior::kurbo::Point;
use craft_behavior::overlay::{Align, Side};
use craft_behavior::{EditEvent, IconId, Metrics, Mixed, Sense};
use egui::{Pos2, Rect, Response, Ui};
use egui::{Pos2, Rect, Response, Ui, Vec2};
use std::sync::Arc;
/// Where the task bar sits: pinned or following its anchor, and where the user moved it. The one owner of the bar's
@@ -50,9 +51,10 @@ impl TaskBarPlace {
}
}
/// The contextual task bar: a movable modeless layer hung below the screen bounds of `anchor` while its place is
/// unset, with a body of members and a More menu (Hide, Reset, Pin). One place, pin and Hide setting for Crop and
/// Frame.
/// The contextual task bar: a modeless layer with a body of members.
///
/// A movable bar ([`TaskBar::new`]) hangs below the screen bounds of its anchor while its place is unset, with a More
/// menu (Hide, Reset, Pin). One place, pin and Hide setting for Crop and Frame.
///
/// - Place: centred under the anchor's bounds on screen, a section gap below them, following the anchor each pass.
/// Dragged by its grip (any free point of the bar), it stays where it is dropped and keeps its left edge while the
@@ -61,19 +63,32 @@ impl TaskBarPlace {
/// back inside, its left and top edges winning where the bar does not fit.
/// - Menu: Hide bar reports `hide`; Reset bar position clears the place, so the bar follows its anchor again; Pin bar
/// position keeps it where it shows.
/// - Nothing shows outside a canvas, or while the anchor's bounds or `area` is not finite or `area` has no size.
/// - `place` is the caller's value (`Bind::bound`): the bar reads it before it shows and writes the pass's change
/// after.
///
/// A fixed bar ([`TaskBar::fixed`]) hangs centred a section gap below its anchor's bounds, above them when there is no
/// room below, and follows the anchor. An edge bar ([`TaskBar::at_edge`]) hangs at the top edge of `area`, the canvas
/// view's rect, and takes no anchor. Neither has a grip, a move or a More menu, and neither reports `hide`.
///
/// Nothing shows outside a canvas, while `area` is not finite or has no size, or, for an anchored bar, while the
/// anchor's bounds are not finite.
#[must_use = "show the task bar with `show`"]
#[derive(crate::contract::Pattern, crate::contract::Props)]
pub struct TaskBar<'a> {
label: Label,
anchor: &'a [Point],
hang: Hang<'a>,
place: Bind<'a, TaskBarPlace>,
#[allow(dead_code)] // P3(pdf-canvas-w3): CV-C15
kind: TaskBarKind,
}
/// What a bar hangs from: the screen bounds of document points, or the canvas view's top edge, aligned in reading
/// direction.
#[derive(Clone, Copy)]
enum Hang<'a> {
Points(&'a [Point]),
Edge(Align),
}
/// Whether a task bar follows its anchor and moves, or stays where it hangs.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
@@ -112,7 +127,7 @@ pub struct TaskBarCx<'a> {
impl TaskBarCx<'_> {
/// Places the More menu button here, before the members that follow it (the Crop bar puts Cancel and Done after
/// it); without the call the button comes after the body.
/// it); without the call the button comes after the body. A fixed bar has no More menu: the call places nothing.
pub fn more_menu(&mut self, ui: &mut Ui) {
self.menu.place(ui);
}
@@ -129,14 +144,16 @@ enum MenuPick {
/// The More button and its menu, placed once per run of the bar's body.
struct MoreMenu {
words: Arc<CanvasControlWords>,
/// The bar offers the menu: a movable bar does, a fixed one does not.
offered: bool,
placed: bool,
pick: Option<MenuPick>,
}
impl MoreMenu {
/// Shows the button and its menu here unless this run of the body showed them already.
/// Shows the button and its menu here unless the bar offers none or this run of the body showed them already.
fn place(&mut self, ui: &mut Ui) {
if std::mem::replace(&mut self.placed, true) {
if !self.offered || std::mem::replace(&mut self.placed, true) {
return;
}
let words = Arc::clone(&self.words);
@@ -161,46 +178,54 @@ impl MoreMenu {
impl<'a> TaskBar<'a> {
/// A bar named `label` hung below the screen bounds of `anchor` (document points) until `place` moves it.
pub fn new(label: impl Into<Label>, anchor: &'a [Point], place: Bind<'a, TaskBarPlace>) -> Self {
TaskBar { label: label.into(), anchor, place, kind: TaskBarKind::Movable }
TaskBar { label: label.into(), hang: Hang::Points(anchor), place, kind: TaskBarKind::Movable }
}
/// A fixed bar named `label` hung below the screen bounds of `anchor`, above them when there is no room below.
pub fn fixed(label: impl Into<Label>, anchor: &'a [Point]) -> Self {
let _ = (label, anchor);
todo!("CV-C15")
TaskBar { label: label.into(), hang: Hang::Points(anchor), place: Bind::given(TaskBarPlace::default()), kind: TaskBarKind::Fixed }
}
/// A fixed bar at the canvas view's top edge, aligned `edge` in reading direction and inset by the regular pad.
pub fn at_edge(label: impl Into<Label>, edge: Align) -> Self {
let _ = (label, edge);
todo!("CV-C15")
TaskBar { label: label.into(), hang: Hang::Edge(edge), place: Bind::given(TaskBarPlace::default()), kind: TaskBarKind::Fixed }
}
/// Whether the bar is movable or fixed.
pub fn kind(&self) -> TaskBarKind {
todo!("CV-C15")
self.kind
}
/// Shows the bar inside `area`; `body` fills its members.
pub fn show<R>(self, ui: &mut Ui, area: Rect, mut body: impl FnMut(&mut Ui, &mut TaskBarCx<'_>) -> R) -> Inner<TaskBarOutput, R> {
let TaskBar { label, anchor, mut place, .. } = self; // P3(pdf-canvas-w3): CV-C15
let TaskBar { label, hang, mut place, kind } = self;
let env = Env::of(ui);
let words = env.words::<CanvasControlWords>();
// The anchor maps through this pass's view, so the bar follows a scroll or zoom in the same pass.
let bounds = canvas_space(&env.view()).map_or(Rect::NOTHING, |space| {
anchor.iter().fold(Rect::NOTHING, |mut bounds, point| {
bounds.extend_with(space.view.to_screen(*point));
bounds
})
});
let shows = bounds.is_finite() && area.is_finite() && area.is_positive();
let movable = kind == TaskBarKind::Movable;
let room = area.is_finite() && area.is_positive();
let hung = match hang {
Hang::Points(anchor) => {
// The anchor maps through this pass's view, so the bar follows a scroll or zoom in the same pass.
let bounds = canvas_space(&env.view()).map_or(Rect::NOTHING, |space| {
anchor.iter().fold(Rect::NOTHING, |mut bounds, point| {
bounds.extend_with(space.view.to_screen(*point));
bounds
})
});
let gap = env.tokens.space.gap.section;
// A fixed bar keeps the gap on both sides of its anchor: it opens above when there is no room below.
let rect = if movable { hang_rect(bounds, gap) } else { bounds.expand2(Vec2::new(0.0, gap)) };
(room && bounds.is_finite()).then_some((rect, Align::Center))
}
Hang::Edge(align) => room.then(|| (edge_rect(area, env.tokens.space.pad.regular), align)),
};
let shows = hung.is_some();
let held = match place.reborrow().get() {
Some(Mixed::Same(held)) => held,
_ => TaskBarPlace::default(),
};
let hang = shows.then(|| hang_rect(bounds, env.tokens.space.gap.section));
let layer = TaskBarLayer::new(label, words.task_bar_move.clone(), layer_overlay(&held, hang, area), shows);
let mut menu = MoreMenu { words: Arc::clone(&words), placed: false, pick: None };
let layer = TaskBarLayer::new(label, words.task_bar_move.clone(), layer_overlay(&held, hung, area, movable), shows, movable);
let mut menu = MoreMenu { words: Arc::clone(&words), offered: movable, placed: false, pick: None };
let mut shown = layer.show(ui, |ui, _| {
Bar::new(Label::Empty, BarKind::Tool).show(ui, |ui, _| {
menu.placed = false;
@@ -211,7 +236,7 @@ impl<'a> TaskBar<'a> {
});
let rect = shown.output.response.rect;
let pick = menu.pick;
if shows {
if shows && movable {
let moved = shown.output.moved.filter(|moved| moved.min != rect.min);
let next = settled(held, rect, area, moved, pick);
if next != held {
@@ -238,15 +263,21 @@ fn hang_rect(bounds: Rect, gap: f32) -> Rect {
Rect::from_min_max(bounds.min, Pos2::new(bounds.max.x, bounds.max.y + gap))
}
/// The layer the bar shows in: hung below `hang` while `held` has no place, at its place once it has one. A move stays
/// inside `area`. A bar that does not show (`hang` is `None`) gets a closed layer with no place.
fn layer_overlay(held: &TaskBarPlace, hang: Option<Rect>, area: Rect) -> Overlay {
let overlay = Overlay::floating().modeless().movable(true).body_scroll(false);
let Some(hang) = hang else { return overlay };
/// The rect an edge bar hangs below: the top edge of `area`, inset by `pad` on its sides, with no height.
fn edge_rect(area: Rect, pad: f32) -> Rect {
Rect::from_min_max(Pos2::new(area.left() + pad, area.top()), Pos2::new(area.right() - pad, area.top()))
}
/// The layer the bar shows in: hung below `hang`, aligned as it says, while `held` has no place, at its place once it
/// has one. Only a `movable` bar moves, and a move stays inside `area`. A bar that does not show (`hang` is `None`)
/// gets a closed layer with no place.
fn layer_overlay(held: &TaskBarPlace, hang: Option<(Rect, Align)>, area: Rect, movable: bool) -> Overlay {
let overlay = Overlay::floating().modeless().movable(movable).body_scroll(false);
let Some((hang, align)) = hang else { return overlay };
let overlay = overlay.bounds(area);
match held.placed_in(area) {
match held.placed_in(area).filter(|_| movable) {
Some(at) => overlay.placed_at(at),
None => overlay.place(Place::anchored(Anchor::Rect(hang), Side::Below, Align::Center)),
None => overlay.place(Place::anchored(Anchor::Rect(hang), Side::Below, align)),
}
}
@@ -295,8 +326,9 @@ impl Outcome for TaskBarLayerOutput {
}
}
/// The task bar's layer: a floating surface whose line starts with the grip and holds the bar. The move band lies
/// under the whole line, so the grip and every free point between the members move the layer.
/// The task bar's layer: a floating surface that holds the bar. A movable bar's line starts with the grip, and the
/// move band lies under the whole line, so the grip and every free point between the members move the layer; a fixed
/// bar's layer has no header.
#[derive(crate::contract::Component)]
#[component(container, unregistered)]
struct TaskBarLayer {
@@ -311,13 +343,9 @@ struct TaskBarLayer {
}
impl TaskBarLayer {
fn new(label: Label, grip: Label, overlay: Overlay, open: bool) -> Self {
let props = ContainerProps::new()
.mount(Mount::Layer(overlay))
.surface(SurfaceKind::Floating)
.pad(Pad::None)
.sizing(Sizing::Content)
.header(HeaderRegion::new().band(DragBand::Move).inline(true));
fn new(label: Label, grip: Label, overlay: Overlay, open: bool, movable: bool) -> Self {
let props = ContainerProps::new().mount(Mount::Layer(overlay)).surface(SurfaceKind::Floating).pad(Pad::None).sizing(Sizing::Content);
let props = if movable { props.header(HeaderRegion::new().band(DragBand::Move).inline(true)) } else { props };
TaskBarLayer { common: Common::new(), props, grip, open: Bind::given(open), moved: None }.label(label).id_salt("task-bar")
}
}
@@ -7,6 +7,7 @@ use crate::contract::{Bind, Props as _, Show as _};
use crate::testing::{Drive, StoryData, StoryOutput, story};
use craft_behavior::IconId;
use craft_behavior::kurbo::{Point, Vec2};
use craft_behavior::overlay::Align;
use egui::Ui;
/// The corners of a crop frame turned by a few degrees about the document's middle: the Crop tool hangs its bar from
@@ -36,6 +37,38 @@ fn crop_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
})
}
/// A frame low on the story document: the canvas has no room below it, so a fixed bar hangs above it.
fn low_frame() -> [Point; 4] {
[(120.0, 290.0), (520.0, 290.0), (520.0, 390.0), (120.0, 390.0)].map(|(x, y)| Point::new(x, y))
}
/// A fixed bar: no grip and no More menu, hung above its frame where there is no room below it.
#[story(TaskBar<'static>, covers = [], drive = Drive::Never)]
fn fixed_bar(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
let corners = low_frame();
on_canvas(ui, |ui, area, _| {
TaskBar::fixed("Signature", &corners)
.show(ui, area, |ui, _| {
let _ = Button::new("Cancel").show(ui);
let _ = Button::new("Place").show(ui);
})
.output
})
}
/// A fixed bar at the canvas view's top edge, at its end in reading direction: it takes no anchor.
#[story(TaskBar<'static>, covers = [], drive = Drive::Never)]
fn edge_bar(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
on_canvas(ui, |ui, area, _| {
TaskBar::at_edge("Camera", Align::End)
.show(ui, area, |ui, _| {
let _ = Button::new("Capture").show(ui);
let _ = Button::new("Done").show(ui);
})
.output
})
}
/// A bar the user moved and pinned: it keeps its place near the canvas's top left while the frame stays where it is.
#[story(TaskBar<'static>, covers = [], drive = Drive::Never)]
fn placed_and_pinned(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
+15
View File
@@ -108,6 +108,21 @@ fn a_drag_reaches_the_tool_as_one_press_drags_and_one_release() {
assert_eq!(phases.iter().filter(|phase| **phase == GesturePhase::Commit).count(), 1, "one Commit: {phases:?}");
}
#[trial]
fn escape_mid_drag_cancels_the_tool_once_and_its_release_reaches_nothing() {
let mut fixture = ToolFixture::new("Document", Recorder::default());
let from = fixture.canvas().rect.center();
fixture.drag_and_escape_from(from, BY);
let tool = fixture.tool();
let calls = &tool.calls;
assert_eq!(calls.first(), Some(&Call::Press), "the drag starts with the press: {calls:?}");
assert_eq!(tool.count(Call::Cancel(CancelReason::Escape)), 1, "Escape cancels the gesture once: {calls:?}");
assert_eq!(calls.iter().filter(|call| matches!(call, Call::Cancel(_))).count(), 1, "one cancel, with its reason: {calls:?}");
let cancel = calls.iter().position(|call| matches!(call, Call::Cancel(_))).expect("the tool is cancelled");
assert!(calls[cancel + 1..].is_empty(), "no drag or release reaches the tool after the cancel: {calls:?}");
assert_eq!(tool.count(Call::Release), 0, "the release after Escape reaches no release: {calls:?}");
}
#[trial]
fn a_press_on_a_canvas_control_never_reaches_the_tool_and_one_away_from_it_does() {
let crop = Rc::new(RefCell::new(craft_behavior::geometry::CropBox::upright(craft_behavior::kurbo::Rect::new(20.0, 20.0, 100.0, 80.0))));
@@ -1,14 +1,17 @@
//! The contextual task bar (N6): hung centred under its anchor's screen bounds, following the anchor until the grip
//! moves it, reset and pinned from its More menu, and kept inside the canvas area whatever place it is given.
//! moves it, reset and pinned from its More menu, and kept inside the canvas area whatever place it is given. A fixed
//! bar neither moves nor has a menu, and an edge bar sits at the canvas view's top edge.
use craft_behavior::CanvasView;
use craft_behavior::kurbo::{Point, Vec2 as DocVec};
use craft_behavior::overlay::Align;
use craft_ui::buttons::Button;
use craft_ui::canvas_controls::{TaskBar, TaskBarPlace};
use craft_ui::contract::{Bind, Show as _};
use craft_ui::testing::canvas_story::on_canvas;
use craft_ui::testing::canvas_story::{StoryDocument, on_canvas, on_canvas_view};
use craft_ui::testing::{Fixture, trial};
use egui::{Rect, Vec2};
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
const SLACK: f32 = 1.5;
@@ -33,8 +36,14 @@ fn frame(by: DocVec) -> Vec<Point> {
[(120.0, 40.0), (520.0, 40.0), (520.0, 200.0), (120.0, 200.0)].into_iter().map(|(x, y)| Point::new(x, y) + by).collect()
}
/// A canvas that shows the bar for the scene's anchor and place, with the More menu before a Done button.
fn fixture(scene: &Rc<RefCell<Scene>>) -> Fixture {
/// A frame low on the story canvas: below it the canvas has no room for a bar.
fn low_frame() -> Vec<Point> {
[(120.0, 290.0), (520.0, 290.0), (520.0, 390.0), (120.0, 390.0)].into_iter().map(|(x, y)| Point::new(x, y)).collect()
}
/// A canvas that shows the bar for the scene's anchor and place, with the More menu before a Done button: a movable
/// bar, or a `fixed` one, which takes no place.
fn fixture(scene: &Rc<RefCell<Scene>>, fixed: bool) -> Fixture {
let shared = Rc::clone(scene);
let mut fixture = Fixture::new(move |ui| {
let _ = on_canvas(ui, |ui, area, view| {
@@ -42,7 +51,8 @@ fn fixture(scene: &Rc<RefCell<Scene>>) -> Fixture {
let scene = &mut *held;
scene.bounds = Rect::from_points(&scene.anchor.iter().map(|point| view.to_screen(*point)).collect::<Vec<_>>());
scene.area = area;
let shown = TaskBar::new("Crop", &scene.anchor, Bind::bound(&mut scene.place)).show(ui, area, |ui, cx| {
let bar = if fixed { TaskBar::fixed("Crop", &scene.anchor) } else { TaskBar::new("Crop", &scene.anchor, Bind::bound(&mut scene.place)) };
let shown = bar.show(ui, area, |ui, cx| {
cx.more_menu(ui);
let _ = Button::new("Done").show(ui);
});
@@ -83,7 +93,7 @@ fn the_task_bar_follows_its_anchor_until_moved_and_stays_inside_the_area() {
area: Rect::NOTHING,
rect: Rect::NOTHING,
}));
let mut fixture = fixture(&scene);
let mut fixture = fixture(&scene, false);
fixture.settle();
let first = seen(&scene);
assert!(first.rect.is_positive(), "the bar shows: {:?}", first.rect);
@@ -134,3 +144,63 @@ fn the_task_bar_follows_its_anchor_until_moved_and_stays_inside_the_area() {
let far = seen(&scene);
assert!(inside_area(&far), "a place far outside comes back inside {:?}: {:?}", far.area, far.rect);
}
#[trial]
fn a_fixed_task_bar_ignores_a_drag_shows_no_more_menu_and_opens_above_with_no_room_below() {
let scene = Rc::new(RefCell::new(Scene {
anchor: low_frame(),
place: TaskBarPlace::default(),
bounds: Rect::NOTHING,
area: Rect::NOTHING,
rect: Rect::NOTHING,
}));
let mut fixture = fixture(&scene, true);
fixture.settle();
let shown = seen(&scene);
assert!(shown.rect.is_positive(), "the bar shows: {:?}", shown.rect);
assert!(fixture.by_label("Move bar").is_none(), "a fixed bar has no grip");
assert!(fixture.by_label("More options").is_none(), "a fixed bar has no More menu");
assert!(shown.rect.bottom() < shown.bounds.top(), "with no room below, the bar hangs above {:?}: {:?}", shown.bounds, shown.rect);
assert!(inside_area(&shown), "inside the canvas {:?}: {:?}", shown.area, shown.rect);
let free = shown.rect.left_center() + Vec2::new(2.0, 0.0);
fixture.drag_at(free, Vec2::new(-120.0, -60.0)).settle();
let dragged = seen(&scene);
assert!((dragged.rect.min - shown.rect.min).length() < SLACK, "a drag moves nothing: {:?} then {:?}", shown.rect, dragged.rect);
assert_eq!(dragged.place, TaskBarPlace::default(), "a fixed bar keeps no place");
// An edge bar takes no anchor: it sits at the view's top edge, at its end, wherever the view scrolls.
let centre = Rc::new(Cell::new(StoryDocument::STANDARD.centre()));
let reported = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING)));
let (view_centre, shown_at) = (Rc::clone(&centre), Rc::clone(&reported));
let mut fixture = Fixture::new(move |ui| {
let at = view_centre.get();
let _ = on_canvas_view(
ui,
|room, ppp| CanvasView::new(room, at, 1.0 / f64::from(ppp)),
Some(&StoryDocument::STANDARD),
|ui, area, _| {
let bar = TaskBar::at_edge("Find", Align::End).show(ui, area, |ui, _| {
let _ = Button::new("Next").show(ui);
});
shown_at.set((area, bar.output.rect));
bar.output
},
);
});
fixture.room(Vec2::new(1120.0, 720.0));
fixture.settle();
let (area, edge) = reported.get();
assert!(edge.is_positive(), "the edge bar shows with no anchor: {edge:?}");
assert!(area.expand(SLACK).contains_rect(edge), "inside the canvas {area:?}: {edge:?}");
assert!(edge.top() - area.top() < edge.height(), "at the top edge of {area:?}: {edge:?}");
assert!(area.right() - edge.right() < edge.left() - area.left(), "nearer the end edge of {area:?}: {edge:?}");
centre.set(centre.get() + DocVec::new(80.0, 60.0));
fixture.settle();
let (_, scrolled) = reported.get();
assert!(
(scrolled.min - edge.min).length() < SLACK && (scrolled.size() - edge.size()).length() < SLACK,
"the edge bar keeps its rect while the view scrolls: {edge:?} then {scrolled:?}"
);
}
+2 -2
View File
@@ -110,8 +110,8 @@ impl PartBuilder<'_> {
/// The part's stacking order: stacked parts of one priority rank by it before the nearest centre, the higher winning.
pub fn stacking(self, order: u32) -> Self {
let _ = order;
todo!("CV-C31")
self.decl.stacking = order;
self
}
/// The cursor while the pointer is over the part.
+22 -3
View File
@@ -129,7 +129,7 @@ pub(crate) struct PartDecl {
/// The component holds a press on the part (`PartBuilder::held`).
pub held: bool,
/// The named stacking order among parts of one priority (default 0).
#[allow(dead_code)] // P3(pdf-canvas-w4): CV-C31
pub stacking: u32,
}
@@ -315,7 +315,7 @@ fn rotate(state: &mut ArenaState, pass_nr: u64) {
}
fn own_part_shape(part: &PartDecl, root: Id, position: u32, target: f32) -> Shape<Id> {
Shape::new(part.shape.clone(), part.sense, root, Some(part.part_ref()), part.priority, position).min_across(target)
Shape::new(part.shape.clone(), part.sense, root, Some(part.part_ref()), part.priority, position).stacking(part.stacking).min_across(target)
}
/// The root's own parts but the `over` ones, at position 0.
@@ -340,7 +340,10 @@ fn over_position(count: usize) -> u32 {
}
fn member_part_shape(member: &MemberDecl, part: &PartDecl, position: u32, target: f32) -> Shape<Id> {
Shape::new(part.shape.clone(), part.sense, member.id, Some(part.part_ref()), part.priority, position).local(member.local).min_across(target)
Shape::new(part.shape.clone(), part.sense, member.id, Some(part.part_ref()), part.priority, position)
.stacking(part.stacking)
.local(member.local)
.min_across(target)
}
/// The member's root shape and its parts but the `over` ones, at its stack position.
@@ -894,6 +897,22 @@ fn outcome_in(ctx: &Context, read: &PassRead, arena: ArenaId, layer: Layer, enab
(hit, if drag_elsewhere { sense.difference(Sense::DRAG) } else { sense })
})
});
// A press on a shape that passes its drag (`Sense::PASSES_DRAG`) moved past slop: the drag goes to the shape the
// press split gave it at the press (`pointer::press_winners` at the press's origin, with the press's own
// targets). When that shape is this root's, the press carries on there from its start; another root's took the
// drag at the press, and this press, no click any more, is abandoned.
let step = match step.passes {
Some(start) => {
let root = state.root.map(|root| root.id);
let winners = pointer::press_winners(ctx, start.origin, pass_pointer.press_targets);
winners
.drag
.filter(|(_, owner)| Some(*owner) == root)
.and_then(|(winner, _)| machine.hand_over(Hit::from(winner), winner.sense))
.unwrap_or(step)
}
None => step,
};
cancelled = matches!(step.phase, Some(PressPhase::Cancel { .. }));
release_held = machine.release_held();
let open = machine.target();
+26 -8
View File
@@ -589,7 +589,8 @@ pub(crate) fn made_by_component(ctx: &Context, viewport: ViewportId, id: Id) ->
/// their winning shapes' place in the pass's paint order, top first. The top one takes every kind of press its shape
/// senses. Under a top shape that only drags (a window's resize grip), the click goes to the first root below whose
/// shape clicks; under one that only clicks (a button), the drag goes to the first root below whose shape drags, when
/// that root takes no click anywhere.
/// that root takes no click anywhere. Under a top shape that clicks and passes its drag (`Sense::PASSES_DRAG`), the
/// drag goes to the next shape under it that drags: its own root's, else the first root's below.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct PressWinners {
pub click: Option<(Winner<Id>, Id)>,
@@ -760,7 +761,24 @@ fn find_under(ctx: &Context, viewport: ViewportId, at: Pos2, targets: PressTarge
top = Some((rank, winner, root));
}
if let Some((rank, winner)) = pick(&kept, ResolveFor::Press) {
// A shape that passes its drag keeps the click; the root's next shape under it that drags follows it
// in the ranking, at its rank: the stable sort in `winners_of` keeps it right after the winner.
let passes = winner.sense.contains(craft_behavior::Sense::CLICK | craft_behavior::Sense::PASSES_DRAG)
&& !winner.sense.contains(craft_behavior::Sense::DRAG);
let below = passes
.then(|| {
let dragging: Vec<usize> = kept
.iter()
.copied()
.filter(|&index| index != winner.index && entry.shapes[index].sense.contains(craft_behavior::Sense::DRAG))
.collect();
pick(&dragging, ResolveFor::Press)
})
.flatten();
ranked.push((rank, winner, root, entry.click));
if let Some((_, under)) = below {
ranked.push((rank, under, root, entry.click));
}
}
}
if foreign {
@@ -775,7 +793,8 @@ fn find_under(ctx: &Context, viewport: ViewportId, at: Pos2, targets: PressTarge
}
/// The press winners among `ranked`, each root's topmost shape under a point that takes a press with its rank and
/// whether the root takes clicks anywhere: by the per-kind rule of [`PressWinners`].
/// whether the root takes clicks anywhere, and under a top shape that passes its drag the root's next shape that drags:
/// by the per-kind rule of [`PressWinners`].
fn winners_of(mut ranked: Vec<((u8, u32), Winner<Id>, Id, bool)>) -> PressWinners {
ranked.sort_by(|a, b| b.0.cmp(&a.0));
let mut winners = PressWinners::default();
@@ -798,15 +817,14 @@ fn winners_of(mut ranked: Vec<((u8, u32), Winner<Id>, Id, bool)>) -> PressWinner
}
}
// Under a top shape that only clicks, the first root below whose shape drags takes the drag, unless the
// root takes clicks anywhere: a drag-only root (a scroll view) is dragged from a button in it.
// root takes clicks anywhere: a drag-only root (a scroll view) is dragged from a button in it. Under a top
// shape that passes its drag, the next shape that drags takes it, in the same root or one below.
(true, false) => {
if clicks || root_clicks {
break;
}
if drags {
let passes = winners.click.is_some_and(|(top, _)| top.sense.contains(craft_behavior::Sense::PASSES_DRAG));
if drags && (passes || !(clicks || root_clicks)) {
winners.drag = Some((winner, root));
break;
}
break;
}
(true, true) => break,
}