diff --git a/crates/behavior/src/keys.rs b/crates/behavior/src/keys.rs index 6e98332f1..533e2ed70 100644 --- a/crates/behavior/src/keys.rs +++ b/crates/behavior/src/keys.rs @@ -217,12 +217,29 @@ pub enum DropOperation { Link, } -/// The drop operation the held modifiers pick. -pub fn drop_operation(os: Os, mods: Mods) -> DropOperation { - let link = if os == Os::Mac { mods.cmd && mods.alt } else { mods.cmd && mods.shift }; +/// Which held key turns a drag into a copy over a target. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum CopyKeys { + /// Alt, Option on macOS: a design app's duplicating drag (Photoshop's layers). + #[default] + Alt, + /// The file manager's: Ctrl off macOS, Option on macOS (Explorer, Finder, a document's page grid). + Platform, +} + +/// The drop operation the held modifiers pick over a target that copies with `copy`. Link is Ctrl+Shift, Cmd+Option on +/// macOS, whatever the copy keys. +pub fn drop_operation(os: Os, mods: Mods, copy: CopyKeys) -> DropOperation { + let mac = os == Os::Mac; + let link = if mac { mods.cmd && mods.alt } else { mods.cmd && mods.shift }; + let copies = match copy { + CopyKeys::Platform if !mac => mods.cmd, + _ => mods.alt, + }; if link { DropOperation::Link - } else if mods.alt { + } else if copies { DropOperation::Copy } else { DropOperation::Move diff --git a/crates/behavior/src/lib.rs b/crates/behavior/src/lib.rs index 75357d8b7..2ca15409c 100644 --- a/crates/behavior/src/lib.rs +++ b/crates/behavior/src/lib.rs @@ -89,7 +89,7 @@ pub use intent::{AccessRequest, EditCommand, Granularity, Intent, MoveMods, NavM pub use item_layout::{FreeLayout, ItemLayout, LineIndex, SHEET_ZOOM, SheetLayout, SpanLayout, TileLayout}; pub use item_marquee::{MarqueeMode, MarqueeSelect}; pub use item_source::{DisplayOrder, ItemSource, Keyed, Outline, SizeHint, keyed}; -pub use keys::{DropOperation, KeyRole, ReorderKeys}; +pub use keys::{CopyKeys, DropOperation, KeyRole, ReorderKeys}; pub use label_column::{LabelColumn, LabelPlacement}; pub use layout_memory::SizeTween; pub use middle_scroll::{MiddleButton, MiddleScroll}; diff --git a/crates/draw/src/ui/transform/transform_box.rs b/crates/draw/src/ui/transform/transform_box.rs index 471d47997..6fa3d9c41 100644 --- a/crates/draw/src/ui/transform/transform_box.rs +++ b/crates/draw/src/ui/transform/transform_box.rs @@ -107,7 +107,7 @@ pub enum RotateZone { /// Only the band outside a corner (PhotoCraft's Move tool controls); the rest of the outside is the tool's. Band, /// A round handle on a stem above the box's top side, or below its bottom side when the canvas has no room above. - /// It rotates like the outside, and no outside region is declared. + /// It rotates like the outside under the grab pointer (grabbing while it turns), and no outside region is declared. Knob, /// Only within `points` screen points of the box's sides (PhotoCraft's type box with ⌘ held). The whole outside is /// still the box's: a press further out starts nothing and applies nothing, and reaches neither the content under @@ -568,10 +568,14 @@ impl<'a> TransformBox<'a> { let turn = || Cursor::from(PaintedCursor::turn(quad::bisector(screen, corner))); let along = |from: usize| vec2_of(screen.quad[(from + 1) % 4] - screen.quad[from % 4]); match (kind, part) { + // The knob is a handle the pointer takes hold of and swings, not a stretch of the outside. + (BoxDrag::Rotate, BoxPart::Outside) if self.rotate_zone == RotateZone::Knob => { + if dragging { CursorIcon::Grabbing } else { CursorIcon::Grab }.into() + } (BoxDrag::Rotate, BoxPart::Outside) if !dragging && !self.rotate_zone.rotates_at(&screen.quad, pointer) => CursorIcon::Default.into(), (BoxDrag::Rotate, BoxPart::Outside) => { if dragging - || matches!(self.rotate_zone, RotateZone::Band | RotateZone::Knob | RotateZone::Border { .. }) + || matches!(self.rotate_zone, RotateZone::Band | RotateZone::Border { .. }) || away <= style.rotate_reach { turn() diff --git a/crates/draw/tests/it/transform_box.rs b/crates/draw/tests/it/transform_box.rs index 84620d2e1..5ef021c9b 100644 --- a/crates/draw/tests/it/transform_box.rs +++ b/crates/draw/tests/it/transform_box.rs @@ -1092,7 +1092,8 @@ fn a_sides_only_box_takes_presses_on_its_side_edges_only() { } /// The rotate knob stands above the box, or below it at the canvas's top edge; a ⇧ drag on it turns the box by whole -/// rotate steps, and a click on it applies nothing. The knob is found as the app finds it, by its access-tree name. +/// rotate steps under the grab pointer, and a click on it applies nothing. The knob is found as the app finds it, by +/// its access-tree name. #[trial] fn a_knob_sits_below_a_box_at_the_top_turns_in_shift_steps_and_a_click_on_it_applies_nothing() { let knob_of = |h: &Harness| h.fixture.by_label("Rotate").map(|target| target.center()); @@ -1128,9 +1129,11 @@ fn a_knob_sits_below_a_box_at_the_top_turns_in_shift_steps_and_a_click_on_it_app centre + by(v.x * cos - v.y * sin, v.x * sin + v.y * cos) }; frame(&mut h, vec![pointer::moved(knob)]); + assert_eq!(h.fixture.cursor_icon(), egui::CursorIcon::Grab, "the knob offers to be taken hold of"); frame(&mut h, vec![pointer::press(knob)]); frame(&mut h, vec![pointer::moved(around(10.0))]); frame(&mut h, vec![pointer::moved(around(25.0))]); + assert_eq!(h.fixture.cursor_icon(), egui::CursorIcon::Grabbing, "and holds it while it turns"); frame(&mut h, vec![pointer::release(around(25.0))]); frame(&mut h, Vec::new()); let angle = h.state().angle().rem_euclid(360.0); diff --git a/crates/layers/src/ui/panel/body.rs b/crates/layers/src/ui/panel/body.rs index 3e101044a..4ba9abf36 100644 --- a/crates/layers/src/ui/panel/body.rs +++ b/crates/layers/src/ui/panel/body.rs @@ -9,7 +9,7 @@ pub(in crate::ui::panel) use map::start_rename; pub(in crate::ui::panel) use rows::{LayerRows, ToggleSweeps, reveal_plan, thumb_click_replaces_select}; use rows::{RevealPlan, list_selection}; -use craft_behavior::{ColumnWidth, IconId}; +use craft_behavior::{ColumnWidth, CopyKeys, IconId}; use craft_keymap::Mods; use craft_ui::contract::{ Bind, CollectionEvent, ColumnSpec, DropAt, DropKind, DropPlace, ListDrag, PendingDrop, Props as _, ReorderRule, ShowCollection as _, ToggleColumn, @@ -69,7 +69,7 @@ pub(super) fn show_body( let mut list = List::new(cx.words.list.clone()) .id(cx.list) .tree(true) - .reorder(ReorderRule::new().into_groups().copy_with_alt()) + .reorder(ReorderRule::new().into_groups().copy_with(CopyKeys::Alt)) .allow_empty(true) .rename(true) .rename_column(NAME) diff --git a/crates/pages/src/ui/thumbnails.rs b/crates/pages/src/ui/thumbnails.rs index 39fed1af3..bfa895929 100644 --- a/crates/pages/src/ui/thumbnails.rs +++ b/crates/pages/src/ui/thumbnails.rs @@ -24,7 +24,7 @@ mod stories; use super::view::PageSource; -use craft_behavior::{EditEvent, IconId, MiddleButton, Selection, SelectionChange, SelectionModel as _, keyed}; +use craft_behavior::{CopyKeys, EditEvent, IconId, MiddleButton, Selection, SelectionChange, SelectionModel as _, keyed}; use craft_ui::contract::{ Bind, CollectionEvent, ContextMenuRequest, DropAt, DropKind, DropPlace, IdSource, NoValue, OsFiles, Outcome, PendingDrop, Props as _, ReorderMove, ReorderRule, Show as _, ShowCollection as _, @@ -448,7 +448,8 @@ impl<'a> PageThumbnails<'a> { grid = grid.checks(true).action_place(TileActionPlace::Band); } if editable { - let rule = if organize { ReorderRule::new().copy_with_alt() } else { ReorderRule::new() }; + // Pages copy as files do in a file manager: Ctrl off macOS, Option on macOS. + let rule = if organize { ReorderRule::new().copy_with(CopyKeys::Platform) } else { ReorderRule::new() }; grid = grid .reorder(rule) .accepts(move |_, _, insert| insert <= new_page) diff --git a/crates/pages/tests/it/thumbnails.rs b/crates/pages/tests/it/thumbnails.rs index b077a62ee..210ab0c9e 100644 --- a/crates/pages/tests/it/thumbnails.rs +++ b/crates/pages/tests/it/thumbnails.rs @@ -44,6 +44,61 @@ fn a_moved_page_keeps_its_identity_across_a_move() { assert_eq!(moved, vec![1, 2, 3, 0, 4]); } +/// An Organize grid of `count` pages with id `id` and current page `current`; the events it reports and the picked set. +fn organize_rig(count: usize, id: egui::Id, current: usize) -> (Fixture, Rc>>, Rc>>) { + let events: Rc>> = Rc::default(); + let seen = Rc::clone(&events); + let picked: Rc>> = Rc::default(); + let held = Rc::clone(&picked); + let pages = DemoPages::new(count); + let mut fixture = Fixture::new(move |ui| { + let mut picked = held.borrow_mut(); + let out = + PageThumbnails::new("Pages", &pages, &mut picked, current, PAPER).arrangement(ThumbnailArrangement::Organize).id(id).show(ui); + seen.borrow_mut().extend(out.events); + }); + fixture.room(vec2(600.0, 600.0)); + fixture.settle(); + (fixture, events, picked) +} + +/// The middle of page `n`'s tile (counted from 1). +fn tile(fixture: &Fixture, n: usize) -> egui::Pos2 { + fixture.by_label(&format!("Page {n}")).expect("a tile per page").center() +} + +/// A drag the host ends with `cancel_press` (its pages changed under it) lands nothing on its release, and the next +/// drag lands its move on its release as any drag does. +#[trial] +fn after_a_cancelled_drag_the_next_drag_lands_its_move() { + let id = egui::Id::new("organize"); + let (mut fixture, events, _) = organize_rig(4, id, 0); + let (from, to) = (tile(&fixture, 1), tile(&fixture, 3)); + let reorders = |events: &RefCell>| events.borrow().iter().filter(|event| matches!(event, ThumbnailEvent::Reorder(_))).count(); + fixture.drag_hold_at(from, to - from); + PageThumbnails::cancel_press(fixture.ctx(), id); + fixture.frame(Vec::new()); + fixture.release_at(to).settle(); + assert_eq!(reorders(&events), 0, "the cancelled drag lands nothing: {:?}", events.borrow()); + fixture.drag_at(from, to - from).settle(); + assert_eq!(reorders(&events), 1, "the next drag lands its move: {:?}", events.borrow()); +} + +/// With no page picked, the current page counts as picked: a Cmd/Ctrl-click on another page picks both, and a +/// Shift-click picks the run from the current page. +#[trial] +fn a_modified_click_on_an_empty_pick_starts_from_the_current_page() { + for (modifiers, want) in [(egui::Modifiers::COMMAND, vec![1, 3]), (egui::Modifiers::SHIFT, vec![1, 2, 3])] { + let (mut fixture, _, picked) = organize_rig(5, egui::Id::new("organize"), 1); + let page = tile(&fixture, 4); + fixture.hold(modifiers).click_at(page).settle(); + fixture.hold(egui::Modifiers::NONE); + let picked = picked.borrow(); + let got: Vec = (0..5).filter(|page| picked.contains(page)).collect(); + assert_eq!(got, want, "{modifiers:?}-click on page 4 with page 2 current"); + } +} + /// In Organize a click on a page's check adds it to the picked pages without a modifier, and goes to it. #[trial] fn an_organize_check_toggles_its_page_without_modifiers_and_goes_to_it() { diff --git a/crates/pages/tests/it/views.rs b/crates/pages/tests/it/views.rs index 9d9c232fe..2b448994b 100644 --- a/crates/pages/tests/it/views.rs +++ b/crates/pages/tests/it/views.rs @@ -181,6 +181,47 @@ fn a_changed_zoom_keeps_the_point_at_the_centre_and_a_new_room_the_current_pages assert!((after - before).abs() < 1.0, "the current page's top stays put: {before} then {after}"); } +/// Turning the page gaps off keeps the scroll offset, as production did, so the pages below the top close up toward +/// it; also when the gaps change while the view is hidden (a page grid shown in its place) and it shows again. +#[trial] +fn a_page_gap_change_keeps_the_scroll_offset() { + for fit in [Fit::None, Fit::Width] { + for hidden in [false, true] { + let source = DemoPages::new(5); + let state = Rc::new(RefCell::new(state_with(|s| s.fit = fit))); + let shows = Rc::new(Cell::new(true)); + let rects: Rc>> = Rc::default(); + let (kept, seen, showing) = (Rc::clone(&state), Rc::clone(&rects), Rc::clone(&shows)); + let mut fixture = Fixture::new(move |ui| { + if !showing.get() { + return; + } + let mut now = kept.borrow().clone(); + let shown = PageView::new("Pages", &source, &mut now, PAPER).options(LayoutOptions::ACROBAT).show(ui, &mut |_: &mut egui::Ui, _: &PageBody<'_>| ()); + *seen.borrow_mut() = shown.layout.rects.clone(); + *kept.borrow_mut() = now; + }); + fixture.room(vec2(900.0, 600.0)); + fixture.settle(); + state.borrow_mut().go_to_fraction(1, 0.0); + fixture.idle(3); + let offset = state.borrow().offset; + assert_eq!(state.borrow().current, 1, "precondition: the second page is current"); + shows.set(!hidden); + fixture.idle(2); + state.borrow_mut().page_gaps = false; + fixture.idle(2); + shows.set(true); + fixture.idle(3); + let after = state.borrow().offset; + assert!( + (after.0 - offset.0).abs() < 0.5 && (after.1 - offset.1).abs() < 0.5, + "{fit:?}, hidden {hidden}: the offset stays: {offset:?} then {after:?}" + ); + } + } +} + /// A wheel step of `lines` over the middle of the room. fn wheel(fixture: &mut Fixture, lines: f32) { let middle = pos2(450.0, 300.0); diff --git a/crates/ui-canvas/tests/it/canvas/mod.rs b/crates/ui-canvas/tests/it/canvas/mod.rs index 315dbd878..fba37e58e 100644 --- a/crates/ui-canvas/tests/it/canvas/mod.rs +++ b/crates/ui-canvas/tests/it/canvas/mod.rs @@ -2,6 +2,8 @@ mod crop; +mod modal_wheel; + mod navigate; mod navigator; diff --git a/crates/ui-canvas/tests/it/canvas/modal_wheel.rs b/crates/ui-canvas/tests/it/canvas/modal_wheel.rs new file mode 100644 index 000000000..314fe1eeb --- /dev/null +++ b/crates/ui-canvas/tests/it/canvas/modal_wheel.rs @@ -0,0 +1,83 @@ +//! The wheel over a canvas a modal covers. + +use craft_behavior::CanvasView; +use craft_behavior::kurbo::{Point, Size}; +use craft_ui::canvas::{Canvas, NavigationOptions}; +use craft_ui::contract::{Common, Component, Container, ContainerProps, Cx, Mount, Overlay, Props as _, Role, ShowContainer as _}; +use craft_ui::style::StyleCx; +use craft_ui::testing::{Fixture, pointer, trial}; +use craft_ui_test_kit::contract::PlainStyle; +use egui::{Response, Vec2}; +use std::cell::Cell; +use std::rc::Rc; + +/// A modal layer with an empty body. +#[derive(craft_ui::contract::Component)] +#[component(container, unregistered)] +struct Modal { + #[common] + common: Common, + #[container] + props: ContainerProps, +} + +impl Component for Modal { + const ROLE: Role = Role::GROUP; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: ModalStyleKey) -> PlainStyle { + PlainStyle::min(Vec2::new(120.0, 60.0)) + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +impl Container for Modal {} + +/// A modal opened over a canvas holds the wheel: neither a wheel line nor a press the canvas held from before the +/// modal opened moves the view, plain or eased. +#[trial] +fn the_wheel_over_a_canvas_under_a_modal_moves_nothing() { + for eased in [false, true] { + for held in [false, true] { + let mut options = NavigationOptions::default(); + options.eased_wheel = eased; + let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0))); + let open = Rc::new(Cell::new(false)); + let (shown, modal) = (Rc::clone(&view), Rc::clone(&open)); + let mut fixture = Fixture::new(move |ui| { + let mut given = shown.get(); + given.rect = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |_, _| {}); + shown.set(canvas.output.view.unwrap_or(given)); + if modal.get() { + let props = ContainerProps::new().mount(Mount::Layer(Overlay::modal())); + Modal { common: Common::new(), props }.id_salt("modal").show(ui, |_, _| {}); + } + }); + fixture.settle(); + let at = view.get().rect.center() + Vec2::new(0.0, 150.0); + fixture.frame(vec![pointer::moved(at)]); + let start = view.get(); + fixture.frame(vec![pointer::wheel(-30.0)]); + fixture.idle(40); + assert!(view.get().center.y > start.center.y + 1.0, "precondition: the wheel scrolls the bare canvas"); + if held { + fixture.frame(vec![pointer::press(at)]); + } + open.set(true); + fixture.idle(3); + let before = view.get(); + fixture.frame(vec![pointer::wheel(-30.0)]); + fixture.idle(40); + let after = view.get(); + assert!( + (after.center.y - before.center.y).abs() < 1e-3 && after.zoom == before.zoom, + "eased {eased}, held {held}: the view moved under the modal: {before:?} -> {after:?}" + ); + } + } +} diff --git a/crates/ui-contract/src/contract/collection/events.rs b/crates/ui-contract/src/contract/collection/events.rs index 1791e044f..3d3640a0c 100644 --- a/crates/ui-contract/src/contract/collection/events.rs +++ b/crates/ui-contract/src/contract/collection/events.rs @@ -24,7 +24,7 @@ pub struct ReorderMove { pub keys: Vec, /// The new position of the first of `keys`, counted in the order that remains once all of them are taken out. pub to: usize, - /// The drag was a copy (Alt held, `ReorderRule::copy_with_alt`): the item stays and a copy goes to `to`. + /// The drag was a copy (the copy keys of `ReorderRule::copy_with` held): the item stays and a copy goes to `to`. pub copy: bool, /// The group the items land in: `None` at the top level, and always `None` unless the rule has `into_groups`. pub parent: Option, diff --git a/crates/ui-contract/src/contract/collection/props.rs b/crates/ui-contract/src/contract/collection/props.rs index a4df19641..3fb6dc6c5 100644 --- a/crates/ui-contract/src/contract/collection/props.rs +++ b/crates/ui-contract/src/contract/collection/props.rs @@ -6,7 +6,7 @@ use crate::contract::Notch; pub use crate::runtime::env::RowPressed; use crate::runtime::env::{Counted, Label}; use crate::style::StyleCx; -use craft_behavior::{Axis, ColumnKey, MiddleButton, ReorderKeys}; +use craft_behavior::{Axis, ColumnKey, CopyKeys, MiddleButton, ReorderKeys}; use std::any::Any; use std::sync::Arc; @@ -29,8 +29,8 @@ pub enum SelectMode { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct ReorderRule { - /// Alt turns a drag into a copy (8.4). - pub copy_with_alt: bool, + /// The held key that turns a drag into a copy (8.4); `None`: a drag only moves. + pub copy: Option, /// In a tree, a drop or a stacking-key move may land inside a group, and `ReorderMove::parent` names the group. A row /// that `has_children` is a group; an open group without visible children takes items through the middle of its row. pub into_groups: bool, @@ -41,7 +41,7 @@ pub struct ReorderRule { impl ReorderRule { /// A rule that only moves. pub const fn new() -> Self { - ReorderRule { copy_with_alt: false, into_groups: false, keys: ReorderKeys::Stacking } + ReorderRule { copy: None, into_groups: false, keys: ReorderKeys::Stacking } } /// The key scheme that reorders the items. @@ -58,10 +58,11 @@ impl ReorderRule { self } - /// Alt copies. + /// A drag with `keys` held copies: [`CopyKeys::Alt`] in a design app's layers, [`CopyKeys::Platform`] (Ctrl off + /// macOS) in a file or page grid. #[must_use] - pub const fn copy_with_alt(mut self) -> Self { - self.copy_with_alt = true; + pub const fn copy_with(mut self, keys: CopyKeys) -> Self { + self.copy = Some(keys); self } } diff --git a/crates/ui-contract/src/contract/cx/pointer.rs b/crates/ui-contract/src/contract/cx/pointer.rs index 623ae4e1f..f1899e110 100644 --- a/crates/ui-contract/src/contract/cx/pointer.rs +++ b/crates/ui-contract/src/contract/cx/pointer.rs @@ -158,10 +158,10 @@ impl Pointer for CxCore<'_> { fn window_drop_target>(&mut self, target: &T) -> Option { let payload = drag::active::

