graph-w2: net change of 2 commits

- graph-w2: written by an agent
- graph-w2: review fixes (round 1)
This commit is contained in:
Dylan M. Taylor committed 2026-11-26 07:43:51 -05:00
1 parent 958796611c
commit ceba7ae17f
17 files changed
+765 -69

No files matched your search

+40 -5
View File
@@ -311,6 +311,7 @@ pub struct PressState {
/// Where a secondary press made during another open press came up on this part in this pass
/// ([`PressStep::aside`]): a context request beside the running phase, which goes on.
pub context: Option<Pos2>,
dragged: bool,
}
impl PressState {
@@ -319,7 +320,19 @@ impl PressState {
/// A state in `phase` with no modifiers, sample, capture or aside context request.
pub const fn new(phase: PressPhase) -> Self {
PressState { phase, mods: Mods::NONE, sample: None, captured: false, context: None }
PressState { phase, mods: Mods::NONE, sample: None, captured: false, context: None, dragged: false }
}
/// Whether the press has passed slop as a drag.
pub const fn with_dragged(mut self, dragged: bool) -> Self {
self.dragged = dragged;
self
}
/// Whether the press passed slop and began a drag: true from the drag's start until the press ends, a `Cancel`
/// of a press that dragged included, so a cancel reader tells it from a press that never moved.
pub const fn dragged(&self) -> bool {
self.dragged
}
/// The aside secondary press that came up on the part at `at` in this pass.
@@ -668,7 +681,7 @@ impl<T: Copy> PressMachine<T> {
let mut pos = input.pos;
// The press released or cancelled in this pass, and whether it was silent: one that ends silent reports nothing.
let mut released: Option<(T, PressStart, Pos2, bool, bool, bool)> = None;
let mut cancelled: Option<(T, PressStart, PressCancel, bool)> = None;
let mut cancelled: Option<(T, PressStart, PressCancel, bool, bool)> = None;
let mut aside: Option<PressAside<T>> = 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
@@ -686,7 +699,7 @@ impl<T: Copy> PressMachine<T> {
self.open = None;
}
if let (Some(reason), Some(open)) = (input.cancel, self.open) {
cancelled = Some((open.target, open.start, reason, open.silent));
cancelled = Some((open.target, open.start, reason, open.silent, open.dragging));
self.open = None;
}
for event in input.events {
@@ -807,12 +820,12 @@ impl<T: Copy> PressMachine<T> {
self.aside = None;
}
let quiet = PressStep { aside, ..PressStep::default() };
if let Some((target, start, reason, silent)) = cancelled {
if let Some((target, start, reason, silent, dragged)) = cancelled {
if silent {
return quiet;
}
let phase = PressPhase::Cancel { start, reason };
return PressStep { target: Some(target), phase: Some(phase), ..quiet };
return PressStep { target: Some(target), phase: Some(phase), dragging: dragged, ..quiet };
}
if let Some((target, start, at, was_dragging, click, silent)) = released {
if silent {
@@ -959,6 +972,28 @@ mod tests {
.join(" ")
}
/// A cancelled press reports whether it had begun a drag, so a cancel reader tells a drag that is abandoned from a
/// press that never moved.
#[test]
fn a_cancel_reports_whether_the_press_had_dragged() {
let cancel = |moved: bool| {
let mut machine = PressMachine::new();
let at = pos2(0.0, 0.0);
let mut step = |events: &[PointerEvent], cancel| {
let input = PassInput::new(events, SLOP, at, true).cancel(cancel);
machine.step(input, |_, _| Some(PressPick::new(1u8, Sense::DRAG)))
};
step(&[press(0.0, 1.0)], None);
if moved {
step(&[PointerEvent::Moved { at: pos2(40.0, 0.0), sample: None }], None);
}
step(&[], Some(PressCancel::Escape))
};
let (dragged, still) = (cancel(true), cancel(false));
assert!(matches!(dragged.phase, Some(PressPhase::Cancel { .. })) && dragged.dragging);
assert!(matches!(still.phase, Some(PressPhase::Cancel { .. })) && !still.dragging);
}
/// A press of the held button, where nothing takes a press (a modal opened over the drag's target), leaves the open
/// press its drag, and the release ends that press from its own start. Replacing it would end the drag with no
/// release, and its owner would never see the button come up.
@@ -134,7 +134,8 @@ impl BodyHooks<'_> {
} else if props.label.is_some() {
scoped.bracket = None;
}
scoped.transform = props.transform;
// `scoped` starts as the enclosing scope's: nested zooms multiply.
scoped.view_scale *= props.transform.map_or(1.0, |transform| transform.scale);
scoped.content_column = content_column;
scoped.given_column = !content_column && matches!(props.layout, crate::layout::BodyLayout::Stack);
scoped.row_room = None;
@@ -216,10 +216,9 @@ impl Pointer for CxCore<'_> {
}
fn drag_ended<P: Clone + Send + Sync + 'static>(&self) -> Option<DragEnd<P>> {
// P3(graph-w2): q118: the release point and the no-taker case are not recorded yet.
let op = drag::ended::<P>(&self.ctx, self.id)?;
let payload = drag::ended_payload::<P>(&self.ctx, self.id)?;
Some(DragEnd { op: Some(op), at: Pos2::ZERO, payload })
let (op, at, payload) = drag::ended::<P>(&self.ctx, self.id)?;
let at = areas::layer_map(&self.ctx, self.response.layer_id).map_or(at, |map| map.to_layer(at));
Some(DragEnd { op, at, payload })
}
fn scroll_moved(&self, key: PartKey) -> Option<Range<f64>> {
+32 -5
View File
@@ -675,6 +675,7 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
(rect, offset, rtl): (Rect, ScrollPos, bool),
place: DropPlace,
at: Pos2,
spot_side: f32,
) -> Option<(DropAt<C::Key>, DropMark)> {
match place {
DropPlace::Between if self.source.is_empty() => {
@@ -683,7 +684,17 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
DropPlace::Between => self
.spot(layout, rect, offset, rtl, None, at)
.map(|spot| (DropAt::Gap { key: Some(self.source.key(spot.over)), insert: spot.insert }, spot.mark)),
DropPlace::Spot => todo!("ge.C10"),
// A point means something only where items sit at points; a flow layout takes no `Spot` drop. No bound on
// `at`: zoomed out, the items' space reaches past `rect`, and the target lies only over the shown body.
DropPlace::Spot if !matches!(layout.nav(), NavShape::Spatial) => None,
DropPlace::Spot => {
let over = layout
.hit(Self::logical(layout, rect, rtl, at), offset)
.filter(|&over| self.source.enabled(over))
.map(|over| self.source.key(over));
let mark = Rect::from_center_size(self.on_screen(at), Vec2::splat(spot_side));
Some((DropAt::Spot { over, at }, DropMark::Into(mark)))
}
DropPlace::Onto => {
let over = (at.y >= rect.min.y).then(|| layout.hit(Self::logical(layout, rect, rtl, at), offset)).flatten()?;
if !self.source.enabled(over) {
@@ -714,6 +725,7 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
fn kind_drop(&mut self, comp: &C, cx: &mut Cx<'_, C>, layout: &C::ItemLayout, place: (Rect, ScrollPos, bool), own: bool) {
let xf = self.xf;
let (rect, _, rtl) = place;
let spot_side = cx.core.env.shared_tokens().size.handle.sm;
let drops = comp.drops();
for kind in drops {
if own && !matches!(kind.place(), DropPlace::Onto) {
@@ -725,7 +737,7 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
if matches!(kind.place(), DropPlace::Between) && onto_too() && self.over_middle(layout, place, point) {
continue;
}
let Some((at, mark)) = self.kind_spot(layout, place, kind.place(), point).filter(|(at, _)| kind.accepts(&*payload, at)) else {
let Some((at, mark)) = self.kind_spot(layout, place, kind.place(), point, spot_side).filter(|(at, _)| kind.accepts(&*payload, at)) else {
continue;
};
if !own {
@@ -741,7 +753,16 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
}
}
/// Step 9: sweeps, row drags, drops and the free-layout move, from the collection's own press and the drag session.
/// The press of the part of the collection that holds the pointer's press, when the collection moves the selection
/// from it (`Collection::moves_from_part`). That press is the part's own, never the collection's: its phase drives
/// the move, its release commits it and its cancel cancels it.
fn moving_part_press(comp: &C, cx: &Cx<'_, C>) -> Option<PressPhase> {
let part = crate::runtime::pointer::pressed_part(&cx.core.ctx, cx.core.id).filter(|&part| comp.moves_from_part(part))?;
Some(cx.part_if_declared(part)?.press.phase).filter(PressPhase::is_press)
}
/// Step 9: sweeps, row drags, drops and the free-layout move, from the collection's own press (or the press of a
/// part it moves from) and the drag session.
pub(super) fn drag_step(
&mut self,
comp: &C,
@@ -752,14 +773,20 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
) {
self.drags.pending = None;
let free = matches!(layout.nav(), NavShape::Spatial);
let phase = cx.core.press.phase;
if phase.is_press() && !matches!(phase, PressPhase::Cancel { .. }) {
let part_phase = if free { Self::moving_part_press(comp, cx) } else { None };
let from_part = part_phase.is_some();
let phase = part_phase.unwrap_or(cx.core.press.phase);
if !from_part && phase.is_press() && !matches!(phase, PressPhase::Cancel { .. }) {
self.sweep_to(cx, layout, Placement { rect, offset, rtl }, phase);
}
// The pointer comes in screen space; the rows and a move's offset are in the rows' own space.
let xf = self.xf;
let layer = |point: Pos2| xf.map_or(point, |map| map.to_layer(point));
match phase {
// A sweep opens only from the collection's own press, so none runs beside a part's move.
PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } if start.button == PointerButton::Primary && from_part => {
self.free_move(cx, layer(start.origin), layer(pos));
}
PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } if start.button == PointerButton::Primary => {
let origin = layer(start.origin);
let hit = (origin.y >= rect.min.y)
+12 -2
View File
@@ -5,7 +5,7 @@ use crate::contract::collection::{CollectionEvent, HoverLead, LeadOnOpen, LeadSo
use crate::contract::{Collection, Cx};
use crate::runtime::memory::sub;
use crate::runtime::{drag, pointer};
use craft_behavior::{Flow, ItemLayout, PointerEvent, SelectionChange, SelectionModel, Sense};
use craft_behavior::{Flow, ItemLayout, NavShape, PointerEvent, SelectionChange, SelectionModel, Sense};
use craft_keymap::Mods;
use egui::{Context, Id, Pos2, Rect, Vec2};
use std::any::TypeId;
@@ -141,7 +141,17 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> {
// With nothing picked, the current item counts as picked: a modified click adds to it, as a file
// manager's or a page grid's does.
let seed = if extend || toggle { self.current_when_unpicked(comp) } else { None };
if extend && toggle {
// Items at points have no order a range could follow: Shift adds, Cmd (with or without Shift) toggles.
let spatial = self.layout.as_ref().is_some_and(|layout| matches!(layout.nav(), NavShape::Spatial));
if spatial && toggle {
self.change_by(SelectionChange::Toggle(key), by);
} else if spatial && extend {
if !self.holds(at) {
let mut keys = self.selected_keys(&self.selection);
keys.push(key);
self.change_by(SelectionChange::Set(keys), by);
}
} else if extend && toggle {
self.add_range(at);
} else if extend {
let anchor = self.selection.anchor().and_then(|key| self.index_of(key)).or(seed).unwrap_or(self.lead.at);
@@ -166,7 +166,7 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
}
} else {
if primary && start.clicks == 2 {
self.events.push(CollectionEvent::EmptyActivated { at: start.origin }); // P3(graph-w2): ge.C9
self.events.push(CollectionEvent::EmptyActivated { at: start.origin });
}
if primary
&& props.allow_empty
@@ -59,7 +59,9 @@ pub(super) fn record_lead(ctx: &Context, collection: Id, at: Option<usize>) {
crate::runtime::memory::adopt::<LeadFact>(ctx, collection, slot);
}
/// The position of the lead of `collection` after its last item step, `None` while it has none.
/// The position in display order of the lead of collection `collection` after its last item step, `None` while it has
/// none. It reads what the collection recorded, so code outside a pass (an inspector, an automation query) reads it
/// too.
pub fn lead_position(ctx: &Context, collection: Id) -> Option<usize> {
store::peek_clone::<LeadFact>(ctx, lead_slot(collection)).and_then(|fact| fact.0)
}
+2 -2
View File
@@ -119,7 +119,7 @@ use crate::runtime::memory::sub;
use crate::runtime::overlay::CloseReason;
use crate::style::{ComponentStyle, Flags, StyleCx, StyleKey};
pub use craft_behavior::Input;
use craft_behavior::{CellSpace, ItemLayout, ItemSource, Proposal, ScrollPos, SelectionModel, Sense};
use craft_behavior::{CellSpace, ItemLayout, ItemSource, PartRef, Proposal, ScrollPos, SelectionModel, Sense};
use egui::{Id, IdSalt, Pos2, Rect, Ui, Vec2};
use run::ShowAt;
use std::hash::Hash;
@@ -728,7 +728,7 @@ pub trait Collection: Component + HasProps + Meta<Shape = shape::Items> {
/// Whether a primary drag pressed on the part `part` of the collection moves the selection, as a drag from an item
/// does, in a spatial layout. The default keeps every collection as it is.
fn moves_from_part(&self, _part: craft_behavior::PartRef) -> bool {
fn moves_from_part(&self, _part: PartRef) -> bool {
false
}
+4 -2
View File
@@ -1274,7 +1274,8 @@ fn part_press_in(
};
let captured = won.is_some() && outcome.dragging && phase.is_drag();
let context = aside_at(outcome, |hit| is_known && mine(hit));
let press = PressState::new(phase).mods(mods).sample(sample).captured(captured).context(context);
let dragged = won.is_some() && outcome.dragging && !matches!(phase, PressPhase::Release { .. });
let press = PressState::new(phase).mods(mods).sample(sample).captured(captured).context(context).with_dragged(dragged);
PartPress { press, hovered, hover_pos }
}
@@ -1297,7 +1298,8 @@ fn shape_press_in(outcome: &Outcome, mods: Mods, sample: Option<PointerSample>,
};
let captured = won.is_some() && phase.is_drag();
let context = aside_at(outcome, |hit| hit.owner == owner && hit.part.is_none());
PressState::new(phase).mods(mods).sample(sample).captured(captured).context(context)
let dragged = won.is_some() && outcome.dragging && !matches!(phase, PressPhase::Release { .. });
PressState::new(phase).mods(mods).sample(sample).captured(captured).context(context).with_dragged(dragged)
}
/// The cursor a hovered part of `decls` declares, if any: the sensing core's request for the cursor service.
+38 -26
View File
@@ -267,6 +267,8 @@ struct Session {
hovering_next: Vec<OsFile>,
/// The root frame the session started in, the only one in which [`amend`] changes its payload.
began: u64,
/// The last pointer position the source viewport saw, where a release outside that window is placed.
last_pointer: Option<Pos2>,
}
/// The mark of the target that would take a drop, with the viewport that registered it and the tokens of the region
@@ -278,13 +280,16 @@ struct ShownMark {
tokens: Arc<UiTokens>,
}
/// A drop a target took: the source's `drag_ended` reads it in the next frame.
/// How a session ended at a release, a drop a target took or a release no target took: the source's `drag_ended`
/// reads it in the next frame. A cancel records none.
struct Ended {
source: Id,
payload: TypeId,
/// The payload of that type the session carried.
value: Option<Arc<dyn Any + Send + Sync>>,
op: DropOperation,
/// The payloads a reader of their type sees: the one the target took, or every payload of a drag nobody took.
values: Vec<Arc<dyn Any + Send + Sync>>,
/// `None` when no target took the drop.
op: Option<DropOperation>,
/// The release point, in screen space.
at: Pos2,
frame: u64,
}
@@ -374,6 +379,7 @@ pub fn start(
dropped_at: None,
hovering_next: Vec::new(),
began,
last_pointer: None,
});
board.ended = None;
board.started += 1;
@@ -581,6 +587,7 @@ fn os_session(files: Vec<OsFile>, viewport: ViewportId, frame: u64) -> Session {
dropped_at: None,
hovering_next: Vec::new(),
began: frame,
last_pointer: None,
}
}
@@ -746,14 +753,22 @@ pub(crate) fn take_drop(ctx: &Context, owner: Id, ordinal: u32, op: DropOperatio
return false;
}
let frame = pass::root_frame_nr(ctx);
let viewport = pass::current_viewport(ctx);
let source = source_viewport(ctx);
// A drop taken in another window lies in that window's space; the source reads it in its own.
let pointer = pointer::frame_raw(ctx).pos.map(|pos| match source {
Some(source) if source != viewport => WindowHost::of(ctx).offset_between(viewport, source).map_or(pos, |by| pos + by),
_ => pos,
});
board(ctx, |board| {
let Some(session) = board.session.as_mut() else { return false };
if session.taken || board.ended.as_ref().is_some_and(|ended| ended.frame == frame) {
return false;
}
session.taken = true;
let value = std::iter::once(&session.payload).chain(&session.also).find(|value| (***value).type_id() == payload).cloned();
board.ended = Some(Ended { source: session.source, payload, value, op, frame });
let values = std::iter::once(&session.payload).chain(&session.also).filter(|value| (***value).type_id() == payload).cloned().collect();
let at = session.dropped_at.or(pointer).unwrap_or_default();
board.ended = Some(Ended { source: session.source, values, op: Some(op), at, frame });
true
})
}
@@ -828,27 +843,14 @@ impl<P: 'static, T: DropTarget<P>> DropTarget<dyn Any + Send + Sync> for Typed<'
}
}
/// The operation of the drop of `source`'s payload of type `P` that the previous frame took.
pub(crate) fn ended<P: 'static>(ctx: &Context, source: Id) -> Option<DropOperation> {
/// How the drag of `source`'s payload of type `P` ended at a release in the previous frame: the operation of the drop
/// (`None` when no target took it), the release point in screen space and the payload. `None` after a cancel.
pub(crate) fn ended<P: Clone + 'static>(ctx: &Context, source: Id) -> Option<(Option<DropOperation>, Pos2, P)> {
let frame = pass::root_frame_nr(ctx);
board(ctx, |board| {
board
.ended
.as_ref()
.filter(|ended| ended.source == source && ended.payload == TypeId::of::<P>() && ended.frame + 1 == frame)
.map(|ended| ended.op)
})
}
/// The payload of the drop of `source`'s payload of type `P` that the previous frame took.
pub(crate) fn ended_payload<P: Clone + 'static>(ctx: &Context, source: Id) -> Option<P> {
let frame = pass::root_frame_nr(ctx);
board(ctx, |board| {
board
.ended
.as_ref()
.filter(|ended| ended.source == source && ended.payload == TypeId::of::<P>() && ended.frame + 1 == frame)
.and_then(|ended| ended.value.as_ref()?.downcast_ref::<P>().cloned())
let ended = board.ended.as_ref().filter(|ended| ended.source == source && ended.frame + 1 == frame)?;
let payload = ended.values.iter().find_map(|value| value.downcast_ref::<P>().cloned())?;
Some((ended.op, ended.at, payload))
})
}
@@ -903,11 +905,21 @@ pub(crate) fn end_pass(ctx: &Context) {
}
let elsewhere = is_source && held_elsewhere(ctx);
let foreign_target = is_source && !held && (elsewhere || foreign_winner(ctx, viewport));
let release = pointer::frame_raw(ctx).pos;
let running = board(ctx, |board| {
if let Some(session) = &mut board.session {
if is_source {
session.last_pointer = release.or(session.last_pointer);
}
let expired = session.released.is_some_and(|released| frame > released + 1);
let ended_here = is_source && !held && session.released.is_none();
if expired || (ended_here && !foreign_target) {
// A release no target took: the source reads it as a drag that ended where it was let go.
if !session.taken && !session.os {
let values = std::iter::once(&session.payload).chain(&session.also).cloned().collect();
board.ended =
Some(Ended { source: session.source, values, op: None, at: release.or(session.last_pointer).unwrap_or_default(), frame });
}
let next = std::mem::take(&mut session.hovering_next);
board.session = (!next.is_empty()).then(|| os_session(next, viewport, frame));
board.started += u64::from(board.session.is_some());
+5 -9
View File
@@ -17,7 +17,7 @@ use crate::runtime::egui::{pass, repaint, scale, stack, style};
use crate::runtime::frame::PerViewport;
use crate::runtime::windows;
use crate::style::{EnvKey, GlyphRole, Ink, SurfaceKind, UiTokens};
use craft_behavior::{CanvasTransform, MotionMode};
use craft_behavior::MotionMode;
use craft_host::target::{Os, ShellInfo};
use craft_host::{Host, Jobs};
pub use craft_i18n::Direction;
@@ -136,10 +136,7 @@ pub struct Scoped {
/// The roving group of the innermost body with `ContainerProps.roving`: components shown under it put
/// their stops in it instead of the scope's Tab order.
pub(crate) roving: Option<Id>,
/// From `ContainerProps.transform`.
pub transform: Option<CanvasTransform>,
/// The product of the `ContainerProps::transform` scales around the scope, 1.0 outside them.
#[allow(dead_code)] // P3(graph-w2): ge.C12
pub(crate) view_scale: f32,
/// The `Grid` or spread `Row` body whose cursor places the children in flow.
pub(crate) grid: Option<Id>,
@@ -441,7 +438,6 @@ impl Scoped {
self.measure = None;
self.arena = None;
self.roving = None;
self.transform = None;
self.view_scale = 1.0;
self.scroll_owner = None;
self.fallback_collection = None;
@@ -551,7 +547,7 @@ impl Scoped {
/// The key of everything a memoized view shown in this scope inherits beyond `key` and `flow` (the style inputs and
/// the flow facts, which its place compares): the scope's state (enabled, read-only, size, glyphs, ink, surface,
/// wheel, directions), the containers around it (arena, roving group, transform, collection item and row, inside
/// wheel, directions), the containers around it (arena, roving group, view scale, collection item and row, inside
/// label, footer slot, line length, scroll owner), the command chain, motion, the host's formats and date, and every
/// app value. Computed once per scope, on the first view that asks; the bytes it fed are counted then.
pub(crate) fn scope_key(&self) -> u128 {
@@ -561,7 +557,8 @@ impl Scoped {
key.feed_hash(&(self.enabled, self.read_only, self.size, self.glyphs, self.ink, self.surface, self.wheel));
key.feed_hash(&(self.direction, self.text_direction, self.ids_stable));
key.feed_hash(&(self.arena, self.roving, self.item, self.row, self.scroll_owner.map(|owner| (owner.id, owner.view))));
self.transform.map(|transform| (transform.scale, transform.offset)).key(&mut key);
// The scale only: a zoom re-measures, a pan moves the settled region, which the layer's transform places.
key.feed_hash(&self.view_scale.to_bits());
self.footer_slot.map(|slot| (slot.owner, slot.size)).key(&mut key);
self.measure.key(&mut key);
// State a key cannot follow, rebuilt each pass: a view under it runs in every pass.
@@ -726,7 +723,6 @@ impl Env {
ids_stable: true,
arena: None,
roving: None,
transform: None,
view_scale: 1.0,
grid: None,
grid_top: false,
@@ -877,7 +873,7 @@ impl Env {
}
/// A child entry that changes layer-local fields only (arena, item, row, roving, grid, scroll owner,
/// transform, ink): the key carries over, because none of its inputs change.
/// view scale, ink): the key carries over, because none of its inputs change.
pub(crate) fn derive_local(&self, f: impl FnOnce(&mut Scoped)) -> Env {
let mut scoped = (*self.scoped).clone();
f(&mut scoped);
+5 -4
View File
@@ -14,17 +14,18 @@ use craft_theme::Mode;
use egui::Id;
use std::sync::Arc;
/// What component code sees: everything in `Env` except tokens, size, enabled, read-only, arena, transform
/// and `ids_stable`.
/// What component code sees: everything in `Env` except tokens, size, enabled, read-only, arena and `ids_stable`. Of
/// the transforms around it, it sees only their scale (`view_scale`), so it measures for the zoom it shows at.
#[derive(Clone, Copy)]
pub struct EnvView<'a> {
pub(super) scoped: &'a Scoped,
}
impl<'a> EnvView<'a> {
/// The product of the `ContainerProps::transform` scales around the scope, 1.0 outside them.
/// The product of the `ContainerProps::transform` scales around the scope, 1.0 outside them and in a layer opened
/// inside them.
pub fn view_scale(&self) -> f32 {
todo!("ge.C12")
self.scoped.view_scale
}
/// The footer a `FooterSlot` under this scope places, if a container offers one.
+79 -5
View File
@@ -10,7 +10,7 @@ use craft_ui::runtime::InstallSpec;
use craft_ui::runtime::drag;
use craft_ui::runtime::env::Label;
use craft_ui::style::{ComponentStyle, StyleCx};
use craft_ui::testing::pointer::{moved, press, release};
use craft_ui::testing::pointer::{gone, moved, press, release};
use craft_ui::testing::windows::FakeSystem;
use craft_ui::testing::{Frames, trial};
use craft_ui_test_kit::windows::{FilesOver, Windows};
@@ -44,7 +44,8 @@ struct Payload(u32);
#[derive(Default)]
struct Seen {
dropped: Vec<(u32, DropOperation)>,
ended: Vec<DropOperation>,
/// How each drag the chip started ended: the operation (`None` with no taker) and the release point.
ended: Vec<(Option<DropOperation>, Pos2)>,
/// Drops a window-wide target took.
caught: usize,
}
@@ -80,8 +81,7 @@ impl Component for Chip<'_> {
cx.start_drag(Payload(7), self.preview.clone());
}
if let Some(end) = cx.drag_ended::<Payload>() {
// P3(graph-w2): q118
self.seen.borrow_mut().ended.push(end.op.unwrap_or(DropOperation::Move));
self.seen.borrow_mut().ended.push((end.op, end.at));
}
}
@@ -234,7 +234,81 @@ fn a_drag_crosses_windows_and_the_target_in_the_other_window_takes_the_drop() {
}
let seen = seen.borrow();
assert_eq!(seen.dropped, vec![(7, DropOperation::Move)], "the other window's target took the drop once");
assert_eq!(seen.ended, vec![DropOperation::Move], "the source saw the operation once");
let ops: Vec<_> = seen.ended.iter().map(|(op, _)| *op).collect();
assert_eq!(ops, vec![Some(DropOperation::Move)], "the source saw the operation once");
}
/// The chip and the slot, the chip dragged from its centre to `to` over four frames.
fn drag_chip_to(frames: &mut Frames, to: Pos2, show: &mut impl FnMut(&mut Ui)) {
let from = CHIP.center();
frames.frame(vec![moved(from)], &mut *show);
frames.frame(vec![press(from)], &mut *show);
for step in 1..=4 {
frames.frame(vec![moved(from + (to - from) * (step as f32 / 4.0))], &mut *show);
}
}
/// q118: a drag released where no target takes it ends with no operation, at the point the button went up, in the
/// source's layer space; the source reads it once.
#[trial]
fn a_drag_released_with_no_taker_ends_at_its_release_point() {
let seen = RefCell::new(Seen::default());
let mut show = |ui: &mut Ui| {
Chip { common: Common::new(), seen: &seen, preview: DragPreview::None }.id_salt("chip").show_at(ui, CHIP);
Slot { common: Common::new(), seen: &seen, mark: DropMark::region(SLOT) }.id_salt("slot").show_at(ui, SLOT);
};
let mut frames = Frames::new();
let open = Pos2::new(120.0, 200.0);
assert!(!SLOT.contains(open) && !CHIP.contains(open));
drag_chip_to(&mut frames, open, &mut show);
frames.frame(vec![release(open)], &mut show);
frames.idle(2, &mut show);
let seen = seen.borrow();
assert!(seen.dropped.is_empty(), "no target took the drop");
assert_eq!(seen.ended.len(), 1, "the source saw the end once: {:?}", seen.ended);
let (op, at) = seen.ended[0];
assert_eq!(op, None, "no taker means no operation");
assert!((at - open).length() < 0.5, "the end is where the button went up: {at:?}");
}
/// A drag let go with the pointer outside the window ends where the pointer last was in it, never at the origin.
#[trial]
fn a_drag_released_outside_the_window_ends_at_the_last_pointer_place() {
let seen = RefCell::new(Seen::default());
let mut show = |ui: &mut Ui| {
Chip { common: Common::new(), seen: &seen, preview: DragPreview::None }.id_salt("chip").show_at(ui, CHIP);
Slot { common: Common::new(), seen: &seen, mark: DropMark::region(SLOT) }.id_salt("slot").show_at(ui, SLOT);
};
let mut frames = Frames::new();
let open = Pos2::new(120.0, 200.0);
drag_chip_to(&mut frames, open, &mut show);
frames.frame(vec![gone(), release(open)], &mut show);
frames.idle(2, &mut show);
let seen = seen.borrow();
assert_eq!(seen.ended.len(), 1, "the source saw the end once: {:?}", seen.ended);
let (op, at) = seen.ended[0];
assert_eq!(op, None);
assert!((at - open).length() < 0.5, "the end is the last place the pointer was in the window: {at:?}");
}
/// q118: a drag cancelled with Escape reports no end, and the release that follows reports none either.
#[trial]
fn a_cancelled_drag_reports_no_end() {
let seen = RefCell::new(Seen::default());
let mut show = |ui: &mut Ui| {
Chip { common: Common::new(), seen: &seen, preview: DragPreview::None }.id_salt("chip").show_at(ui, CHIP);
Slot { common: Common::new(), seen: &seen, mark: DropMark::region(SLOT) }.id_salt("slot").show_at(ui, SLOT);
};
let mut frames = Frames::new();
drag_chip_to(&mut frames, SLOT.center(), &mut show);
frames.idle(1, &mut show);
assert!(drag::mark(&frames.ctx).is_some(), "the slot would take the drop");
frames.frame(vec![craft_ui::testing::input::key_press(egui::Key::Escape, egui::Modifiers::NONE)], &mut show);
frames.frame(vec![release(SLOT.center())], &mut show);
frames.idle(2, &mut show);
let seen = seen.borrow();
assert!(seen.dropped.is_empty(), "the cancelled drag drops nothing");
assert!(seen.ended.is_empty(), "a cancel is no end: {:?}", seen.ended);
}
/// Sb-9 (3): a drag out of an OS window whose window-wide target (a tab strip's tear-off) takes what no other target
@@ -0,0 +1,409 @@
//! Collections over a free layout, where items sit at points the document stores: Shift and Cmd picks that add and
//! toggle without a range, drop kinds that take a drop at a point (`DropPlace::Spot`) and report the empty space's
//! double click at its screen point, and a move of the selection started from a part the collection declares
//! (`Collection::moves_from_part`).
use crate::collection::kit::{Count, Dismissed, List, Row, Words};
use craft_behavior::{CanvasTransform, EditEvent, FreeLayout, HitLevel, HitPriority, ItemSource, PartKey, PartRef, Selection};
use craft_ui::contract::{
Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, Common, Component, ContainerProps, Cx, DropAt, DropKind,
DropPlace, ListDrag, PartsCx, Props as _, Role, SelectMode, ShowCollection as _,
};
use craft_ui::style::StyleCx;
use craft_ui::testing::layout::in_region;
use craft_ui::testing::pointer::{moved, press, release, secondary};
use craft_ui::testing::{Fixture, Frames, trial};
use craft_ui_test_kit::contract::PlainStyle;
use egui::{Key, Modifiers, Pos2, Rect, Ui, Vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
/// A part a press on which moves the selection.
const GRIP: PartKey = PartKey::new("grip");
/// A part the board does not move from.
const KNOB: PartKey = PartKey::new("knob");
/// Places that differ by less are the same place: the rounding of the layout.
const SAME: f32 = 0.5;
type Events = Vec<CollectionEvent<usize, Dismissed>>;
/// Items at the rects the trial gives, in the board's own space from its top left.
#[derive(craft_ui::contract::Component)]
#[component(collection)]
struct Board<'a> {
#[common]
common: Common,
#[container]
props: ContainerProps,
items: CollectionProps,
rects: Vec<Rect>,
selection: Option<Bind<'a, Selection<usize>>>,
drops: Vec<DropKind<'a, usize>>,
/// Declares `GRIP` and `KNOB` at these rects, in the board's own space from its top left.
grips: Option<(Rect, Rect)>,
}
impl<'a> Board<'a> {
fn new(rects: Vec<Rect>) -> Self {
Board {
common: Common::new(),
props: ContainerProps::new().sizing(craft_ui::contract::Sizing::Fill),
items: CollectionProps::new().select(SelectMode::Multi),
rects,
selection: None,
drops: Vec::new(),
grips: None,
}
}
fn selection(mut self, selection: Bind<'a, Selection<usize>>) -> Self {
self.selection = Some(selection);
self
}
fn takes_drop(mut self, kind: DropKind<'a, usize>) -> Self {
self.drops.push(kind);
self
}
fn transformed(mut self, transform: CanvasTransform) -> Self {
self.props = self.props.transform(transform);
self
}
fn with_parts(mut self, grip: Rect, knob: Rect) -> Self {
self.grips = Some((grip, knob));
self
}
}
impl Component for Board<'_> {
const ROLE: Role = Role::GROUP;
type Style = PlainStyle;
type Output = CollectionResponse<usize, Dismissed>;
fn style(_: &StyleCx<'_>, _: BoardStyleKey) -> PlainStyle {
PlainStyle::default()
}
/// The grip and the knob sit over the empty space at `Edge` priority, as a node graph's wires do.
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
if let Some((grip, knob)) = self.grips {
for (key, at) in [(GRIP, grip), (KNOB, knob)] {
cx.part(key, at.translate(rect.min.to_vec2()))
.sense(craft_behavior::Sense::DRAG)
.priority(HitPriority::new(HitLevel::Edge, 0))
.pointer_only("the part is dragged with the pointer");
}
}
}
fn finish(self, mut cx: Cx<'_, Self>) -> Self::Output {
cx.collection_response()
}
}
impl Collection for Board<'_> {
type Key = usize;
type ItemLayout = FreeLayout;
type Selection = Selection<usize>;
type Item<'r> = Row;
type ItemEvent = Dismissed;
fn items(&self) -> &CollectionProps {
&self.items
}
fn selection(&mut self) -> Option<BindMut<'_, Selection<usize>>> {
self.selection.as_mut().map(Bind::reborrow)
}
fn drops(&self) -> &[DropKind<'_, usize>] {
&self.drops
}
fn moves_from_part(&self, part: PartRef) -> bool {
part.key == GRIP
}
fn item_layout(&self, source: &dyn ItemSource<usize>, _: f32, _: &StyleCx<'_>) -> FreeLayout {
FreeLayout::new((0..source.len()).map(|at| self.rects.get(source.key(at)).copied().unwrap_or(Rect::NOTHING)).collect())
}
}
/// Where each item was last shown, in its collection's own space.
#[derive(Default)]
struct Shown(RefCell<Vec<(usize, Rect)>>);
impl Shown {
fn note(&self, key: usize, rect: Rect) {
let mut rows = self.0.borrow_mut();
rows.retain(|(held, _)| *held != key);
rows.push((key, rect));
}
fn rect(&self, key: usize) -> Rect {
self.0.borrow().iter().find(|(held, _)| *held == key).map(|(_, rect)| *rect).expect("the item was shown")
}
}
/// Three items apart from each other, at the board's top left, low on the right and in the middle.
fn three_items() -> Vec<Rect> {
vec![
Rect::from_min_size(Pos2::new(0.0, 0.0), Vec2::splat(40.0)),
Rect::from_min_size(Pos2::new(150.0, 120.0), Vec2::splat(40.0)),
Rect::from_min_size(Pos2::new(60.0, 60.0), Vec2::splat(40.0)),
]
}
fn sorted(selection: &RefCell<Selection<usize>>) -> Vec<usize> {
let mut items = selection.borrow().items.clone();
items.sort_unstable();
items
}
/// S-G4 (ge.C11): over a free layout Shift adds the item and never the items between it and the anchor in display
/// order, and keeps an item already selected; Cmd toggles and so does Shift+Cmd. In a flow list beside it Shift still
/// selects the range.
#[trial]
fn shift_click_in_a_free_layout_adds_without_a_range() {
let (board_sel, list_sel) = (Rc::new(RefCell::new(Selection::<usize>::default())), Rc::new(RefCell::new(Selection::<usize>::default())));
let (board_at, list_at) = (Rc::new(Shown::default()), Rc::new(Shown::default()));
let words = Rc::new(Words::flat(&["a", "b", "c"]));
let mut fixture = Fixture::new({
let (board_sel, list_sel, board_at, list_at, words) = (board_sel.clone(), list_sel.clone(), board_at.clone(), list_at.clone(), words.clone());
move |ui: &mut Ui| {
in_region(ui, Rect::from_min_size(Pos2::new(0.0, 0.0), Vec2::new(240.0, 200.0)), |ui| {
let mut held = board_sel.borrow().clone();
let _ = Board::new(three_items()).selection(Bind::bound(&mut held)).id_salt("board").show_items(ui, &Count(3), &mut |key, cx| {
board_at.note(*key, cx.rect);
Row::new()
});
*board_sel.borrow_mut() = held;
});
in_region(ui, Rect::from_min_size(Pos2::new(260.0, 0.0), Vec2::new(120.0, 100.0)), |ui| {
let mut held = list_sel.borrow().clone();
let _ = List::new(SelectMode::Multi).selection(Bind::bound(&mut held)).id_salt("list").show_items(ui, &*words, &mut |key, cx| {
list_at.note(*key, cx.rect);
Row::new()
});
*list_sel.borrow_mut() = held;
});
}
});
// The PC keys: Ctrl is the toggle key.
craft_ui::testing::windows::set_os(fixture.ctx(), craft_host::target::Os::Linux);
fixture.idle(3);
let item = |key: usize| board_at.rect(key).center();
// Each click waits past the double-click time, so none is the second click of a double click.
let click = |fixture: &mut Fixture, at: Pos2, mods: Modifiers| {
fixture.hold(mods).click_at(at).hold(Modifiers::NONE).advance(1.0).idle(1);
};
// Item 1 lies between items 0 and 2 in display order: a range from 0 to 2 would hold it.
click(&mut fixture, item(0), Modifiers::NONE);
assert_eq!(sorted(&board_sel), [0]);
click(&mut fixture, item(2), Modifiers::SHIFT);
assert_eq!(sorted(&board_sel), [0, 2], "Shift adds the item and not the item between them in display order");
click(&mut fixture, item(2), Modifiers::SHIFT);
assert_eq!(sorted(&board_sel), [0, 2], "Shift on a selected item keeps it");
click(&mut fixture, item(0), Modifiers::COMMAND);
assert_eq!(sorted(&board_sel), [2], "Cmd toggles a selected item off");
click(&mut fixture, item(0), Modifiers::SHIFT | Modifiers::COMMAND);
assert_eq!(sorted(&board_sel), [0, 2], "Shift+Cmd toggles an item on, with no range");
click(&mut fixture, item(2), Modifiers::SHIFT | Modifiers::COMMAND);
assert_eq!(sorted(&board_sel), [0], "and off");
click(&mut fixture, list_at.rect(0).center(), Modifiers::NONE);
click(&mut fixture, list_at.rect(2).center(), Modifiers::SHIFT);
assert_eq!(sorted(&list_sel), [0, 1, 2], "a flow list still selects the range");
}
/// A payload another list's row drag also carries, which the board takes at a point.
#[derive(Clone, Debug, PartialEq)]
struct Photo(usize);
/// ge.C10 and ge.C9 under a body transform: a `Spot` kind reports the drop at the point in the items' own space with
/// the item under it, none over the empty space; an `Onto` kind on the same board is unchanged; a double click on the
/// empty space reports its screen point, the one a secondary click there reports.
#[trial]
fn a_drop_in_a_free_layout_reports_its_spot_and_the_empty_space_its_screen_point() {
let (scale, offset) = (0.5, Vec2::new(30.0, 20.0));
let words = Words::flat(&["a", "b", "c"]);
let (photos, rows, board_at) = (Shown::default(), Shown::default(), Shown::default());
let events = RefCell::new(Events::new());
let mut frames = Frames::new();
let mut show = |ui: &mut Ui| {
in_region(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(150.0, 100.0)), |ui| {
let from = List::new(SelectMode::Single).drag_payload(|drag: &ListDrag<usize>| Some(Photo(drag.grabbed)));
let _ = from.id_salt("photos").show_items(ui, &words, &mut |key, cx| {
photos.note(*key, cx.rect);
Row::new()
});
});
in_region(ui, Rect::from_min_size(Pos2::new(10.0, 130.0), Vec2::new(150.0, 100.0)), |ui| {
let _ = List::new(SelectMode::Single).reorder().id_salt("rows").show_items(ui, &words, &mut |key, cx| {
rows.note(*key, cx.rect);
Row::new()
});
});
in_region(ui, Rect::from_min_size(Pos2::new(200.0, 10.0), Vec2::new(400.0, 300.0)), |ui| {
let spot = DropKind::new(DropPlace::Spot, |_: &Photo, _: &DropAt<usize>| true);
let onto = DropKind::new(DropPlace::Onto, |_: &ListDrag<usize>, _: &DropAt<usize>| true);
let board = Board::new(three_items()).takes_drop(spot).takes_drop(onto).transformed(CanvasTransform::new(scale, offset));
let out = board.id_salt("board").show_items(ui, &Count(3), &mut |key, cx| {
board_at.note(*key, cx.rect);
Row::new()
});
events.borrow_mut().extend(out.events);
});
};
frames.idle(3, &mut show);
// The board's own space starts at its first item; the transform scales about it and moves by `offset`.
let origin = board_at.rect(0).min;
let screen = |own: Pos2| origin + (own - origin) * scale + offset;
let drop_at = |frames: &mut Frames, from: Pos2, own: Pos2, show: &mut dyn FnMut(&mut Ui)| {
let to = screen(own);
frames.frame(vec![moved(from)], &mut *show);
frames.frame(vec![press(from)], &mut *show);
for step in 1..=4 {
frames.frame(vec![moved(from + (to - from) * (step as f32 / 4.0))], &mut *show);
}
frames.idle(1, &mut *show);
frames.frame(vec![release(to)], &mut *show);
frames.idle(2, &mut *show);
};
let drops = |events: &RefCell<Events>| -> Vec<DropAt<usize>> {
let taken = events.borrow().iter().filter_map(|event| if let CollectionEvent::Dropped { at, .. } = event { Some(at.clone()) } else { None }).collect();
events.borrow_mut().clear();
taken
};
let on_item = board_at.rect(1).center() + Vec2::new(5.0, -5.0);
drop_at(&mut frames, photos.rect(0).center(), on_item, &mut show);
let got = drops(&events);
assert!(
matches!(got.as_slice(), [DropAt::Spot { over: Some(1), at, .. }] if (*at - on_item).length() < SAME),
"the drop over an item is at its point in the items' own space, over the item: {got:?}"
);
assert!((screen(on_item) - on_item).length() > 10.0, "the transform moves the point, so a forgotten mapping shows");
let empty = origin + Vec2::new(300.0, 40.0);
drop_at(&mut frames, photos.rect(1).center(), empty, &mut show);
let got = drops(&events);
assert!(
matches!(got.as_slice(), [DropAt::Spot { over: None, at, .. }] if (*at - empty).length() < SAME),
"the drop on the empty space is at its point, over no item: {got:?}"
);
drop_at(&mut frames, rows.rect(0).center(), board_at.rect(2).center(), &mut show);
assert_eq!(drops(&events), [DropAt::Onto(2)], "an `Onto` kind of a free layout still drops onto the item");
let space = screen(empty);
frames.advance(1.0);
for _ in 0..2 {
frames.frame(vec![moved(space)], &mut show);
frames.frame(vec![press(space)], &mut show);
frames.frame(vec![release(space)], &mut show);
}
frames.idle(1, &mut show);
frames.advance(1.0);
frames.frame(vec![secondary(space, true)], &mut show);
frames.frame(vec![secondary(space, false)], &mut show);
frames.idle(1, &mut show);
let events = events.borrow();
let activated: Vec<Pos2> =
events.iter().filter_map(|event| if let CollectionEvent::EmptyActivated { at, .. } = event { Some(*at) } else { None }).collect();
let menu: Vec<Pos2> =
events.iter().filter_map(|event| if let CollectionEvent::EmptyContextMenu { at, .. } = event { Some(*at) } else { None }).collect();
assert_eq!(activated.len(), 1, "the double click on the empty space is reported once: {events:?}");
assert!((activated[0] - space).length() < SAME, "at its screen point, not mapped into the items' space: {activated:?}");
assert!(menu.iter().any(|at| (*at - activated[0]).length() < SAME), "the point a secondary click there reports: {menu:?}");
}
/// What the `Move` events of a run were: begins, updates, commits with their offset, and cancels.
#[derive(Debug, Default, PartialEq)]
struct Moves {
begins: usize,
updates: usize,
commits: Vec<Vec2>,
cancels: usize,
}
fn moves(events: &RefCell<Events>) -> Moves {
let mut seen = Moves::default();
for event in events.borrow_mut().drain(..) {
match event {
CollectionEvent::Move(EditEvent::Begin { .. }) => seen.begins += 1,
CollectionEvent::Move(EditEvent::Update { .. }) => seen.updates += 1,
CollectionEvent::Move(EditEvent::Commit { after, .. }) => seen.commits.push(after),
CollectionEvent::Move(EditEvent::Cancel { .. }) => seen.cancels += 1,
_ => {}
}
}
seen
}
/// ge.C32 (q78): a primary drag pressed on a part the board moves from reports the selection's move, one gesture whose
/// commit carries the pointer's travel, also when a pass of the drag reruns; Escape cancels it; a drag pressed on a
/// part the board does not move from reports no move.
#[trial]
fn a_press_on_a_declared_part_moves_the_selection_when_the_collection_says_so() {
let (grip, knob) = (Rect::from_min_size(Pos2::new(200.0, 20.0), Vec2::new(40.0, 20.0)), Rect::from_min_size(Pos2::new(200.0, 80.0), Vec2::new(40.0, 20.0)));
let selection = Rc::new(RefCell::new(Selection::<usize>::default()));
let (shown, events, discard) = (Rc::new(Shown::default()), Rc::new(RefCell::new(Events::new())), Rc::new(Cell::new(false)));
let mut fixture = Fixture::new({
let (selection, shown, events, discard) = (selection.clone(), shown.clone(), events.clone(), discard.clone());
move |ui: &mut Ui| {
// A pass the trial discards reports nothing the app keeps: its rerun is the frame's pass.
let discarded = discard.take();
if discarded {
craft_ui::runtime::frame::discard_pass(ui.ctx(), "the trial reruns a pass of the drag");
}
let mut held = selection.borrow().clone();
let board = Board::new(three_items()).with_parts(grip, knob).selection(Bind::bound(&mut held));
let out = board.id_salt("board").show_items(ui, &Count(3), &mut |key, cx| {
shown.note(*key, cx.rect);
Row::new()
});
*selection.borrow_mut() = held;
if !discarded {
events.borrow_mut().extend(out.events);
}
}
});
fixture.idle(3);
// The parts sit at their rects from the board's top left, where its first item sits.
let origin = shown.rect(0).min;
let (grip_at, knob_at) = (origin + grip.center().to_vec2(), origin + knob.center().to_vec2());
fixture.click_at(shown.rect(0).center()).advance(1.0).idle(1);
assert_eq!(sorted(&selection), [0]);
moves(&events);
let by = Vec2::new(40.0, 30.0);
fixture.frame(vec![moved(grip_at)]).frame(vec![press(grip_at)]);
for step in 1..=4 {
// The third step's frame runs two passes; only its first gets the input.
discard.set(step == 3);
fixture.frame(vec![moved(grip_at + by * (step as f32 / 4.0))]);
}
fixture.frame(vec![release(grip_at + by)]).idle(1);
let grip_drag = moves(&events);
assert_eq!((grip_drag.begins, grip_drag.cancels), (1, 0), "one gesture: {grip_drag:?}");
assert!(grip_drag.updates > 0, "the move follows the pointer: {grip_drag:?}");
assert!(
matches!(grip_drag.commits.as_slice(), [after] if (*after - by).length() < SAME),
"the release commits the pointer's travel: {grip_drag:?}"
);
fixture.advance(1.0).drag_hold_at(grip_at, by);
fixture.key(Key::Escape, Modifiers::NONE).release_at(grip_at + by);
let cancelled = moves(&events);
assert_eq!((cancelled.begins, cancelled.cancels), (1, 1), "Escape cancels the move: {cancelled:?}");
assert!(cancelled.commits.is_empty(), "and nothing commits: {cancelled:?}");
fixture.advance(1.0).drag_at(knob_at, by);
assert_eq!(moves(&events), Moves::default(), "a part the board does not move from moves nothing");
assert_eq!(sorted(&selection), [0], "the selection is as it was");
}
+2
View File
@@ -11,6 +11,7 @@ pub(crate) mod contract;
pub(crate) mod drag;
pub(crate) mod egui_surface;
pub(crate) mod fonts;
pub(crate) mod free_layout_selection;
pub(crate) mod icon_ids;
pub(crate) mod keys_consumed;
pub(crate) mod layout;
@@ -23,6 +24,7 @@ pub(crate) mod story_command_subsets;
pub(crate) mod style;
pub(crate) mod text;
pub(crate) mod textures;
pub(crate) mod view_scale;
craft_ui::registry!();
+128
View File
@@ -0,0 +1,128 @@
//! The view scale (`EnvView::view_scale`): the product of the transform scales of the bodies around a scope, which a
//! child measures for, starting over at 1.0 in a layer opened inside them.
use craft_behavior::CanvasTransform;
use craft_ui::contract::{
Common, Component, Container, ContainerProps, Cx, MemoProps, MemoView, Mount, Overlay, Props as _, Role, Show as _, ShowContainer as _, Sizing,
};
use craft_ui::runtime::env::Env;
use craft_ui::style::StyleCx;
use craft_ui::testing::layout::in_region;
use craft_ui::testing::{Frames, MemoRun, last_frame_memo_runs, trial};
use craft_ui_test_kit::contract::{PlainStyle, Probe, Seen};
use egui::{Pos2, Rect, Response, Ui, Vec2};
use std::cell::{Cell, RefCell};
/// A container whose body shows through the transform its props give, or opens a layer.
#[derive(Component)]
#[component(container, unregistered)]
struct Zoomed {
#[common]
common: Common,
#[container]
props: ContainerProps,
}
impl Zoomed {
fn through(transform: CanvasTransform) -> Self {
Zoomed { common: Common::new(), props: ContainerProps::new().sizing(Sizing::Fill).transform(transform) }
}
fn layer() -> Self {
Zoomed { common: Common::new(), props: ContainerProps::new().mount(Mount::Layer(Overlay::modal())) }
}
}
impl Component for Zoomed {
const ROLE: Role = Role::GROUP;
type Style = PlainStyle;
type Output = Response;
fn style(_: &StyleCx<'_>, _: ZoomedStyleKey) -> PlainStyle {
PlainStyle::min(Vec2::new(120.0, 60.0))
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
impl Container for Zoomed {}
thread_local! {
/// The view scale the `Scaled` view measured for in its last run.
static MEASURED: Cell<f32> = const { Cell::new(0.0) };
}
/// A view that sizes its content by the view scale, as text that keeps its size on screen does.
#[derive(MemoProps)]
struct Scaled {
width: f32,
}
fn scaled(props: &mut Scaled, ui: &mut Ui) {
let scale = Env::of(ui).view().view_scale();
MEASURED.with(|measured| measured.set(scale));
let seen = RefCell::new(Seen::default());
Probe::new(&seen).size(Vec2::new(props.width / scale, 20.0)).id_salt("content").show(ui);
}
/// How many times the `Scaled` view ran in the last frame.
fn runs(frames: &Frames) -> usize {
last_frame_memo_runs(&frames.ctx).into_iter().filter(|(name, _, run)| name.contains("Scaled") && *run == MemoRun::Ran).count()
}
/// What each scope read.
#[derive(Default)]
struct Read {
outside: f32,
outer: f32,
inner: f32,
layer: Option<f32>,
}
/// ge.C12 (q51): nested transformed bodies multiply their scales; a layer opened inside them reads 1.0; a child that
/// measures from the view scale runs again when the zoom changes and not when the view pans.
#[trial]
fn view_scale_multiplies_through_zoomed_bodies_and_starts_over_in_a_layer() {
let outer = Cell::new(CanvasTransform::new(2.0, Vec2::ZERO));
let inner = CanvasTransform::new(1.5, Vec2::new(4.0, 2.0));
let read = RefCell::new(Read::default());
let scale_of = |ui: &Ui| Env::of(ui).view().view_scale();
let mut frames = Frames::new();
let mut show = |ui: &mut Ui| {
in_region(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(500.0, 400.0)), |ui| {
read.borrow_mut().outside = scale_of(ui);
Zoomed::through(outer.get()).id_salt("outer").show(ui, |ui, _| {
read.borrow_mut().outer = scale_of(ui);
Zoomed::through(inner).id_salt("inner").show(ui, |ui, _| {
read.borrow_mut().inner = scale_of(ui);
let _ = MemoView::new("scaled", Scaled { width: 80.0 }, scaled).show(ui);
Zoomed::layer().id_salt("popup").show(ui, |ui, _| {
read.borrow_mut().layer = Some(scale_of(ui));
});
});
});
});
};
frames.idle(30, &mut show);
{
let read = read.borrow();
assert_eq!(read.outside, 1.0, "outside every transform the scale is 1");
assert!((read.outer - outer.get().scale).abs() < 1e-4, "one transform gives its scale: {}", read.outer);
assert!((read.inner - read.outer * inner.scale).abs() < 1e-4, "a nested transform multiplies: {}", read.inner);
assert_eq!(read.layer, Some(1.0), "a layer opened inside the zoomed bodies starts over");
}
assert!((MEASURED.with(Cell::get) - read.borrow().inner).abs() < 1e-4, "the view measured for the scale around it");
assert_eq!(runs(&frames), 0, "a settled view replays");
outer.set(CanvasTransform::new(outer.get().scale, Vec2::new(25.0, 10.0)));
frames.idle(1, &mut show);
assert_eq!(runs(&frames), 0, "a pan leaves the view's measure as it was");
outer.set(CanvasTransform::new(3.0, outer.get().offset));
frames.idle(1, &mut show);
assert!(runs(&frames) > 0, "a zoom runs the view again");
assert!((read.borrow().inner - 3.0 * inner.scale).abs() < 1e-4, "the product follows the zoom");
assert!((MEASURED.with(Cell::get) - read.borrow().inner).abs() < 1e-4, "and the view measured for it");
}
@@ -162,13 +162,11 @@ fn a_double_click_on_the_background_activates_the_empty_space() {
seen.borrow().collection.iter().filter(|event| of(event)).count()
};
fixture.click_at(empty_space).click_at(empty_space).idle(1);
// P3(graph-w2): ge.C9
assert_eq!(count(&seen, |event| matches!(event, CollectionEvent::EmptyActivated { .. })), 1, "the background's double click is reported once");
assert_eq!(count(&seen, |event| matches!(event, CollectionEvent::Activate(_))), 0, "no tile activates");
fixture.advance(1.0).idle(1);
fixture.click_at(tile.center()).click_at(tile.center()).idle(1);
assert_eq!(count(&seen, |event| matches!(event, CollectionEvent::Activate(1))), 1, "a double click on a tile activates it");
// P3(graph-w2): ge.C9
assert_eq!(count(&seen, |event| matches!(event, CollectionEvent::EmptyActivated { .. })), 1, "and is no background double click");
}