diff --git a/crates/draw/tests/it/brush_presets.rs b/crates/draw/tests/it/brush_presets.rs index c8ac780f9..af6b8b41a 100644 --- a/crates/draw/tests/it/brush_presets.rs +++ b/crates/draw/tests/it/brush_presets.rs @@ -64,6 +64,10 @@ struct Opened { values: BrushPickerValues, open: bool, tip_edits: usize, + /// Where the app opens the picker without its field; `None` shows the field. + at: Option, + /// The space above the field. + offset: f32, } const POINT: Pos2 = Pos2::new(160.0, 120.0); @@ -72,21 +76,31 @@ const OPENED: BrushPickerValues = BrushPickerValues::new(12.0, Some(0.5)).with_t /// A picker over two presets showing `opened`'s values, opened by the app at [`POINT`] when `at_point`, else from its /// field; with `remember`, resizable with its size saved. The host applies every edit and Escape's revert. fn opened_rig(at_point: bool, remember: bool) -> (Fixture, Rc>) { - let host = Rc::new(RefCell::new(Opened { current: Some(HARD), state: BrushPickerState::new(), values: OPENED, open: at_point, tip_edits: 0 })); + let at = at_point.then_some(POINT); + let host = Rc::new(RefCell::new(Opened { + current: Some(HARD), + state: BrushPickerState::new(), + values: OPENED, + open: at_point, + tip_edits: 0, + at, + offset: 0.0, + })); let shown = Rc::clone(&host); let mut fixture = Fixture::new(move |ui| { let env = Env::of(ui); let paint = BrushRowPaint::new(|_, _| {}, |_, _| {}); let mut host = shown.borrow_mut(); - let Opened { current, state, values, open, tip_edits } = &mut *host; + let Opened { current, state, values, open, tip_edits, at, offset } = &mut *host; + ui.add_space(*offset); let rows = vec![brush_row(1, "Soft Round", 0, 45.0, state.parts, &env, &paint), brush_row(HARD, "Hard Round", 0, 12.0, state.parts, &env, &paint)]; let mut picker = BrushPresetPicker::new("Brush Preset picker", Bind::bound(current), &rows, Bind::bound(state), *values); if remember { picker = picker.resizable(SaveKey::new("craft_draw_tests.brush_picker")); } - if at_point { - picker = picker.open_at(POINT, Bind::bound(open)); + if let Some(at) = *at { + picker = picker.open_at(at, Bind::bound(open)); } let out = picker.show(ui); if let Some(diameter) = out.diameter.landed() { @@ -125,13 +139,19 @@ fn the_app_opens_the_picker_at_a_point_without_its_field() { assert!(fixture.by_role(Role::DIALOG).is_empty(), "the popover is gone"); } +/// A resized popover keeps only its size: each opening places it from its field or point at that size. Its grips +/// stand only on the edges its anchor leaves free. #[trial] fn a_resized_picker_reopens_at_the_size_its_grip_left() { - let (mut fixture, _host) = opened_rig(false, true); + let (mut fixture, host) = opened_rig(false, true); let field = fixture.by_role(Role::COMBO_BOX).first().copied().expect("the closed field shows"); fixture.click(&field); fixture.idle(3); let first = popover(&fixture); + fixture.drag_at(first.left_center() + Vec2::new(1.0, 0.0), Vec2::new(-60.0, 0.0)); + fixture.idle(3); + let held = popover(&fixture); + assert!((held.width() - first.width()).abs() < 1.0, "the edge at the field's start has no grip: {first:?} -> {held:?}"); fixture.drag_at(first.right_bottom() - Vec2::splat(1.0), Vec2::new(60.0, 80.0)); fixture.idle(3); let resized = popover(&fixture); @@ -139,10 +159,34 @@ fn a_resized_picker_reopens_at_the_size_its_grip_left() { fixture.key(Key::Escape, Modifiers::NONE); fixture.idle(3); assert!(fixture.by_role(Role::DIALOG).is_empty(), "Escape closes the popover"); - fixture.click(&field); + + host.borrow_mut().offset = 120.0; + fixture.idle(3); + let moved = fixture.by_role(Role::COMBO_BOX).first().copied().expect("the field shows"); + assert!(moved.rect.min.y > field.rect.min.y + 100.0, "the field moved down: {:?} -> {:?}", field.rect, moved.rect); + fixture.click(&moved); fixture.idle(3); let reopened = popover(&fixture); assert!((reopened.size() - resized.size()).abs().max_elem() < 1.0, "the reopened popover keeps the size: {resized:?} -> {reopened:?}"); + let under = reopened.min.y - moved.rect.max.y; + assert!( + (-1.0..16.0).contains(&under) && (reopened.min.x - moved.rect.min.x).abs() < 16.0, + "it hangs under the moved field: {:?} / {reopened:?}", + moved.rect + ); + fixture.key(Key::Escape, Modifiers::NONE); + fixture.idle(3); + + let point = Pos2::new(220.0, 60.0); + { + let mut host = host.borrow_mut(); + host.at = Some(point); + host.open = true; + } + fixture.idle(3); + let at_point = popover(&fixture); + assert!((at_point.size() - resized.size()).abs().max_elem() < 1.0, "opened at a point it keeps the size: {resized:?} -> {at_point:?}"); + assert!((at_point.min - point).length() < 32.0, "it hangs from the new point: {at_point:?}"); } #[trial] diff --git a/crates/imaging/src/ui/layer_style/contour/mod.rs b/crates/imaging/src/ui/layer_style/contour/mod.rs index a94ad2cf1..c9f7914f5 100644 --- a/crates/imaging/src/ui/layer_style/contour/mod.rs +++ b/crates/imaging/src/ui/layer_style/contour/mod.rs @@ -256,6 +256,7 @@ impl<'a> ContourField<'a> { Row::new().show(ui, |ui, root| { let picker = PresetPicker::new(label.clone(), Bind::bound(&mut key), rows, state.reborrowed()) .field(PickerField::Thumbnail) + .columns(4) .can_delete(|key| matches!(key, ContourKey::User(_))) .edit_face() .show(ui); diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 96ed4c47a..4c5863b93 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -171,7 +171,8 @@ impl ShapeHooks for BodyHooks<'_> { let screen = crate::contract::overlay::screen_for(&ctx, &env, overlay); shown_placement(&ctx, id, save.as_ref(), overlay, screen, env.tokens.space.inset.screen) }); - placement.pos.is_some() && placement.size.is_some() + // A layer the user sized takes that size, at its saved position or where its anchor places it. + placement.size.is_some() } _ => false, }; diff --git a/crates/ui-contract/src/contract/body/placement.rs b/crates/ui-contract/src/contract/body/placement.rs index 52404b250..193b624b6 100644 --- a/crates/ui-contract/src/contract/body/placement.rs +++ b/crates/ui-contract/src/contract/body/placement.rs @@ -43,17 +43,20 @@ pub(crate) fn placement_id(id: Id) -> Id { /// The one store of a layer's placement: the saved tier when `save` is set, else shown memory. A layer whose overlay /// is `placed` has the caller's rect instead: the slot reads it and writes nothing, since the caller owns the -/// placement and learns of the user's changes from `PlacementChange` reports. +/// placement and learns of the user's changes from `PlacementChange` reports. A layer hung from its anchor that the +/// user cannot move keeps only its size: each opening places it from its anchor at that size. pub(super) struct PlacementSlot<'s> { stage: &'s mut MemoryStage, id: Id, save: Option<&'s SaveKey>, controlled: Option, + anchored: bool, } impl<'s> PlacementSlot<'s> { pub(super) fn new(stage: &'s mut MemoryStage, id: Id, save: Option<&'s SaveKey>, overlay: &crate::contract::Overlay) -> Self { - PlacementSlot { stage, id, save, controlled: Placement::given(overlay) } + let anchored = matches!(overlay.place, Place::Anchored { .. }) && !overlay.movable; + PlacementSlot { stage, id, save, controlled: Placement::given(overlay), anchored } } fn stored(&mut self) -> &mut Placement { @@ -72,7 +75,8 @@ impl<'s> PlacementSlot<'s> { pub(super) fn write(&mut self, placement: Placement) { if self.controlled.is_none() { - *self.stored() = placement; + let pos = if self.anchored { None } else { placement.pos }; + *self.stored() = Placement { pos, ..placement }; } } } @@ -88,7 +92,8 @@ fn placement_of(ctx: &Context, id: Id, save: Option<&SaveKey>) -> Placement { /// The placement a layer is shown at: the caller's `placed` rect or `placed_at` position, else the saved or session placement, else for a /// floating resizable layer with a default size (`Overlay::size`) that size, within the screen less `screen_inset` on -/// each side, centred or at the overlay's float position. A saved size and position win over the default. +/// each side, centred or at the overlay's float position. A saved size and position win over the default. A size with +/// no position places an anchored layer from its anchor at that size. pub(crate) fn shown_placement( ctx: &Context, id: Id, diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index 97d330961..0da20b77a 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -204,6 +204,54 @@ const GRIPS: [(i8, i8, CursorIcon); 8] = [ (-1, 1, CursorIcon::ResizeNeSw), ]; +/// The edges of a layer its placement holds in place, by screen side (`-1` left or top, `1` right or bottom). A layer +/// hung from its anchor that the user cannot move keeps only its size, so its placement holds the edge that faces the +/// anchor and the edge it aligns to the anchor's: a grip on such an edge would move the opposite one. A centred layer +/// has both edges across its side held. +#[derive(Clone, Copy)] +struct Pinned { + x: [bool; 2], + y: [bool; 2], +} + +impl Pinned { + const NONE: Pinned = Pinned { x: [false; 2], y: [false; 2] }; + + fn of(overlay: &crate::contract::Overlay, ctx: &Context, id: Id, rtl: bool) -> Pinned { + use craft_behavior::overlay::{Align, Side}; + let crate::contract::overlay::Place::Anchored { side, align, .. } = &overlay.place else { return Pinned::NONE }; + if overlay.movable { + return Pinned::NONE; + } + let side = crate::runtime::overlay::placed_side(ctx, id).unwrap_or(*side); + // Index 0 is the left or top edge, 1 the right or bottom one; reading order flips the horizontal ones. + let (start, end) = if rtl { (1, 0) } else { (0, 1) }; + let edge = |at: usize| { + let mut held = [false; 2]; + held[at] = true; + held + }; + let aligned = |start: usize, end: usize| match align { + Align::Start => edge(start), + Align::End => edge(end), + _ => [true; 2], + }; + match side { + Side::Below => Pinned { x: aligned(start, end), y: edge(0) }, + Side::Above => Pinned { x: aligned(start, end), y: edge(1) }, + Side::Start => Pinned { x: edge(end), y: aligned(0, 1) }, + Side::End => Pinned { x: edge(start), y: aligned(0, 1) }, + _ => Pinned::NONE, + } + } + + /// Whether the grip that moves the edges `dx`, `dy` moves a held edge. + fn holds(self, dx: i8, dy: i8) -> bool { + let held = |edges: [bool; 2], d: i8| d != 0 && edges[usize::from(d > 0)]; + held(self.x, dx) || held(self.y, dy) + } +} + impl BodyHooks<'_> { /// The `window.Move` and `window.Size` commands and the keys of the mode they start (16.3): arrows move or /// resize by a step (Shift: four steps), Enter, the command again or a primary press keeps the placement, Escape @@ -518,7 +566,11 @@ impl BodyHooks<'_> { if !grips || !stands.grips { return; } + let pinned = overlay_of(props).map_or(Pinned::NONE, |overlay| Pinned::of(overlay, &ctx, pcx.id, pcx.env.direction().is_rtl())); for (index, (dx, dy, cursor)) in GRIPS.into_iter().enumerate() { + if pinned.holds(dx, dy) { + continue; + } let along = |edge: i8, low: f32, high: f32| match edge { -1 => (low - handle / 2.0 + inset, low + handle / 2.0 + inset), 1 => (high - handle / 2.0 - inset, high + handle / 2.0 - inset), diff --git a/crates/ui-contract/src/contract/mount.rs b/crates/ui-contract/src/contract/mount.rs index d70ada738..2b4fa9ad5 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -222,18 +222,23 @@ impl Host for LayerHost { if let Some(pos) = placement.pos { overlay.place = Place::Float(FloatPlace::at(Pos2::from(pos))); } - let at = placement.pos.zip(placement.size).map(|(pos, size)| ShowAt::Rect(Rect::from_min_size(Pos2::from(pos), Vec2::from(size)))); + let sized = placement.size.map(Vec2::from); + let at = placement.pos.zip(sized).map(|(pos, size)| ShowAt::Rect(Rect::from_min_size(Pos2::from(pos), size))); // Without an opener, an anchor given as a rect or point is in the parent's layer, and `Response` is the // parent's cursor. let own = Rect::from_min_max(parent.cursor().min, parent.cursor().min); let anchor = overlay::resolve_anchor(&ctx, id, &overlay, own, areas::layer_to_screen(&ctx, parent.layer_id())); - // The layer is placed by the size the container takes in this pass: its placed rect, else what it measured. - let size = at.map_or(self.size, |shown| match shown { + // The layer is placed by the size the container takes in this pass: its placed rect or the size the user gave + // it, else what it measured. + let size = at.map_or(sized.unwrap_or(self.size), |shown| match shown { ShowAt::Rect(rect) => rect.size(), ShowAt::Flow => self.size, }); let layer = Layer { id, owner: id, overlay: &overlay, anchor, env, exiting: self.exiting, fade: self.fade, size: Some(size), region }; let out = overlay::host(&ctx, &layer, &mut |ui| { + // A layer the user sized with no position of its own shows at that size where the host placed it from its + // anchor, within the room the host leaves it. + let at = at.or_else(|| sized.map(|size| ShowAt::Rect(Rect::from_min_size(ui.max_rect().min, size.min(ui.max_rect().size()))))); // The container runs in the env the layer installed, not in its opener's. pass(ui, Some(at.unwrap_or(ShowAt::Flow)), Some(&Env::of(ui))); // A body shown at a rect takes no room in the layer's flow: the layer covers the rect, so the pointer @@ -349,7 +354,7 @@ impl Host for ViewportHost { crate::runtime::focus::push_scope(&ctx, id, focus, None); } if real { - crate::runtime::overlay::begin_layer(&ctx, id, false); + crate::runtime::overlay::begin_layer(&ctx, id, false, None); } pass(ui, Some(ShowAt::Rect(window)), Some(&scoped_env)); if real { diff --git a/crates/ui-contract/src/contract/overlay/host.rs b/crates/ui-contract/src/contract/overlay/host.rs index f69d2dc96..7dcfbeae9 100644 --- a/crates/ui-contract/src/contract/overlay/host.rs +++ b/crates/ui-contract/src/contract/overlay/host.rs @@ -181,7 +181,7 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U let recorded = overlay.opener.as_ref().and_then(|first| focus::stop_rec(ctx, (first.id, None))).map(|rec| rec.stop.key()); owned.map(|rec| rec.stop.key()).or(pressed).or(recorded).or_else(|| focus::focused_stop(ctx)) }); - overlay::begin_layer(ctx, layer.id, layer.exiting); + overlay::begin_layer(ctx, layer.id, layer.exiting, placed.side); let shown = areas::show_layer(ctx, &spec, |ui| { if let Some(region) = layer.region { ui.set_clip_rect(ui.clip_rect().intersect(region)); @@ -260,7 +260,7 @@ pub fn show_beside_modal(ctx: &Context, id: Id, modal: egui::Modal, body: imp let real = !ui.is_sizing_pass(); if real { focus::push_scope(ctx, id, BESIDE, None); - overlay::begin_layer(ctx, id, false); + overlay::begin_layer(ctx, id, false, None); } let out = body(ui); if real { diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index beb931140..ed8675d48 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -204,6 +204,8 @@ pub(crate) struct Pass { last: Vec, /// The layers whose bodies are running, innermost last. drawing: Vec, + /// The side of its anchor each anchored layer was placed on this pass, set before its body runs. + sides: Vec<(Id, Side)>, /// Each activation of this pass: the component and a layer whose body was running around it. activated: Vec<(Id, Id)>, /// The components whose activation this pass opened or closed a popup (`claim_activation`). @@ -264,6 +266,7 @@ fn with_pass(ctx: &Context, f: impl FnOnce(&mut Pass) -> R) -> R { pass.last.clear(); } pass.drawing.clear(); + pass.sides.clear(); pass.activated.clear(); pass.claimed.clear(); pass.pressed_outside.clear(); @@ -398,6 +401,11 @@ pub fn entry(ctx: &Context, id: Id) -> Option { with_pass(ctx, |pass| pass.last.iter().find(|entry| entry.id == id).cloned()) } +/// The side of its anchor the layer `id` was placed on in this pass, once its host placed it by a known size. +pub(crate) fn placed_side(ctx: &Context, id: Id) -> Option { + with_pass(ctx, |pass| pass.sides.iter().rev().find(|(layer, _)| *layer == id).map(|(_, side)| *side)) +} + /// The parent a layer opened now has: the layer whose body is running. #[doc(hidden)] pub fn drawing_parent(ctx: &Context) -> Option { @@ -416,12 +424,17 @@ pub(crate) fn appears(ctx: &Context, id: Id, exiting: bool) -> bool { reopened(ctx, id, exiting) || with_persist(ctx, pass::current_viewport(ctx), |persist| !persist.appeared.contains_key(&id)) } -/// Marks the layer `id`'s body as running, so layers opened from inside it become its children. A layer shown -/// again while it fades out opens anew: it appears in this frame and pass. -pub(crate) fn begin_layer(ctx: &Context, id: Id, exiting: bool) { +/// Marks the layer `id`'s body as running, so layers opened from inside it become its children, with the `side` of +/// its anchor it was placed on. A layer shown again while it fades out opens anew: it appears in this frame and pass. +pub(crate) fn begin_layer(ctx: &Context, id: Id, exiting: bool, side: Option) { crate::runtime::replay::block(ctx); let reopened = reopened(ctx, id, exiting); - with_pass(ctx, |pass| pass.drawing.push(id)); + with_pass(ctx, |pass| { + pass.drawing.push(id); + if let Some(side) = side { + pass.sides.push((id, side)); + } + }); let viewport = pass::current_viewport(ctx); let first = (pass::root_frame_nr(ctx), pass::pass_nr(ctx, viewport)); let (down, released) = pointer::with_pass_pointer(ctx, |read| { diff --git a/docs/contract-api.md b/docs/contract-api.md index 03dd8cc59..632eac96a 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -1277,7 +1277,7 @@ The one-press-per-pass rule: a pass carries at most one press, as its last point - `craft_behavior::overlay::Align`: `pub enum Align { Start, Center, End }`. How the overlay lines up with the anchor along the edge it hangs from. - `craft_behavior::overlay::MinWidth`: `pub enum MinWidth { None, Anchor, Points(f32) }`. The narrowest an overlay may be. - - `pub fn points(self, anchor_width: f32, side: Side) -> f32`. The width in points, given the anchor's width and the side the overlay takes: beside its anchor (`Start`, `End`) an overlay shares no horizontal edge with it, so `Anchor` asks for nothing there. + - `pub fn points(self, anchor_width: f32, side: Side) -> f32`. The width in points, given the anchor's width and the side the overlay takes: beside its anchor (`Start`, - `craft_behavior::overlay::PlaceRequest`: `pub struct PlaceRequest { pub anchor: Rect, pub size: Vec2, pub side: Side, pub align: Align, pub rtl: bool, pub gap: f32, pub min_width: MinWidth, pub bounds: Rect, pub kept: Option, pub flips_across: bool }`. What `place` reads. - `pub const fn new(anchor: Rect, size: Vec2, bounds: Rect) -> Self`. A request for `size` around `anchor` inside `bounds`: below, aligned to the start, no gap, free width. - `pub const fn size(mut self, size: Vec2) -> Self`. Sets the content size. @@ -2164,7 +2164,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn value_text(&self) -> Option<&str>`. The shown value as the component words it to assistive technology; `None` for a component that gives none. - `fn story_facts(&self) -> crate::testing::StoryOutput`. The facts a story reports about this output: its id, click, edit kinds, collection kinds and visible range. - `craft_ui::contract::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. - - `pub fn popover() -> Overlay`. A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window, taking focus in. It closes when the focus moves out of it. + - `pub fn popover() -> Overlay`. A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window, - `pub fn dropdown() -> Overlay`. A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor. It - `pub fn menu() -> Overlay`. A menu: a popup the arrow keys move through. A press outside closes it and goes no further. - `pub fn submenu() -> Overlay`. A submenu: beside its parent entry, opening upward from a low entry when it fits there and not below. @@ -2439,7 +2439,7 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the - `craft_ui::contract::overlay::Opener`: `pub struct Opener { pub id: Id, pub rect: Rect, pub layer: areas::Layer, pub trigger: Trigger, pub enabled: bool, pub anchor: Option, pub others: Vec }`. A component that opens a free-standing popup, and how. A layer with several openers keeps the first as its - `craft_ui::contract::overlay::Outside`: `pub enum Outside { Close, Keep, Absorb }`. What a press outside the layer and its anchor does. - `craft_ui::contract::overlay::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. - - `pub fn popover() -> Overlay`. A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window, taking focus in. It closes when the focus moves out of it. + - `pub fn popover() -> Overlay`. A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window, - `pub fn dropdown() -> Overlay`. A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor. It - `pub fn menu() -> Overlay`. A menu: a popup the arrow keys move through. A press outside closes it and goes no further. - `pub fn submenu() -> Overlay`. A submenu: beside its parent entry, opening upward from a low entry when it fits there and not below.