diff --git a/crates/behavior/src/press.rs b/crates/behavior/src/press.rs index b9eb2d3a5..f094f2d40 100644 --- a/crates/behavior/src/press.rs +++ b/crates/behavior/src/press.rs @@ -556,6 +556,33 @@ impl PressMachine { self.open.is_some_and(|open| open.dragging) } + /// The press the open press began as. + pub fn start(&self) -> Option { + self.open.map(|open| open.start) + } + + /// Takes over a press whose button is down and went down elsewhere, as a drag of `target` from `start`: the next + /// pass reports `DragStart`, and later ones the press's own `Drag`, `Release` or `Cancel` from their input. A + /// press this machine holds already stays as it is. + // PLAN: the sheet's Files table has no row for this file; the handover of a held press (decision q346) needs the + // machine to open a press that did not begin on it, which only the machine can build. + pub fn take_over(&mut self, target: T, sense: Sense, start: PressStart) { + if self.open.is_some() { + return; + } + self.open = Some(Open { + target, + sense: sense - Sense::CLICK, + start, + dragging: true, + abandoned: false, + left: false, + reported: true, + drag_reported: false, + released_at: None, + }); + } + /// Whether the button went up and the release waits for a later pass, which the caller must ask for: no input may /// come to start it. pub fn release_held(&self) -> bool { @@ -770,6 +797,22 @@ mod tests { assert!(machine.target().is_none(), "the release ends the press"); } + /// A press taken over from another machine reports its drag's start first, then the held button's own drag and + /// release, which never clicks. + #[test] + fn a_press_taken_over_reports_its_drag_start_then_its_own_phases() { + let origin = pos2(10.0, 0.0); + let mut machine = PressMachine::new(); + machine.take_over(1u8, Sense::DRAG | Sense::CLICK, PressStart::new(origin, PointerButton::Primary, 1.0, 1)); + let first = pass(&mut machine, &[], Sense::DRAG); + assert!(matches!(first.phase, Some(PressPhase::DragStart { start, .. }) if start.origin == origin), "{:?}", first.phase); + let moved = pass(&mut machine, &[PointerEvent::moved(pos2(30.0, 0.0), None)], Sense::DRAG); + assert!(matches!(moved.phase, Some(PressPhase::Drag { pos, .. }) if pos == pos2(30.0, 0.0)), "{:?}", moved.phase); + let up = pass(&mut machine, &[PointerEvent::released(pos2(30.0, 0.0))], Sense::DRAG); + assert!(matches!(up.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", up.phase); + assert_eq!(up.activated, None, "a taken-over press is no click"); + } + /// The pointer leaving the window (a press on a window's edge grip pulled outward) ends the press's click but not /// its drag: the window keeps getting the held button's moves from outside, and they start the drag once past slop. /// The resize from a window edge used to fail whenever the pointer left the window before it passed slop. diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index f6ef7e55f..d7e192d46 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -731,6 +731,12 @@ impl BodyHooks<'_> { if let Some(hit) = exclusive(WindowHit::Move).or(moves_window.then_some(WindowHit::Move)) { part.exclusive(hit); } + // A layer that continues a press begun elsewhere takes it before step 8 reads this pass's presses, so its + // move begins in this pass from the window's own rect (`window_drag`). Only a layer can: the OS gives an + // OS window no press that went down in another window. + if let Some(grab) = overlay_of(props).and_then(|overlay| overlay.continue_move).filter(|_| os.is_none() && !moves_window) { + crate::primitives::sensing::hand_over_press(&ctx, pcx.id, MOVE_BAND.into(), rect.min + grab); + } } // The grips of a layer straddle its edge; those of a window lie inside it, where the window has pixels. They // stack above the body (`over`), so a root in the body never covers their inner half (8.3). diff --git a/crates/ui-contract/src/contract/overlay/props.rs b/crates/ui-contract/src/contract/overlay/props.rs index 506444946..453a19b2c 100644 --- a/crates/ui-contract/src/contract/overlay/props.rs +++ b/crates/ui-contract/src/contract/overlay/props.rs @@ -142,6 +142,12 @@ pub struct Overlay { /// title row, whose move docks the window). The window is opened knowing it, so its hit test never hands the band /// to the system. A layer is always moved by the app. pub moved_by_app: bool, + /// A request of the pass for a movable layer: its move band takes over the primary press that is held, with the + /// pointer at this point inside the layer, so the layer follows a press that began elsewhere (a group torn off a + /// tool rail's flyout). With no press held it does nothing. + // PLAN: the sheet's Files table has no row for this file; `FloatingGroup::continue_move` (ch.K16) reaches the move + // band only through the layer it mounts, as sheet note 6 says ("sets that state through the overlay"). + pub continue_move: Option, /// What the layer is for; a progress window is left out of `any_open`. pub role: LayerRole, /// Set only by [`Overlay::full_window`]. @@ -182,6 +188,7 @@ impl Overlay { body_scroll: true, moves_window: false, moved_by_app: false, + continue_move: None, role: LayerRole::default(), full_window: false, } @@ -460,6 +467,13 @@ impl Overlay { self } + /// The move band takes over the held primary press in this pass, with the pointer at `grab` inside the layer + /// ([`Overlay::continue_move`]). + pub fn continue_move(mut self, grab: Vec2) -> Overlay { + self.continue_move = Some(grab); + self + } + /// Sets the focus scope. pub fn focus(mut self, focus: FocusPolicy) -> Overlay { self.focus = focus; diff --git a/crates/ui-contract/src/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index 7cce1927b..f80f82ab3 100644 --- a/crates/ui-contract/src/primitives/sensing.rs +++ b/crates/ui-contract/src/primitives/sensing.rs @@ -16,7 +16,8 @@ use crate::runtime::memory::{MemoryStage, sub}; use crate::runtime::pointer; use crate::runtime::pointer::PassPointer; use craft_behavior::{ - Cursor, HitLevel, HitPriority, HitShape, PartKey, PartRef, PassInput, PointerSample, PressMachine, PressPhase, PressState, Sense, Shape, Winner, + Cursor, HitLevel, HitPriority, HitShape, PartKey, PartRef, PassInput, PointerButton, PointerSample, PressMachine, PressPhase, PressStart, + PressState, Sense, Shape, Winner, }; use craft_keymap::Mods; use craft_theme::Flags; @@ -268,6 +269,9 @@ struct ArenaState { outcome: Option, /// The host asked to end the open press (`cancel_press_of`): the arena's next lifecycle run ends it. host_cancel: bool, + /// The part the open press was handed to (`hand_over_press`) and the pass that handed it: it reads the press in + /// that pass, though it was first declared then. + handed: Option<(PartRef, u64)>, } #[derive(Default)] @@ -394,6 +398,32 @@ pub fn cancel_press_of(ctx: &Context, owner: Id) { }); } +/// Gives the held primary press to the part `part` of the root `owner`, as a drag from `origin`: the move band of a +/// window floated from a torn-off group carries on the press that tore it off (`Overlay::continue_move`). The arena +/// that holds the press lets it go with no phase; the owner's next lifecycle run reports `DragStart`, and the runs +/// after it the press's own `Drag`, `Release` or `Cancel` from their pass's input, so the handover turns no held +/// button into an event. Nothing happens when no arena of the running viewport holds an open primary press other than +/// `owner`'s, and so a rerun of the pass that asks again takes nothing. Call it before the owner's step 8 (in its parts +/// step) for the press to show in the same pass. +pub(crate) fn hand_over_press(ctx: &Context, owner: Id, part: PartRef, origin: Pos2) { + let read = PassRead::of(ctx); + let start = PerViewport::::with(ctx, read.viewport, |arenas| { + let (_, state) = arenas.by_root.iter_mut().find(|(root, state)| { + **root != owner && state.machine.button() == Some(PointerButton::Primary) && !state.machine.release_held() + })?; + let start = state.machine.start()?; + state.machine = PressMachine::default(); + state.host_cancel = false; + Some(start) + }); + let Some(start) = start else { return }; + let target = Hit { owner, part: Some(part), sense: Sense::DRAG, local: false }; + with_arena_in(ctx, read.viewport, ArenaId::new(owner), read.pass_nr, |state| { + state.machine.take_over(target, Sense::DRAG, PressStart::new(origin, PointerButton::Primary, start.time, 1)); + state.handed = Some((part, read.pass_nr)); + }); +} + /// Records the transformed body's egui layer. pub(crate) fn set_layer(ctx: &Context, arena: ArenaId, layer: Layer) { crate::runtime::replay::journal(ctx, || (arena, layer), |ctx, &(arena, layer)| set_layer(ctx, arena, layer)); @@ -966,7 +996,8 @@ fn known_in(state: &ArenaState, owner: Id) -> Vec<(PartKey, Option)> { } else { state.previous.iter().find(|member| member.id == owner).map_or(&[], |member| member.parts.as_slice()) }; - parts.iter().map(|part| (part.key, part.index)).collect() + let handed = state.handed.filter(|(_, pass)| *pass == state.pass).map(|(part, _)| part).filter(|_| state.root.is_some_and(|root| root.id == owner)); + parts.iter().map(|part| (part.key, part.index)).chain(handed.map(|part| (part.key, part.index))).collect() } /// The part results of one owner: a part reads the press phase when it is the press winner, `Hover` when it is diff --git a/crates/ui-gallery/src/mock/panels.rs b/crates/ui-gallery/src/mock/panels.rs index 7fad69c94..8e2709ba2 100644 --- a/crates/ui-gallery/src/mock/panels.rs +++ b/crates/ui-gallery/src/mock/panels.rs @@ -15,7 +15,7 @@ use craft_ui::canvas_controls::{Guides, Marquee}; use craft_ui::contract::SizeLimits; use craft_ui::contract::{ Bind, BodyCx, CollectionEvent, ColumnKind, ColumnSpec, Props as _, Remember as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, - SweepApply, SweepStep, ToggleColumn, WordSetCx as _, + SweepApply, SweepStep, ThemeScope, ToggleColumn, WordSetCx as _, }; use craft_ui::docking::{DockPanels, GroupAt, PanelSpec}; use craft_ui::list::{ListRow, ToggleCell}; @@ -97,7 +97,7 @@ impl DockPanels for Panels<'_> { match panel { Panel::Canvas => spec.canvas(), // The toolbar's column is whole tool columns wide. - Panel::Tools => spec.grid(ToolRail::::dock_grid(self.ctx, Tool::slots().len())), + Panel::Tools => spec.grid(ToolRail::::dock_grid(self.ctx, &ThemeScope::new(), Tool::slots().len())), _ => spec, } } @@ -229,10 +229,8 @@ fn canvas(ui: &mut Ui, document: &mut Document, tool: Tool, tools: &mut Tools) { *unit = picked; } } - let mut controls = Guides::new("Guides", canvas_id, Bind::bound(guides)).interactive(editing); - if let Some(selected) = *guide { - controls = controls.selected_guide(selected); - } + let selected = *guide; + let mut controls = Guides::new("Guides", canvas_id, Bind::bound(guides)).interactive(editing).selected_guides(selected.as_slice()); if let Some(drag) = pending { controls = controls.pending(drag); } diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 0592252dd..cb58701d4 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -244,6 +244,9 @@ pub struct FloatingGroup<'a> { take_drop: Option>, /// A move by the title began this pass. moving: bool, + /// Where the pointer is inside the window whose move band takes over the held press this pass; set by + /// `continue_move`. + continue_move: Option, /// The files dropped on the group's OS window that no target there took. files: Vec, } @@ -285,6 +288,7 @@ impl<'a> FloatingGroup<'a> { start_drag: None, take_drop: None, moving: false, + continue_move: None, files: Vec::new(), } .label(title) @@ -318,13 +322,16 @@ impl<'a> FloatingGroup<'a> { self } - /// The window takes over the held primary press in its first pass: its own move gesture begins from that press with - /// the pointer at `grab` inside the window, so the window follows the pointer and docks where it would dock on - /// release. Without a held press it does nothing. + /// The window takes over the held primary press in this pass: its own move gesture begins from that press with the + /// pointer at `grab` inside the window, so the window follows the pointer and, with + /// [`window_of`](FloatingGroup::window_of), docks where it would dock on release. A request of the pass, for the + /// pass after a rail's `torn_off`; without a held press it does nothing. Only a window on a layer takes the press: + /// the OS keeps a held button's moves with the window it went down in, so a group shown in an OS window + /// ([`native`](FloatingGroup::native)) moves only when pressed again. #[must_use] - pub fn continue_move(self, grab: Vec2) -> Self { - let _ = grab; - todo!("ch.K16") + pub fn continue_move(mut self, grab: Vec2) -> Self { + self.continue_move = Some(grab); + self } /// The action parts at the end of the title row, in reading order. @@ -377,6 +384,9 @@ impl<'a> FloatingGroup<'a> { if self.start_drag.is_some() { overlay = overlay.moved_by_app(); } + if let Some(grab) = self.continue_move { + overlay = overlay.continue_move(grab); + } match &self.native { Some(spec) => Mount::viewport_with(overlay, spec.clone()), None => Mount::Layer(overlay), diff --git a/crates/ui-panels/src/rails/flyout.rs b/crates/ui-panels/src/rails/flyout.rs index 8c1460b55..cbe695093 100644 --- a/crates/ui-panels/src/rails/flyout.rs +++ b/crates/ui-panels/src/rails/flyout.rs @@ -1,18 +1,22 @@ //! `FlyoutButton`: a rail button that stands for a group of tools and opens them as a flyout. use super::tool::{RailTool, SlotDrop, SlotId, ToolDrag, ToolDropped, ToolTips}; +use super::words::RailWords; use crate::buttons::{IconButton, PopupMark}; use crate::contract::overlay::{Anchor, Place}; use crate::contract::{ - Access, Common, Component, Cx, DragPreview, MeasureCx, Name, NoValue, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, - PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, Trigger, + Access, Common, Component, Cx, DragPreview, Focus as _, MeasureCx, Name, NoValue, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, + Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, Trigger, WordSetCx as _, }; +use crate::display::TargetMark; +use crate::layout_components::Row; use crate::menu::{self, Menu, MenuItem}; +use crate::primitives::{PaintShape, StrokeWidth}; use crate::runtime::commands::{CommandRef, FireSource, ResolvedCommand}; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, GlyphRole, StyleCx}; +use crate::style::{ComponentStyle, GlyphRole, StyleColor, StyleCx}; use craft_behavior::overlay::{Align, Side}; -use craft_behavior::{HitLevel, HitPriority, IconId, Metrics, PartKey, PointerButton, PressPhase, Sense, Value}; +use craft_behavior::{CursorIcon, HitLevel, HitPriority, IconId, Metrics, PartKey, PointerButton, PressPhase, Sense, Value}; use egui::{Pos2, Rect, Response, Vec2}; #[cfg(feature = "testing")] @@ -22,6 +26,8 @@ mod stories; const FACE: PartKey = PartKey::new("face"); /// The corner mark: a press on it opens the flyout at once, and releasing over a row picks it. const MARK: PartKey = PartKey::new("mark"); +/// The tear-off bar's one part, over the whole bar. +const BAR: PartKey = PartKey::new("bar"); /// The style of a flyout button: it paints through its face, so it holds no look of its own besides its side, the rail /// button's, and the size of the corner mark's press area, which is the size and the inset of the mark the face paints. @@ -105,6 +111,12 @@ struct Laid { /// unless `hold_selects` is off, as for a command button. An Alt-click selects the next enabled tool of the slot, /// wrapping, and opens no flyout. With a `click` command, a click fires that command and selects nothing, and the /// release that ends a hold fires nothing. A modified press is never a double click. +/// +/// With `tear_off` a bar runs down the flyout's end edge, named by `RailWords::tear_off`: a press on it dragged past +/// the press slop, a click on it, or the release over it of the press that opened the flyout closes the flyout and +/// reports the pointer in `torn_off`, once per press. The bar is the pointer's: the rows are the keyboard's way to the +/// tools. With `tips` a row whose tool has a tip shows it, and the button leaves its command tooltip to the host, which +/// shows the shown tool's tip with `Show::show_with_tip`. #[derive(crate::contract::Component, crate::contract::Props)] #[component(overlay, probe(FlyoutButton<'static, u8>))] pub struct FlyoutButton<'a, T: Value + 'static> { @@ -125,20 +137,29 @@ pub struct FlyoutButton<'a, T: Value + 'static> { /// drag away, a right click or the Menu key. #[prop(into)] click: Option, - /// A tear-off bar along the flyout's far side: a drag past slop, a click, or a hold-release over it closes the flyout + /// A tear-off bar along the flyout's end edge: a drag past slop, a click, or a hold-release over it closes the flyout /// and reports the pointer. #[prop(flag)] - #[allow(dead_code)] // P3(chrome-w4): ch.K15 tear_off: bool, - /// The tips of the tools: where one `has` a tip, the button and the flyout's row show it. + /// The tips of the tools: where one `has` a tip, its row shows it, and while it is the shown tool the button leaves + /// its command tooltip to the tip the host shows the button with. #[prop] - #[allow(dead_code)] // P3(chrome-w4): ch.K17 tips: Option<&'a dyn ToolTips>, + /// A request of the pass, the index of a tool among `tools`: the button comes into view in its scroll owner and, + /// when the tool is not the shown one, opens its flyout. + #[prop(vis = "pub(crate)")] + reveal_row: Option, + /// The index of the tool among `tools` whose row wears the target mark while the flyout is open. + #[prop(vis = "pub(crate)")] + marked_row: Option, laid: Option, picked: Option, open: bool, double: bool, + /// The press of this pass opened the flyout (`Held`): its release over the bar tears the group off. + held: bool, dropped: Option, + torn_off: Option, } impl<'a, T: Value + 'static> FlyoutButton<'a, T> { @@ -154,11 +175,15 @@ impl<'a, T: Value + 'static> FlyoutButton<'a, T> { click: None, tear_off: false, tips: None, + reveal_row: None, + marked_row: None, laid: None, picked: None, open: false, double: false, + held: false, dropped: None, + torn_off: None, } } @@ -233,7 +258,8 @@ impl Component for FlyoutButton<'_, T> { fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let laid = self.resolve(cx); let face = cx.part(FACE, rect).priority(HitPriority::new(HitLevel::Body, 0)); - if let Some(resolved) = self.lead(&laid) { + let tipped = self.tips.is_some_and(|tips| tips.has(self.shown)); + if let Some(resolved) = self.lead(&laid).filter(|_| !tipped) { face.tooltip(match &resolved.chord_text { Some(chord) => Label::from(format!("{} ({chord})", resolved.label)), None => Label::Shared(resolved.label.clone()), @@ -281,11 +307,16 @@ impl Component for FlyoutButton<'_, T> { } _ => false, }; - if away && !menu.is_open(cx) { + // A reveal of another tool than the shown one opens the flyout on its row; it selects nothing. + let reveal = self.reveal_row.is_some_and(|at| at != shown_at); + if (away || reveal) && !menu.is_open(cx) { menu.open(cx); } open = menu.is_open(cx); } + if self.reveal_row.is_some() { + cx.reveal(cx.rect); + } let pressing = cx.press().phase.is_press(); let activated = cx.activation().is_some(); let held = { @@ -300,6 +331,7 @@ impl Component for FlyoutButton<'_, T> { held }; self.open = open; + self.held = held; self.double = cx.press().double_pressed() && cx.press().mods.is_none(); if alt { // The release that ends a hold or a drag away fires nothing, with Alt held or not. @@ -327,34 +359,61 @@ impl Component for FlyoutButton<'_, T> { } } - /// The flyout: one row per tool, each the tool's command, the shown tool with the radio mark. Running a row - /// reports its tool and closes the flyout. + /// The flyout: one row per tool, each the tool's command, the shown tool with the radio mark, and with `tear_off` + /// the bar beside the rows. Running a row reports its tool and closes the flyout; tearing it off by the bar + /// reports the pointer and closes it. fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) { if !self.has_flyout() { return; } let popup = cx.popup("menu"); - let (tools, shown) = (self.tools, self.shown); + let (tools, shown, tips, marked, tear_off) = (self.tools, self.shown, self.tips, self.marked_row, self.tear_off); let name = self.laid.as_ref().and_then(|laid| laid.resolved.get(laid.shown)).and_then(Option::as_ref).map(|resolved| resolved.label.clone()); let name = name.map_or(Label::Empty, Label::Shared); + let bar_name = cx.words::().tear_off.clone(); let layer = menu::layer(false).place(Place::anchored(Anchor::Response, self.opens, Align::Start)); - let ran = ui.show(popup, layer, |ui, _| { - Menu::inline(name.clone()) + // PLAN: dp.T2 asks the flyout to bring `reveal_row` into view, but a menu row has no reveal request of its own + // (`MenuItem` calls no `Focus::reveal`); the rows show from the top, which holds a tool group in every window + // the rail fits. Owner of the menu rows: ui-widgets. + let shown_rows = ui.show(popup, layer, |ui, _| { + Row::new() .show(ui, |ui, _| { - let mut ran = None; - for (at, tool) in tools.iter().enumerate() { - if MenuItem::command(tool.command.clone()).radio_mark(tool.id == *shown).show(ui).ran { - ran = Some(at); + let rows = Menu::inline(name.clone()).show(ui, |ui, _| { + let mut ran = None; + for (at, tool) in tools.iter().enumerate() { + let item = MenuItem::command(tool.command.clone()).radio_mark(tool.id == *shown); + let row = match tips.filter(|tips| tips.has(&tool.id)) { + Some(tips) => item.show_with_tip(ui, |ui| tips.show(&tool.id, ui)), + None => item.show(ui), + }; + if marked == Some(at) { + TargetMark::new(row.response.rect).id_salt("marked_row").show_mark(ui); + } + if row.ran { + ran = Some(at); + } } - } - ran + ran + }); + let height = rows.output.response.rect.height(); + let bar = tear_off.then(|| TearOffBar::new(height).label(bar_name.clone()).show(ui)); + (rows.inner.flatten(), bar) }) .inner - .flatten() }); - if let Some(at) = ran.flatten() { + let Some((ran, bar)) = shown_rows.flatten() else { return }; + // The release of the press that opened the flyout tears it off over the bar, as a click on the bar does. + let released = match cx.press().phase { + PressPhase::Release { pos, .. } if self.held => Some(pos), + _ => None, + }; + let torn = bar.and_then(|bar| bar.torn.or(released.filter(|pos| bar.response.rect.contains(*pos)))); + if let Some(at) = ran { self.picked = Some(tools[at].id.clone()); popup.close(cx); + } else if let Some(pointer) = torn { + self.torn_off = Some(pointer); + popup.close(cx); } } @@ -390,7 +449,117 @@ impl Component for FlyoutButton<'_, T> { double_clicked: self.double, opened: self.open, dropped: self.dropped, - torn_off: None, + torn_off: self.torn_off, } } } + +/// The style of a tear-off bar: a large handle's width, its grip in the faint ink. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +struct TearOffBarStyle { + #[style(metrics)] + metrics: Metrics, + width: f32, + /// The grip's lines: their length, the gap between them and their ink. + grip: f32, + gap: f32, + ink: StyleColor, +} + +/// What a tear-off bar reports. +struct TearOffOutput { + response: Response, + /// Where the pointer tore the group off this pass: the drag past slop began, or a click ended. + torn: Option, +} + +impl Outcome for TearOffOutput { + type Value = NoValue; + + fn response(&self) -> &Response { + &self.response + } +} + +/// The bar down a flyout's end edge that tears the group off, as tall as the rows it runs beside: a press on it +/// dragged past the press slop reports where the drag began, a click where it ended, so a press reports once. It is +/// the pointer's alone and takes no focus. +#[derive(crate::contract::Component, crate::contract::Props)] +#[component(sample = TearOffBar::sample)] +struct TearOffBar { + #[common] + common: Common, + height: f32, + torn: Option, +} + +impl TearOffBar { + /// A bar `height` tall. + fn new(height: f32) -> Self { + TearOffBar { common: Common::new(), height, torn: None } + } + + fn sample() -> Self { + TearOffBar::new(96.0).label("Tear Off Group") + } +} + +impl Component for TearOffBar { + const ROLE: Role = Role::BUTTON; + const SHOWS_LABEL: bool = false; + const OVERLAYS: bool = false; + type Style = TearOffBarStyle; + type Output = TearOffOutput; + + fn style(cx: &StyleCx<'_>, _: TearOffBarStyleKey) -> TearOffBarStyle { + let tokens = cx.tokens; + TearOffBarStyle { + metrics: Metrics::new(), + width: tokens.size.handle.md, + grip: tokens.size.icon.sm, + gap: tokens.stroke.thick, + ink: cx.color(tokens.color.text.faint), + } + } + + fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(cx.style.width, self.height) + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { + let _ = cx + .part(BAR, rect) + .sense(Sense::DRAG | Sense::CLICK) + .cursor(CursorIcon::Grab) + .drag_cursor(CursorIcon::Grabbing) + .state_layer() + .pointer_only("the flyout's rows reach its tools from the keys"); + } + + fn update(&mut self, cx: &mut Cx<'_, Self>) { + self.torn = match cx.part(BAR).press.phase { + PressPhase::DragStart { pos, .. } | PressPhase::Release { pos, click: true, .. } => Some(pos), + _ => None, + }; + } + + /// Three short lines across the middle of the bar. + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let style = cx.style; + let centre = cx.rect.center(); + for step in [-1.0, 0.0, 1.0] { + let x = centre.x + step * style.gap; + let line = vec![Pos2::new(x, centre.y - style.grip / 2.0), Pos2::new(x, centre.y + style.grip / 2.0)]; + ui.draw().stroke(&PaintShape::Path(line), StrokeWidth::Thin, style.ink); + } + } + + fn finish(self, cx: Cx<'_, Self>) -> TearOffOutput { + TearOffOutput { response: cx.response.clone(), torn: self.torn } + } +} diff --git a/crates/ui-panels/src/rails/flyout/stories.rs b/crates/ui-panels/src/rails/flyout/stories.rs index e446f993b..068f9aa5f 100644 --- a/crates/ui-panels/src/rails/flyout/stories.rs +++ b/crates/ui-panels/src/rails/flyout/stories.rs @@ -29,3 +29,16 @@ fn flyout_button_open(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { let tools = tools(&[BRUSH, BRUSH + 1, BRUSH + 2]); FlyoutButton::new(&tools, &BRUSH).show(ui).into() } + +/// The flyout with its tear-off bar down its end edge; the readout tells where the last tear-off left the bar. +#[story(FlyoutButton<'static, u8>, covers = [], drive = Drive::Custom(hold_button))] +fn flyout_button_tear_off(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let tools = tools(&[BRUSH, BRUSH + 1, BRUSH + 2]); + let out = FlyoutButton::new(&tools, &BRUSH).tear_off().show(ui); + let note = data.note("torn off", "Not torn off".to_owned()); + if let Some(at) = out.torn_off { + *note = format!("torn off at {:.0}, {:.0}", at.x, at.y); + } + let readout = note.clone(); + StoryOutput::from(out).readout(readout) +} diff --git a/crates/ui-panels/src/rails/tool.rs b/crates/ui-panels/src/rails/tool.rs index 58cf314aa..862444fe6 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -9,13 +9,14 @@ use crate::contract::{ ShowContainer as _, Sizing, WordSetCx as _, }; use crate::contract::{BodyCx, BodyLayout, ThemeScope}; +use crate::display::{Elide, Shade, TargetMark, Text}; use crate::docking::DockGrid; use crate::layout::RowAlign; use crate::layout_components::{Row, Stack}; use crate::runtime::access::Name; use crate::runtime::commands::Commands as _; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, GlyphRole, StyleCx, SurfaceKind}; +use crate::style::{ComponentStyle, GlyphRole, StyleCx, SurfaceKind, TypeRole}; use crate::tabs::TornOff; use craft_behavior::overlay::Side; use craft_behavior::{IconId, Metrics, NavShape, Proposal, Roving, Sense, Value}; @@ -89,11 +90,12 @@ struct Collected { edit_toolbar: Option, flyout: Option, dropped: Option, + torn_off: Option>, } impl Default for Collected { fn default() -> Self { - Collected { select: None, double_clicked: None, edit_toolbar: None, flyout: None, dropped: None } + Collected { select: None, double_clicked: None, edit_toolbar: None, flyout: None, dropped: None, torn_off: None } } } @@ -110,6 +112,11 @@ type FooterFn<'a> = Box; /// buttons show the rail's glyphs. The rail is exactly as tall as its rows and footer at the width it gets /// ([`measure_rail`](ToolRail::measure_rail)). The buttons are one roving group: arrow keys move between them by the /// grid. While the toolbar is edited the buttons are dragged and take drops, and report the drop in the output. +/// +/// With `captions` the caption of the first slot of a row group that has one ([`ToolSlot::captioned`]) stands above +/// the group in the caption type, cut at the rail's width; without it a caption takes no room. The grid's width +/// ([`dock_grid`](ToolRail::dock_grid)) does not change for captions, which only add height. With `tear_off` a group +/// torn off its flyout comes out in `torn_off`. #[derive(crate::contract::Component, crate::contract::Props)] #[component(container, probe(ToolRail<'static, u8>))] pub struct ToolRail<'a, T: Value + 'static> { @@ -132,25 +139,21 @@ pub struct ToolRail<'a, T: Value + 'static> { /// The tools the user's toolbar settings hide. #[prop] hidden: &'a [T], - /// Whether each flyout shows a tear-off bar along its far side. + /// Whether each flyout shows a tear-off bar along its end edge: tearing a group off by it reports `torn_off`. #[prop(flag)] - #[allow(dead_code)] // P3(chrome-w4): ch.K15 tear_off: bool, /// Whether the slots' captions show above their row groups. #[prop(flag)] - #[allow(dead_code)] // P3(chrome-w4): ch.K14 captions: bool, /// The tool whose button, or whose row while that slot's flyout is open, wears the target mark. #[prop] - #[allow(dead_code)] // P3(chrome-w4): dp.T1 mark: Option<&'a T>, /// A request of the pass: scrolls the tool's slot into view and opens its flyout when the slot shows another tool. + /// It selects nothing. #[prop] - #[allow(dead_code)] // P3(chrome-w4): dp.T1 reveal: Option<&'a T>, - /// The tips the tools' buttons show. + /// The tips the tools' buttons and flyout rows show in place of the command tooltip, where a tool has one. #[prop] - #[allow(dead_code)] // P3(chrome-w4): ch.K17 tips: Option<&'a dyn ToolTips>, footer: Option>, /// The columns the rail lays out in this pass. @@ -193,25 +196,41 @@ impl<'a, T: Value + 'static> ToolRail<'a, T> { /// The grid of a rail of `cells` cells (its visible slots and the Edit Toolbar button) as its dock column sizes /// it ([`PanelSpec::grid`](crate::docking::PanelSpec::grid)): `first` is a button and the control padding on both - /// sides, `step` a button and the tight gap before it, and `most` the cells. + /// sides, `step` a button and the tight gap before it, and `most` the cells. The sizes are the tokens `scope` + /// resolves: a rail whose props carry a scope (a compact one) passes it, so its column fits its own buttons. pub fn dock_grid(ctx: &egui::Context, scope: &ThemeScope, cells: usize) -> DockGrid { - let _ = scope; // P3(chrome-w4): ch.K18 - StyleCx::with_root(ctx, |cx| { + StyleCx::with_root_scoped(ctx, scope, |cx| { let button = cx.tokens.size.rail.button; let most = u16::try_from(cells).unwrap_or(u16::MAX).max(1); DockGrid::new(button + 2.0 * cx.tokens.space.pad.control, button + cx.tokens.space.gap.tight, most) }) } + /// The rail, what it shows and the flyouts it opens resolve their tokens through `scope` (a compact rail's + /// density), and its columns follow the grid of that scope ([`dock_grid`](ToolRail::dock_grid)). + // PLAN: the sheet has `prepare` read the rail's own `ContainerProps::theme`, which no builder of the rail set: a + // bare `#[container]` does not forward `theme`. + #[must_use] + pub fn theme(mut self, scope: ThemeScope) -> Self { + self.props = std::mem::take(&mut self.props).theme(scope); + self + } + /// The cells the rail lays out: its visible slots and the Edit Toolbar button. fn cells(&self) -> usize { visible_slots(self.slots, self.hidden).len() + usize::from(self.edit_toolbar.is_some()) } + /// The grid of the rail's own scope (`ContainerProps::theme`, the root's when it has none) for `cells` cells. + fn grid(&self, ctx: &egui::Context, cells: usize) -> DockGrid { + let root = ThemeScope::new(); + Self::dock_grid(ctx, self.props.theme.as_ref().unwrap_or(&root), cells) + } + /// Sets up the pass for a rail `width` wide: its columns, its roving grid and its footer. Returns what the body /// draws from. fn prepare(&mut self, ctx: &egui::Context, width: f32, footer: impl FnMut(&mut Ui, RailFooter) + 'a) -> Draw<'a, T> { - self.columns = usize::from(Self::dock_grid(ctx, &self.props.theme.clone().unwrap_or_default(), self.cells()).steps_within(width)); + self.columns = usize::from(self.grid(ctx, self.cells()).steps_within(width)); self.props = std::mem::take(&mut self.props).roving(Roving::new(NavShape::wrapped_grid(self.columns))); self.footer = Some(Box::new(footer)); Draw { @@ -223,6 +242,11 @@ impl<'a, T: Value + 'static> ToolRail<'a, T> { edit_label: self.edit_toolbar.clone(), opens: self.opens, columns: self.columns, + captions: self.captions, + tear_off: self.tear_off, + tips: self.tips, + mark: self.mark, + reveal: self.reveal, } } } @@ -237,22 +261,38 @@ struct Draw<'a, T> { edit_label: Option