chrome-w4: net change of 1 commits

- chrome-w4: written by an agent
This commit is contained in:
bflatastic committed 2026-11-21 21:26:40 +07:00
1 parent 3846cbbaac
commit 76fd7a1e5b
13 files changed
+752 -85

No files matched your search

+43
View File
@@ -556,6 +556,33 @@ impl<T: Copy> PressMachine<T> {
self.open.is_some_and(|open| open.dragging)
}
/// The press the open press began as.
pub fn start(&self) -> Option<PressStart> {
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.
@@ -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).
@@ -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<Vec2>,
/// 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;
+33 -2
View File
@@ -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<Outcome>,
/// 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::<Arenas>::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<u64>)> {
} 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
+4 -6
View File
@@ -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<Panel> for Panels<'_> {
match panel {
Panel::Canvas => spec.canvas(),
// The toolbar's column is whole tool columns wide.
Panel::Tools => spec.grid(ToolRail::<Tool>::dock_grid(self.ctx, Tool::slots().len())),
Panel::Tools => spec.grid(ToolRail::<Tool>::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);
}
+16 -6
View File
@@ -244,6 +244,9 @@ pub struct FloatingGroup<'a> {
take_drop: Option<TakeDrop<'a>>,
/// 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<Vec2>,
/// The files dropped on the group's OS window that no target there took.
files: Vec<OsFile>,
}
@@ -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),
+193 -24
View File
@@ -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<CommandRef>,
/// 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<T>>,
/// 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<usize>,
/// 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<usize>,
laid: Option<Laid>,
picked: Option<T>,
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<ToolDropped>,
torn_off: Option<Pos2>,
}
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<T: Value + 'static> 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<T: Value + 'static> 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<T: Value + 'static> 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<T: Value + 'static> 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::<RailWords>().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<T: Value + 'static> 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<Pos2>,
}
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<Pos2>,
}
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 }
}
}
@@ -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)
}
+82 -18
View File
@@ -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<T> {
edit_toolbar: Option<Response>,
flyout: Option<SlotId>,
dropped: Option<ToolDropped>,
torn_off: Option<TornOff<SlotId>>,
}
impl<T> Default for Collected<T> {
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<dyn FnMut(&mut Ui, RailFooter) + 'a>;
/// 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<T>>,
footer: Option<FooterFn<'a>>,
/// 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<Label>,
opens: Side,
columns: usize,
captions: bool,
tear_off: bool,
tips: Option<&'a dyn ToolTips<T>>,
mark: Option<&'a T>,
reveal: Option<&'a T>,
}
impl<T: Value + 'static> Draw<'_, T> {
/// The grid of buttons in rows of `columns`, with the pass's results in `collected`.
/// The grid of buttons in rows of `columns`, each row group under its caption while the rail shows captions, with
/// the pass's results in `collected`.
fn run(&self, ui: &mut Ui, cx: &mut BodyCx<'_>, collected: &mut Collected<T>) {
let Draw { slots, current, last_used, hidden, editing, columns, opens, .. } = *self;
let Draw { slots, current, last_used, hidden, editing, columns, opens, captions, tear_off, tips, mark, reveal, .. } = *self;
*collected = Collected::default();
let visible = visible_slots(slots, hidden);
let cells = visible.len() + usize::from(self.edit_label.is_some());
let enabled = |tool: &RailTool<T>| cx.resolve_command(tool.command.clone()).is_some_and(|resolved| resolved.enabled);
let at: Vec<usize> = visible.iter().map(|(index, _)| *index).collect();
// The first caption among a group's slots heads the group.
let caption_of = |group: &[usize]| {
let first = *group.first()?;
let end = group.last().map_or(first, |last| (last + columns).min(cells));
visible.get(first..end.min(visible.len()))?.iter().find_map(|(index, _)| slots[*index].caption.clone())
};
// The grid of buttons sits at the centre of the rail's width.
Row::new().fill_width().align(RowAlign::Center).show(ui, |ui, _| {
Stack::new().gap(Gap::Inline).show(ui, |ui, _| {
for group in row_groups(slots, &at, cells, columns) {
let caption = captions.then(|| caption_of(&group)).flatten();
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
if let Some(caption) = caption.clone() {
Text::new(caption).id_salt(("caption", group[0])).role(TypeRole::Caption).shade(Shade::Muted).elide(Elide::End).show(ui);
}
for &first in &group {
Row::new().gap(Gap::Tight).show(ui, |ui, _| {
for k in first..(first + columns).min(cells) {
@@ -270,7 +310,31 @@ impl<T: Value + 'static> Draw<'_, T> {
if editing {
button = button.edit(SlotEdit::new(slot.id, *index, slot.tools.len(), columns == 1));
}
let out = button.show(ui);
if tear_off {
button = button.tear_off();
}
if let Some(tips) = tips {
button = button.tips(tips);
}
let row_of = |tool: Option<&T>| tool.and_then(|tool| owned.iter().position(|own| own.id == *tool));
let marked = row_of(mark);
if let Some(at) = marked {
button = button.marked_row(at);
}
if let Some(at) = row_of(reveal) {
button = button.reveal_row(at);
}
let out = match tips.filter(|tips| tips.has(&shown.id)) {
Some(tips) => button.show_with_tip(ui, |ui| tips.show(&shown.id, ui)),
None => button.show(ui),
};
// The slot wears the mark; while its flyout is open the tool's row does.
if marked.is_some() && !out.opened {
TargetMark::new(out.response.rect).id_salt(("mark", slot.id)).show_mark(ui);
}
if let Some(pointer) = out.torn_off {
collected.torn_off = Some(TornOff::new(vec![slot.id], slot.id, pointer));
}
if out.select.is_some() {
collected.select = out.select;
}
@@ -311,7 +375,7 @@ impl<'a, T: Value + 'static> ToolRail<'a, T> {
/// Shows the rail one column wide, for a host that lays it at the start of a row (the full-window workspaces'
/// tool strips): the width `ui` has left belongs to what follows it in the row.
pub fn show_column(self, ui: &mut Ui, footer: impl FnMut(&mut Ui, RailFooter) + 'a) -> ToolRailOutput<T> {
let one = Self::dock_grid(ui.ctx(), &self.props.theme.clone().unwrap_or_default(), 1).first; // P3(chrome-w4): ch.K18
let one = self.grid(ui.ctx(), 1).first;
self.show_within(ui, one, footer)
}
@@ -327,7 +391,7 @@ impl<'a, T: Value + 'static> ToolRail<'a, T> {
edit_toolbar: collected.edit_toolbar,
flyout: collected.flyout,
dropped: collected.dropped,
torn_off: None,
torn_off: collected.torn_off,
last_used: last,
..shown.output
}
+87 -16
View File
@@ -1,7 +1,9 @@
//! Stories of `ToolRail`, and the commands its stories and the flyout's use as tools.
use super::{LastUsed, RailTool, ToolRail, ToolSlot};
use crate::contract::ThemeScope;
use super::{LastUsed, RailTool, ToolRail, ToolRailOutput, ToolSlot, ToolTips};
use crate::contract::{Show as _, ThemeScope};
use crate::display::{Shade, Text};
use crate::style::TypeRole;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
@@ -33,6 +35,9 @@ const SHORT_ROOM: f32 = 120.0;
/// The id of the brush tool; the tools that follow it are the pencil and the eraser.
pub(crate) const BRUSH: u8 = 1;
/// The id of the eraser tool.
const ERASER: u8 = 3;
/// Tools with the given ids, each running the story command of its id.
pub(crate) fn tools(ids: &[u8]) -> Vec<RailTool<u8>> {
const ALL: [StoryTools; 5] = [StoryTools::Move, StoryTools::Brush, StoryTools::Pencil, StoryTools::Eraser, StoryTools::Stamp];
@@ -40,11 +45,36 @@ pub(crate) fn tools(ids: &[u8]) -> Vec<RailTool<u8>> {
}
fn slots() -> Vec<ToolSlot<u8>> {
vec![ToolSlot::new(0, tools(&[0])), ToolSlot::new(1, tools(&[BRUSH, BRUSH + 1])), ToolSlot::new(2, tools(&[3])), ToolSlot::new(3, tools(&[4]))]
vec![ToolSlot::new(0, tools(&[0])), ToolSlot::new(1, tools(&[BRUSH, BRUSH + 1])), ToolSlot::new(2, tools(&[ERASER])), ToolSlot::new(3, tools(&[4]))]
}
/// The rail in a room as wide as its grid at `columns` columns: the stage a dock column of that many steps gives it. A
/// short room is lower than the rail's rows, so they scroll under the overlay bar.
/// The story slots in two captioned groups: Move alone, then the painting tools.
fn captioned_slots() -> Vec<ToolSlot<u8>> {
vec![
ToolSlot::ending_group(0, tools(&[0])).captioned("Select"),
ToolSlot::new(1, tools(&[BRUSH, BRUSH + 1])).captioned("Paint and Retouch"),
ToolSlot::new(2, tools(&[ERASER])),
ToolSlot::new(3, tools(&[4])),
]
}
/// Shows `rail` in a room as wide as the grid of `cells` cells at `columns` columns, the stage a dock column of that
/// many steps gives it, and at most `height` high.
fn in_columns(ui: &mut Ui, columns: u8, cells: usize, height: Option<f32>, rail: ToolRail<'_, u8>) -> ToolRailOutput<u8> {
let width = ToolRail::<u8>::dock_grid(ui.ctx(), &ThemeScope::new(), cells).width(u16::from(columns));
// design: allow[contract/memory](the story gives the rail the width of its chosen columns, as a dock column does)
ui.scope(|ui| {
ui.set_max_width(width);
if let Some(height) = height {
ui.set_max_height(height);
}
rail.show_rail(ui, |_, _| {})
})
.inner
}
/// The rail in a room as wide as its grid at `columns` columns. A short room is lower than the rail's rows, so they
/// scroll under the overlay bar.
#[story(ToolRail<'static, u8>, covers = [Default], drive = Drive::Never)]
fn tool_rail(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let columns = *data.ranged("columns", 1_u8, 1.0..=4.0);
@@ -53,17 +83,8 @@ fn tool_rail(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
data.choice("hidden", Vec::<u8>::new(), &[("None", Vec::new()), ("Pencil", vec![2]), ("Stamp", vec![4]), ("Eraser", vec![3])]).clone();
let slots = slots();
let last = LastUsed::default();
let width = ToolRail::<u8>::dock_grid(ui.ctx(), &ThemeScope::new(), slots.len() + 1).width(u16::from(columns)); // P3(chrome-w4): ch.K18
// design: allow[contract/memory](the story gives the rail the width of its chosen columns, as a dock column does)
let out = ui
.scope(|ui| {
ui.set_max_width(width);
if short {
ui.set_max_height(SHORT_ROOM);
}
ToolRail::new("Tools", &slots, &BRUSH, &last).hidden(&hidden).edit_toolbar("Edit Toolbar").show_rail(ui, |_, _| {})
})
.inner;
let rail = ToolRail::new("Tools", &slots, &BRUSH, &last).hidden(&hidden).edit_toolbar("Edit Toolbar");
let out = in_columns(ui, columns, slots.len() + 1, short.then_some(SHORT_ROOM), rail);
let note = data.note("note", "Nothing yet".to_owned());
if let Some(tool) = out.select {
*note = format!("selected {tool}");
@@ -76,3 +97,53 @@ fn tool_rail(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let readout = format!("{note}; flyout {flyout}");
StoryOutput::from(out).readout(readout)
}
/// The rail with its groups' captions in one or two columns: each caption heads its row group, cut at the rail's
/// width.
#[story(ToolRail<'static, u8>, covers = [], drive = Drive::Never)]
fn tool_rail_captions(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let columns = *data.ranged("columns", 1_u8, 1.0..=2.0);
let slots = captioned_slots();
let last = LastUsed::default();
in_columns(ui, columns, slots.len(), None, ToolRail::new("Tools", &slots, &0, &last).captions()).into()
}
/// The tips of the brush and the eraser: the tool's name over what it does.
struct StoryTips;
impl ToolTips<u8> for StoryTips {
fn has(&self, tool: &u8) -> bool {
matches!(*tool, BRUSH | ERASER)
}
fn show(&self, tool: &u8, ui: &mut Ui) {
let (name, does) = if *tool == BRUSH { ("Brush", "Paints with the foreground colour.") } else { ("Eraser", "Erases to transparency.") };
Text::new(name).show(ui);
Text::new(does).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
}
}
/// The rail whose brush and eraser show a tip in place of their command tooltip, on their buttons and in the brush
/// slot's flyout.
#[story(ToolRail<'static, u8>, covers = [], drive = Drive::Never)]
fn tool_rail_tips(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let slots = slots();
let last = LastUsed::default();
in_columns(ui, 1, slots.len(), None, ToolRail::new("Tools", &slots, &0, &last).tips(&StoryTips)).into()
}
/// The pencil marked while the brush slot shows the brush: the reveal of the first pass opens the slot's flyout, whose
/// pencil row wears the mark; closed again, the slot's button wears it.
#[story(ToolRail<'static, u8>, covers = [], drive = Drive::Never)]
fn tool_rail_marked_in_a_closed_group(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let slots = slots();
let last = LastUsed::default();
let pencil = BRUSH + 1;
// The reveal is a request of one pass.
let revealed = std::mem::replace(data.note("revealed", false), true);
let mut rail = ToolRail::new("Tools", &slots, &0, &last).mark(&pencil);
if !revealed {
rail = rail.reveal(&pencil);
}
in_columns(ui, 1, slots.len(), None, rail).into()
}
+67 -4
View File
@@ -1,4 +1,5 @@
//! Trials of `ToolRail`: its columns for a width, its measure, a short room and its glyph role.
//! Trials of `ToolRail`: its columns for a width, its measure, a short room, its glyph role, its captions and its grid
//! in a scope of its own.
#![allow(clippy::panic, clippy::expect_used, reason = "trials assert by panicking")]
use super::stories::tools;
@@ -9,6 +10,7 @@ use crate::contract::{Props as _, ThemeScope};
use crate::testing::pointer::{moved, wheel};
use crate::testing::relations::{above, grows_with};
use crate::testing::{Fixture, trial};
use craft_theme::Size;
use egui::{Rect, Vec2};
use std::cell::Cell;
use std::rc::Rc;
@@ -61,7 +63,7 @@ fn rail_in(width: f32, height: f32) -> (Fixture, Rc<Cell<Vec2>>) {
/// of them one fewer, and a wider one no more columns than the rail has cells.
#[trial]
fn a_tool_rail_lays_out_the_most_whole_columns_its_width_holds() {
let grid = ToolRail::<u8>::dock_grid(Fixture::new(|_| {}).ctx(), &ThemeScope::new(), LABELS.len()); // P3(chrome-w4): ch.K18
let grid = ToolRail::<u8>::dock_grid(Fixture::new(|_| {}).ctx(), &ThemeScope::new(), LABELS.len());
for steps in 1..=3_u16 {
let (fixture, _) = rail_in(grid.width(steps), 800.0);
assert_eq!(columns_of(&fixture), usize::from(steps), "a width of {steps} steps shows {steps} columns");
@@ -80,7 +82,7 @@ fn a_tool_rail_lays_out_the_most_whole_columns_its_width_holds() {
/// and fewer columns need more rows.
#[trial]
fn a_tool_rail_measures_its_rows_plus_its_footer_at_a_width() {
let grid = ToolRail::<u8>::dock_grid(Fixture::new(|_| {}).ctx(), &ThemeScope::new(), LABELS.len()); // P3(chrome-w4): ch.K18
let grid = ToolRail::<u8>::dock_grid(Fixture::new(|_| {}).ctx(), &ThemeScope::new(), LABELS.len());
let mut heights = Vec::new();
for steps in [1_u16, 2] {
let (fixture, measured) = rail_in(grid.width(steps), 800.0);
@@ -99,7 +101,7 @@ fn a_tool_rail_measures_its_rows_plus_its_footer_at_a_width() {
/// above it, down to a room smaller than one scroll region's usual least height.
#[trial]
fn in_a_short_room_the_rows_scroll_above_the_footer_that_stays_in_view() {
let grid = ToolRail::<u8>::dock_grid(Fixture::new(|_| {}).ctx(), &ThemeScope::new(), LABELS.len()); // P3(chrome-w4): ch.K18
let grid = ToolRail::<u8>::dock_grid(Fixture::new(|_| {}).ctx(), &ThemeScope::new(), LABELS.len());
for height in [160.0, 100.0] {
let (mut fixture, measured) = rail_in(grid.width(1), height);
let foot = rect(&fixture, "Foot");
@@ -149,6 +151,67 @@ fn the_tool_rail_shows_its_buttons_icons_in_its_glyph_role() {
assert!(tool.color.off.rest != tool.color.off.hover, "a tool rail icon rests quieter than under the pointer");
}
/// A caption longer than any rail is wide.
const CAPTION: &str = "Painting, Retouching and Every Other Tool That Puts Pixels Down";
/// A rail with a caption on its first slot measures taller with captions shown than without, and as tall as a rail with
/// no caption while they are off; the shown caption is cut at the rail's width.
#[trial]
fn captions_take_room_only_while_the_rail_shows_them() {
let width = ToolRail::<u8>::dock_grid(Fixture::new(|_| {}).ctx(), &ThemeScope::new(), LABELS.len()).width(1);
let measured = Rc::new(Cell::new([Vec2::ZERO; 3]));
let report = Rc::clone(&measured);
let mut fixture = Fixture::new(move |ui| {
let plain = slots();
let captioned: Vec<ToolSlot<u8>> =
slots().into_iter().enumerate().map(|(at, slot)| if at == 0 { slot.captioned(CAPTION) } else { slot }).collect();
let last = LastUsed::default();
let none = ToolRail::new("Tools", &plain, &0, &last).measure_rail(ui, width, |_, _| {});
let off = ToolRail::new("Tools", &captioned, &0, &last).measure_rail(ui, width, |_, _| {});
let on = ToolRail::new("Tools", &captioned, &0, &last).captions().measure_rail(ui, width, |_, _| {});
report.set([none, off, on]);
ToolRail::new("Tools", &captioned, &0, &last).captions().show_rail(ui, |_, _| {});
});
fixture.room(Vec2::new(width, 800.0)).settle();
let [none, off, on] = measured.get();
assert!(near(off.y, none.y), "a caption takes no room while captions are off: {off:?} against {none:?}");
assert!(on.y >= off.y + 1.0, "a shown caption adds its row: {on:?} against {off:?}");
let (rail, caption) = (rect(&fixture, "Tools"), rect(&fixture, CAPTION));
assert!(rail.contains_rect(caption), "the caption {caption:?} is cut at the rail's width {rail:?}");
assert!(above(caption, rect(&fixture, "Move")), "the caption heads its group");
}
/// A rail at `width` in a room 800 high, its tokens resolved in `scope`: its columns, its rect and its Move button.
fn rail_in_scope(width: f32, scope: ThemeScope) -> (usize, Rect, Rect) {
let mut fixture = Fixture::new(move |ui| {
let slots = slots();
ToolRail::new("Tools", &slots, &0, &LastUsed::default()).theme(scope.clone()).show_rail(ui, |_, _| {});
});
fixture.room(Vec2::new(width, 800.0)).settle();
(columns_of(&fixture), rect(&fixture, "Tools"), rect(&fixture, "Move"))
}
/// A rail in a compact scope fills the grid `dock_grid` gives for that scope: its first step shows one column, its
/// second two, each of buttons smaller than a rail at the root's density shows; the compact grid is narrower than the
/// root one.
#[trial]
fn a_rail_in_a_compact_scope_fills_the_grid_dock_grid_gives_for_that_scope() {
let probe = Fixture::new(|_| {});
let compact = ThemeScope::new().density(Size::Compact);
let (root, scoped) = (
ToolRail::<u8>::dock_grid(probe.ctx(), &ThemeScope::new(), LABELS.len()),
ToolRail::<u8>::dock_grid(probe.ctx(), &compact, LABELS.len()),
);
assert!(scoped.first < root.first && scoped.step < root.step, "the compact grid {scoped:?} is narrower than the root one {root:?}");
let (_, _, root_button) = rail_in_scope(root.width(1), ThemeScope::new());
for steps in [1_u16, 2] {
let (columns, rail, button) = rail_in_scope(scoped.width(steps), compact.clone());
assert_eq!(columns, usize::from(steps), "the compact rail fills {steps} steps of its own grid");
assert!(near(rail.width(), scoped.width(steps)), "{steps} steps: the rail is as wide as its compact columns: {rail:?}");
assert!(button.width() < root_button.width(), "{steps} steps: a compact button {button:?} is smaller than a root one {root_button:?}");
}
}
fn near(a: f32, b: f32) -> bool {
(a - b).abs() < 1.0
}
+189 -5
View File
@@ -1,15 +1,19 @@
//! The rail's own logic: which tool a slot shows, what the rail remembers, where a drop goes, and the flyout's hold
//! and click, and a press dragged away.
//! The rail's own logic: which tool a slot shows, what the rail remembers, where a drop goes, the flyout's hold and
//! click, a press dragged away, the flyout's tear-off bar and the window a torn-off group floats in.
mod drawer;
use craft_behavior::GesturePhase;
use craft_ui::contract::overlay::{PlacementChange, PlacementKind};
use craft_ui::contract::{Role, Show as _};
use craft_ui::docking::{FloatingGroup, GroupDrag};
use craft_ui::rails::{FlyoutButton, RailTool};
use craft_ui::runtime::commands::EditCommands;
use craft_ui::runtime::drag;
use craft_ui::runtime::frame::take_output;
use craft_ui::testing::pointer::{moved, secondary};
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers};
use craft_ui::testing::pointer::{moved, press, secondary};
use craft_ui::testing::{Fixture, Target, trial};
use egui::{Key, Modifiers, Pos2, Rect, Vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
@@ -200,3 +204,183 @@ fn alt_click_steps_a_slot_and_a_modified_click_is_never_a_double_click() {
rig.fixture.click(&target);
assert_eq!(rig.doubles.get(), 1, "two plain clicks are a double click");
}
/// The name of the flyout's tear-off bar.
const TEAR_OFF: &str = "Tear Off Group";
/// A button over the three tools, with the tear-off bar when `tear_off` holds, and the pointers it reported torn off
/// and the tools it selected.
struct TearRig {
fixture: Fixture,
torn: Rc<RefCell<Vec<Pos2>>>,
selected: Rc<RefCell<Vec<u8>>>,
}
fn tear_rig(tear_off: bool) -> TearRig {
let (torn, selected) = (Rc::new(RefCell::new(Vec::new())), Rc::new(RefCell::new(Vec::new())));
let (tears, picks) = (Rc::clone(&torn), Rc::clone(&selected));
let mut fixture = Fixture::new(move |ui| {
let all = tools(&[UNDO, REDO, CUT]);
let mut button = FlyoutButton::new(&all, &UNDO);
if tear_off {
button = button.tear_off();
}
let out = button.show(ui);
tears.borrow_mut().extend(out.torn_off);
picks.borrow_mut().extend(out.select);
});
fixture.settle();
TearRig { fixture, torn, selected }
}
/// The first button of `fixture`.
fn first_button(fixture: &Fixture) -> Target {
fixture.by_role(Role::BUTTON).into_iter().next().expect("the flyout button shows")
}
/// Opens the flyout of the button at `at` by a right click, which leaves no press held.
fn open_by_context(fixture: &mut Fixture, at: Pos2) {
fixture.frame(vec![moved(at)]);
fixture.frame(vec![secondary(at, true)]);
fixture.frame(vec![secondary(at, false)]);
fixture.idle(3);
assert!(!fixture.by_role(Role::MENU).is_empty(), "a right click opens the flyout");
}
fn bar(fixture: &Fixture) -> Target {
fixture.by_label(TEAR_OFF).expect("the flyout shows its tear-off bar")
}
/// A press on the bar dragged past the slop, a click on it and the release over it of the hold that opened the flyout
/// each close the flyout and report the pointer once; a release over a row picks the row and tears nothing off; a
/// flyout without `tear_off` has no bar.
#[trial]
fn dragging_the_flyout_bar_clicking_it_or_releasing_a_hold_over_it_reports_the_tear_off_once() {
let away = Vec2::new(0.0, 40.0);
let mut dragged = tear_rig(true);
let at = first_button(&dragged.fixture).center();
open_by_context(&mut dragged.fixture, at);
let from = bar(&dragged.fixture).center();
dragged.fixture.drag_hold_at(from, away);
dragged.fixture.release_at(from + away);
let torn = dragged.torn.borrow().clone();
assert_eq!(torn.len(), 1, "a drag on the bar tears the group off once: {torn:?}");
assert!(torn[0] != from && torn[0].distance(from) <= away.length(), "where the drag passed the slop: {torn:?} from {from:?}");
assert!(dragged.fixture.by_role(Role::MENU).is_empty(), "the drag closes the flyout");
assert!(dragged.selected.borrow().is_empty(), "a tear-off selects no tool");
let mut clicked = tear_rig(true);
let at = first_button(&clicked.fixture).center();
open_by_context(&mut clicked.fixture, at);
let target = bar(&clicked.fixture);
clicked.fixture.click(&target);
clicked.fixture.idle(2);
assert_eq!(*clicked.torn.borrow(), [target.center()], "a click on the bar tears the group off where it was clicked, once");
assert!(clicked.fixture.by_role(Role::MENU).is_empty(), "the click closes the flyout");
let mut held = tear_rig(true);
let target = first_button(&held.fixture);
held.fixture.press(&target);
held.fixture.advance(HELD);
held.fixture.idle(3);
let over = bar(&held.fixture).center();
held.fixture.frame(vec![moved(over)]);
held.fixture.release_at(over).idle(2);
assert_eq!(*held.torn.borrow(), [over], "the release of the hold over the bar tears the group off, once");
assert!(held.selected.borrow().is_empty(), "the release over the bar picks no row");
assert!(held.fixture.by_role(Role::MENU).is_empty(), "the release closes the flyout");
let mut row = tear_rig(true);
let target = first_button(&row.fixture);
row.fixture.press(&target);
row.fixture.advance(HELD);
row.fixture.idle(3);
let redo = row.fixture.by_label("Redo").expect("the flyout lists Redo").center();
row.fixture.frame(vec![moved(redo)]);
row.fixture.release_at(redo).idle(2);
assert!(row.torn.borrow().is_empty(), "a release over a row tears nothing off");
assert_eq!(*row.selected.borrow(), [REDO], "it picks the row");
let mut plain = tear_rig(false);
let at = first_button(&plain.fixture).center();
open_by_context(&mut plain.fixture, at);
assert!(plain.fixture.by_label(TEAR_OFF).is_none(), "a flyout without tear_off has no bar");
}
/// Where the pointer holds the window a group floats in, from its top left: on its title row.
const GRAB: Vec2 = Vec2::new(30.0, 8.0);
/// The size the window floats at.
const FLOAT: Vec2 = Vec2::new(140.0, 90.0);
/// What the host of a torn-off group keeps: the window's rect, and the placement changes it reported.
#[derive(Default)]
struct Floated {
rect: Cell<Option<Rect>>,
changes: RefCell<Vec<PlacementChange>>,
}
/// A button over the three tools with its tear-off bar, whose host floats a torn-off group in a window of the dock
/// model: in the pass that reports the tear-off the window continues the press at `GRAB`, a pass that runs twice.
fn floating_rig() -> (Fixture, Rc<Floated>) {
let floated = Rc::new(Floated::default());
let host = Rc::clone(&floated);
let mut fixture = Fixture::new(move |ui| {
let all = tools(&[UNDO, REDO, CUT]);
let out = FlyoutButton::new(&all, &UNDO).tear_off().show(ui);
if let Some(pointer) = out.torn_off {
host.rect.set(Some(Rect::from_min_size(pointer - GRAB, FLOAT)));
// The second pass of the frame has no input of its own: the press is the window's already.
if ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("the tear-off pass runs twice");
}
}
let Some(rect) = host.rect.get() else { return };
let mut group = FloatingGroup::new("Edit", rect).window_of("Edit");
if out.torn_off.is_some() {
group = group.continue_move(GRAB);
}
let shown = group.show_group(ui, |_, _| {});
if let Some(change) = shown.output.placed {
host.rect.set(Some(change.rect));
host.changes.borrow_mut().push(change);
}
});
fixture.settle();
(fixture, floated)
}
/// The window a group torn off by a drag of the bar floats in follows the press still held from its first pass,
/// keeping the pointer at the grab point, reports the move and runs the dock drag that docks it until the release
/// commits the move. A group torn off by a click, with no press held, floats where it was put and does not move.
#[trial]
fn a_window_floated_from_a_torn_off_group_follows_the_held_press_and_docks_on_release() {
let (mut fixture, floated) = floating_rig();
let at = first_button(&fixture).center();
open_by_context(&mut fixture, at);
let from = bar(&fixture).center();
fixture.frame(vec![moved(from)]);
fixture.frame(vec![press(from)]);
let path = [from + Vec2::new(0.0, 12.0), from + Vec2::new(40.0, 30.0), from + Vec2::new(90.0, 60.0)];
for pointer in path {
fixture.frame(vec![moved(pointer)]);
let rect = floated.rect.get().expect("the torn-off group floats in a window");
assert!((rect.min + GRAB).distance(pointer) < 1.0, "the window keeps the pointer at its grab point: {rect:?} at {pointer:?}");
}
assert!(drag::active::<GroupDrag<&'static str>>(fixture.ctx()).is_some(), "the move runs the window's dock drag");
let moving = |change: &PlacementChange| change.kind == PlacementKind::Move && change.phase == GesturePhase::Update;
assert!(floated.changes.borrow().iter().any(moving), "the window reports its move");
fixture.release_at(path[2]).idle(2);
let last = floated.changes.borrow().last().copied().expect("the window reported its move");
assert!(last.kind == PlacementKind::Move && last.phase == GesturePhase::Commit, "the release commits the move: {last:?}");
assert!(drag::active::<GroupDrag<&'static str>>(fixture.ctx()).is_none(), "the release ends the dock drag");
let (mut fixture, floated) = floating_rig();
let at = first_button(&fixture).center();
open_by_context(&mut fixture, at);
let target = bar(&fixture);
fixture.click(&target);
let put = floated.rect.get().expect("a click on the bar floats the group too");
fixture.frame(vec![moved(target.center() + Vec2::new(60.0, 40.0))]).idle(2);
assert!(floated.changes.borrow().is_empty(), "with no press held the window reports no move");
assert_eq!(floated.rect.get(), Some(put), "with no press held the window stays where it was put");
}
+5 -4
View File
@@ -32,7 +32,8 @@ use std::sync::{Arc, Mutex, PoisonError};
const OVERFLOW: PartKey = PartKey::new("overflow");
/// A tab dragged away from every strip and released: the tabs the drag carried and where the pointer was.
/// A tab dragged away from every strip and released: the tabs the drag carried and where the pointer was. A tool rail
/// reports a group torn off a flyout as one too, its slot as both `keys` and `grabbed`.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct TornOff<K> {
@@ -45,10 +46,10 @@ pub struct TornOff<K> {
}
impl<K> TornOff<K> {
/// A tear-off of `keys`, the tab `grabbed` among them, released with the pointer at `pointer`.
/// A tear-off of `keys`, the tab `grabbed` among them, released with the pointer at `pointer`. The struct is
/// `#[non_exhaustive]`, so this is how another crate (a tool rail) reports one.
pub fn new(keys: Vec<K>, grabbed: K, pointer: Pos2) -> Self {
let _ = (keys, grabbed, pointer);
todo!("ch.K15")
TornOff { keys, grabbed, pointer }
}
}