(&self.ctx).filter(|_| !drag::moves_viewport(&self.ctx))?; - let op = drag::current_operation(&self.ctx); + let op = drag::current_operation(&self.ctx, craft_behavior::CopyKeys::Alt); let drop = target.accept(&payload, op)?; let ordinal = drag::next_ordinal(&self.ctx, self.id); - drag::register(&self.ctx, self.id, self.response.layer_id, target.mark(&drop), true); + drag::register(&self.ctx, self.id, self.response.layer_id, target.mark(&drop), op, true); drag::take_drop(&self.ctx, self.id, ordinal, op, TypeId::of::

()).then_some(drop) } diff --git a/crates/ui-contract/src/contract/items/drag.rs b/crates/ui-contract/src/contract/items/drag.rs index 7e6c48fa2..eb421a6a7 100644 --- a/crates/ui-contract/src/contract/items/drag.rs +++ b/crates/ui-contract/src/contract/items/drag.rs @@ -18,7 +18,7 @@ use crate::contract::{Collection, Cx, DragPreview, DropMark, DropTarget, Pointer use crate::runtime::drag; use crate::runtime::env::Label; use craft_behavior::{ - Axis, CancelReason, ColumnKey, DropOperation, EditEvent, Flow, GestureId, ItemLayout, Mixed, NavShape, Outline, PointerButton, PressCancel, + Axis, CancelReason, ColumnKey, CopyKeys, DropOperation, EditEvent, Flow, GestureId, ItemLayout, Mixed, NavShape, Outline, PointerButton, PressCancel, PressPhase, ScrollPos, }; use egui::{Pos2, Rect, Vec2}; @@ -243,15 +243,15 @@ struct Landed { struct RowDrop { spot: Option, - /// Whether the held Alt may turn the drop into a copy. - copy_ok: bool, + /// The held key that turns the drop into a copy; `None`: the drop only moves. + copy: Option, } impl DropTarget> for RowDrop { type Drop = Landed; fn accept(&self, _: &ListDrag, _: Pos2, op: DropOperation) -> Option { - if matches!(op, DropOperation::Copy) && !self.copy_ok { + if matches!(op, DropOperation::Copy) && self.copy.is_none() { return None; } self.spot.map(|spot| Landed { spot, op }) @@ -260,6 +260,10 @@ impl DropTarget> for RowDrop { fn mark(&self, drop: &Landed) -> DropMark { drop.spot.mark } + + fn copy_keys(&self) -> CopyKeys { + self.copy.unwrap_or_default() + } } /// A drop kind's target: the place under the pointer was tested before it registers. @@ -661,15 +665,15 @@ impl ItemsHooks<'_, '_, C> { .filter(|spot| comp.accepts(&payload, Some(&self.source.key(spot.over)), spot.insert)) .filter(|spot| !groups || !self.inside_dragged(&payload, spot.parent)) }; - let copy_ok = rule.copy_with_alt; + let copy = rule.copy; let ordinal = drag::next_ordinal(&cx.core.ctx, cx.core.id); - if let Some(landed) = cx.drop_target::, _>(&RowDrop { spot, copy_ok }) { + if let Some(landed) = cx.drop_target::, _>(&RowDrop { spot, copy }) { self.land(cx, &payload, landed, groups); } else if let Some(spot) = spot && drag::winning(&cx.core.ctx, cx.core.id, ordinal) { - let op = drag::current_operation(&cx.core.ctx); - if copy_ok || !matches!(op, DropOperation::Copy) { + let op = drag::current_operation(&cx.core.ctx, copy.unwrap_or_default()); + if copy.is_some() || !matches!(op, DropOperation::Copy) { self.drags.pending = self.own_move(&payload, Landed { spot, op }, groups).map(|(_, after)| PendingDrop::Reorder(after)); } } diff --git a/crates/ui-contract/src/contract/items/lead.rs b/crates/ui-contract/src/contract/items/lead.rs index d78d489ef..d57544bb7 100644 --- a/crates/ui-contract/src/contract/items/lead.rs +++ b/crates/ui-contract/src/contract/items/lead.rs @@ -72,6 +72,13 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { clicks > 1 && self.holds(at) } + /// The position of the collection's current item (`CollectionProps::current`) when nothing is picked. + fn current_when_unpicked(&self, comp: &C) -> Option { + let current = comp.items().current.as_deref().and_then(|key| key.downcast_ref::())?; + let at = self.index_of(current)?; + self.placed().rows().is_empty().then_some(at) + } + /// A press or key that selects row `at` the way the modifiers say. pub(super) fn pick(&mut self, comp: &C, at: usize, extend: bool, toggle: bool) { if self.source.section_stop(at) { @@ -86,11 +93,17 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { self.select_rows(comp, anchor, at); } SelectMode::Multi | SelectMode::Cells => { + // 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 { - let anchor = self.anchor_at(self.lead.at); + let anchor = self.selection.anchor().and_then(|key| self.index_of(key)).or(seed).unwrap_or(self.lead.at); self.change(SelectionChange::Set(self.range(anchor, at))); } else if toggle { - self.change(SelectionChange::Toggle(key)); + match seed.filter(|¤t| current != at) { + Some(current) => self.change(SelectionChange::Set(vec![self.source.key(current), key])), + None => self.change(SelectionChange::Toggle(key)), + } } else { self.change(SelectionChange::Set(vec![key])); } diff --git a/crates/ui-contract/src/primitives/draw.rs b/crates/ui-contract/src/primitives/draw.rs index 41892a99b..1c5bfd364 100644 --- a/crates/ui-contract/src/primitives/draw.rs +++ b/crates/ui-contract/src/primitives/draw.rs @@ -43,6 +43,29 @@ pub enum PaintShape { Path(Vec), } +impl PaintShape { + /// Where `Draw::stroke` puts the shape's stroke. + fn stroke_place(&self) -> StrokePlace { + match self { + PaintShape::Rect(..) => StrokePlace::Inside, + PaintShape::Circle(..) => StrokePlace::Outside, + PaintShape::Polygon(_) | PaintShape::Path(_) => StrokePlace::Centre, + } + } +} + +/// Where a stroke lies against the edge of a closed shape (`Rect`, `Circle`, `Polygon`); an open `Path` always strokes +/// on its centre line. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StrokePlace { + /// Wholly inside the edge, so the shape keeps its outer size. + Inside, + /// Centred on the edge. + Centre, + /// Wholly outside the edge, so the stroke covers nothing the shape covers. + Outside, +} + /// A line width from the theme, so content never picks a literal one. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] @@ -506,9 +529,16 @@ impl<'a> Draw<'a> { } /// Strokes `shape` at a theme width or a width from the document, in a theme colour or a colour from data (a - /// chart series, a curve). A data colour paints as `data_fill` paints it. + /// chart series, a curve). A data colour paints as `data_fill` paints it. A rect strokes inside its edge, a circle + /// outside it and a polygon on it; [`stroke_placed`](Self::stroke_placed) picks the place. pub fn stroke(&self, shape: &PaintShape, width: impl Into, color: impl Into) { - self.paint(shape, None, Some(self.line(width.into(), color.into()))); + self.stroke_placed(shape, shape.stroke_place(), width, color); + } + + /// Strokes `shape` as [`stroke`](Self::stroke) does, with the stroke `place`d against the shape's edge: an outline + /// around a selected item that must not cover it strokes `Outside`. + pub fn stroke_placed(&self, shape: &PaintShape, place: StrokePlace, width: impl Into, color: impl Into) { + self.paint_placed(shape, None, Some(self.line(width.into(), color.into())), place); } /// Fills `shape` with a colour from data (a swatch well, a layer label dot, an avatar). A component that paints its @@ -526,6 +556,26 @@ impl<'a> Draw<'a> { data_picture(self.painter, self.env.tokens, self.data, texture, rect, uv, CornerRadius::ZERO); } + /// Paints the part `uv` of `texture` onto the quad `corners`, untinted, as [`texture`](Self::texture) paints into a + /// rect: `corners` are where the top left, top right, bottom right and bottom left of `uv` land, so a picture turned + /// by a quarter turn (or any affine map) paints from the one cached texture. For an inactive part the quad is + /// filled with the theme's disabled fill. + pub fn texture_quad(&self, corners: [Pos2; 4], texture: TextureId, uv: Rect) { + let tint = self.data.color(self.env.tokens, super::textures::UNTINTED); + if self.data == DataMode::Inactive { + self.paint(&PaintShape::Polygon(corners.to_vec()), Some(tint), None); + return; + } + let mut mesh = egui::Mesh::with_texture(texture); + let uvs = [uv.left_top(), uv.right_top(), uv.right_bottom(), uv.left_bottom()]; + for (pos, uv) in corners.into_iter().zip(uvs) { + mesh.vertices.push(egui::epaint::Vertex { pos, uv, color: tint }); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + self.painter.add(Shape::mesh(mesh)); + } + /// The texture for `key` from the `TextureCache` of the context this painter paints in, for [`texture`](Self::texture): /// `image()` is built on the first request only (see `TextureCache::texture`). A painter with no `egui::Context` /// of its own, such as a canvas tool's paint call, loads its pictures through here. @@ -622,12 +672,36 @@ impl<'a> Draw<'a> { paint(&Draw { painter: &painter, record: self.record, env: self.env, data: self.data, text_direction: self.text_direction }); } + /// Paints `shape` with its stroke where [`stroke`](Self::stroke) puts it. fn paint(&self, shape: &PaintShape, fill: Option, stroke: Option) { + self.paint_placed(shape, fill, stroke, shape.stroke_place()); + } + + fn paint_placed(&self, shape: &PaintShape, fill: Option, stroke: Option, place: StrokePlace) { let fill_color = fill.unwrap_or(Color32::TRANSPARENT); let stroke = stroke.unwrap_or(Stroke::NONE); + let kind = match place { + StrokePlace::Inside => StrokeKind::Inside, + StrokePlace::Centre => StrokeKind::Middle, + StrokePlace::Outside => StrokeKind::Outside, + }; let shape = match shape { - PaintShape::Rect(rect, radius) => Shape::Rect(RectShape::new(*rect, *radius, fill_color, stroke, StrokeKind::Inside)), - PaintShape::Circle(center, radius) => Shape::Circle(CircleShape { center: *center, radius: *radius, fill: fill_color, stroke }), + PaintShape::Rect(rect, radius) => Shape::Rect(RectShape::new(*rect, *radius, fill_color, stroke, kind)), + PaintShape::Circle(center, radius) => { + // egui strokes a circle outside its radius, so the fill and the stroke paint as two circles when the + // stroke moves in. + let offset = match place { + StrokePlace::Inside => -stroke.width, + StrokePlace::Centre => -stroke.width / 2.0, + StrokePlace::Outside => 0.0, + }; + if offset != 0.0 && fill.is_some() { + self.painter.add(Shape::Circle(CircleShape { center: *center, radius: *radius, fill: fill_color, stroke: Stroke::NONE })); + } + let fill_color = if offset == 0.0 { fill_color } else { Color32::TRANSPARENT }; + let radius = (*radius + offset).max(0.0); + Shape::Circle(CircleShape { center: *center, radius, fill: fill_color, stroke }) + } PaintShape::Polygon(points) => { if fill.is_some() { let feather = self.painter.ctx().tessellation_options(|options| { @@ -641,7 +715,9 @@ impl<'a> Draw<'a> { if stroke.is_empty() { return; } - Shape::closed_line(points.clone(), stroke) + let mut line = egui::epaint::PathStroke::from(stroke); + line.kind = kind; + Shape::closed_line(points.clone(), line) } PaintShape::Path(points) => Shape::line(points.clone(), stroke), }; diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index 42d78bfa3..9cccd2626 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -34,7 +34,7 @@ mod tool; pub use auto_scroll_mark::AutoScrollMark; pub use content::{ContentPainterCx, DocRun, DocText}; -pub use draw::{Dashes, DataStrokeWidth, DataWidth, Draw, PaintShape, StrokeColor, StrokeWidth, WellFill}; +pub use draw::{Dashes, DataStrokeWidth, DataWidth, Draw, PaintShape, StrokeColor, StrokePlace, StrokeWidth, WellFill}; pub use faces::FacesCx; pub use focus_ring::{FocusKind, FocusRing}; pub use handle::{Handle, HandleShape}; diff --git a/crates/ui-contract/src/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index a045b7cf9..30ca13519 100644 --- a/crates/ui-contract/src/primitives/sensing.rs +++ b/crates/ui-contract/src/primitives/sensing.rs @@ -393,8 +393,10 @@ pub fn member_gesture_running(ctx: &Context, viewport: ViewportId, arena: Id) -> /// Ends the press `owner` holds open the way Escape ends a captured press: the next lifecycle run of the arena it is /// open in reports `PressPhase::Cancel` with `PressCancel::Host`, and step 9 cancels the gesture the press carries /// (`CancelReason::HostChanged`). For a host whose own state no longer matches what the press acts on; it may ask -/// inside or outside a pass. Nothing happens when `owner` holds no open press. +/// inside or outside a pass. A drag session `owner` started ends with its press, without a drop. Nothing happens when +/// `owner` holds no open press. pub fn cancel_press_of(ctx: &Context, owner: Id) { + crate::runtime::drag::cancel_of(ctx, owner); PerViewport::::each(ctx, |arenas| { for state in arenas.by_root.values_mut() { if state.machine.target().is_some_and(|target| target.owner == owner) { diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index 2c33c959f..ed48ba32c 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -11,7 +11,7 @@ use crate::runtime::pass_state; use crate::runtime::windows::{self, WindowHost}; use crate::runtime::{cursor, frame, pointer}; use craft_behavior::keys::drop_operation; -use craft_behavior::{Buttons, CancelReason, Cursor, CursorIcon, CursorPriority, DropOperation, PointerButton, PressCancel}; +use craft_behavior::{Buttons, CancelReason, CopyKeys, Cursor, CursorIcon, CursorPriority, DropOperation, PointerButton, PressCancel}; use craft_keymap::Mods; use egui::{Context, Id, Pos2, Rect, Vec2, ViewportId}; use std::any::{Any, TypeId}; @@ -115,6 +115,12 @@ pub trait DropTarget { /// Where `drop` would land, a value the ghost layer paints. fn mark(&self, drop: &Self::Drop) -> DropMark; + + /// The held key that makes a drop on this target a copy: the `op` that [`accept`](Self::accept) gets, and the + /// pointer over the target, follow it. + fn copy_keys(&self) -> CopyKeys { + CopyKeys::Alt + } } /// What a component registers with `Pointer::window_drop_target`: a target over the whole window, which needs no @@ -213,6 +219,8 @@ struct Registration { /// The overlay layer whose body registered the target; `None` for the window's own content. scope: Option, mark: DropMark, + /// What a drop on the target does with the keys held now; the pointer shows it while the target wins. + op: DropOperation, /// The target covers the whole window: any target over a component beats it. window: bool, } @@ -264,8 +272,8 @@ pub fn start(ctx: &Context, source: Id, payload: Arc, als crate::runtime::egui::repaint::request(ctx); } -fn operation(ctx: &Context, mods: Mods) -> DropOperation { - drop_operation(windows::os_of(ctx), mods) +fn operation(ctx: &Context, mods: Mods, copy: CopyKeys) -> DropOperation { + drop_operation(windows::os_of(ctx), mods, copy) } /// Changes the running session's payload of type `P` (or its second payload of that type) with `change`, in the frame @@ -331,6 +339,16 @@ pub fn cancel(ctx: &Context, reason: CancelReason) { frame::note_cancelled_press(ctx); } +/// Ends the session `source` started without a drop, for a host that ends `source`'s press +/// (`primitives::cancel_press_of`); a session another source started runs on. +pub(crate) fn cancel_of(ctx: &Context, source: Id) { + board(ctx, |board| { + if board.session.as_ref().is_some_and(|session| session.source == source) { + board.session = None; + } + }); +} + /// The begin hook: the window losing focus ends the session. pub(crate) fn begin(ctx: &Context) { if source_viewport(ctx) == Some(pass::current_viewport(ctx)) && pointer::with_pass_pointer(ctx, |pointer| pointer.focus_lost) { @@ -456,10 +474,10 @@ pub(crate) fn show_mark(ctx: &Context, mark: Option) { }); } -/// Records that `owner`'s `ordinal`th target on `layer` accepts at the pointer, with its mark in layer space. A -/// `window` target covers the whole window. -pub(crate) fn register(ctx: &Context, owner: Id, layer: Layer, mark: DropMark, window: bool) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| register(ctx, owner, layer, mark, window)); +/// Records that `owner`'s `ordinal`th target on `layer` accepts at the pointer a drop doing `op`, with its mark in +/// layer space. A `window` target covers the whole window. +pub(crate) fn register(ctx: &Context, owner: Id, layer: Layer, mark: DropMark, op: DropOperation, window: bool) { + crate::runtime::replay::journal(ctx, || move |ctx: &Context| register(ctx, owner, layer, mark, op, window)); let mark = match areas::layer_map(ctx, layer) { Some(map) => mark.mapped(|point| map.to_screen(point)), None => mark, @@ -467,7 +485,7 @@ pub(crate) fn register(ctx: &Context, owner: Id, layer: Layer, mark: DropMark, w let scope = overlay::drawing_parent(ctx); PerViewport::::with(ctx, pass::current_viewport(ctx), |targets| { let ordinal = targets.this.iter().filter(|registration| registration.owner == owner).count() as u32; - targets.this.push(Registration { owner, ordinal, layer, scope, mark, window }); + targets.this.push(Registration { owner, ordinal, layer, scope, mark, op, window }); }); } @@ -485,9 +503,9 @@ pub fn next_ordinal(ctx: &Context, owner: Id) -> u32 { }) } -/// The operation the held modifiers pick now. -pub(crate) fn current_operation(ctx: &Context) -> DropOperation { - operation(ctx, pointer::frame(ctx).mods) +/// The operation the held modifiers pick now over a target that copies with `copy`. +pub(crate) fn current_operation(ctx: &Context, copy: CopyKeys) -> DropOperation { + operation(ctx, pointer::frame(ctx).mods, copy) } /// Whether the session's button was released in this pass. @@ -542,10 +560,10 @@ pub(crate) fn target_of>( if moves_viewport(ctx) || !zone.rect.contains(at) || top != Some(zone.layer) { return None; } - let op = current_operation(ctx); + let op = current_operation(ctx, target.copy_keys()); let drop = target.accept(&*payload, at, op)?; let ordinal = next_ordinal(ctx, owner); - register(ctx, owner, zone.layer, target.mark(&drop), false); + register(ctx, owner, zone.layer, target.mark(&drop), op, false); take_drop(ctx, owner, ordinal, op, payload_type).then_some(drop) } @@ -575,6 +593,10 @@ impl> DropTarget for Typed<' fn mark(&self, drop: &T::Drop) -> DropMark { self.0.mark(drop) } + + fn copy_keys(&self) -> CopyKeys { + self.0.copy_keys() + } } /// The operation of the drop of `source`'s payload of type `P` that the previous frame took. @@ -608,12 +630,11 @@ pub(crate) fn end_pass(ctx: &Context) { .filter(|(at, _)| open[*at]) .max_by_key(|(at, registration)| (!registration.window, areas::layer_position(ctx, registration.layer), *at)) .map(|(_, registration)| registration); - let best = best.map(|registration| ((registration.owner, registration.ordinal), registration.mark)); + let best = best.map(|registration| ((registration.owner, registration.ordinal), (registration.mark, registration.op))); targets.winner = best.map(|(key, _)| key); targets.this.clear(); - best.map(|(_, mark)| mark) + best.map(|(_, won)| won) }); - let op = current_operation(ctx); let over_this_window = pointer::frame(ctx).pos.is_some(); let primary_down = pointer::with_pass_pointer(ctx, |pointer| pointer.primary_down); let buttons = pointer::frame(ctx).buttons; @@ -643,7 +664,7 @@ pub(crate) fn end_pass(ctx: &Context) { } if let Some(session) = &mut board.session { match winner { - Some(mark) => session.mark = Some((viewport, mark)), + Some((mark, _)) => session.mark = Some((viewport, mark)), None if session.mark.is_some_and(|(marked, _)| marked == viewport) => session.mark = None, None => {} } @@ -662,7 +683,7 @@ pub(crate) fn end_pass(ctx: &Context) { if running && over_this_window { match winner { None => cursor::request(ctx, Cursor::System(CursorIcon::NotAllowed), CursorPriority::Drag), - Some(_) => { + Some((_, op)) => { let icon = match op { DropOperation::Copy => CursorIcon::Copy, DropOperation::Link => CursorIcon::Alias, diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index ff5f5d032..c5c92f91a 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -396,6 +396,11 @@ impl Fixture { self.frames.repaint_requested() } + /// The system cursor the latest frame's output asked for. + pub fn cursor_icon(&self) -> egui::CursorIcon { + self.frames.cursor_icon() + } + /// The IME output of the latest frame. pub fn ime(&self) -> Option<&fixture::ImeSeen> { self.frames.ime() diff --git a/crates/ui-contract/tests/it/collection/drops.rs b/crates/ui-contract/tests/it/collection/drops.rs index 118d7dd8e..714f452eb 100644 --- a/crates/ui-contract/tests/it/collection/drops.rs +++ b/crates/ui-contract/tests/it/collection/drops.rs @@ -136,6 +136,40 @@ fn rows_from_another_list_drop_into_a_gap_only_where_a_kind_takes_them() { assert_eq!(keys, vec![(DropAt::gap(Some(2), 2), Some(vec![0]))]); } +/// A list's copy keys decide which held key makes its own row drag a copy, and the pointer over it shows the copy +/// while they are held: off macOS Ctrl for the platform's keys, Alt for Alt; the other key moves. +#[trial] +fn a_lists_copy_keys_pick_the_key_that_copies_its_rows() { + use craft_behavior::{Cursor, CursorIcon, CopyKeys}; + use egui::Modifiers; + let ctrl = Modifiers::CTRL | Modifiers::COMMAND; + for (keys, copies, moves) in [(CopyKeys::Platform, ctrl, Modifiers::ALT), (CopyKeys::Alt, Modifiers::ALT, ctrl)] { + for (held, copy) in [(copies, true), (moves, false)] { + let words = Words::flat(&["a", "b", "c", "d"]); + let run = Run::default(); + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| show(ui, List::new(SelectMode::Multi).reorder_copying(keys), "list", Pos2::new(10.0, 10.0), &words, &run); + frames.idle(3, &mut show); + let gap = run.row(2).min + Vec2::new(10.0, 2.0); + frames.hold(held); + drag_to(&mut frames, run.row(0).center(), gap, &mut show); + let pointer = craft_ui::runtime::cursor::current(&frames.ctx); + assert_eq!(pointer == Some(Cursor::System(CursorIcon::Copy)), copy, "{keys:?} with {held:?}: the pointer {pointer:?}"); + release_at(&mut frames, gap, &mut show); + let moved: Vec = run + .events + .borrow() + .iter() + .filter_map(|event| match event { + CollectionEvent::Reorder(edit) => edit.value().map(|mv| mv.copy), + _ => None, + }) + .collect(); + assert_eq!(moved, vec![copy], "{keys:?} with {held:?}"); + } + } +} + /// Rows dropped in the empty room below the last row land after it, as at the last row's lower half. #[trial] fn a_drop_below_the_last_row_lands_at_the_end() { diff --git a/crates/ui-contract/tests/it/collection/kit.rs b/crates/ui-contract/tests/it/collection/kit.rs index d9a680830..0f76a5f4b 100644 --- a/crates/ui-contract/tests/it/collection/kit.rs +++ b/crates/ui-contract/tests/it/collection/kit.rs @@ -200,6 +200,12 @@ impl<'a> List<'a> { self } + /// Reordering, where a drag with `keys` held copies. + pub fn reorder_copying(mut self, keys: craft_behavior::CopyKeys) -> Self { + self.items = self.items.reorder(craft_ui::contract::ReorderRule::new().copy_with(keys)); + self + } + /// `seen` takes the rect of the empty state. pub fn on_empty(mut self, seen: &'a Cell) -> Self { self.on_empty = Some(seen); diff --git a/crates/ui-contract/tests/it/paint/draw_place.rs b/crates/ui-contract/tests/it/paint/draw_place.rs new file mode 100644 index 000000000..dbf4674cf --- /dev/null +++ b/crates/ui-contract/tests/it/paint/draw_place.rs @@ -0,0 +1,90 @@ +//! Where `Draw` puts a stroke against a closed shape's edge, and a picture on a turned quad. + +use craft_theme::{Contrast, Mode}; +use craft_ui::primitives::{PaintShape, StrokePlace, StrokeWidth}; +use craft_ui::runtime::env::Direction; +use craft_ui::style::Ink; +use craft_ui::testing::style::{paint_frame, tokens}; +use craft_ui::testing::{Frames, trial}; +use egui::epaint::{Mesh, TessellationOptions, Tessellator}; +use egui::{CornerRadius, Pos2, Rect, Shape, pos2}; + +/// Slack for the polygon a tessellated circle is. +const EPS: f32 = 0.05; + +/// The vertices `shapes` tessellate to, without feathering. +fn vertices(shapes: Vec) -> Vec { + let options = TessellationOptions { feathering: false, ..TessellationOptions::default() }; + let mut tessellator = Tessellator::new(1.0, options, [1, 1], vec![]); + let mut mesh = Mesh::default(); + for shape in shapes { + tessellator.tessellate_shape(shape, &mut mesh); + } + mesh.vertices.iter().map(|vertex| vertex.pos).collect() +} + +/// An inside stroke stays within every closed shape's edge and an outside one stays out of it, whatever the shape; +/// a centred one crosses it. +#[trial] +fn a_placed_stroke_lies_on_its_side_of_every_closed_shapes_edge() { + let tokens = tokens(Mode::Dark, Contrast::Standard); + let rect = Rect::from_min_max(pos2(20.0, 20.0), pos2(80.0, 60.0)); + let centre = pos2(50.0, 50.0); + let radius = 20.0; + let square = vec![rect.left_top(), rect.right_top(), rect.right_bottom(), rect.left_bottom()]; + let shapes = [PaintShape::Rect(rect, CornerRadius::ZERO), PaintShape::Polygon(square), PaintShape::Circle(centre, radius)]; + // How far a point lies outside the shape's edge (negative inside). + let outside = |shape: &PaintShape, p: Pos2| match shape { + PaintShape::Circle(..) => p.distance(centre) - radius, + _ => { + let dx = (rect.left() - p.x).max(p.x - rect.right()); + let dy = (rect.top() - p.y).max(p.y - rect.bottom()); + dx.max(dy) + } + }; + let mut frames = Frames::new(); + for shape in &shapes { + for place in [StrokePlace::Inside, StrokePlace::Centre, StrokePlace::Outside] { + let (painted, _) = paint_frame(&mut frames, &tokens, Direction::Ltr, Ink::OnPanel, |draw| { + draw.stroke_placed(shape, place, StrokeWidth::Heavy, draw.role(|colors| colors.text.muted)); + }); + let points = vertices(painted); + assert!(!points.is_empty(), "{shape:?} {place:?} paints"); + let (low, high) = points.iter().map(|p| outside(shape, *p)).fold((f32::MAX, f32::MIN), |(lo, hi), d| (lo.min(d), hi.max(d))); + match place { + StrokePlace::Inside => assert!(high <= EPS, "{shape:?}: an inside stroke reaches {high} past the edge"), + StrokePlace::Outside => assert!(low >= -EPS, "{shape:?}: an outside stroke reaches {low} into the shape"), + StrokePlace::Centre => assert!(low < -EPS && high > EPS, "{shape:?}: a centred stroke crosses the edge ({low}..{high})"), + } + } + } +} + +/// A picture painted on a quarter-turned quad puts each corner of its part where the quad names it, so one cached +/// texture paints at any turn. +#[trial] +fn a_texture_quad_lands_each_corner_of_its_part_on_the_quads_corner() { + let tokens = tokens(Mode::Dark, Contrast::Standard); + let uv = Rect::from_min_max(pos2(0.25, 0.0), pos2(0.75, 1.0)); + // The rect (10, 10)–(50, 30) turned a quarter clockwise about its top left: its top left lands top right. + let corners = [pos2(30.0, 10.0), pos2(30.0, 50.0), pos2(10.0, 50.0), pos2(10.0, 10.0)]; + let mut frames = Frames::new(); + let (painted, _) = paint_frame(&mut frames, &tokens, Direction::Ltr, Ink::OnPanel, |draw| { + draw.texture_quad(corners, egui::TextureId::User(7), uv); + }); + let [Shape::Mesh(mesh)] = painted.as_slice() else { panic!("one mesh, got {painted:?}") }; + assert_eq!(mesh.texture_id, egui::TextureId::User(7)); + for (want, at) in [uv.left_top(), uv.right_top(), uv.right_bottom(), uv.left_bottom()].into_iter().zip(corners) { + let vertex = mesh.vertices.iter().find(|v| v.uv == want).expect("a vertex per corner of the part"); + assert_eq!(vertex.pos, at, "the part's corner {want:?} lands on the quad's corner"); + } + let area: f32 = mesh + .indices + .chunks(3) + .map(|t| { + let [a, b, c] = [0, 1, 2].map(|i| mesh.vertices[t[i] as usize].pos); + ((b - a).x * (c - a).y - (b - a).y * (c - a).x).abs() / 2.0 + }) + .sum(); + assert!((area - 800.0).abs() < 1e-3, "the triangles cover the quad once: {area}"); +} diff --git a/crates/ui-contract/tests/it/paint/mod.rs b/crates/ui-contract/tests/it/paint/mod.rs index 2f42bfe96..a99d9606c 100644 --- a/crates/ui-contract/tests/it/paint/mod.rs +++ b/crates/ui-contract/tests/it/paint/mod.rs @@ -1,5 +1,7 @@ mod backdrop; +mod draw_place; + mod painters; mod surround; diff --git a/crates/ui-contract/tests/it/runtime/windows.rs b/crates/ui-contract/tests/it/runtime/windows.rs index 8de3c2f18..6c69e80f0 100644 --- a/crates/ui-contract/tests/it/runtime/windows.rs +++ b/crates/ui-contract/tests/it/runtime/windows.rs @@ -298,6 +298,38 @@ fn an_app_modal_in_one_window_blocks_the_cursor_and_the_close_of_the_others() { } } +/// A window that a modal in another window blocks takes no wheel, as it takes no press or key: what is under the +/// pointer there does not scroll. +#[trial] +fn a_window_an_app_modal_in_another_window_blocks_takes_no_wheel() { + use craft_behavior::WheelTaker; + use craft_ui::testing::wheel::{register, take}; + for open in [false, true] { + let windows = Windows::new(); + let view = egui::Id::new("view"); + let taken = Cell::new(None); + let frame = |events: Vec| { + windows.frame(events, vec![], |ui| { + register(ui.ctx(), WheelTaker::new(view, Rect::from_min_size(Pos2::ZERO, Vec2::splat(400.0))).vertical(true).scrolls(true)); + if let Some(scroll) = take(ui.ctx(), view) { + taken.set(Some(scroll)); + } + if open { + ui.ctx().show_viewport_immediate(child(), ViewportBuilder::default(), |cui, _| { + let props = ContainerProps::new().mount(Mount::Layer(Overlay::modal())); + Modal { common: Common::new(), props }.id_salt("modal").show(cui, |_, _| {}); + }); + } + }) + }; + for _ in 0..4 { + frame(vec![moved(Pos2::new(200.0, 200.0))]); + } + frame(vec![wheel(-30.0)]); + assert_eq!(taken.get().is_some(), !open, "modal open {open}: the view's share {:?}", taken.get()); + } +} + /// L-17: the user clicking the main window while a modal in another window blocks it brings the modal's window /// forward with it, in the pass the main window gains focus; a pass without a focus change sends nothing. #[trial]