craft-ui-panels: the tool rail's slots, last-used tools and hidden tools are Tracked values, so its key does not walk them

This commit is contained in:
aiongg committed 2026-11-20 18:17:24 +00:00
1 parent 95d7fc34b4
commit 75f2d453b0
19 files changed
+164 -106

No files matched your search

+2 -2
View File
@@ -3,7 +3,7 @@
use super::{PairWell, SwatchPair, Well};
use craft_behavior::Mixed;
use craft_theme::Srgba;
use craft_ui::contract::{Show as _, Validity};
use craft_ui::contract::{Show as _, Tracked, Validity};
use craft_ui::rails::{LastUsed, ToolRail, ToolSlot};
use craft_ui::runtime::env::Message;
use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story};
@@ -101,7 +101,7 @@ fn swatch_pair_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
#[story(SwatchPair<'static>, covers = [], drive = Drive::Never)]
fn swatch_pair_tool_rail(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let (active, active_at) = data.value_at("active", Well::Primary);
let (slots, last): (Vec<ToolSlot<u8>>, LastUsed<u8>) = (Vec::new(), LastUsed::default());
let (slots, last): (Tracked<Vec<ToolSlot<u8>>>, Tracked<LastUsed<u8>>) = (Tracked::default(), Tracked::default());
let wells = [PairWell::new("Foreground colour", Srgba::rgb(0.0, 0.0, 0.0)), PairWell::new("Background colour", Srgba::rgb(1.0, 1.0, 1.0))];
let mut shown = None;
ToolRail::new("Tools", &slots, &0, &last).show_rail(ui, |ui, _| {
+10 -9
View File
@@ -62,7 +62,7 @@ use craft_ui::buttons::IconButton;
use craft_ui::canvas::{HandTool, NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick};
use craft_ui::canvas_controls::brush::{BrushCursorOptions, TipFalloff};
use craft_ui::canvas_controls::{Marquee, MarqueeLook};
use craft_ui::contract::{Bind, BodyCx, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked};
use craft_ui::contract::{Bind, Tracked, BodyCx, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked};
use craft_ui::dialog::{
DialogResult, DialogWords, FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowTitle, FullWindowView,
FullWindowWorkspace, RasterOverlay, SideFooter, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field,
@@ -238,7 +238,8 @@ pub struct ContentAwareFillWorkspace {
preview_view: FullWindowView,
framing: PreviewFraming,
tool: FillTool,
last_used: LastUsed<FillTool>,
last_used: Tracked<LastUsed<FillTool>>,
slots: Tracked<Vec<ToolSlot<FillTool>>>,
options: FillToolOptions,
canvas: FillCanvas,
hand: HandTool,
@@ -294,7 +295,8 @@ impl ContentAwareFillWorkspace {
preview_view: FullWindowView::new(),
framing: PreviewFraming::default(),
tool: FillTool::SamplingBrush,
last_used: LastUsed::default(),
last_used: Tracked::new(LastUsed::default()),
slots: Tracked::new(FillTool::slots()),
canvas: FillCanvas::new(),
hand: HandTool::new(navigation),
zoom: ZoomTool::new(navigation),
@@ -388,7 +390,6 @@ impl ContentAwareFillWorkspace {
let params = env.words::<ParamDialogWords>();
let title =
FullWindowTitle::new(env.words::<FillWords>().name.clone()).subject(self.subject.clone()).zoom(self.view.zoom_percent()).label(&env);
let slots = FillTool::slots();
let mut reset_all = false;
let this = RefCell::new(&mut *self);
@@ -410,7 +411,7 @@ impl ContentAwareFillWorkspace {
})
.show(ui, |ui, cx| {
let mut guard = this.borrow_mut();
guard.show_body(ui, cx, &env, &slots, source);
guard.show_body(ui, cx, &env, source);
});
let work = this.into_inner();
@@ -604,7 +605,7 @@ impl ContentAwareFillWorkspace {
}
/// The body: the steps and keys, the options bar, the tool strip and the canvas; then the preview job.
fn show_body(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>, env: &Env, slots: &[ToolSlot<FillTool>], source: &dyn FillSource) {
fn show_body(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>, env: &Env, source: &dyn FillSource) {
let ctx = ui.ctx().clone();
let words = env.words::<FillWords>();
while let Some((command, _)) = cx.take_command::<ViewCommands>() {
@@ -623,7 +624,7 @@ impl ContentAwareFillWorkspace {
if fired.phase == FirePhase::Release {
continue;
}
let slot = slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool));
let slot = self.slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool));
let tools: Vec<&RailTool<FillTool>> = slot.into_iter().flat_map(|slot| slot.tools.iter()).collect();
let picked = slot.and_then(|slot| {
tool_pick(&tools, slot.id, &self.tool, &self.last_used, PickStep::of(&fired), |_| true).map(|entry| (slot.id, entry.id))
@@ -652,9 +653,9 @@ impl ContentAwareFillWorkspace {
}
Row::new().fill().show(ui, |ui, _| {
let rail = ToolRail::new(words.tools.clone(), slots, &self.tool, &self.last_used).show_column(ui, |_, _| {});
let rail = ToolRail::new(words.tools.clone(), &self.slots, &self.tool, &self.last_used).show_column(ui, |_, _| {});
if let Some(next) = rail.last_used {
self.last_used = next;
*self.last_used = next;
}
if let Some(tool) = rail.select {
self.pick(Some(&ctx), tool);
+1 -1
View File
@@ -18,7 +18,7 @@ use super::session::{FillLimit, FillLimits, FillSession, FillStrokeEvent, Sampli
use crate::ui::select_mask::EditMode;
/// The tools of Content-Aware Fill's strip: Sampling Brush (B), Lasso (L), Hand (H), Zoom (Z).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[non_exhaustive]
pub enum FillTool {
/// The Sampling Brush.
+20 -8
View File
@@ -72,14 +72,14 @@ use craft_behavior::{CancelReason, Cursor, EditEvent, EditHistory, Mixed};
use craft_ui::canvas::{NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, tool_pick};
use craft_ui::canvas_controls::brush::{BrushCursorOptions, TipFalloff};
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, Pattern, Props as _, Show as _, ShowContainer as _};
use craft_ui::contract::{Bind, Tracked, Pattern, Props as _, Show as _, ShowContainer as _};
use craft_ui::dialog::{
FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowTitle, FullWindowView, FullWindowWorkspace, RasterOverlay,
WorkspaceCx, WorkspacePass, serde_fields, set_serde_field,
};
use craft_ui::layout_components::Row;
use craft_ui::primitives::Checker;
use craft_ui::rails::{LastUsed, ToolRail};
use craft_ui::rails::{LastUsed, ToolRail, ToolSlot};
use craft_ui::runtime::commands::{CommandSet as _, Commands as _, FirePhase};
use craft_ui::runtime::env::Env;
use craft_ui::runtime::memory::{SaveKey, saved_value, set_saved_value};
@@ -223,15 +223,28 @@ pub struct LiquifyDone {
/// What the workspace keeps between passes besides the session: the view, the strip's memory and the tool in progress. None of it is
/// the app's, and none of it is in the history.
#[derive(Clone, Default)]
#[derive(Clone)]
struct LiquifyView {
view: FullWindowView,
last_used: LastUsed<LiquifyTool>,
last_used: Tracked<LastUsed<LiquifyTool>>,
slots: Tracked<Vec<ToolSlot<LiquifyTool>>>,
canvas: LiquifyCanvas,
/// The canvas the tools run under, to cancel their gestures outside a pass.
canvas_id: Option<Id>,
}
impl Default for LiquifyView {
fn default() -> Self {
LiquifyView {
view: FullWindowView::default(),
last_used: Tracked::default(),
slots: Tracked::new(LiquifyTool::slots()),
canvas: LiquifyCanvas::default(),
canvas_id: None,
}
}
}
/// The Liquify workspace: the session and its history and the settings, as one value the app keeps while Liquify
/// is open, with the view, the strip's memory and the stroke in progress.
///
@@ -441,7 +454,6 @@ impl LiquifyWorkspace {
self.edit.events.push(LiquifyEvent::BackdropWanted(of));
self.asked = Some(of);
}
let slots = LiquifyTool::slots();
let preview_label = words.preview.clone();
let this = RefCell::new(&mut *self);
@@ -499,7 +511,7 @@ impl LiquifyWorkspace {
if fired.phase == FirePhase::Release {
continue;
}
let slot = slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool));
let slot = work.view.slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool));
let tools: Vec<_> = slot.into_iter().flat_map(|slot| slot.tools.iter()).collect();
let picked = slot.and_then(|slot| {
tool_pick(&tools, slot.id, &work.edit.settings.tool, &work.view.last_used, PickStep::of(&fired), |_| true)
@@ -544,9 +556,9 @@ impl LiquifyWorkspace {
.fill()
.show(ui, |ui, _| {
let rail =
ToolRail::new(words.tools.clone(), &slots, &work.edit.settings.tool, &state.last_used).show_column(ui, |_, _| {});
ToolRail::new(words.tools.clone(), &state.slots, &work.edit.settings.tool, &state.last_used).show_column(ui, |_, _| {});
if let Some(next) = rail.last_used {
state.last_used = next;
*state.last_used = next;
}
if let Some(tool) = rail.select {
work.edit.pick(Some(&ctx), state, tool);
+1 -1
View File
@@ -11,7 +11,7 @@ use super::session::{LiquifyStroke, StrokeEvent};
/// The tools of Liquify's strip, in strip order, with Photoshop's letters. Serialised with the
/// engine's names (`forwardWarp`, `twirlCw`, `lassoMask`, …) so a [`LiquifyStroke`] passes to
/// PhotoCraft's engine unchanged.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::MemoProps)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum LiquifyTool {
+9 -8
View File
@@ -68,14 +68,14 @@ use craft_theme::Srgba;
use craft_ui::buttons::IconButton;
use craft_ui::canvas::{NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick};
use craft_ui::canvas_controls::brush::{BrushCursorOptions, TipFalloff};
use craft_ui::contract::{Bind, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked};
use craft_ui::contract::{Bind, Tracked, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked};
use craft_ui::dialog::{
FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowWorkspace,
SideFooter, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field,
};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::primitives::Checker;
use craft_ui::rails::{LastUsed, ToolRail};
use craft_ui::rails::{LastUsed, ToolRail, ToolSlot};
use craft_ui::runtime::commands::{CommandSet as _, Commands as _, FirePhase};
use craft_ui::runtime::edit::next_gesture_id;
use craft_ui::runtime::env::Env;
@@ -295,7 +295,8 @@ pub struct SelectMaskWorkspace {
view: FullWindowView,
mask_view: MaskViewState,
tool: SelectMaskTool,
last_used: LastUsed<SelectMaskTool>,
last_used: Tracked<LastUsed<SelectMaskTool>>,
slots: Tracked<Vec<ToolSlot<SelectMaskTool>>>,
options: SelectMaskToolOptions,
canvas: SelectMaskCanvas,
zoom_tool: ZoomTool,
@@ -351,7 +352,8 @@ impl SelectMaskWorkspace {
checkerboard: open.checkerboard,
view: FullWindowView::new(),
tool: SelectMaskTool::Quick,
last_used: LastUsed::default(),
last_used: Tracked::new(LastUsed::default()),
slots: Tracked::new(SelectMaskTool::slots()),
options: SelectMaskToolOptions::default(),
canvas,
zoom_tool: ZoomTool::new(open.navigation),
@@ -486,7 +488,6 @@ impl SelectMaskWorkspace {
let words = env.words::<SelectMaskWords>();
let common = env.words::<CommonWords>();
let title = FullWindowTitle::new(words.name.clone()).subject(self.subject.clone()).zoom(self.zoom_percent).label(&env);
let slots = SelectMaskTool::slots();
self.start_pass(ui.ctx());
let request = self.request_now();
let key = format!("{request:?}");
@@ -552,7 +553,7 @@ impl SelectMaskWorkspace {
if fired.phase == FirePhase::Release {
continue;
}
let slot = slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool));
let slot = work.slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == tool));
let tools: Vec<_> = slot.into_iter().flat_map(|slot| slot.tools.iter()).collect();
let picked = slot.and_then(|slot| {
tool_pick(&tools, slot.id, &work.tool, &work.last_used, PickStep::of(&fired), |_| true).map(|entry| (slot.id, entry.id))
@@ -590,9 +591,9 @@ impl SelectMaskWorkspace {
let preview = falloff.as_ref().and_then(|falloff| work.canvas.resize().preview(falloff));
let shown = Row::new().fill().show(ui, |ui, _| {
let rail = ToolRail::new(words.tools.clone(), &slots, &work.tool, &work.last_used).show_column(ui, |_, _| {});
let rail = ToolRail::new(words.tools.clone(), &work.slots, &work.tool, &work.last_used).show_column(ui, |_, _| {});
if let Some(next) = rail.last_used {
work.last_used = next;
*work.last_used = next;
}
if let Some(tool) = rail.select {
work.pick(Some(&ctx), tool);
+1 -1
View File
@@ -84,7 +84,7 @@ impl<T> EditPhase<T> {
/// The tools of Select and Mask's strip, with Photoshop's letters. Quick Selection and Object
/// Selection share the W slot, Lasso and Polygonal Lasso the L slot.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[non_exhaustive]
pub enum SelectMaskTool {
/// W.
@@ -47,7 +47,7 @@ pub enum VanishingPointStripTool {
}
/// A slot of the strip.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
pub(super) enum Pick {
EditPlane,
CreatePlane,
+13 -7
View File
@@ -52,7 +52,7 @@ use craft_behavior::edit_history::Step;
use craft_behavior::{CancelReason, EditEvent, EditHistory, Mixed};
use craft_ui::bars::StatusMessage;
use craft_ui::canvas::{HandTool, NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick};
use craft_ui::contract::{Bind, Job, Pending, Remember as _, Show as _, ShowContainer as _};
use craft_ui::contract::{Bind, Job, Tracked, Pending, Remember as _, Show as _, ShowContainer as _};
use craft_ui::dialog::{
FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowWorkspace,
RasterOverlay, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field,
@@ -187,14 +187,21 @@ pub enum VanishingPointEvent {
}
/// What the dialog's body keeps between passes: the view, the strip's memory and the canvas the tools run under.
#[derive(Clone, Default)]
#[derive(Clone)]
struct VanishingView {
view: FullWindowView,
last_used: LastUsed<Pick>,
last_used: Tracked<LastUsed<Pick>>,
slots: Tracked<Vec<ToolSlot<Pick>>>,
/// The canvas the tools run under, to cancel their gestures outside a pass.
canvas: Option<Id>,
}
impl Default for VanishingView {
fn default() -> Self {
VanishingView { view: FullWindowView::default(), last_used: Tracked::default(), slots: Tracked::new(slots()), canvas: None }
}
}
/// The New Plane form's state.
#[derive(Clone, Default)]
struct NewPlaneState {
@@ -368,7 +375,6 @@ impl FullWindowWorkspace for VanishingPointWorkspace {
let words = env.words::<VanishingPointWords>();
let common = env.words::<CommonWords>();
let title = FullWindowTitle::new(words.name.clone()).subject(self.subject.clone()).zoom(self.zoom_percent).label(&env);
let slots = slots();
let status: RefCell<Option<Pending<PreviewDone, String>>> = RefCell::new(None);
let events = RefCell::new(Vec::<VanishingPointEvent>::new());
let shown_canvas = std::cell::Cell::new(None);
@@ -416,7 +422,7 @@ impl FullWindowWorkspace for VanishingPointWorkspace {
}
// A tool key's release picks nothing.
let Some(pick) = command.pick().filter(|_| fired.phase != FirePhase::Release) else { continue };
let slot = slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == pick));
let slot = state.slots.iter().find(|slot| slot.tools.iter().any(|entry| entry.id == pick));
let tools: Vec<_> = slot.into_iter().flat_map(|slot| slot.tools.iter()).collect();
let current = Pick::of(work.strip, work.editor.tool());
let picked = slot.and_then(|slot| {
@@ -464,9 +470,9 @@ impl FullWindowWorkspace for VanishingPointWorkspace {
let shown = Row::new()
.fill()
.show(ui, |ui, _| {
let rail = ToolRail::new(words.tools.clone(), &slots, &current, &state.last_used).show_column(ui, |_, _| {});
let rail = ToolRail::new(words.tools.clone(), &state.slots, &current, &state.last_used).show_column(ui, |_, _| {});
if let Some(next) = rail.last_used {
state.last_used = next;
*state.last_used = next;
}
chosen = rail.select.filter(|pick| *pick != current);
let mut canvas = FullWindowCanvas::new(Bind::bound(&mut state.view), image)
+28 -11
View File
@@ -37,7 +37,7 @@ use std::time::Duration;
use craft_behavior::edit_history::Step;
use craft_behavior::{CancelReason, EditEvent, EditHistory, Mixed};
use craft_ui::canvas::{CanvasTool, HandTool, NavigationOptions, PickStep, RasterSource, ToolHost, ViewCommands, ZoomTool, tool_pick};
use craft_ui::contract::{Bind, Pattern, Remember as _, Show as _, ShowContainer as _};
use craft_ui::contract::{Bind, Tracked, Pattern, Remember as _, Show as _, ShowContainer as _};
use craft_ui::dialog::{
FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowWorkspace,
WorkspaceCx, WorkspacePass, serde_fields, set_serde_field,
@@ -58,7 +58,7 @@ use serde_json::Value;
use crate::ui::live_preview::settings_hash;
/// The tools of the strip.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[non_exhaustive]
pub enum WideAngleTool {
/// A.
@@ -146,11 +146,12 @@ pub enum WideAngleEvent {
}
/// The state the dialog body keeps between passes: what the app does not read.
#[derive(Clone, Default)]
#[derive(Clone)]
struct Body {
view: Option<FullWindowView>,
tool: WideAngleTool,
last_used: LastUsed<WideAngleTool>,
last_used: Tracked<LastUsed<WideAngleTool>>,
slots: Tracked<Vec<ToolSlot<WideAngleTool>>>,
constraint: ConstraintTool,
hand: Option<HandTool>,
zoom: Option<ZoomTool>,
@@ -162,6 +163,24 @@ struct Body {
adding: bool,
}
impl Default for Body {
fn default() -> Self {
let slots = TOOL_SLOT.iter().zip(0..).map(|(&(tool, command), slot)| ToolSlot::new(slot, vec![RailTool::new(tool, command)])).collect();
Body {
view: None,
tool: WideAngleTool::default(),
last_used: Tracked::default(),
slots: Tracked::new(slots),
constraint: ConstraintTool::default(),
hand: None,
zoom: None,
canvas: None,
menu: None,
adding: false,
}
}
}
/// A change the passes ask of the session, applied after the dialog has been shown.
enum Action {
/// The panel's correction edit.
@@ -349,11 +368,9 @@ impl FullWindowWorkspace for WideAngleWorkspace {
end_gesture(&ctx, &mut body, CancelReason::UndoDuringGesture);
}
let slots: Vec<ToolSlot<WideAngleTool>> =
TOOL_SLOT.iter().zip(0..).map(|(&(tool, command), slot)| ToolSlot::new(slot, vec![RailTool::new(tool, command)])).collect();
let mut next = None;
while let Some((command, fired)) = cx.take_command::<WideAngleCommands>() {
next = pick(&slots, command, &fired, &body).or(next);
next = pick(command, &fired, &body).or(next);
}
let image = source.source();
@@ -369,10 +386,10 @@ impl FullWindowWorkspace for WideAngleWorkspace {
}
Row::new().fill().show(ui, |ui, _| {
let rail = ToolRail::new(words.tools.clone(), &slots, &body.tool, &body.last_used).show_column(ui, |_, _| {});
let rail = ToolRail::new(words.tools.clone(), &body.slots, &body.tool, &body.last_used).show_column(ui, |_, _| {});
next = rail.select.or(next);
if let Some(last_used) = rail.last_used {
body.last_used = last_used;
*body.last_used = last_used;
}
if let Some(tool) = next.take().filter(|tool| *tool != body.tool) {
end_gesture(&ctx, &mut body, CancelReason::Removed);
@@ -566,12 +583,12 @@ fn edit_name<'a>(words: &'a WideAngleWords, edit: &WideAngleConstraintEdit) -> &
}
/// The tool a fired tool command picks, through its slot's pick rule; a tool key's release picks nothing.
fn pick(slots: &[ToolSlot<WideAngleTool>], command: WideAngleCommands, fired: &Fired, body: &Body) -> Option<WideAngleTool> {
fn pick(command: WideAngleCommands, fired: &Fired, body: &Body) -> Option<WideAngleTool> {
if fired.phase == FirePhase::Release {
return None;
}
let tool = TOOL_SLOT.iter().find(|(_, c)| *c == command)?.0;
let slot = slots.iter().find(|slot| slot.tools.iter().any(|t| t.id == tool))?;
let slot = body.slots.iter().find(|slot| slot.tools.iter().any(|t| t.id == tool))?;
let visible: Vec<&RailTool<WideAngleTool>> = slot.tools.iter().collect();
tool_pick(&visible, slot.id, &body.tool, &body.last_used, PickStep::of(fired), |_| true).map(|t| t.id)
}
+1 -1
View File
@@ -96,7 +96,7 @@ impl<'a> EditorMock<'a> {
fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, state: &mut MockState) {
let mut tools = cx.keep::<Tools>().clone();
let (events, picked) = {
let mut panels = Panels { document: &mut state.document, tool: state.tool, tools: &mut tools, last_used: &mut state.last_used, picked: None };
let mut panels = Panels { document: &mut state.document, tool: state.tool, tools: &mut tools, slots: &state.slots, last_used: &mut state.last_used, picked: None };
// The mock app is a preview inside the gallery's page: its floats stay in it.
let mut area =
DockArea::new("Dock", Bind::bound(&mut state.workspace), &state.specs, &mut panels, DockConfig::default().native_windows(false))
+6 -3
View File
@@ -33,7 +33,7 @@ const TOOLS_DOCK_WIDTH: f32 = 120.0;
/// The tools of the rail. Each is a command of the `tools` group; a tool alone in its slot carries its letter, and the
/// letter of a slot with several is the pick command of [`ToolKey`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet, craft_ui::contract::MemoProps)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[command(prefix = "mockTool")]
#[non_exhaustive]
pub enum Tool {
@@ -414,7 +414,9 @@ pub struct MockState {
/// The current tool.
pub tool: Tool,
/// The tool each rail slot showed last.
pub last_used: LastUsed<Tool>,
pub last_used: Tracked<LastUsed<Tool>>,
/// The rail's slots.
pub slots: Tracked<Vec<ToolSlot<Tool>>>,
/// The status bar's item.
pub status_item: StatusItem,
/// The status bar's message: the newest thing the mock had to say.
@@ -442,7 +444,8 @@ impl Default for MockState {
specs: Tracked::new(MockSpecs),
document: Document::default(),
tool: Tool::Move,
last_used: LastUsed::default(),
last_used: Tracked::new(LastUsed::default()),
slots: Tracked::new(Tool::slots()),
status_item: StatusItem::DocumentDimensions,
status: None,
colors: ColorPair::default(),
+8 -7
View File
@@ -13,7 +13,7 @@ use craft_ui::canvas::{
tool_pass,
};
use craft_ui::canvas_controls::{Guides, Marquee};
use craft_ui::contract::SizeLimits;
use craft_ui::contract::{SizeLimits, Tracked};
use craft_ui::contract::{
Bind, BodyCx, CollectionEvent, ColumnKind, ColumnSpec, MemoProps, MemoView, Props as _, Remember as _, SelectMode, Show as _,
ShowCollection as _, ShowContainer as _, SweepApply, SweepStep, ToggleColumn, WordSetCx as _,
@@ -22,7 +22,7 @@ use craft_ui::docking::{DockGrid, DockPanels, GroupAt, PanelSpec, PanelSpecs};
use craft_ui::list::{ListRow, ToggleCell};
use craft_ui::patterns::canvas::NavigatorPanel;
use craft_ui::primitives::textures::Revision;
use craft_ui::rails::{LastUsed, ToolRail};
use craft_ui::rails::{LastUsed, ToolRail, ToolSlot};
use craft_ui::runtime::env::UnitKind;
use craft_ui::shell::CanvasPanel;
use craft_ui::table::Table;
@@ -45,7 +45,9 @@ pub(super) struct Panels<'a> {
pub(super) tool: Tool,
pub(super) tools: &'a mut Tools,
/// The tool each toolbar slot showed last; the toolbar writes it.
pub(super) last_used: &'a mut LastUsed<Tool>,
pub(super) last_used: &'a mut Tracked<LastUsed<Tool>>,
/// The toolbar's slots.
pub(super) slots: &'a Tracked<Vec<ToolSlot<Tool>>>,
/// The tool the toolbar picked in this pass.
pub(super) picked: Option<Tool>,
}
@@ -58,9 +60,8 @@ impl Panels<'_> {
/// The toolbar's rail in the rect the dock gives it, or its height at a width: as many tool columns as the width
/// holds. The rail's own padding surrounds the buttons, so no group padding applies.
fn toolbar(&mut self, ui: &mut Ui, at: GroupAt) -> f32 {
let slots = Tool::slots();
let (current, last_used) = (self.tool, self.last_used.clone());
let rail = ToolRail::new("Tools", &slots, &current, &last_used);
let current = self.tool;
let rail = ToolRail::new("Tools", self.slots, &current, self.last_used);
match at {
GroupAt::Measure(width) => rail.measure_rail(ui, width, |_, _| {}).y,
GroupAt::Show(rect) => {
@@ -69,7 +70,7 @@ impl Panels<'_> {
self.picked = output.select;
}
if let Some(next) = output.last_used {
*self.last_used = next;
**self.last_used = next;
}
rect.height()
}
+3 -2
View File
@@ -1,6 +1,7 @@
//! Stories of `ToolbarDrawer`.
use super::{DrawerGroup, ToolbarDrawer};
use crate::contract::Tracked;
use crate::rails::tool::stories::{BRUSH, tools};
use crate::rails::tool::{LastUsed, ToolRail, ToolSlot};
use crate::testing::{Drive, StoryData, StoryOutput, story};
@@ -11,8 +12,8 @@ use egui::Ui;
#[story(ToolbarDrawer<'static, u8>, covers = [], drive = Drive::Never)]
fn toolbar_drawer(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let groups = [DrawerGroup::new("Drawing", tools(&[0, 1, 2])), DrawerGroup::new("Retouching", tools(&[3, 4]))];
let slots = [ToolSlot::new(0, tools(&[0])), ToolSlot::new(1, tools(&[BRUSH, BRUSH + 1]))];
let last = LastUsed::default();
let slots = Tracked::new(vec![ToolSlot::new(0, tools(&[0])), ToolSlot::new(1, tools(&[BRUSH, BRUSH + 1]))]);
let last = Tracked::new(LastUsed::default());
let rail = ToolRail::new("Tools", &slots, &BRUSH, &last).edit_toolbar("Edit Toolbar").show_rail(ui, |_, _| {});
let open = data.value("open", false);
let Some(opener) = rail.edit_toolbar.as_ref() else { return rail.into() };
+38 -24
View File
@@ -8,7 +8,7 @@ use crate::contract::{
Access, Common, Component, Container, ContainerProps, Cx, FooterRegion, Gap, NoValue, Outcome, Pad, Props as _, Role, Scroll, Show as _,
ShowContainer as _, Sizing, WordSetCx as _,
};
use crate::contract::{BodyCx, BodyLayout, MemoProps, MemoView, Outbox};
use crate::contract::{BodyCx, BodyLayout, MemoProps, MemoView, Outbox, PlainData, Tracked};
use crate::docking::{DockGrid, DockSizes};
use crate::layout::RowAlign;
use crate::layout_components::{Row, Stack};
@@ -102,14 +102,14 @@ type FooterFn<'a> = Box<dyn FnMut(&mut Ui, RailFooter) + 'a>;
/// grid. While the toolbar is edited the buttons are dragged and take drops, and report the drop in the output.
#[derive(crate::contract::Component, crate::contract::Props)]
#[component(container, probe(ToolRail<'static, u8>))]
pub struct ToolRail<'a, T: Value + MemoProps + 'static> {
pub struct ToolRail<'a, T: Value + MemoProps + PlainData + 'static> {
#[common]
common: Common,
#[container]
props: ContainerProps,
slots: &'a [ToolSlot<T>],
slots: &'a Tracked<Vec<ToolSlot<T>>>,
current: &'a T,
last_used: &'a LastUsed<T>,
last_used: &'a Tracked<LastUsed<T>>,
/// The side of the rail its flyouts and drawer open on: the side of the canvas.
#[prop]
opens: Side,
@@ -120,17 +120,16 @@ pub struct ToolRail<'a, T: Value + MemoProps + 'static> {
#[prop(flag)]
editing: bool,
/// The tools the user's toolbar settings hide.
#[prop]
hidden: &'a [T],
hidden: Option<&'a Tracked<Vec<T>>>,
footer: Option<FooterFn<'a>>,
/// The columns the rail lays out in this pass.
columns: usize,
}
impl<'a, T: Value + MemoProps + 'static> ToolRail<'a, T> {
impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> {
/// A one-column rail named `label` over `slots`, with `current` the host's tool and `last_used` what the slots
/// showed last.
pub fn new(label: impl Into<Label>, slots: &'a [ToolSlot<T>], current: &'a T, last_used: &'a LastUsed<T>) -> Self {
pub fn new(label: impl Into<Label>, slots: &'a Tracked<Vec<ToolSlot<T>>>, current: &'a T, last_used: &'a Tracked<LastUsed<T>>) -> Self {
let props = ContainerProps::new()
.surface(SurfaceKind::Chrome)
.pad(Pad::Control)
@@ -149,16 +148,23 @@ impl<'a, T: Value + MemoProps + 'static> ToolRail<'a, T> {
opens: Side::End,
edit_toolbar: None,
editing: false,
hidden: &[],
hidden: None,
footer: None,
columns: 1,
}
.label(label)
}
/// The tools the user's toolbar settings hide.
#[must_use]
pub fn hidden(mut self, hidden: &'a Tracked<Vec<T>>) -> Self {
self.hidden = Some(hidden);
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())
visible_slots(self.slots, hidden_in(self.hidden)).len() + usize::from(self.edit_toolbar.is_some())
}
/// Sets up the pass for a rail `width` wide: its columns, its roving grid and its footer. Returns what the body
@@ -182,14 +188,22 @@ impl<'a, T: Value + MemoProps + 'static> ToolRail<'a, T> {
}
}
/// The tools a rail hides: the host's, or none.
fn hidden_in<'a, T>(hidden: Option<&'a Tracked<Vec<T>>>) -> &'a [T]
where
T: PlainData,
{
hidden.map_or(&[], |hidden| hidden.as_slice())
}
/// What the grid's memoized view reads: the slots and the tool state they show, and an outbox for what the buttons
/// report. The host's footer is not in it: it runs every pass, outside the view.
#[derive(MemoProps)]
struct GridProps<'a, T> {
slots: &'a [ToolSlot<T>],
struct GridProps<'a, T: PlainData> {
slots: &'a Tracked<Vec<ToolSlot<T>>>,
current: &'a T,
last_used: &'a LastUsed<T>,
hidden: &'a [T],
last_used: &'a Tracked<LastUsed<T>>,
hidden: Option<&'a Tracked<Vec<T>>>,
editing: bool,
edit_label: Option<Label>,
opens: Side,
@@ -198,18 +212,18 @@ struct GridProps<'a, T> {
}
/// What the body of one pass draws from.
struct Draw<'a, T> {
slots: &'a [ToolSlot<T>],
struct Draw<'a, T: PlainData> {
slots: &'a Tracked<Vec<ToolSlot<T>>>,
current: &'a T,
last_used: &'a LastUsed<T>,
hidden: &'a [T],
last_used: &'a Tracked<LastUsed<T>>,
hidden: Option<&'a Tracked<Vec<T>>>,
editing: bool,
edit_label: Option<Label>,
opens: Side,
columns: usize,
}
impl<T: Value + MemoProps> Draw<'_, T> {
impl<T: Value + MemoProps + PlainData> Draw<'_, T> {
/// Shows the grid as a memoized view; what the buttons report goes into `events` (nothing on a replay). Returns the
/// Edit Toolbar button's id while the rail shows it.
fn run(&self, ui: &mut Ui, events: &mut Vec<RailEvent<T>>) -> Option<Id> {
@@ -230,9 +244,9 @@ impl<T: Value + MemoProps> Draw<'_, T> {
/// The grid of buttons in rows of `columns`. The result is the Edit Toolbar button's id, which the rail's output
/// turns into its response.
fn grid<T: Value + MemoProps>(props: &mut GridProps<'_, T>, ui: &mut Ui) -> Option<Id> {
fn grid<T: Value + MemoProps + PlainData>(props: &mut GridProps<'_, T>, ui: &mut Ui) -> Option<Id> {
let GridProps { slots, current, last_used, hidden, editing, columns, opens, .. } = *props;
let visible = visible_slots(slots, hidden);
let visible = visible_slots(slots, hidden_in(hidden));
let cells = visible.len() + usize::from(props.edit_label.is_some());
let resolve = resolver_in(ui);
let enabled = |tool: &RailTool<T>| resolve(tool.command.clone()).is_some_and(|resolved| resolved.enabled);
@@ -291,7 +305,7 @@ fn grid<T: Value + MemoProps>(props: &mut GridProps<'_, T>, ui: &mut Ui) -> Opti
edit_toolbar
}
impl<'a, T: Value + MemoProps + 'static> ToolRail<'a, T> {
impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> {
/// Shows the rail in the width `ui` has left. `footer` draws under the last slot (colour chips, Quick Mask,
/// Screen Mode); it stays in view when the room is short.
pub fn show_rail(self, ui: &mut Ui, footer: impl FnMut(&mut Ui, RailFooter) + 'a) -> ToolRailOutput<T> {
@@ -342,7 +356,7 @@ impl<'a, T: Value + MemoProps + 'static> ToolRail<'a, T> {
}
}
impl<T: Value + MemoProps + 'static> Component for ToolRail<'_, T> {
impl<T: Value + MemoProps + PlainData + 'static> Component for ToolRail<'_, T> {
const ROLE: Role = Role::TOOLBAR;
const PARTS: bool = false;
const STOPS: bool = false;
@@ -378,7 +392,7 @@ impl<T: Value + MemoProps + 'static> Component for ToolRail<'_, T> {
}
}
impl<T: Value + MemoProps + 'static> Container for ToolRail<'_, T> {
impl<T: Value + MemoProps + PlainData + 'static> Container for ToolRail<'_, T> {
/// The host's footer.
fn footer(&mut self, ui: &mut Ui, _: &mut BodyCx<'_>) {
let columns = self.columns;
+3 -3
View File
@@ -7,7 +7,7 @@ pub type SlotId = u32;
/// One tool of a slot. A tool is a command: the command gives the label, the icon, the chord and the enabled state,
/// and picking the tool runs it.
#[derive(Clone, Debug, crate::contract::MemoProps)]
#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps, crate::contract::PlainData)]
#[non_exhaustive]
pub struct RailTool<T> {
/// The host's identifier for the tool, reported when the tool is selected.
@@ -24,7 +24,7 @@ impl<T> RailTool<T> {
}
/// A group of tools that share one button; its flyout lists them.
#[derive(Clone, Debug, crate::contract::MemoProps)]
#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps, crate::contract::PlainData)]
#[non_exhaustive]
pub struct ToolSlot<T> {
/// The slot's name, chosen by the host; keys the remembered last-used tool.
@@ -49,7 +49,7 @@ impl<T> ToolSlot<T> {
}
/// The tool each slot showed last. Plain data the host keeps with its workspace.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, crate::contract::MemoProps)]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, crate::contract::MemoProps, crate::contract::PlainData)]
pub struct LastUsed<T> {
tools: Vec<(SlotId, T)>,
}
+4 -2
View File
@@ -1,5 +1,6 @@
//! Stories of `ToolRail`, and the commands its stories and the flyout's use as tools.
use crate::contract::Tracked;
use super::{LastUsed, RailTool, ToolRail, ToolSlot};
use crate::docking::{DockGrid, DockSizes};
use crate::testing::{Drive, StoryData, StoryOutput, story};
@@ -51,8 +52,9 @@ fn tool_rail(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let short = *data.choice("room", false, &[("Tall", false), ("Short", true)]);
let hidden =
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 hidden = Tracked::new(hidden);
let slots = Tracked::new(slots());
let last = Tracked::new(LastUsed::default());
let width = DockGrid::rail(slots.len() + 1).resolved(&DockSizes::of_scope(ui)).width(u16::from(columns));
// design: allow[contract/memory](the story gives the rail the width of its chosen columns, as a dock column does)
let out = ui
+9 -10
View File
@@ -6,6 +6,7 @@ use super::stories::tools;
use super::{LastUsed, ToolRail, ToolSlot};
use crate::buttons::Button;
use crate::contract::Props as _;
use crate::contract::Tracked;
use crate::contract::Show as _;
use crate::contract::ShowContainer as _;
use crate::docking::{DockGrid, DockSizes};
@@ -48,9 +49,8 @@ fn columns_of(fixture: &Fixture) -> usize {
fn rail_in(width: f32, height: f32) -> (Fixture, Rc<Cell<Vec2>>) {
let measured = Rc::new(Cell::new(Vec2::ZERO));
let report = Rc::clone(&measured);
let (slots, last) = (Tracked::new(slots()), Tracked::new(LastUsed::default()));
let mut fixture = Fixture::new(move |ui| {
let slots = slots();
let last = LastUsed::default();
let size = ToolRail::new("Tools", &slots, &0, &last).measure_rail(ui, width, |ui, _| {
Button::new("Foot").show(ui);
});
@@ -137,10 +137,10 @@ fn the_tool_rail_shows_its_buttons_icons_in_its_glyph_role() {
use crate::buttons::IconButton;
use craft_behavior::IconId;
let glyphs = |rail: bool| {
let (slots, last) = (Tracked::new(vec![ToolSlot::new(0, tools(&[0, 1]))]), Tracked::new(LastUsed::default()));
let mut fixture = Fixture::new(move |ui| {
if rail {
let slots = vec![ToolSlot::new(0, tools(&[0, 1]))];
ToolRail::new("Tools", &slots, &0, &LastUsed::default()).show_rail(ui, |_, _| {});
ToolRail::new("Tools", &slots, &0, &last).show_rail(ui, |_, _| {});
} else {
IconButton::new(IconId::new("move")).label("Alone").show(ui);
}
@@ -168,9 +168,8 @@ struct Seen {
fn memo_rail() -> (Fixture, Rc<RefCell<Seen>>) {
let seen = Rc::new(RefCell::new(Seen::default()));
let shared = Rc::clone(&seen);
let (slots, last) = (Tracked::new(slots()), Tracked::new(LastUsed::default()));
let mut fixture = Fixture::new(move |ui| {
let slots = slots();
let last = LastUsed::default();
let current = shared.borrow().current;
let footer = &shared;
let out = ToolRail::new("Tools", &slots, &current, &last).edit_toolbar("Edit Toolbar").show_rail(ui, |ui, _| {
@@ -253,10 +252,9 @@ fn a_rail_in_another_density_counts_its_columns_in_that_density() {
let width = grid.width(2);
assert_eq!(root.steps_within(width), 1, "the root's rail fits one column in two compact steps: {grid:?}, root {root:?}");
let (slots, last) = (Tracked::new(slots()), Tracked::new(LastUsed::default()));
let mut fixture = Fixture::new(move |ui| {
Stack::new().theme(compact()).show(ui, |ui, _| {
let slots = slots();
let last = LastUsed::default();
ToolRail::new("Tools", &slots, &0, &last).show_rail(ui, |ui, _| {
Button::new("Foot").show(ui);
});
@@ -288,12 +286,13 @@ fn an_open_flyout_builds_no_derived_values() {
/// The key bytes of an idle pass of a rail of `count` slots, a quarter of whose tools are hidden and half remembered.
fn idle_key_bytes(count: u8) -> usize {
let slots: Vec<ToolSlot<u8>> = (0..count).map(|id| ToolSlot::new(u32::from(id), tools(&[id]))).collect();
let hidden: Vec<u8> = (0..count / 4).collect();
let slots = Tracked::new((0..count).map(|id| ToolSlot::new(u32::from(id), tools(&[id]))).collect::<Vec<_>>());
let hidden = Tracked::new((0..count / 4).collect::<Vec<u8>>());
let mut last = LastUsed::default();
for id in 0..count / 2 {
last.set(u32::from(id), id);
}
let last = Tracked::new(last);
let mut fixture = Fixture::new(move |ui| {
ToolRail::new("Tools", &slots, &0, &last).hidden(&hidden).show_rail(ui, |_, _| {});
});
+6 -5
View File
@@ -2,6 +2,7 @@
//! drag, where the rail leaves group gaps and which side the drawer opens on.
use craft_ui::rails::{DropAt, RailTool, ToolSlot, ToolbarEdit, apply_toolbar_edit};
use craft_ui::contract::Tracked;
use craft_ui::runtime::commands::EditCommands;
use craft_ui::runtime::drag;
use craft_ui::testing::{Fixture, stories, trial};
@@ -48,10 +49,10 @@ fn closing_the_drawer_returns_the_focus_to_the_rails_edit_toolbar_button() {
let open = Rc::new(Cell::new(false));
let shown = open.clone();
let slots = Tracked::new(vec![slot(0, &[UNDO]), slot(1, &[REDO])]);
let last = Tracked::new(LastUsed::default());
let mut fixture = Fixture::new(move |ui| {
let slots = [slot(0, &[UNDO]), slot(1, &[REDO])];
let groups = [DrawerGroup::new("Edit", vec![tool(UNDO), tool(REDO), tool(CUT)])];
let last = LastUsed::default();
let rail = ToolRail::new("Tools", &slots, &UNDO, &last).edit_toolbar("Customize").show_rail(ui, |_, _| {});
let opener = rail.edit_toolbar.expect("the rail shows its Edit Toolbar button");
if craft_ui::contract::clicked(&opener) {
@@ -121,9 +122,9 @@ fn a_click_on_a_tool_selects_it_and_no_row_stays_selected() {
#[trial]
fn a_slot_that_ends_a_group_leaves_a_wider_gap_than_slots_within_a_group() {
use craft_ui::rails::{LastUsed, ToolRail};
let mut fixture = Fixture::new(|ui| {
let slots = [slot(0, &[UNDO]), ToolSlot::ending_group(1, vec![tool(REDO)]), slot(2, &[CUT])];
let last = LastUsed::default();
let slots = Tracked::new(vec![slot(0, &[UNDO]), ToolSlot::ending_group(1, vec![tool(REDO)]), slot(2, &[CUT])]);
let last = Tracked::new(LastUsed::default());
let mut fixture = Fixture::new(move |ui| {
ToolRail::new("Tools", &slots, &UNDO, &last).show_rail(ui, |_, _| {});
});
fixture.room(Vec2::new(60.0, 300.0)).settle();