From b0fc3a65219c249a5d821bd383acd17131feab22 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 15 Nov 2026 04:46:07 +0000 Subject: [PATCH] dialogs-w10: net change of 5 commits - dialogs-w10: written by an agent - dialogs-w10: fill issues resolve their label through the env's view (combine) - dialogs-w10: review fixes (review-1) - dialogs-w10: review fixes (review-1): Props import - dialogs-w10: liquify's command loop borrows the view per call, so the Preview command can toggle through set_preview (combine) --- crates/imaging/src/ui/fill/mod.rs | 512 +++++++++++------- crates/imaging/src/ui/fill/stories.rs | 31 +- crates/imaging/src/ui/liquify/commands.rs | 3 + crates/imaging/src/ui/liquify/mod.rs | 288 ++++++---- crates/imaging/src/ui/liquify/panel.rs | 2 +- crates/imaging/src/ui/liquify/stories.rs | 31 +- crates/imaging/src/ui/liquify/words.rs | 2 + crates/imaging/src/ui/select_mask/mod.rs | 465 +++++++++++----- crates/imaging/src/ui/select_mask/stories.rs | 30 +- crates/imaging/tests/it/fill.rs | 86 ++- crates/imaging/tests/it/liquify.rs | 52 +- crates/imaging/tests/it/select_mask.rs | 73 ++- migration/api-map/imaging-filter-gallery.toml | 6 +- migration/api-map/imaging-liquify.toml | 6 +- migration/api-map/imaging-wide-angle.toml | 6 +- migration/api-map/imaging-workspaces.toml | 23 +- 16 files changed, 1076 insertions(+), 540 deletions(-) diff --git a/crates/imaging/src/ui/fill/mod.rs b/crates/imaging/src/ui/fill/mod.rs index 9031ee810..49699b8d7 100644 --- a/crates/imaging/src/ui/fill/mod.rs +++ b/crates/imaging/src/ui/fill/mod.rs @@ -10,8 +10,11 @@ //! is plain data ([`FillSession`]: the sampling option, the brush strokes, the lasso edits) with //! [`EditHistory`] undo; the app's engine plans the fill (`content_aware_plan`), gives the //! sampling and fill-area planes and the preview through [`FillSource`], and fills on Apply and -//! OK with [`FillCommand`]. Apply keeps the workspace open: the app fills, then calls -//! [`ContentAwareFillWorkspace::rebase`]. Cancel closes, keeping what Apply did. +//! OK with [`FillCommand`]. The workspace is a [`FullWindowWorkspace`] on the app's dialog host. +//! Apply keeps the workspace open: the app fills with the [`FillEvent::Apply`] command, then +//! calls [`ContentAwareFillWorkspace::answer_apply`]. OK is the host's held OK: the app takes the +//! command with `take_ok`, fills and answers with `answer_ok`, and a failed fill keeps the workspace +//! open. Cancel closes, keeping what Apply did. //! //! Files: `session`, `lasso` and `tool`; `overlay`, `panel`, `preview_pane`, `bar`, `commands`, //! `words` and this file's bodies. @@ -47,7 +50,8 @@ pub use words::FillWords; use std::cell::RefCell; use std::sync::Arc; -use egui::{Color32, Context, Id, Response, Ui}; +use egui::{Color32, Context, Id, Ui}; +use serde::Deserialize; use craft_behavior::edit_history::Step; use craft_behavior::geometry::selection_op::SelectionOperation; @@ -58,8 +62,11 @@ 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, NoValue, Outcome, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked}; -use craft_ui::dialog::{DialogWords, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowTitle, FullWindowView, RasterOverlay, SideFooter}; +use craft_ui::contract::{Bind, 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, +}; use craft_ui::layout_components::Row; use craft_ui::patterns::form_dialogs::{FormDialogWords, ParamDialogWords}; use craft_ui::primitives::{Checker, IconSpec}; @@ -73,17 +80,17 @@ use craft_ui::sections::{DialogRole, FooterButton}; use crate::ui::wide_angle::PreviewDone; -/// The key of the colour request for the sampling tint (`FillOutput::pick_color`, +/// The key of the colour request for the sampling tint ([`FillEvent::PickColor`], /// [`ContentAwareFillWorkspace::set_color`]). pub const OVERLAY_COLOR_KEY: &str = "fill.overlayColor"; /// The name the history gives its steps. const HISTORY_NAME: &str = "Content-Aware Fill"; -/// The footer's buttons in the order the workspace gives them, by the index the dialog reports a pick with. +/// The footer's OK and Apply buttons, by the index the dialog reports a pick with (Cancel is the third, and closes the +/// dialog by itself). const PICK_OK: usize = 0; const PICK_APPLY: usize = 1; -const PICK_CANCEL: usize = 2; /// What the app gives the workspace to show each pass. pub trait FillSource: Send + Sync { @@ -174,61 +181,36 @@ pub enum FillEvent { SettingsChanged(FillSettings), } -/// An edit the control requests make of the workspace through [`ContentAwareFillWorkspace::perform`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// An edit the control requests make of the workspace through [`ContentAwareFillWorkspace::perform`]. Each carries what +/// the user would have drawn or chosen. +// PLAN: the stub's `FillOp` was a unit enum, which cannot say which stroke or polygon to record; the variants carry +// their value. dialogs-w20's `control/dialogs.rs` and dialogs-w9's re-export read the new shape. +#[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub enum FillOp { /// A Sampling Brush stroke. - Stroke, + Stroke(SamplingStroke), /// A lasso edit of the fill area. - FillArea, + FillArea(FillAreaEdit), /// A Reset. - Reset, - /// A change of the sampling options. - Sampling, -} - -/// What [`ContentAwareFillWorkspace::show`] reports. -#[derive(Clone, Debug)] -#[non_exhaustive] -pub struct FillOutput { - /// What happened this pass, in order. - pub events: Vec, - /// OK (`Accept`) or Cancel this pass. - pub closed: Option, - /// Apply was pressed (the workspace stays open): the app fills with [`ContentAwareFillWorkspace::command`], - /// then calls [`rebase`](ContentAwareFillWorkspace::rebase). - pub apply: bool, - /// The dialog's response: its rect is the workspace's. - pub response: Response, - /// A fill setting changed this pass. - pub settings_changed: bool, - /// The Color swatch was pressed: the app opens its colour picker and answers with - /// [`ContentAwareFillWorkspace::set_color`]. - pub pick_color: Option, -} - -impl Outcome for FillOutput { - type Value = NoValue; - - fn response(&self) -> &Response { - &self.response - } + Reset(FillReset), + /// A change of the sampling option. + Sampling(SamplingMode), } /// What shows under the panel: the limit a stroke or edit ran into, or the app's message (a failed -/// Apply, an edit that emptied the fill area). +/// Apply or OK, an edit that emptied the fill area). #[derive(Clone, Debug, PartialEq)] enum FillIssue { Limit(FillLimit), - Message(String), + Message(Label), } impl FillIssue { fn text(&self, env: &Env) -> String { match self { FillIssue::Limit(limit) => limit.message(env), - FillIssue::Message(message) => message.clone(), + FillIssue::Message(message) => env.view().resolve(message).as_str().to_owned(), } } } @@ -250,7 +232,6 @@ pub struct ContentAwareFillWorkspace { limits: FillLimits, subject: String, size: PixelSize, - open: bool, // View state outside the history. view: FullWindowView, preview_view: FullWindowView, @@ -275,14 +256,13 @@ pub struct ContentAwareFillWorkspace { error: Option, /// A setting is being dragged (the Opacity slider): the preview waits for its end. settings_gesture: bool, - /// [`set_color`](Self::set_color) changed the color since the last pass: the next - /// [`FillOutput::settings_changed`] says so. - color_owed: bool, + /// The settings as the app last heard them, so a change made between passes (a control request, a colour answer) + /// is reported once by the next pass. + reported: FillSettings, /// The outline of the fill area's covered cells, kept for as long as the plane is the same. ants: Option, - /// This pass's events and colour request. + /// The events the next pass reports first: what the methods between passes queued, then the pass's own. events: Vec, - pick_color: Option, } impl ContentAwareFillWorkspace { @@ -300,11 +280,11 @@ impl ContentAwareFillWorkspace { grow_by: FillToolOptions::GROW_BY, }, session, + reported: open.settings.clone(), settings: open.settings, limits: open.limits, subject: open.subject, size: PixelSize::new(width, height), - open: true, view: FullWindowView::new(), preview_view: FullWindowView::new(), framing: PreviewFraming::default(), @@ -323,10 +303,8 @@ impl ContentAwareFillWorkspace { preview: Pending::default(), error: None, settings_gesture: false, - color_owed: false, ants: None, events: Vec::new(), - pick_color: None, } } @@ -360,28 +338,27 @@ impl ContentAwareFillWorkspace { /// sampling option or Reset from the panel goes through [`FillSession::set_sampling`] and /// [`FillSession::reset`] (Custom makes the brush add, the others subtract). Then a change of the /// fill, once no stroke, lasso or slider drag is under way, starts a preview job through - /// [`FillSource::preview_job`]. An Apply or OK the app reports failing ([`Self::apply_failed`]) - /// keeps the workspace open. - pub fn show(&mut self, ui: &mut Ui, source: &dyn FillSource) -> FillOutput { + /// [`FillSource::preview_job`]. OK is the host's held OK when the app asks for one (`hold_ok`): the pass reports the + /// command as `held`, and the app answers it. A second pass of a frame reports only what its own input did: the + /// frame's steps and commands went to the first pass. + fn pass(&mut self, ui: &mut Ui, cx: WorkspaceCx<'_, dyn FillSource>) -> WorkspacePass { // pc: crates/ui-egui/src/dialogs/caf_ui/view.rs:265 `show`; caf_ui/controls.rs:151 `keys`. + let WorkspaceCx { source, open, hold_ok, ok_waits, .. } = cx; let env = Env::of(ui); let common = env.words::(); let dialog = env.words::(); let params = env.words::(); let title = FullWindowTitle::new(env.words::().name.clone()).subject(self.subject.clone()).zoom(self.view.zoom_percent()).label(&env); - let settings_before = self.settings.clone(); - self.pick_color = None; let slots = FillTool::slots(); - let mut open = self.open; let mut reset_all = false; let this = RefCell::new(&mut *self); let shown = FullWindowDialog::new(title) .command_scope(FillCommands::SCOPE) - .opened(Bind::bound(&mut open)) + .opened(open) .buttons([ - FooterButton::new(common.ok.clone(), DialogRole::Accept), + FooterButton::new(common.ok.clone(), DialogRole::Accept).stays_open(hold_ok).enabled(!ok_waits), FooterButton::new(dialog.apply.clone(), DialogRole::Other).stays_open(true), FooterButton::new(common.cancel.clone(), DialogRole::Cancel), ]) @@ -399,42 +376,33 @@ impl ContentAwareFillWorkspace { }); let work = this.into_inner(); - work.open = open; if reset_all { - // The footer's Reset sets the session and every setting back, whether or not the session was already - // at its defaults. - let before = work.session.clone(); - work.session.reset(FillReset::All, &mut work.settings); - work.synced(); - work.record_history(before); - work.events.push(FillEvent::Reset(FillReset::All)); + work.apply_reset(FillReset::All); } let picked = shown.output.picked; - let closed = match picked { - Some(PICK_OK) => Some(DialogRole::Accept), - Some(PICK_CANCEL) => Some(DialogRole::Cancel), - _ => shown.output.closed.map(|_| DialogRole::Cancel), - }; - let color_owed = std::mem::take(&mut work.color_owed); - FillOutput { - events: std::mem::take(&mut work.events), - closed, - apply: picked == Some(PICK_APPLY), - response: shown.output.response.clone(), - settings_changed: work.settings != settings_before || color_owed, - pick_color: work.pick_color.take(), + if picked == Some(PICK_APPLY) { + work.events.push(FillEvent::Apply(work.command())); } + if work.settings != work.reported { + work.reported = work.settings.clone(); + work.events.push(FillEvent::SettingsChanged(work.reported.clone())); + } + // A held OK files the command and keeps the dialog open; Esc and Cancel close it either way. + let (result, held) = if hold_ok { + (shown.output.closed.map(|_| DialogResult::Cancel), (picked == Some(PICK_OK)).then(|| work.command())) + } else { + (shown.output.result(|| work.command()), None) + }; + let events = std::mem::take(&mut work.events); + WorkspacePass::new(shown.output.response, events).held(held).result(result) } - /// The app's colour picker answered a [`FillOutput::pick_color`] request. A key this workspace - /// did not ask for is ignored. + /// The app's colour picker answered a [`FillEvent::PickColor`] request. A key this workspace + /// did not ask for is ignored. The next pass reports the new colour as [`FillEvent::SettingsChanged`]. pub fn set_color(&mut self, key: &str, color: Srgba) { if key == OVERLAY_COLOR_KEY { let [r, g, b, _] = Color32::from(color).to_array(); - if self.settings.color != [r, g, b] { - self.settings.color = [r, g, b]; - self.color_owed = true; - } + self.settings.color = [r, g, b]; } } @@ -448,43 +416,68 @@ impl ContentAwareFillWorkspace { &self.settings } - /// Answers the Apply: `Ok` clears the history, `Err` shows the message. + /// Answers the [`FillEvent::Apply`]: `Ok` means the app filled, so the session's history clears (Apply is one + /// document step), the strokes and edits stay, and a preview is asked for over the new document. `Err` shows the + /// message under the panel; OK stays enabled either way. pub fn answer_apply(&mut self, answer: Result<(), String>) { - let _ = answer; - todo!("dl.K64") + // pc: crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs:80 `apply` (refresh), caf_ui/preview.rs:135 `rebase`. + match answer { + Ok(()) => { + self.history = EditHistory::new(&self.session); + self.error = None; + self.job = None; + } + Err(message) => self.error = Some(FillIssue::Message(message.into())), + } } - /// The fill settings, for the control requests that change them. + /// The fill settings, for the control requests that change them. The next pass reports a change as + /// [`FillEvent::SettingsChanged`]. pub fn settings_mut(&mut self) -> &mut FillSettings { - todo!("dl.K64") + &mut self.settings } - /// Runs `op` as the user would; its events come out of the next pass. `Err` when a limit refuses it. + /// Runs `op` as the user would; its events come out of the next pass. `Err` when a limit refuses it: nothing is + /// recorded, the panel shows the limit and the next pass reports [`FillEvent::Refused`]. The caller asks for the + /// repaint that runs the next pass (this method has no context). pub fn perform(&mut self, op: FillOp) -> Result<(), FillLimit> { - let _ = op; - todo!("dl.K64") + match op { + FillOp::Stroke(stroke) => self.record_stroke(stroke), + FillOp::FillArea(edit) => self.add_edit(edit), + FillOp::Reset(what) => { + self.apply_reset(what); + Ok(()) + } + FillOp::Sampling(mode) => { + self.apply_sampling(mode); + Ok(()) + } + } } - /// Undoes the last edit; its events come out of the next pass. + /// Undoes the last edit, abandoning a stroke still open first. The session changes at once; the app reads it + /// after its next pass. pub fn undo(&mut self) { - todo!("dl.K64") + self.cancel_gesture(None, CancelReason::UndoDuringGesture); + self.step_now(Step::Undo); } - /// Redoes the last undone edit; its events come out of the next pass. + /// Redoes the last undone edit, abandoning a stroke still open first. pub fn redo(&mut self) { - todo!("dl.K64") + self.cancel_gesture(None, CancelReason::UndoDuringGesture); + self.step_now(Step::Redo); } /// Picks the canvas tool. pub fn set_tool(&mut self, tool: FillTool) { - let _ = tool; - todo!("dl.K64") + self.pick(None, tool); } - /// Sets the Sampling Brush size. + /// Sets the Sampling Brush size, in 1..=[`FillToolOptions::SIZE_MAX`] pixels; a non-finite size changes nothing. pub fn set_brush(&mut self, size: f64) { - let _ = size; - todo!("dl.K64") + if size.is_finite() { + self.options.brush_size = size.round().clamp(1.0, FillToolOptions::SIZE_MAX); + } } /// Apply's and OK's parameters. @@ -492,23 +485,6 @@ impl ContentAwareFillWorkspace { FillCommand::new(&self.session, &self.settings) } - /// The app applied the fill: the session's history clears (Apply is one document step), the - /// strokes and edits stay, and a preview is asked for over the new document. - pub fn rebase(&mut self) { - // pc: crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs:80 `apply` (refresh), caf_ui/preview.rs:135 - // `rebase`. - self.history = EditHistory::new(&self.session); - self.error = None; - self.job = None; - } - - /// The app's Apply or OK failed: the message shows under the panel and the workspace stays (it opens again if - /// OK had closed it). - pub fn apply_failed(&mut self, message: String) { - self.error = Some(FillIssue::Message(message)); - self.open = true; - } - /// The app found that the last fill-area edit empties the fill area: the edit is taken back /// and `message` shows under the panel. The history takes the step back without a redo entry. pub fn refuse_fill_edit(&mut self, message: String) { @@ -520,7 +496,7 @@ impl ContentAwareFillWorkspace { } } self.synced(); - self.error = Some(FillIssue::Message(message)); + self.error = Some(FillIssue::Message(message.into())); } } @@ -555,23 +531,37 @@ impl ContentAwareFillWorkspace { None => {} } if let Some(mode) = panel.sampling { - let before = self.session.clone(); - if self.session.set_sampling(mode) { - self.synced(); - self.record_history(before); - self.events.push(FillEvent::Reset(FillReset::Sampling)); - } + self.apply_sampling(mode); } if let Some(what) = panel.reset { - let before = self.session.clone(); - if self.session.reset(what, &mut self.settings) || what == FillReset::Fill { - self.synced(); - self.record_history(before); - self.events.push(FillEvent::Reset(what)); - } + self.apply_reset(what); } - if panel.pick_color.is_some() { - self.pick_color = panel.pick_color; + if let Some(request) = panel.pick_color { + self.events.push(FillEvent::PickColor(request)); + } + } + + /// A Reset: the session and the settings it covers go back, the step is recorded and the app hears of it. A Reset of + /// the fill settings or of everything is reported whether or not the session was already at its defaults. + fn apply_reset(&mut self, what: FillReset) { + let before = self.session.clone(); + let changed = self.session.reset(what, &mut self.settings); + if changed || matches!(what, FillReset::Fill | FillReset::All) { + self.synced(); + self.record_history(before); + self.error = None; + self.events.push(FillEvent::Reset(what)); + } + } + + /// A new sampling option: the strokes start over, the step is recorded and the app hears of it. The same option + /// with no strokes changes nothing. + fn apply_sampling(&mut self, mode: SamplingMode) { + let before = self.session.clone(); + if self.session.set_sampling(mode) { + self.synced(); + self.record_history(before); + self.events.push(FillEvent::Reset(FillReset::Sampling)); } } @@ -585,7 +575,7 @@ impl ContentAwareFillWorkspace { // An open stroke is cancelled first; the step follows. while let Some(step) = cx.take_step(self.history.can_undo(), self.history.can_redo()) { // pc: crates/ui-egui/src/dialogs/caf_ui/controls.rs:151-159 (⌘Z, ⇧⌘Z). - self.cancel_gesture(&ctx, CancelReason::UndoDuringGesture); + self.cancel_gesture(Some(&ctx), CancelReason::UndoDuringGesture); self.step_now(step); } { @@ -597,7 +587,7 @@ impl ContentAwareFillWorkspace { tool_pick(&tools, slot.id, &self.tool, &self.last_used, PickStep::of(&fired), |_| true).map(|entry| (slot.id, entry.id)) }); if let Some((slot_id, tool)) = picked { - self.pick(&ctx, tool); + self.pick(Some(&ctx), tool); self.last_used.set(slot_id, tool); } continue; @@ -612,15 +602,11 @@ impl ContentAwareFillWorkspace { let bar = FillBar::new(self.tool, &mut self.options).show(ui); if let Some(edit) = bar.edit { - self.add_edit(edit); + // A refusal is already shown and reported by `add_edit`. + let _ = self.add_edit(edit); } if bar.reset_fill_area { - let before = self.session.clone(); - if self.session.reset(FillReset::FillArea, &mut self.settings) { - self.error = None; - self.record_history(before); - self.events.push(FillEvent::Reset(FillReset::FillArea)); - } + self.apply_reset(FillReset::FillArea); } Row::new().fill().show(ui, |ui, _| { @@ -629,7 +615,7 @@ impl ContentAwareFillWorkspace { self.last_used = next; } if let Some(tool) = rail.select { - self.pick(&ctx, tool); + self.pick(Some(&ctx), tool); } self.show_canvas(ui, source, &words); }); @@ -720,15 +706,11 @@ impl ContentAwareFillWorkspace { fn absorb(&mut self, event: FillEvent) { match event { FillEvent::FillArea(edit) => { - self.add_edit(edit); - } - FillEvent::Stroke(FillStrokeEvent::Commit(stroke)) => { - let before = self.session.clone(); - self.session.add_stroke(stroke.clone()); - self.error = None; - self.record_history(before); - self.events.push(FillEvent::Stroke(FillStrokeEvent::Commit(stroke))); + // A refusal is already shown and reported by `add_edit`. + let _ = self.add_edit(edit); } + // The tool checked the limits as the stroke grew. + FillEvent::Stroke(FillStrokeEvent::Commit(stroke)) => self.commit_stroke(stroke), FillEvent::Refused(limit) => { self.error = Some(FillIssue::Limit(limit)); self.events.push(FillEvent::Refused(limit)); @@ -737,25 +719,49 @@ impl ContentAwareFillWorkspace { } } - /// Records a fill-area edit within the limits, or sets the reason as the error and reports it. Whether it - /// was recorded. - fn add_edit(&mut self, edit: FillAreaEdit) -> bool { + /// Records a finished stroke in the session and reports it. + fn commit_stroke(&mut self, stroke: SamplingStroke) { let before = self.session.clone(); - match self.session.add_fill_edit(edit.clone(), &self.limits) { + self.session.add_stroke(stroke.clone()); + self.error = None; + self.record_history(before); + self.events.push(FillEvent::Stroke(FillStrokeEvent::Commit(stroke))); + } + + /// Records a whole stroke that did not come from the canvas (a control request) within the limits: the stroke + /// limit and the points limit, a total equal to the limit passing, as the brush and `add_fill_edit` count them. A + /// refusal records nothing, shows under the panel and is reported. + fn record_stroke(&mut self, stroke: SamplingStroke) -> Result<(), FillLimit> { + let fits = match self.session.may_begin_stroke(&self.limits) { + Ok(()) if self.session.points_used(Some(&stroke)) > self.limits.points => Err(FillLimit::Vertices(self.limits.points)), + other => other, + }; + match fits { Ok(()) => { - self.error = None; - self.record_history(before); - self.events.push(FillEvent::FillArea(edit)); - true - } - Err(limit) => { - self.error = Some(FillIssue::Limit(limit)); - self.events.push(FillEvent::Refused(limit)); - false + self.commit_stroke(stroke); + Ok(()) } + Err(limit) => Err(self.refuse(limit)), } } + /// Records a fill-area edit within the limits, or refuses it. + fn add_edit(&mut self, edit: FillAreaEdit) -> Result<(), FillLimit> { + let before = self.session.clone(); + self.session.add_fill_edit(edit.clone(), &self.limits).map_err(|limit| self.refuse(limit))?; + self.error = None; + self.record_history(before); + self.events.push(FillEvent::FillArea(edit)); + Ok(()) + } + + /// Shows `limit` under the panel and reports it; the limit, for the caller to return. + fn refuse(&mut self, limit: FillLimit) -> FillLimit { + self.error = Some(FillIssue::Limit(limit)); + self.events.push(FillEvent::Refused(limit)); + limit + } + /// Records the session as one history step when it differs from `before`. fn record_history(&mut self, before: FillSession) { if before == self.session { @@ -780,7 +786,7 @@ impl ContentAwareFillWorkspace { } /// Switches to `tool`, cancelling the old tool's gesture first. - fn pick(&mut self, ctx: &Context, tool: FillTool) { + fn pick(&mut self, ctx: Option<&Context>, tool: FillTool) { if tool != self.tool { self.cancel_gesture(ctx, CancelReason::Removed); self.tool = tool; @@ -788,9 +794,10 @@ impl ContentAwareFillWorkspace { } /// Cancels the gesture the current tool holds (a stroke, a lasso or a resize, or the Hand's or Zoom's drag) - /// through the host, and the canvas's own state if the host held none. - fn cancel_gesture(&mut self, ctx: &Context, reason: CancelReason) { - if let Some(id) = self.canvas_id { + /// through the host, and the canvas's own state if the host held none. Without a context (a request between + /// passes) only the canvas's own state is dropped. + fn cancel_gesture(&mut self, ctx: Option<&Context>, reason: CancelReason) { + if let (Some(ctx), Some(id)) = (ctx, self.canvas_id) { match self.tool { FillTool::Hand => ToolHost::cancel(ctx, id, &mut self.hand, reason), FillTool::Zoom => ToolHost::cancel(ctx, id, &mut self.zoom, reason), @@ -807,34 +814,159 @@ impl ContentAwareFillWorkspace { } } -// P3(dialogs-w10): dl.K64 — the workspace's trait surface; `show` and the automation fields are written in phase 3. -impl craft_ui::dialog::FullWindowWorkspace for ContentAwareFillWorkspace { +/// The names the automation surface gives the tools. +const TOOL_KEYS: [(&str, FillTool); 4] = + [("samplingBrush", FillTool::SamplingBrush), ("lasso", FillTool::Lasso), ("hand", FillTool::Hand), ("zoom", FillTool::Zoom)]; + +/// The names the automation surface gives the lasso's operations. +const LASSO_KEYS: [(&str, SelectionOperation); 4] = [ + ("new", SelectionOperation::New), + ("add", SelectionOperation::Add), + ("subtract", SelectionOperation::Subtract), + ("intersect", SelectionOperation::Intersect), +]; + +/// The name `table` gives `item`; empty for an item it does not list. +fn key_of(table: &[(&'static str, T)], item: T) -> &'static str { + table.iter().find(|(_, listed)| *listed == item).map_or("", |(key, _)| *key) +} + +/// The item `table` lists under `key`. +fn item_of(table: &[(&str, T)], key: &str) -> Option { + table.iter().find(|(listed, _)| *listed == key).map(|(_, item)| *item) +} + +/// The value of the `stroke` action key. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct StrokeArg { + points: Vec<[f64; 2]>, + size: Option, + #[serde(default)] + alt: bool, +} + +/// The value of the `lasso` action key. +#[derive(Deserialize)] +struct LassoArg { + points: Vec<[f64; 2]>, + op: String, +} + +/// Whether every coordinate is a finite number. +fn finite(points: &[[f64; 2]]) -> bool { + points.iter().flatten().all(|coordinate| coordinate.is_finite()) +} + +/// The workspace on the app's dialog host. OK is the host's held OK (`HostedWorkspace::held_ok`): the app takes the +/// command with `take_ok`, fills and answers with `answer_ok`. Apply is the footer's own button, answered by +/// [`ContentAwareFillWorkspace::answer_apply`]. +impl FullWindowWorkspace for ContentAwareFillWorkspace { type Source = dyn FillSource; type Event = FillEvent; type Result = FillCommand; const KEY: &'static str = "edit.contentAwareFill"; - fn show( - &mut self, - ui: &mut egui::Ui, - cx: craft_ui::dialog::WorkspaceCx<'_, Self::Source>, - ) -> craft_ui::dialog::WorkspacePass { - let _ = (ui, cx); - todo!("dl.K64") + fn show(&mut self, ui: &mut Ui, cx: WorkspaceCx<'_, Self::Source>) -> WorkspacePass { + self.pass(ui, cx) } + /// The settings, and the bar's `tool`, `brushSize`, `brushMode` (`"add"`, `"subtract"`), `lassoMode` (`"new"`, + /// `"add"`, `"subtract"`, `"intersect"`) and `expandBy`. fn json_fields(&self) -> Option { - todo!("dl.K64") + let mut fields = serde_fields(&self.settings)?; + let bar = fields.as_object_mut()?; + let brush_mode = if self.options.brush_add { "add" } else { "subtract" }; + bar.insert("tool".to_owned(), key_of(&TOOL_KEYS, self.tool).into()); + bar.insert("brushSize".to_owned(), self.options.brush_size.into()); + bar.insert("brushMode".to_owned(), brush_mode.into()); + bar.insert("lassoMode".to_owned(), key_of(&LASSO_KEYS, self.options.lasso).into()); + bar.insert("expandBy".to_owned(), self.options.grow_by.into()); + Some(fields) } - fn set_json_field(&mut self, ctx: &egui::Context, source: &Self::Source, field: &str, value: serde_json::Value) -> Result<(), String> { - let _ = (ctx, source, field, value); - todo!("dl.K64") + /// A settings key, a bar key of [`json_fields`](Self::json_fields), or an action: `stroke` (`{points, size?, alt?}`), + /// `lasso` (`{points, op}`), `reset` (`"all"`, `"fillArea"`, `"sampling"`), `undo`, `redo` and `apply` (each `true`). + /// A stroke or lasso edit goes through the limits like the canvas's; one a limit refuses is rejected and the panel + /// shows the limit. + fn set_json_field(&mut self, ctx: &Context, _source: &Self::Source, field: &str, value: serde_json::Value) -> Result<(), String> { + let rejects = |value: &serde_json::Value| FieldRefusal::Rejects(value).message(field); + match field { + "tool" => { + let tool = value.as_str().and_then(|key| item_of(&TOOL_KEYS, key)).ok_or_else(|| rejects(&value))?; + self.pick(Some(ctx), tool); + } + "brushSize" => self.set_brush(value.as_f64().ok_or_else(|| rejects(&value))?), + "brushMode" => { + self.options.brush_add = match value.as_str() { + Some("add") => true, + Some("subtract") => false, + _ => return Err(rejects(&value)), + }; + } + "lassoMode" => { + self.options.lasso = value.as_str().and_then(|key| item_of(&LASSO_KEYS, key)).ok_or_else(|| rejects(&value))?; + } + "expandBy" => { + let by = value.as_f64().ok_or_else(|| rejects(&value))?; + self.options.grow_by = by.clamp(FillAreaEdit::GROW_RANGE.0, FillAreaEdit::GROW_RANGE.1); + } + "sampling" => { + let mode = serde_json::from_value::(value.clone()).map_err(|_| rejects(&value))?; + self.perform(FillOp::Sampling(mode)).map_err(|limit| limit.message(&Env::of_root(ctx)))?; + } + "stroke" => { + let arg = serde_json::from_value::(value.clone()).map_err(|_| rejects(&value))?; + if arg.points.is_empty() || !finite(&arg.points) { + return Err(rejects(&value)); + } + let size = arg.size.filter(|size| size.is_finite()).unwrap_or(self.options.brush_size).clamp(1.0, FillToolOptions::SIZE_MAX); + let mode = FillToolOptions::stroke_mode(self.options.brush_add, arg.alt); + self.perform(FillOp::Stroke(SamplingStroke::new(mode, size, arg.points))).map_err(|limit| limit.message(&Env::of_root(ctx)))?; + } + "lasso" => { + let arg = serde_json::from_value::(value.clone()).map_err(|_| rejects(&value))?; + let operation = item_of(&LASSO_KEYS, &arg.op).ok_or_else(|| rejects(&value))?; + if !finite(&arg.points) { + return Err(rejects(&value)); + } + let edit = FillAreaEdit::lasso(operation, arg.points).ok_or_else(|| rejects(&value))?; + self.perform(FillOp::FillArea(edit)).map_err(|limit| limit.message(&Env::of_root(ctx)))?; + } + "reset" => { + let what = match value.as_str() { + Some("all") => FillReset::All, + Some("fillArea") => FillReset::FillArea, + Some("sampling") => FillReset::Sampling, + _ => return Err(rejects(&value)), + }; + self.perform(FillOp::Reset(what)).map_err(|limit| limit.message(&Env::of_root(ctx)))?; + } + "undo" | "redo" | "apply" => { + if value != serde_json::Value::Bool(true) { + return Err(rejects(&value)); + } + match field { + "undo" => self.undo(), + "redo" => self.redo(), + _ => { + let command = self.command(); + self.events.push(FillEvent::Apply(command)); + } + } + } + _ => set_serde_field(&mut self.settings, field, value)?, + } + Ok(()) } - fn confirm(&mut self, ctx: &egui::Context, source: &Self::Source) -> Option { - let _ = (ctx, source); - todo!("dl.K64") + fn confirm(&mut self, _ctx: &Context, _source: &Self::Source) -> Option { + Some(self.command()) + } + + /// The app's fill failed: the reason shows under the panel and the workspace stays open. + fn ok_failed(&mut self, reason: Label) { + self.error = Some(FillIssue::Message(reason)); } } diff --git a/crates/imaging/src/ui/fill/stories.rs b/crates/imaging/src/ui/fill/stories.rs index a220c8b44..1b705f307 100644 --- a/crates/imaging/src/ui/fill/stories.rs +++ b/crates/imaging/src/ui/fill/stories.rs @@ -5,7 +5,7 @@ //! the lasso in progress, the brush outline and the Alt + right-drag resize with its readout are the pointer's: draw //! on the picture to see them. -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::Arc; use std::time::Duration; use egui::Ui; @@ -13,7 +13,8 @@ use egui::Ui; use craft_behavior::kurbo::Rect; use craft_ui::canvas::RasterSource; use craft_ui::contract::Bind; -use craft_ui::dialog::FullWindowView; +use craft_ui::dialog::stories::hosted; +use craft_ui::dialog::{FullWindowView, HostedWorkspace}; use craft_ui::runtime::pending::{Job, Pending}; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; @@ -115,24 +116,16 @@ impl FillSource for StorySource { } } -/// The workspace a story keeps between passes, compared by identity. -#[derive(Clone)] -struct Kept(Arc>); - -impl PartialEq for Kept { - fn eq(&self, other: &Self) -> bool { - Arc::ptr_eq(&self.0, &other.0) - } -} - -/// Shows the workspace over the mock picture with `settings` and a preview job that `preview` says how it ends. +/// Shows the workspace over the mock picture with `settings` and a preview job that `preview` says how it ends, on the +/// story's dialog host with the open flag the story keeps. fn show_workspace(ui: &mut Ui, data: &mut StoryData, settings: FillSettings, preview: Preview) -> StoryOutput { - let image = MockImage::default(); - let size = image.size(); - let open = FillOpen::new([size.width, size.height], "House", LIMITS).settings(settings); - let kept = data.value("workspace", Kept(Arc::new(Mutex::new(ContentAwareFillWorkspace::new(open))))).clone(); - let mut workspace = kept.0.lock().unwrap_or_else(PoisonError::into_inner); - workspace.show(ui, &StorySource::new(image, preview)).into() + // A pass's `WorkspaceCx` is built by the host only, so this runs the workspace on a `DialogHost`. + hosted(ui, data, (settings.clone(), preview), || { + let image = MockImage::default(); + let size = image.size(); + let open = FillOpen::new([size.width, size.height], "House", LIMITS).settings(settings); + HostedWorkspace::new(ContentAwareFillWorkspace::new(open), Arc::new(StorySource::new(image, preview))) + }) } #[story(ContentAwareFillWorkspace, covers = [Default], drive = Drive::Never)] diff --git a/crates/imaging/src/ui/liquify/commands.rs b/crates/imaging/src/ui/liquify/commands.rs index ba6651a3b..f8f0e4932 100644 --- a/crates/imaging/src/ui/liquify/commands.rs +++ b/crates/imaging/src/ui/liquify/commands.rs @@ -58,6 +58,9 @@ pub enum LiquifyCommands { /// Zoom. #[command(modal = "in_dialogs", label = "Zoom Tool", icon = "zoom_in", kind = "tool", default = "Z")] Zoom, + /// Turns the preview on or off. + #[command(modal = "in_dialogs", label = "Preview", default = "P")] + Preview, /// Makes the brush smaller. #[command(modal = "in_dialogs", label = "Smaller Brush", default = "[")] Smaller, diff --git a/crates/imaging/src/ui/liquify/mod.rs b/crates/imaging/src/ui/liquify/mod.rs index 565ab3461..0fed29df1 100644 --- a/crates/imaging/src/ui/liquify/mod.rs +++ b/crates/imaging/src/ui/liquify/mod.rs @@ -10,25 +10,30 @@ //! the engine replays them ([`LiquifySession`]), with [`EditHistory`] undo. The app owns the //! displacement field and its preview: it applies each [`LiquifyEvent`] to the field as it comes, //! replays the list after undo, redo and Restore All, and shows the result through -//! [`LiquifySource`]. OK runs `filter.liquify` with [`LiquifySession::steps`]; Cancel changes -//! nothing. +//! [`LiquifySource`]. The workspace is a [`FullWindowWorkspace`] that the app's dialog host owns as a +//! `HostedWorkspace`: OK answers [`LiquifyDone`] (the steps `filter.liquify` runs and the settings to +//! remember); Cancel changes nothing. //! //! ```ignore -//! let out = app.liquify.show(ui, &PcLiquifySource { proxy: &app.liquify_proxy, doc: &doc }); -//! for event in out.events { -//! match event { -//! LiquifyEvent::Stroke(e) => app.liquify_engine.stroke(e), -//! LiquifyEvent::Global(op) => app.liquify_engine.global(op), -//! LiquifyEvent::Replay(steps) => app.liquify_engine.replay(&steps), -//! LiquifyEvent::BackdropWanted(of) => app.load_backdrop(of), +//! dialogs.open(HostedWorkspace::new(LiquifyWorkspace::new(open), Arc::new(source))); +//! dialogs.run(ui); +//! if let Some(liquify) = dialogs.get_mut::>() { +//! for event in liquify.take_events() { +//! match event { +//! LiquifyEvent::Stroke(e) => app.liquify_engine.stroke(e), +//! LiquifyEvent::Global(op) => app.liquify_engine.global(op), +//! LiquifyEvent::Replay(steps) => app.liquify_engine.replay(&steps), +//! LiquifyEvent::BackdropWanted(of) => app.load_backdrop(of), +//! LiquifyEvent::Preview(on) => app.liquify_engine.show_preview(on), +//! LiquifyEvent::SettingsChanged(settings) => app.prefs.liquify = settings, +//! _ => {} +//! } //! } //! } -//! match out.closed { -//! Some(DialogRole::Accept) => app.run("filter.liquify", app.liquify.session().steps()), -//! Some(DialogRole::Cancel) => app.close_liquify(), -//! _ => {} +//! if let Some(DialogResult::Ok(done)) = dialogs.take::>() { +//! app.run("filter.liquify", done.steps); +//! app.prefs.liquify = done.settings; //! } -//! app.prefs.liquify = app.liquify.settings().clone(); //! ``` //! //! Files: `session` (the steps, the settings), `tools` (the tools and the stroke @@ -37,6 +42,7 @@ //! (`show`, `step`). //! //! [`FullWindowDialog`]: craft_ui::dialog::FullWindowDialog +//! [`FullWindowWorkspace`]: craft_ui::dialog::FullWindowWorkspace //! [`FullWindowSide`]: craft_ui::dialog::FullWindowSide //! [`EditHistory`]: craft_behavior::EditHistory @@ -61,14 +67,18 @@ pub use words::LiquifyWords; use std::cell::RefCell; use std::sync::Arc; -use egui::{Color32, Id, Response, Ui}; +use egui::{Color32, Context, Id, Ui}; use craft_behavior::edit_history::Step; 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::contract::{Bind, NoValue, Outcome, Pattern, Show as _, ShowContainer as _}; -use craft_ui::dialog::{FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowTitle, FullWindowView, RasterOverlay}; +use craft_ui::choice::Checkbox; +use craft_ui::contract::{Bind, 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}; @@ -119,7 +129,8 @@ pub struct LiquifyOpen { pub size: [u32; 2], /// The layer's name: the title's subject. pub subject: String, - /// The remembered settings (PhotoCraft: `prefs.dialogs["filter.liquify"]`). + /// The remembered settings, the SAVED tier (PhotoCraft: `prefs.dialogs["filter.liquify"]`). The Preview check box + /// is not among them: it is on at each opening. pub settings: LiquifySettings, /// The recorded steps of a smart filter opened again; empty for a new Liquify. pub steps: Vec, @@ -198,7 +209,6 @@ pub enum LiquifyEvent { /// The settings differ from the last ones reported. SettingsChanged(LiquifySettings), /// The Preview checkbox or the `P` key turned the preview on or off. - // P3(dialogs-w10): dl.K63 `LiquifyEvent::Preview` Preview(bool), } @@ -212,34 +222,6 @@ pub struct LiquifyDone { pub settings: LiquifySettings, } -/// What [`LiquifyWorkspace::show`] reports. -#[derive(Clone, Debug)] -#[non_exhaustive] -pub struct LiquifyOutput { - /// What happened this pass, in order. - pub events: Vec, - /// OK (`Accept`) or Cancel this pass. - pub closed: Option, - /// The dialog's response: its rect is the workspace's. - pub response: Response, - /// The settings changed this pass (compared before and after, whatever changed them: the - /// panel, the keys, the strip or a brush resize); the app may persist them. - pub settings_changed: bool, - /// The cursor the canvas tool asked for this pass: the brush outline over the canvas, none off it. - pub cursor: Option, - /// The timing of the latest brush stroke, for the app's diagnostics (PhotoCraft's stats line - /// is not drawn; lead call 14); `None` before the first stroke. - pub timing: Option, -} - -impl Outcome for LiquifyOutput { - type Value = NoValue; - - fn response(&self) -> &Response { - &self.response - } -} - /// 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)] @@ -279,6 +261,11 @@ pub struct LiquifyWorkspace { timing: Option, /// The cursor the canvas tool asked for in the last pass. cursor: Option, + /// The Preview checkbox: on at each opening, never remembered. + preview: bool, + /// The settings as the app last heard them, so a change made between passes (a control request, a colour answer) + /// is reported once by the next pass. + reported: LiquifySettings, } /// The parts of the workspace the canvas tool's gestures and the history change together: kept apart from the view so a @@ -289,7 +276,7 @@ struct Edit { history: EditHistory, settings: LiquifySettings, cursor_options: BrushCursorOptions, - /// This pass's events. + /// The events the next pass reports first: what the methods between passes queued, then the pass's own. events: Vec, } @@ -298,6 +285,7 @@ impl LiquifyWorkspace { pub fn new(open: LiquifyOpen) -> Self { let session = LiquifySession::from_steps(open.steps); Self { + reported: open.settings.clone(), edit: Edit { history: EditHistory::new(&session), session, @@ -313,6 +301,7 @@ impl LiquifyWorkspace { zoom_percent: 100.0, timing: None, cursor: None, + preview: true, } } @@ -326,30 +315,60 @@ impl LiquifyWorkspace { self.timing } - /// The settings, for the control requests that change them. + /// Whether the Preview checkbox is on. + pub fn preview(&self) -> bool { + self.preview + } + + /// Turns the preview on or off; the next pass reports [`LiquifyEvent::Preview`] when it changed. + pub fn set_preview(&mut self, on: bool) { + if self.preview != on { + self.preview = on; + self.edit.events.push(LiquifyEvent::Preview(on)); + } + } + + /// The settings, for the control requests that change them. The next pass reports a change as + /// [`LiquifyEvent::SettingsChanged`]. pub fn settings_mut(&mut self) -> &mut LiquifySettings { &mut self.edit.settings } - /// Records `step` in the session and queues its events for the next pass. + /// Records `step` in the session and queues its events for the next pass. A stroke reports only its `Commit` + /// with every point, as a Freeze Lasso does; a stroke the session does not record (no points, a lasso of fewer + /// than three) reports nothing. The caller asks for the repaint that runs the next pass (this method has no + /// context). pub fn perform(&mut self, step: LiquifyStep) { - let _ = step; - todo!("dl.K63") + match step { + LiquifyStep::Stroke(stroke) => { + let (steps, events) = (self.edit.session.len(), self.edit.events.len()); + self.edit.absorb(LiquifyEvent::Stroke(StrokeEvent::Commit(stroke))); + if self.edit.session.len() == steps { + self.edit.events.truncate(events); + } + } + LiquifyStep::Global(op) => self.edit.record_global(None, op), + } } - /// Undoes the last step; its events come out of the next pass. + /// Undoes the last step; its events come out of the next pass. A stroke still open is abandoned first. pub fn undo(&mut self) { - todo!("dl.K63") + self.edit.step(None, &mut self.view, Step::Undo); } - /// Redoes the last undone step; its events come out of the next pass. + /// Redoes the last undone step; its events come out of the next pass. A stroke still open is abandoned first. pub fn redo(&mut self) { - todo!("dl.K63") + self.edit.step(None, &mut self.view, Step::Redo); } /// Restores every step; its events come out of the next pass. pub fn restore_all(&mut self) { - todo!("dl.K63") + self.edit.restore_all(); + } + + /// The result OK answers. + fn done(&self) -> LiquifyDone { + LiquifyDone { steps: self.edit.session.steps().to_vec(), settings: self.edit.settings.clone() } } /// The user's navigation options (wheel, flick, animated zoom); Photoshop's by default. @@ -376,7 +395,10 @@ impl LiquifyWorkspace { /// [`BackdropLayering`], the freeze mask as a `RasterOverlay` tinted red while Show Mask is on, the mesh while /// Show Mesh is on, the lasso and the resize preview as canvas controls, and [`LiquifyCanvasTool`] as its tool. /// Undo and redo report [`LiquifyEvent::Replay`] in the same pass. - pub fn show(&mut self, ui: &mut Ui, source: &dyn LiquifySource) -> LiquifyOutput { + /// + /// The events of the methods that ran between passes come first. A second pass of a frame reports only what its + /// own input did, since the first pass took the frame's steps and commands. + fn pass(&mut self, ui: &mut Ui, source: &dyn LiquifySource, open: Bind<'_, bool>) -> WorkspacePass { // pc: crates/ui-egui/src/dialogs/liquify_ui.rs:950 `show` (title, strip, panel, footer, // preview, brush circle); :730 `history_keys`; :740 `keys`. let env = Env::of(ui); @@ -384,22 +406,33 @@ impl LiquifyWorkspace { let common = env.words::(); let layers = source.layers(); let title = FullWindowTitle::new(words.name.clone()).subject(self.subject.clone()).zoom(self.zoom_percent).label(&env); - let settings_before = self.edit.settings.clone(); - self.edit.events.clear(); if !self.edit.settings.show_backdrop { self.asked = None; - } else if self.asked.is_none() { - // Show Backdrop was already on when the workspace opened. + } else if self.asked != Some(backdrop_id(self.edit.settings.backdrop)) { + // Show Backdrop was on when the workspace opened, or a control request turned it on or changed its Use + // between passes. let of = backdrop_id(self.edit.settings.backdrop); 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); let mut shown = FullWindowDialog::new(title) .command_scope(LiquifyCommands::SCOPE) + .opened(open) .buttons([FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]) + .footer(|ui, _| { + ui.vertical_centered(|ui| { + let mut guard = this.borrow_mut(); + let work: &mut LiquifyWorkspace = &mut guard; + let events = Checkbox::new(Bind::given(work.preview)).label(preview_label.clone()).show(ui).events; + if let Some(on) = events.value().copied() { + work.set_preview(on); + } + }); + }) .sides(|ui, _| { let mut guard = this.borrow_mut(); let work: &mut LiquifyWorkspace = &mut guard; @@ -413,10 +446,7 @@ impl LiquifyWorkspace { work.edit.record_global(None, op); } if panel.restore_all { - let before = work.edit.session.clone(); - work.edit.session.restore_all(); - work.edit.record_history(before); - work.edit.events.push(LiquifyEvent::Replay(Vec::new())); + work.edit.restore_all(); } if let Some(of) = panel.backdrop_wanted { work.edit.events.push(LiquifyEvent::BackdropWanted(of)); @@ -429,12 +459,11 @@ impl LiquifyWorkspace { let work: &mut LiquifyWorkspace = &mut guard; // Before the canvas runs, so an undo during a releasing stroke cancels it instead of undoing. while let Some(step) = cx.take_step(work.edit.history.can_undo(), work.edit.history.can_redo()) { - work.edit.step(&ctx, &mut work.view, step); + work.edit.step(Some(&ctx), &mut work.view, step); } - let state = &mut work.view; - state.canvas.navigate(work.navigation); + work.view.canvas.navigate(work.navigation); while let Some((command, _)) = cx.take_command::() { - state.view.apply(command); + work.view.view.apply(command); } { @@ -443,24 +472,26 @@ impl LiquifyWorkspace { let slot = 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, &state.last_used, PickStep::of(&fired), |_| true) + tool_pick(&tools, slot.id, &work.edit.settings.tool, &work.view.last_used, PickStep::of(&fired), |_| true) .map(|entry| (slot.id, entry.id)) }); if let Some((slot_id, tool)) = picked { - work.edit.pick(&ctx, state, tool); - state.last_used.set(slot_id, tool); + work.edit.pick(Some(&ctx), &mut work.view, tool); + work.view.last_used.set(slot_id, tool); } continue; } match command { LiquifyCommands::Smaller => work.edit.settings.brush = work.edit.settings.brush.smaller(), LiquifyCommands::Larger => work.edit.settings.brush = work.edit.settings.brush.larger(), + LiquifyCommands::Preview => work.set_preview(!work.preview), LiquifyCommands::ShowMask => work.edit.settings.show_mask = !work.edit.settings.show_mask, - LiquifyCommands::InvertMask => work.edit.record_global(Some(&mut *state), LiquifyGlobal::InvertAll), - LiquifyCommands::ClearMask => work.edit.record_global(Some(&mut *state), LiquifyGlobal::MaskNone), + LiquifyCommands::InvertMask => work.edit.record_global(Some(&mut work.view), LiquifyGlobal::InvertAll), + LiquifyCommands::ClearMask => work.edit.record_global(Some(&mut work.view), LiquifyGlobal::MaskNone), _ => {} } } + let state = &mut work.view; let backdrop = source.backdrop().filter(|_| work.edit.settings.show_backdrop); let layering = BackdropLayering::of(backdrop.is_some(), work.edit.settings.backdrop_mode, work.edit.settings.backdrop_opacity); @@ -488,7 +519,7 @@ impl LiquifyWorkspace { state.last_used = next; } if let Some(tool) = rail.select { - work.edit.pick(&ctx, state, tool); + work.edit.pick(Some(&ctx), state, tool); } let LiquifyView { view, canvas: tools, .. } = &mut *state; let mut canvas = FullWindowCanvas::new(Bind::bound(view), image) @@ -534,17 +565,13 @@ impl LiquifyWorkspace { work.timing = work.view.canvas.timing(); }); let this = this.into_inner(); - let timing = this.timing; - let picked = shown.output.picked.and_then(|at| [DialogRole::Accept, DialogRole::Cancel].get(at).copied()); - let closed = picked.or(shown.output.closed.map(|_| DialogRole::Cancel)); - LiquifyOutput { - events: std::mem::take(&mut this.edit.events), - closed, - response: shown.output.response, - settings_changed: this.edit.settings != settings_before, - cursor: this.cursor.take(), - timing, + if this.edit.settings != this.reported { + this.reported = this.edit.settings.clone(); + this.edit.events.push(LiquifyEvent::SettingsChanged(this.reported.clone())); } + let result = shown.output.result(|| this.done()); + let events = std::mem::take(&mut this.edit.events); + WorkspacePass::new(shown.output.response, events).result(result) } /// What OK applies. @@ -610,12 +637,21 @@ impl Edit { self.events.push(LiquifyEvent::Global(op)); } + /// Restore All: drops every step as one history step; the app rebuilds its field from the empty replay. + fn restore_all(&mut self) { + let before = self.session.clone(); + self.session.restore_all(); + self.record_history(before); + self.events.push(LiquifyEvent::Replay(Vec::new())); + } + /// Cancels the gesture the current tool holds (a Liquify tool's stroke, lasso or resize, or the Hand's or Zoom's - /// drag) through the host, and the tool's own state if the host held none. - fn cancel_gesture(&mut self, ctx: &egui::Context, state: &mut LiquifyView, reason: CancelReason) { + /// drag) through the host, and the tool's own state if the host held none. Without a context (a request between + /// passes) only the tool's own state is dropped. + fn cancel_gesture(&mut self, ctx: Option<&Context>, state: &mut LiquifyView, reason: CancelReason) { let cursor = self.cursor_options; let LiquifyView { canvas, canvas_id, .. } = state; - if let Some(id) = *canvas_id { + if let (Some(ctx), Some(id)) = (ctx, *canvas_id) { match self.settings.tool { LiquifyTool::Hand => ToolHost::cancel(ctx, id, &mut canvas.hand, reason), LiquifyTool::Zoom => ToolHost::cancel(ctx, id, &mut canvas.zoom, reason), @@ -630,7 +666,7 @@ impl Edit { /// Undoes or redoes, cancelling an open stroke first (`UndoDuringGesture`); the replay of the step supersedes the /// one the cancel reports. - fn step(&mut self, ctx: &egui::Context, state: &mut LiquifyView, step: Step) { + fn step(&mut self, ctx: Option<&Context>, state: &mut LiquifyView, step: Step) { // pc: crates/ui-egui/src/dialogs/liquify_ui.rs:340 `undo`, :351 `redo`. self.cancel_gesture(ctx, state, CancelReason::UndoDuringGesture); if self.history.step(&mut self.session, step) { @@ -642,7 +678,7 @@ impl Edit { } /// Switches to `tool`, cancelling the old tool's gesture first. - fn pick(&mut self, ctx: &egui::Context, state: &mut LiquifyView, tool: LiquifyTool) { + fn pick(&mut self, ctx: Option<&Context>, state: &mut LiquifyView, tool: LiquifyTool) { if tool != self.settings.tool { self.cancel_gesture(ctx, state, CancelReason::Removed); self.settings.tool = tool; @@ -653,34 +689,72 @@ impl Edit { /// The name the history gives its steps. const HISTORY_NAME: &str = "Liquify"; -// P3(dialogs-w10): dl.K63 — the workspace's trait surface; `show` and the automation fields are written in phase 3. -impl craft_ui::dialog::FullWindowWorkspace for LiquifyWorkspace { +/// The workspace on the app's dialog host. OK answers at once (no held OK): the steps and settings are the whole +/// answer. The key `filter.liquify` is the command the workspace answers for. +impl FullWindowWorkspace for LiquifyWorkspace { type Source = dyn LiquifySource; type Event = LiquifyEvent; type Result = LiquifyDone; const KEY: &'static str = "filter.liquify"; - fn show( - &mut self, - ui: &mut egui::Ui, - cx: craft_ui::dialog::WorkspaceCx<'_, Self::Source>, - ) -> craft_ui::dialog::WorkspacePass { - let _ = (ui, cx); - todo!("dl.K63") + fn show(&mut self, ui: &mut Ui, cx: WorkspaceCx<'_, Self::Source>) -> WorkspacePass { + let WorkspaceCx { source, open, .. } = cx; + self.pass(ui, source, open) } + /// The settings (the brush keys at the top level) and `preview`. fn json_fields(&self) -> Option { - todo!("dl.K63") + let mut fields = serde_fields(&self.edit.settings)?; + fields.as_object_mut()?.insert("preview".to_owned(), serde_json::Value::Bool(self.preview)); + Some(fields) } - fn set_json_field(&mut self, ctx: &egui::Context, source: &Self::Source, field: &str, value: serde_json::Value) -> Result<(), String> { - let _ = (ctx, source, field, value); - todo!("dl.K63") + /// A settings key, `preview`, or an action: `stroke` (a [`LiquifyStroke`]), `reconstruct` (the amount), + /// `maskAll`, `maskNone`, `invertMask`, `restoreAll`, `undo`, `redo` (each `true`). An action runs the way the + /// canvas and the panel run it; its events come out of the next pass. + fn set_json_field(&mut self, ctx: &Context, _source: &Self::Source, field: &str, value: serde_json::Value) -> Result<(), String> { + let rejects = |value: &serde_json::Value| FieldRefusal::Rejects(value).message(field); + match field { + "stroke" => { + let stroke = serde_json::from_value::(value.clone()).map_err(|_| rejects(&value))?; + if stroke.points.is_empty() { + return Err(rejects(&value)); + } + self.perform(LiquifyStep::Stroke(stroke)); + } + "reconstruct" => { + let amount = value.as_f64().filter(|amount| amount.is_finite()).ok_or_else(|| rejects(&value))?; + self.perform(LiquifyStep::Global(LiquifyGlobal::reconstruct(amount.clamp(0.0, 100.0)))); + } + "maskAll" | "maskNone" | "invertMask" | "restoreAll" | "undo" | "redo" => { + if value != serde_json::Value::Bool(true) { + return Err(rejects(&value)); + } + match field { + "maskAll" => self.perform(LiquifyStep::Global(LiquifyGlobal::MaskAll)), + "maskNone" => self.perform(LiquifyStep::Global(LiquifyGlobal::MaskNone)), + "invertMask" => self.perform(LiquifyStep::Global(LiquifyGlobal::InvertAll)), + "restoreAll" => self.restore_all(), + "undo" => self.undo(), + _ => self.redo(), + } + } + "preview" => self.set_preview(value.as_bool().ok_or_else(|| rejects(&value))?), + _ => { + let before = self.edit.settings.clone(); + set_serde_field(&mut self.edit.settings, field, value)?; + // A number out of range is clamped as a loaded record is; a tool switch cancels the old tool's gesture. + let mut settings = self.edit.settings.clone().clamped(&before); + let tool = std::mem::replace(&mut settings.tool, before.tool); + self.edit.settings = settings; + self.edit.pick(Some(ctx), &mut self.view, tool); + } + } + Ok(()) } - fn confirm(&mut self, ctx: &egui::Context, source: &Self::Source) -> Option { - let _ = (ctx, source); - todo!("dl.K63") + fn confirm(&mut self, _ctx: &Context, _source: &Self::Source) -> Option { + Some(self.done()) } } diff --git a/crates/imaging/src/ui/liquify/panel.rs b/crates/imaging/src/ui/liquify/panel.rs index 31cfdec99..544b4d7f5 100644 --- a/crates/imaging/src/ui/liquify/panel.rs +++ b/crates/imaging/src/ui/liquify/panel.rs @@ -47,7 +47,7 @@ pub struct LiquifyPanelOutput { /// Behind, Blend), Opacity (0..=100). /// /// PhotoCraft's stats line ("N stroke(s) · field … · dab … ms · preview … ms") is not drawn (lead -/// call 14); [`LiquifyOutput::timing`](super::LiquifyOutput::timing) carries the timing the library +/// call 14); [`LiquifyWorkspace::timing`](super::LiquifyWorkspace::timing) carries the timing the library /// can measure. Every control is a Tab stop in that order. The panel writes the new values to the /// bound settings and reports the pass's change as [`LiquifyPanelOutput::edit`]. The sections remember their /// open state. diff --git a/crates/imaging/src/ui/liquify/stories.rs b/crates/imaging/src/ui/liquify/stories.rs index 07dba8dea..98aa45523 100644 --- a/crates/imaging/src/ui/liquify/stories.rs +++ b/crates/imaging/src/ui/liquify/stories.rs @@ -5,7 +5,7 @@ //! gently displaced mesh. The stroke in progress, the brush outline and the Alt + right-drag resize with its readout //! are the pointer's: draw on the picture to see them. -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::Arc; use egui::{Color32, ColorImage, Ui}; @@ -13,6 +13,8 @@ use craft_behavior::PixelSize; use craft_behavior::kurbo::Point; use craft_ui::canvas::{PixelRect, RasterSource}; use craft_ui::contract::Bind; +use craft_ui::dialog::HostedWorkspace; +use craft_ui::dialog::stories::hosted; use craft_ui::primitives::Revision; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; @@ -149,24 +151,17 @@ impl LiquifySource for StorySource { } } -/// The workspace a story keeps between passes, compared by identity. -#[derive(Clone)] -struct Kept(Arc>); - -impl PartialEq for Kept { - fn eq(&self, other: &Self) -> bool { - Arc::ptr_eq(&self.0, &other.0) - } -} - -/// Shows the workspace over the mock picture with `settings`. +/// Shows the workspace over the mock picture with `settings`, on the story's dialog host with the open flag the story +/// keeps. A hosted workspace is the only way outside `craft-ui` to give a pass its context (`WorkspaceCx` is +/// non-exhaustive). fn show_workspace(ui: &mut Ui, data: &mut StoryData, settings: &LiquifySettings) -> StoryOutput { - let image = MockImage::default(); - let size = image.size(); - let open = LiquifyOpen::new([size.width, size.height], "House").settings(settings.clone()); - let kept = data.value("workspace", Kept(Arc::new(Mutex::new(LiquifyWorkspace::new(open))))).clone(); - let mut workspace = kept.0.lock().unwrap_or_else(PoisonError::into_inner); - workspace.show(ui, &StorySource::new(image)).into() + // A pass's `WorkspaceCx` is built by the host only, so this runs the workspace on a `DialogHost`. + hosted(ui, data, settings.clone(), || { + let image = MockImage::default(); + let size = image.size(); + let open = LiquifyOpen::new([size.width, size.height], "House").settings(settings.clone()); + HostedWorkspace::new(LiquifyWorkspace::new(open), Arc::new(StorySource::new(image))) + }) } #[story(LiquifyWorkspace, covers = [Default], drive = Drive::Never)] diff --git a/crates/imaging/src/ui/liquify/words.rs b/crates/imaging/src/ui/liquify/words.rs index 86bd51847..ccc83679a 100644 --- a/crates/imaging/src/ui/liquify/words.rs +++ b/crates/imaging/src/ui/liquify/words.rs @@ -8,6 +8,8 @@ craft_ui::words! { pub struct LiquifyWords { /// The title's name: "Liquify (layer, 66%)". name: "liquify.name" = "Liquify"; + /// The footer's Preview check box. + preview: "liquify.preview" = "Preview"; /// The strip's accessible name. tools: "liquify.tools" = "Tools"; /// The side column's header (Photoshop heads Liquify's panel "Properties") and accessible name. diff --git a/crates/imaging/src/ui/select_mask/mod.rs b/crates/imaging/src/ui/select_mask/mod.rs index e5eb07266..e2405dfee 100644 --- a/crates/imaging/src/ui/select_mask/mod.rs +++ b/crates/imaging/src/ui/select_mask/mod.rs @@ -13,23 +13,30 @@ //! shows it through [`SelectMaskSource`]; OK runs `select.refineEdge` with //! [`SelectMaskSession::command`]. Cancel changes nothing. The app opens the workspace only with a //! selection or a layer mask (lead call 26), and closes it when the document or layer changes -//! under it. +//! under it. The workspace is a [`FullWindowWorkspace`] that the app's dialog host owns as a +//! `HostedWorkspace`: OK answers [`SelectMaskDone`]. //! //! ```ignore -//! let out = w.show(ui, &PcSelectMaskSource { view: app.sm_preview.view(), image: app.image(), ants: app.sm_preview.ants() }); -//! if let Some(request) = out.pick_color { app.host.request_color(request) } -//! match out.closed { -//! Some(DialogRole::Accept) => app.run("select.refineEdge", w.command()), -//! Some(_) => app.close_select_mask(), -//! None => {} +//! dialogs.open(HostedWorkspace::new(SelectMaskWorkspace::new(open), Arc::new(source))); +//! dialogs.run(ui); +//! if let Some(select_mask) = dialogs.get_mut::>() { +//! for event in select_mask.take_events() { +//! if let SelectMaskEvent::PickColor(request) = event { app.host.request_color(request) } +//! } +//! select_mask.set_source(Arc::new(next_source)); +//! } +//! if let Some(DialogResult::Ok(done)) = dialogs.take::>() { +//! app.run("select.refineEdge", done.command); //! } -//! if w.settings().remember { prefs.select_mask = w.settings().clone() } //! ``` //! +//! The workspace remembers its settings under a [`SaveKey`] ([`SelectMaskOpen::remember`]) when OK is pressed. +//! //! Files: `session` and `edits`; `tools`, `commands` and `bar`; `panel` and this file's //! `show` and `step`. //! //! [`EditHistory`]: craft_behavior::EditHistory +//! [`FullWindowWorkspace`]: craft_ui::dialog::FullWindowWorkspace mod bar; mod commands; @@ -52,7 +59,8 @@ pub use words::SelectMaskWords; use std::cell::{Cell, RefCell}; use std::sync::Arc; -use egui::{Id, Response, Ui}; +use egui::{Context, Id, Ui}; +use serde::Deserialize; use craft_behavior::edit_history::Step; use craft_behavior::{CancelReason, EditEvent, EditHistory, GestureId, IconId, Mixed}; @@ -60,14 +68,18 @@ 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, NoValue, Outcome, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked}; -use craft_ui::dialog::{FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, SideFooter}; +use craft_ui::contract::{Bind, 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::runtime::commands::{CommandSet as _, Commands as _}; use craft_ui::runtime::edit::next_gesture_id; use craft_ui::runtime::env::Env; +use craft_ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; use craft_ui::runtime::pending::{Job, Pending}; use craft_ui::runtime::requests::ColorRequest; use craft_ui::runtime::words::CommonWords; @@ -134,6 +146,8 @@ pub struct SelectMaskOpen { pub checkerboard: Checker, /// Preferences › Cursors, which shape the brush outline; Photoshop's by default. pub cursor_options: Option, + /// Where the settings are remembered, when the app asks for it. + pub remember: Option, } impl SelectMaskOpen { @@ -148,16 +162,16 @@ impl SelectMaskOpen { navigation: NavigationOptions::default(), checkerboard: Checker::default(), cursor_options: None, + remember: None, } } - /// Remembers the settings under `key`: the stored settings apply at open only when their Remember Settings flag is - /// on. - // P3(dialogs-w10): dialogs-w41 decision, `SelectMaskOpen::remember` + /// Remembers the settings under `key`: OK stores them, and the stored settings apply at open only when their + /// Remember Settings flag is on (they then replace [`settings`](Self::settings)). #[must_use] - pub fn remember(self, key: craft_ui::runtime::memory::SaveKey) -> Self { - let _ = (self, key); - todo!("dialogs-w10") + pub fn remember(mut self, key: SaveKey) -> Self { + self.remember = Some(key); + self } /// Sets the starting settings. @@ -207,8 +221,8 @@ pub enum SelectMaskEvent { Edit(EditPhase), /// A Refine Edge Brush stroke, the same way. Refine(EditPhase), - /// The Overlay colour swatch was pressed: the app opens its colour picker and answers with - /// [`SelectMaskWorkspace::set_color`]. + /// The Overlay colour swatch was pressed: the app opens its colour picker (the request is keyed + /// [`OVERLAY_COLOR_KEY`]) and answers with [`SelectMaskWorkspace::set_color`]. PickColor(ColorRequest), } @@ -232,28 +246,29 @@ pub enum SelectMaskOp { Refine(RefineStroke), } -/// What [`SelectMaskWorkspace::show`] reports. -#[derive(Debug)] -#[non_exhaustive] -pub struct SelectMaskOutput { - /// What happened this pass, in order. - pub events: Vec, - /// OK (`Accept`) or Cancel, once chosen. - pub closed: Option, - /// The dialog's response: its rect is the workspace's. - pub response: Response, - /// A setting changed this pass. - pub settings_changed: bool, - /// The Overlay colour swatch was pressed: open the app's colour picker with this request - /// (keyed [`OVERLAY_COLOR_KEY`]) and answer with [`SelectMaskWorkspace::set_color`]. - pub pick_color: Option, +/// The stroke being drawn, as the canvas reported it last: what Real-Time Refinement previews. +#[derive(Clone, Debug, PartialEq)] +enum Drawn { + Edit(SelectMaskEdit), + Refine(RefineStroke), } -impl Outcome for SelectMaskOutput { - type Value = NoValue; +/// When a released brush stroke's trail stops showing. +#[derive(Clone, Debug, PartialEq)] +enum TrailSince { + /// A preview under another request key than this one is ready. + Key(String), + /// The first preview that is not running, whatever its key (the request already held the stroke). + NextIdle, +} - fn response(&self) -> &Response { - &self.response +impl TrailSince { + /// Whether a ready preview of the request `key` ends the trail. + fn is_over(&self, key: &str) -> bool { + match self { + TrailSince::Key(since) => since != key, + TrailSince::NextIdle => true, + } } } @@ -293,12 +308,25 @@ pub struct SelectMaskWorkspace { request: Option, /// The key of the request a released brush stroke was made under: the stroke stays drawn until another key's /// preview is ready. - trail_since: Option, + trail_since: Option, /// The zoom on screen at the end of the last pass, for the title. zoom_percent: f64, - /// This pass's events. + /// The events the next pass reports first: what the methods between passes queued, then the pass's own. events: Vec, - pick_color: Option, + /// Edits `perform` recorded between passes: the next pass reports each as a `Set` (its gesture id needs the + /// context). + owed: Vec, + /// The stroke being drawn, while the canvas reports it (`Begin`, `Update`). + drawing: Option, + /// The last pass's preview job was still running. + previewing: bool, + /// The settings as the last pass or method left them: a difference means the app edited them through + /// `settings_mut` or a control request, and the view and the refinement follow. + synced: SelectMaskSettings, + /// Where OK stores the settings. + remember: Option, + /// The stored settings were read (the first pass reads them: the context is not at hand in `new`). + recalled: bool, } impl SelectMaskWorkspace { @@ -314,6 +342,7 @@ impl SelectMaskWorkspace { settled: session.clone(), session, mask_view: open.settings.view_state(), + synced: open.settings.clone(), settings: open.settings, limits: open.limits, target_mask: open.target_mask, @@ -333,7 +362,11 @@ impl SelectMaskWorkspace { trail_since: None, zoom_percent: 100.0, events: Vec::new(), - pick_color: None, + owed: Vec::new(), + drawing: None, + previewing: false, + remember: open.remember, + recalled: false, } } @@ -352,57 +385,77 @@ impl SelectMaskWorkspace { self.canvas.cursor_options(cursor_options); } - /// The settings, for the control requests that change them. + /// The settings, for the control requests that change them. The next pass applies a change to the view and the + /// refinement values; Real-Time Refinement, High Quality Preview and Remember Settings are read where they are. pub fn settings_mut(&mut self) -> &mut SelectMaskSettings { - todo!("dl.K65") + &mut self.settings } - /// Runs `op` as the user would; its events come out of the next pass. `Err` when a limit refuses it. + /// Records `op` in the session as the user would; the next pass reports it as a `Set` event and records the + /// history step. `Err` when a limit refuses it: nothing is recorded and the panel shows the limit. The caller asks + /// for the repaint that runs the next pass (this method has no context). pub fn perform(&mut self, op: SelectMaskOp) -> Result<(), LimitRefused> { - let _ = op; - todo!("dl.K65") + let recorded = match &op { + SelectMaskOp::Edit(edit) => self.session.add_edit(edit.clone(), &self.limits), + SelectMaskOp::Refine(stroke) => self.session.add_stroke(stroke.clone(), &self.limits), + }; + match recorded { + Ok(()) => { + self.error = None; + self.owed.push(op); + self.settle(false); + Ok(()) + } + Err(why) => { + self.error = Some(why); + Err(why) + } + } } - /// Undoes the last edit; its events come out of the next pass. + /// Undoes the last edit, abandoning a stroke still open first. The session changes at once. pub fn undo(&mut self) { - todo!("dl.K65") + self.step(None, Step::Undo); } - /// Redoes the last undone edit; its events come out of the next pass. + /// Redoes the last undone edit, abandoning a stroke still open first. pub fn redo(&mut self) { - todo!("dl.K65") + self.step(None, Step::Redo); } - /// Resets the session; its events come out of the next pass. + /// Resets the session: no edits, no strokes, the default refinement values, as one history step. The app reads the + /// session after the next pass. pub fn reset(&mut self) { - todo!("dl.K65") + self.canvas.drop_polygon(); + self.drawing = None; + self.owed.clear(); + self.session.reset(); + self.error = None; + self.follow_session_refine(); + self.settle(false); } /// Picks the canvas tool. pub fn set_tool(&mut self, tool: SelectMaskTool) { - let _ = tool; - todo!("dl.K65") + self.pick(None, tool); } /// Sets Add or Subtract. pub fn set_mode(&mut self, mode: EditMode) { - let _ = mode; - todo!("dl.K65") + self.options.add = mode == EditMode::Add; } /// Sets Sample All Layers. pub fn set_sample_all_layers(&mut self, on: bool) { - let _ = on; - todo!("dl.K65") + self.options.sample_all_layers = on; } - /// Sets Hide View. + /// Sets Hide View, as X held does. pub fn set_hide_view(&mut self, on: bool) { - let _ = on; - todo!("dl.K65") + self.mask_view.hide_view = on; } - /// The app's colour picker answered a [`SelectMaskOutput::pick_color`] request. A key this + /// The app's colour picker answered a [`SelectMaskEvent::PickColor`] request. A key this /// workspace did not ask for is ignored. pub fn set_color(&mut self, key: &str, color: Srgba) { if key == OVERLAY_COLOR_KEY && self.mask_view.overlay_color != color { @@ -422,15 +475,19 @@ impl SelectMaskWorkspace { /// [`SelectMaskCanvasTool`], the Zoom tool or the canvas's Hand as its tool. Commits from the canvas go through /// [`SelectMaskSession::add_edit`] and [`SelectMaskSession::add_stroke`]; a refusal sets the error and reports /// `Cancel`. Then the history settles (not while the canvas or a slider drags). - pub fn show(&mut self, ui: &mut Ui, source: &dyn SelectMaskSource) -> SelectMaskOutput { + /// + /// The events of the methods that ran between passes come first. A second pass of a frame reports only what its + /// own input did, since the first pass took the frame's steps and commands. OK closes an open polygon first, so the + /// result carries it. + fn pass(&mut self, ui: &mut Ui, source: &dyn SelectMaskSource, open: Bind<'_, bool>) -> WorkspacePass { // pc: crates/ui-egui/src/dialogs/select_mask_ui.rs:1812 `show`, :1375 `keys`, :870 // `enter`, :881 `escape`. let env = Env::of(ui); let words = env.words::(); let common = env.words::(); let title = FullWindowTitle::new(words.name.clone()).subject(self.subject.clone()).zoom(self.zoom_percent).label(&env); - let settings_before = self.settings.clone(); let slots = SelectMaskTool::slots(); + self.begin_pass(ui.ctx()); let request = self.request_now(); let key = format!("{request:?}"); let reset = Cell::new(false); @@ -444,6 +501,7 @@ impl SelectMaskWorkspace { let mut shown = FullWindowDialog::new(title) .command_scope(SelectMaskCommands::SCOPE) + .opened(open) .buttons([FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]) .side_footer(SideFooter::bottom().leading(|ui| { let button = IconButton::new(IconId::new("undo")).label(words.reset.clone()).id_salt("reset").show(ui); @@ -479,7 +537,7 @@ impl SelectMaskWorkspace { // Before the canvas runs: an open stroke is cancelled first, so its Commit never lands on the restored // session. while let Some(step) = cx.take_step(work.history.can_undo(), work.history.can_redo()) { - work.step(&ctx, step); + work.step(Some(&ctx), step); } while let Some((command, _)) = cx.take_command::() { work.view.apply(command); @@ -496,14 +554,18 @@ impl SelectMaskWorkspace { tool_pick(&tools, slot.id, &work.tool, &work.last_used, PickStep::of(&fired), |_| true).map(|entry| (slot.id, entry.id)) }); if let Some((slot_id, tool)) = picked { - work.pick(&ctx, tool); + work.pick(Some(&ctx), tool); work.last_used.set(slot_id, tool); } continue; } - let larger = command == SelectMaskCommands::Larger; - if work.tool.brushes() { - work.options.sizes.step(work.tool, larger); + match command { + SelectMaskCommands::Smaller | SelectMaskCommands::Larger if work.tool.brushes() => { + work.options.sizes.step(work.tool, command == SelectMaskCommands::Larger); + } + // A polygon in progress keeps the mode it started with (`polygon_add`). + SelectMaskCommands::ToggleMode if work.tool.edits() => work.options.add = !work.options.add, + _ => {} } } @@ -529,7 +591,7 @@ impl SelectMaskWorkspace { work.last_used = next; } if let Some(tool) = rail.select { - work.pick(&ctx, tool); + work.pick(Some(&ctx), tool); } let canvas = FullWindowCanvas::new(Bind::bound(&mut work.view), image) .checkerboard(work.checkerboard) @@ -559,17 +621,19 @@ impl SelectMaskWorkspace { // events are recorded. shown.settle(|_, (subject, canvas_id, zoom_percent)| { let work: &mut SelectMaskWorkspace = &mut this.borrow_mut(); - if let Some(status) = side_status.take() - && work.trail_since.as_ref().is_some_and(|since| *since != key) - && !matches!(status, Pending::Loading { .. }) - { - work.canvas.drop_trail(); - work.trail_since = None; + if let Some(status) = side_status.take() { + work.previewing = matches!(status, Pending::Loading { .. }); + if !work.previewing && work.trail_since.as_ref().is_some_and(|since| since.is_over(&key)) { + work.canvas.drop_trail(); + work.trail_since = None; + } } if let Some(open) = side_panel_open.take() { work.panel_open = open; } - work.pick_color = side_pick.take(); + if let Some(request) = side_pick.take() { + work.events.push(SelectMaskEvent::PickColor(request)); + } for edit in [side_edit.take(), subject.take()].into_iter().flatten() { work.absorb_edit(&ctx, edit); } @@ -579,26 +643,65 @@ impl SelectMaskWorkspace { work.settle(work.canvas.busy() || work.panel_open); work.settings.take_view(&work.mask_view); work.settings.refine = work.session.refine.clone(); + work.synced = work.settings.clone(); }); let this = this.into_inner(); - let picked = shown.output.picked.and_then(|at| [DialogRole::Accept, DialogRole::Cancel].get(at).copied()); - let closed = picked.or(shown.output.closed.map(|_| DialogRole::Cancel)); - if closed == Some(DialogRole::Accept) && this.canvas.close_polygon() { - this.absorb_canvas(); - } if reset.get() { - this.canvas.drop_polygon(); - this.session.reset(); - this.error = None; - this.settle(false); + this.reset(); } - SelectMaskOutput { - events: std::mem::take(&mut this.events), - closed, - response: shown.output.response, - settings_changed: this.settings != settings_before, - pick_color: this.pick_color.take(), + let result = shown.output.result(|| { + if this.canvas.close_polygon() { + this.absorb_canvas(); + } + this.done(&ctx) + }); + let events = std::mem::take(&mut this.events); + WorkspacePass::new(shown.output.response, events).result(result) + } + + /// The start of a pass: the first pass reads the stored settings, a change the app made to the settings since the + /// last pass reaches the view and the refinement values, and the edits `perform` recorded are reported. + fn begin_pass(&mut self, ctx: &Context) { + if !std::mem::replace(&mut self.recalled, true) + && let Some(key) = &self.remember + { + let stored: SelectMaskSettings = saved_value(ctx, key); + if stored.remember { + // The stored refinement values are the session's starting point, not a step to undo. + self.settings = stored; + self.session.refine = self.settings.refine.clone(); + self.history = EditHistory::new(&self.session); + self.settled = self.session.clone(); + } } + if self.settings != self.synced { + let hidden = self.mask_view.hide_view; + self.mask_view = self.settings.view_state(); + self.mask_view.hide_view = hidden; + self.session.refine = self.settings.refine.clone(); + self.synced = self.settings.clone(); + } + for op in std::mem::take(&mut self.owed) { + let id = next_gesture_id(ctx); + self.events.push(match op { + SelectMaskOp::Edit(value) => SelectMaskEvent::Edit(EditPhase::Set { id, value }), + SelectMaskOp::Refine(value) => SelectMaskEvent::Refine(EditPhase::Set { id, value }), + }); + } + } + + /// OK's answer; the settings are stored under the key the app gave, if any. + fn done(&self, ctx: &Context) -> SelectMaskDone { + if let Some(key) = &self.remember { + set_saved_value(ctx, key, self.settings.clone()); + } + SelectMaskDone { command: self.command(), settings: self.settings.clone() } + } + + /// Mirrors the session's refinement values into the settings after the session changed outside a pass. + fn follow_session_refine(&mut self) { + self.settings.refine = self.session.refine.clone(); + self.synced.refine = self.settings.refine.clone(); } /// The edits and strokes recorded so far. @@ -624,14 +727,27 @@ impl SelectMaskWorkspace { } impl SelectMaskWorkspace { - /// The request for the preview now: the state as of this pass, or the last idle one while a gesture is open. + /// The request for the preview now: the state as of this pass. With Real-Time Refinement on, a stroke being drawn + /// joins the session of the request, so drawing and idle share one preview path; a request made while the + /// preview of the last one still runs waits for it (the last request stands). With it off, an open stroke holds the + /// last idle request, as does a slider drag. fn request_now(&mut self) -> SelectMaskPreviewRequest { - let busy = self.canvas.busy() || self.panel_open; - if busy && let Some(held) = &self.request { + let drawing = self.drawing.clone().filter(|_| self.settings.real_time); + let hold = match drawing { + Some(_) => self.panel_open || self.previewing, + None => self.canvas.busy() || self.panel_open, + }; + if hold && let Some(held) = &self.request { return held.clone(); } + let mut session = self.session.clone(); + match drawing { + Some(Drawn::Edit(edit)) => session.edits.push(edit), + Some(Drawn::Refine(stroke)) => session.strokes.push(stroke), + None => {} + } let request = SelectMaskPreviewRequest { - session: self.session.clone(), + session, recipe: MaskViewRecipe { hidden: false, ..self.mask_view.recipe() }, high_quality: self.settings.high_quality, sample_all_layers: self.options.sample_all_layers, @@ -651,19 +767,19 @@ impl SelectMaskWorkspace { } /// Undoes or redoes, cancelling an open stroke (`UndoDuringGesture`) and dropping an open polygon first. - fn step(&mut self, ctx: &egui::Context, step: Step) { + fn step(&mut self, ctx: Option<&Context>, step: Step) { // pc: crates/ui-egui/src/dialogs/select_mask_ui.rs:644 `undo`, :672 `redo`. self.cancel_gesture(ctx, CancelReason::UndoDuringGesture); self.canvas.drop_polygon(); if self.history.step(&mut self.session, step) { self.error = None; - self.settings.refine = self.session.refine.clone(); + self.follow_session_refine(); self.settled = self.session.clone(); } } /// Records a button's edit (Select Subject, Clear Selection, Invert) as a `Set`. - fn absorb_edit(&mut self, ctx: &egui::Context, edit: SelectMaskEdit) { + fn absorb_edit(&mut self, ctx: &Context, edit: SelectMaskEdit) { match self.session.add_edit(edit.clone(), &self.limits) { Ok(()) => { self.error = None; @@ -678,6 +794,7 @@ impl SelectMaskWorkspace { /// shows under the panel, and the event becomes a `Cancel`). fn absorb_canvas(&mut self) { for event in self.canvas.take_events() { + self.track_drawing(&event); let event = match event { SelectMaskEvent::Edit(EditPhase::Commit { id, value }) => { let recorded = self.session.add_edit(value.clone(), &self.limits).map_err(|why| self.error = Some(why)).is_ok(); @@ -693,12 +810,31 @@ impl SelectMaskWorkspace { } } - /// `Commit` when it was recorded, else the refusal as a `Cancel`. + /// Keeps the stroke being drawn for Real-Time Refinement's request: what `Begin` and `Update` carry, until the + /// gesture ends. + fn track_drawing(&mut self, event: &SelectMaskEvent) { + match event { + SelectMaskEvent::Edit(EditPhase::Begin { value, .. }) => self.drawing = value.clone().map(Drawn::Edit), + SelectMaskEvent::Edit(EditPhase::Update { value, .. }) => self.drawing = Some(Drawn::Edit(value.clone())), + SelectMaskEvent::Refine(EditPhase::Begin { value, .. }) => self.drawing = value.clone().map(Drawn::Refine), + SelectMaskEvent::Refine(EditPhase::Update { value, .. }) => self.drawing = Some(Drawn::Refine(value.clone())), + SelectMaskEvent::Edit(_) | SelectMaskEvent::Refine(_) => self.drawing = None, + SelectMaskEvent::PickColor(_) => {} + } + } + + /// `Commit` when it was recorded, else the refusal as a `Cancel`. The stroke stays drawn until the preview of the + /// session that holds it is ready: with Real-Time Refinement on, the request already held the stroke, so the + /// trail waits for the first preview that is not running, whatever its key. fn settle_event(&mut self, recorded: bool, id: GestureId, value: T) -> EditPhase { if recorded { self.error = None; if self.canvas.trail_shown() { - self.trail_since = self.request.as_ref().map(|request| format!("{request:?}")); + self.trail_since = if self.settings.real_time { + Some(TrailSince::NextIdle) + } else { + self.request.as_ref().map(|request| TrailSince::Key(format!("{request:?}"))) + }; } EditPhase::Commit { id, value } } else { @@ -707,11 +843,12 @@ impl SelectMaskWorkspace { } /// Cancels the gesture the current tool holds (a brush stroke, an outline, a resize or a Zoom drag) through the - /// host, and the tool's own state if the host held none. - fn cancel_gesture(&mut self, ctx: &egui::Context, reason: CancelReason) { + /// host, and the tool's own state if the host held none. Without a context (a request between passes) only the + /// tool's own state is dropped. + fn cancel_gesture(&mut self, ctx: Option<&Context>, reason: CancelReason) { let tool = self.tool; let real_time = self.settings.real_time; - if let Some(id) = self.canvas_id { + if let (Some(ctx), Some(id)) = (ctx, self.canvas_id) { match tool { SelectMaskTool::Hand => false, SelectMaskTool::Zoom => ToolHost::cancel(ctx, id, &mut self.zoom_tool, reason), @@ -725,7 +862,7 @@ impl SelectMaskWorkspace { } /// Switches to `tool`, cancelling the old tool's gesture and dropping an open polygon first. - fn pick(&mut self, ctx: &egui::Context, tool: SelectMaskTool) { + fn pick(&mut self, ctx: Option<&Context>, tool: SelectMaskTool) { if tool != self.tool { self.cancel_gesture(ctx, CancelReason::Removed); self.canvas.drop_polygon(); @@ -737,34 +874,118 @@ impl SelectMaskWorkspace { /// The name the history gives its steps. const HISTORY_NAME: &str = "Select and Mask"; -// P3(dialogs-w10): dl.K65 — the workspace's trait surface; `show` and the automation fields are written in phase 3. -impl craft_ui::dialog::FullWindowWorkspace for SelectMaskWorkspace { +/// The name the automation surface gives `tool`. +fn tool_key(tool: SelectMaskTool) -> &'static str { + match tool { + SelectMaskTool::Quick => "quick", + SelectMaskTool::RefineEdge => "refineEdge", + SelectMaskTool::Brush => "brush", + SelectMaskTool::Object => "object", + SelectMaskTool::Lasso => "lasso", + SelectMaskTool::PolygonalLasso => "polygonalLasso", + SelectMaskTool::Hand => "hand", + SelectMaskTool::Zoom => "zoom", + } +} + +/// The value of the `stroke` action key. +#[derive(Deserialize)] +struct StrokeArg { + points: Vec<[f64; 2]>, + #[serde(default)] + alt: bool, +} + +/// The workspace on the app's dialog host. OK answers at once with the command and the settings. +impl FullWindowWorkspace for SelectMaskWorkspace { type Source = dyn SelectMaskSource; type Event = SelectMaskEvent; type Result = SelectMaskDone; const KEY: &'static str = "select.selectAndMask"; - fn show( - &mut self, - ui: &mut egui::Ui, - cx: craft_ui::dialog::WorkspaceCx<'_, Self::Source>, - ) -> craft_ui::dialog::WorkspacePass { - let _ = (ui, cx); - todo!("dl.K65") + fn show(&mut self, ui: &mut Ui, cx: WorkspaceCx<'_, Self::Source>) -> WorkspacePass { + let WorkspaceCx { source, open, .. } = cx; + self.pass(ui, source, open) } + /// The settings, and the bar's `tool`, `mode` (`"add"`, `"subtract"`), `size` (of the current tool), `hardness`, + /// `sampleAllLayers`, and `hideView`. fn json_fields(&self) -> Option { - todo!("dl.K65") + let mut fields = serde_fields(&self.settings)?; + let bar = fields.as_object_mut()?; + let mode = if self.options.add { "add" } else { "subtract" }; + bar.insert("tool".to_owned(), tool_key(self.tool).into()); + bar.insert("mode".to_owned(), mode.into()); + bar.insert("size".to_owned(), self.options.sizes.get(self.tool).into()); + bar.insert("hardness".to_owned(), self.options.hardness.into()); + bar.insert("sampleAllLayers".to_owned(), self.options.sample_all_layers.into()); + bar.insert("hideView".to_owned(), self.mask_view.hide_view.into()); + Some(fields) } - fn set_json_field(&mut self, ctx: &egui::Context, source: &Self::Source, field: &str, value: serde_json::Value) -> Result<(), String> { - let _ = (ctx, source, field, value); - todo!("dl.K65") + /// A settings key, a bar key of [`json_fields`](Self::json_fields), or an action: `stroke` (`{points, alt?}`: the + /// current tool's edit, with Alt flipping the mode), `selectSubject`, `clearSelection`, `invert`, `reset`, `undo` + /// and `redo` (each `true`). An edit goes through the limits like the canvas's; one a limit refuses is rejected + /// and the panel shows the limit. + fn set_json_field(&mut self, ctx: &Context, _source: &Self::Source, field: &str, value: serde_json::Value) -> Result<(), String> { + let rejects = |value: &serde_json::Value| FieldRefusal::Rejects(value).message(field); + let on = value == serde_json::Value::Bool(true); + match field { + "tool" => { + let tool = value.as_str().and_then(|key| SelectMaskTool::ALL.into_iter().find(|tool| tool_key(*tool) == key)); + self.pick(Some(ctx), tool.ok_or_else(|| rejects(&value))?); + } + "mode" => self.set_mode(serde_json::from_value::(value.clone()).map_err(|_| rejects(&value))?), + "size" => self.options.sizes.set(self.tool, value.as_f64().ok_or_else(|| rejects(&value))?), + "hardness" => self.options.hardness = value.as_f64().ok_or_else(|| rejects(&value))?.clamp(0.0, 100.0), + "sampleAllLayers" => self.set_sample_all_layers(value.as_bool().ok_or_else(|| rejects(&value))?), + "hideView" => self.set_hide_view(value.as_bool().ok_or_else(|| rejects(&value))?), + "stroke" => { + let arg = serde_json::from_value::(value.clone()).map_err(|_| rejects(&value))?; + if arg.points.is_empty() || !arg.points.iter().flatten().all(|coordinate| coordinate.is_finite()) { + return Err(rejects(&value)); + } + let points: Vec<[f64; 2]> = arg.points.into_iter().map(round_point).collect(); + let mode = if self.options.add != arg.alt { EditMode::Add } else { EditMode::Subtract }; + let (sizes, sample_all_layers) = (self.options.sizes, self.options.sample_all_layers); + let op = match self.tool { + SelectMaskTool::Quick => SelectMaskOp::Edit(SelectMaskEdit::quick(points, sizes.quick, mode, sample_all_layers)), + SelectMaskTool::Brush => SelectMaskOp::Edit(SelectMaskEdit::brush(points, sizes.brush, self.options.hardness, mode)), + SelectMaskTool::Lasso | SelectMaskTool::PolygonalLasso if points.len() >= 3 => { + SelectMaskOp::Edit(SelectMaskEdit::lasso(points, mode)) + } + SelectMaskTool::RefineEdge => SelectMaskOp::Refine(RefineStroke::new(points, sizes.refine, mode)), + _ => return Err(rejects(&value)), + }; + self.perform(op).map_err(|why| why.message(&Env::of_root(ctx)))?; + } + "selectSubject" | "clearSelection" | "invert" | "reset" | "undo" | "redo" => { + if !on { + return Err(rejects(&value)); + } + let edit = match field { + "selectSubject" => Some(SelectMaskEdit::subject(self.options.sample_all_layers)), + "clearSelection" => Some(SelectMaskEdit::Clear), + "invert" => Some(SelectMaskEdit::Invert), + _ => None, + }; + match (edit, field) { + (Some(edit), _) => self.perform(SelectMaskOp::Edit(edit)).map_err(|why| why.message(&Env::of_root(ctx)))?, + (None, "reset") => self.reset(), + (None, "undo") => self.undo(), + (None, _) => self.redo(), + } + } + _ => set_serde_field(&mut self.settings, field, value)?, + } + Ok(()) } - fn confirm(&mut self, ctx: &egui::Context, source: &Self::Source) -> Option { - let _ = (ctx, source); - todo!("dl.K65") + fn confirm(&mut self, ctx: &Context, _source: &Self::Source) -> Option { + if self.canvas.close_polygon() { + self.absorb_canvas(); + } + Some(self.done(ctx)) } } diff --git a/crates/imaging/src/ui/select_mask/stories.rs b/crates/imaging/src/ui/select_mask/stories.rs index a825bfa07..40a341d2b 100644 --- a/crates/imaging/src/ui/select_mask/stories.rs +++ b/crates/imaging/src/ui/select_mask/stories.rs @@ -4,12 +4,14 @@ //! engine's composite is the app's), the house is the refined selection. The stroke trail, the open polygon, the //! brush outline and the Alt + right-drag resize are the pointer's: draw on the picture to see them. -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::Arc; use std::time::Duration; use egui::Ui; use craft_ui::canvas::RasterSource; +use craft_ui::dialog::HostedWorkspace; +use craft_ui::dialog::stories::hosted; use craft_ui::runtime::pending::Job; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; @@ -63,24 +65,16 @@ impl SelectMaskSource for StorySource { } } -/// The workspace a story keeps between passes, compared by identity. -#[derive(Clone)] -struct Kept(Arc>); - -impl PartialEq for Kept { - fn eq(&self, other: &Self) -> bool { - Arc::ptr_eq(&self.0, &other.0) - } -} - -/// Shows the workspace over the mock picture with `settings`; `loading` leaves the preview unfinished. +/// Shows the workspace over the mock picture with `settings`; `loading` leaves the preview unfinished. It runs on the +/// story's dialog host with the open flag the story keeps. fn show_workspace(ui: &mut Ui, data: &mut StoryData, settings: SelectMaskSettings, loading: bool) -> StoryOutput { - let image = MockImage::default(); - let size = image.size(); - let open = SelectMaskOpen::new([size.width, size.height], "House", LIMITS).settings(settings); - let kept = data.value("workspace", Kept(Arc::new(Mutex::new(SelectMaskWorkspace::new(open))))).clone(); - let mut workspace = kept.0.lock().unwrap_or_else(PoisonError::into_inner); - workspace.show(ui, &StorySource { image, subject: MockSubject(image), loading }).into() + // A pass's `WorkspaceCx` is built by the host only, so this runs the workspace on a `DialogHost`. + hosted(ui, data, (settings.clone(), loading), || { + let image = MockImage::default(); + let size = image.size(); + let open = SelectMaskOpen::new([size.width, size.height], "House", LIMITS).settings(settings); + HostedWorkspace::new(SelectMaskWorkspace::new(open), Arc::new(StorySource { image, subject: MockSubject(image), loading })) + }) } fn viewing(view: MaskViewMode) -> SelectMaskSettings { diff --git a/crates/imaging/tests/it/fill.rs b/crates/imaging/tests/it/fill.rs index df184769b..83cea8672 100644 --- a/crates/imaging/tests/it/fill.rs +++ b/crates/imaging/tests/it/fill.rs @@ -2,6 +2,7 @@ use std::cell::RefCell; use std::rc::Rc; +use std::sync::Arc; use egui::{Color32, ColorImage, Modifiers, Pos2, vec2}; @@ -9,12 +10,13 @@ use craft_behavior::PixelSize; use craft_behavior::geometry::selection_op::SelectionOperation; use craft_behavior::kurbo::Rect; use craft_imaging::ui::fill::{ - ContentAwareFillWorkspace, FillAreaEdit, FillEvent, FillLimit, FillLimits, FillOpen, FillOutput, FillOverlay, FillPreviewRequest, FillSession, - FillSettings, FillSource, FillStrokeEvent, SamplingPlane, SamplingStroke, + ContentAwareFillWorkspace, FillAreaEdit, FillEvent, FillLimit, FillLimits, FillOpen, FillOverlay, FillPreviewRequest, FillSession, FillSettings, + FillSource, FillStrokeEvent, SamplingPlane, SamplingStroke, }; use craft_imaging::ui::select_mask::EditMode; use craft_imaging::ui::wide_angle::PreviewDone; use craft_ui::canvas::{PixelRect, RasterSource}; +use craft_ui::dialog::{DialogHost, DialogResult, HostedWorkspace}; use craft_ui::primitives::Revision; use craft_ui::runtime::access::Role; use craft_ui::runtime::pending::Job; @@ -79,25 +81,35 @@ impl FillSource for Source { } } -/// The workspace shown in a fixture, with every pass's output kept. +/// The hosted workspace. +type Hosted = HostedWorkspace; + +/// The workspace on a dialog host shown in a fixture, with every pass's events kept. +// A pass's `WorkspaceCx` is built by the host only, so this runs the workspace on a `DialogHost`. struct Rig { fixture: Fixture, - outputs: Rc>>, + host: Rc>, + events: Rc>>, } impl Rig { fn new(settings: FillSettings, limits: FillLimits) -> Rig { let open = FillOpen::new([LAYER.width, LAYER.height], "Layer 1", limits).settings(settings); - let work = Rc::new(RefCell::new(ContentAwareFillWorkspace::new(open))); - let outputs = Rc::new(RefCell::new(Vec::new())); - let (shown, kept) = (Rc::clone(&work), Rc::clone(&outputs)); + let source: Arc = Arc::new(Source); + let mut host = DialogHost::new(); + host.open(HostedWorkspace::new(ContentAwareFillWorkspace::new(open), source)); + let host = Rc::new(RefCell::new(host)); + let events = Rc::new(RefCell::new(Vec::new())); + let (shown, kept) = (Rc::clone(&host), Rc::clone(&events)); let mut fixture = Fixture::new(move |ui| { - let output = shown.borrow_mut().show(ui, &Source); - kept.borrow_mut().push(output); + let mut host = shown.borrow_mut(); + host.run(ui); + let taken = host.get_mut::().map(Hosted::take_events).unwrap_or_default(); + kept.borrow_mut().extend(taken); }); fixture.room(ROOM).settle(); - let rig = Rig { fixture, outputs }; - rig.take(); + let rig = Rig { fixture, host, events }; + rig.events(); rig } @@ -106,14 +118,15 @@ impl Rig { self.fixture.by_role(Role::CANVAS).into_iter().next().expect("the workspace shows a canvas").center() } - /// The outputs since the last call. - fn take(&self) -> Vec { - std::mem::take(&mut *self.outputs.borrow_mut()) - } - /// The events since the last call. fn events(&self) -> Vec { - self.take().into_iter().flat_map(|output| output.events).collect() + std::mem::take(&mut *self.events.borrow_mut()) + } + + /// Runs `answer` on the workspace, as the app does between passes. + fn with(&self, answer: impl FnOnce(&mut ContentAwareFillWorkspace) -> R) -> R { + let mut host = self.host.borrow_mut(); + answer(host.get_mut::().expect("the workspace is open").workspace_mut()) } /// Presses at `from`, moves through `through` and releases at the last point, with `modifiers` held. @@ -191,6 +204,45 @@ fn fill_limits_refuse_at_the_brush() { assert_eq!(committed(&events).map(|stroke| stroke.points.len()), Some(3)); } +// The Apply button reports one `Apply` and the workspace stays open; the app's answer shows its message or clears the +// history; OK is not held by it. A change made between passes is reported once, however many passes the frames run. +#[trial] +fn answer_apply_answers_the_apply_button() { + let mut rig = Rig::new(FillSettings::default(), FillLimits::new(10, 1000)); + rig.line(2); + rig.events(); + + let apply = rig.fixture.by_label("Apply").expect("the footer has Apply"); + rig.fixture.click(&apply); + let events = rig.events(); + let applied: Vec<_> = events.iter().filter_map(|event| if let FillEvent::Apply(command) = event { Some(command) } else { None }).collect(); + assert_eq!(applied.len(), 1, "{events:?}"); + assert_eq!(applied[0].strokes.len(), 1, "the command carries the stroke"); + assert!(rig.host.borrow().is_open::(), "Apply keeps the workspace open"); + + rig.with(|work| work.answer_apply(Err("the fill failed".to_owned()))); + rig.fixture.idle(2); + assert!(rig.fixture.by_label("the fill failed").is_some(), "the message shows under the panel"); + + rig.with(|work| { + work.answer_apply(Ok(())); + work.undo(); + assert_eq!(work.session().strokes.len(), 1, "an applied fill is one document step: undo cannot take the stroke back"); + }); + rig.fixture.idle(2); + assert!(rig.fixture.by_label("the fill failed").is_none(), "the answer clears the message"); + + rig.with(|work| work.settings_mut().opacity = 10.0); + rig.fixture.idle(3); + let changed = rig.events().into_iter().filter(|event| matches!(event, FillEvent::SettingsChanged(settings) if settings.opacity == 10.0)).count(); + assert_eq!(changed, 1, "a change between passes is reported once"); + + let ok = rig.fixture.by_label("OK").expect("the footer has OK"); + rig.fixture.click(&ok); + let result = rig.host.borrow_mut().take::(); + assert!(matches!(result, Some(DialogResult::Ok(command)) if command.strokes.len() == 1), "OK answers the command"); +} + #[trial] fn fill_overlay_tints_the_sampling_area_or_the_excluded_area() { // A 4 by 1 plane of one-pixel cells: sampled, sampled, not sampled, sampled. diff --git a/crates/imaging/tests/it/liquify.rs b/crates/imaging/tests/it/liquify.rs index 665899cc5..7b1ab3524 100644 --- a/crates/imaging/tests/it/liquify.rs +++ b/crates/imaging/tests/it/liquify.rs @@ -2,12 +2,14 @@ use std::cell::RefCell; use std::rc::Rc; +use std::sync::Arc; use craft_behavior::{CancelReason, PixelSize}; use craft_imaging::ui::liquify::{ LiquifyBrush, LiquifyEvent, LiquifyMesh, LiquifyOpen, LiquifySource, LiquifyTool, LiquifyWorkspace, MeshSize, StrokeEvent, StrokeRecorder, }; use craft_ui::canvas::{PixelRect, RasterSource}; +use craft_ui::dialog::{DialogHost, HostedWorkspace}; use craft_ui::primitives::Revision; use craft_ui::runtime::access::Role; use craft_ui::testing::input::key_press; @@ -68,27 +70,33 @@ impl LiquifySource for Source { } } -/// What the app keeps of the workspace and what it saw. +/// What the app keeps: the dialog host that owns the workspace, and the events it took from it. struct App { - workspace: LiquifyWorkspace, - source: Source, + host: DialogHost, events: Vec, } +impl App { + /// The hosted workspace. + fn hosted(&self) -> &HostedWorkspace { + self.host.get::>().expect("the workspace is open") + } +} + /// The workspace over a solid picture, settled. +// A pass's `WorkspaceCx` is built by the host only, so this runs the workspace on a `DialogHost`. fn open() -> (Fixture, Rc>) { let size = PixelSize::new(DOCUMENT[0], DOCUMENT[1]); - let app = Rc::new(RefCell::new(App { - workspace: LiquifyWorkspace::new(LiquifyOpen::new(DOCUMENT, "Photo")), - source: Source { image: Solid { size, colour: Color32::from_rgb(40, 120, 200) } }, - events: Vec::new(), - })); + let source: Arc = Arc::new(Source { image: Solid { size, colour: Color32::from_rgb(40, 120, 200) } }); + let mut host = DialogHost::new(); + host.open(HostedWorkspace::new(LiquifyWorkspace::new(LiquifyOpen::new(DOCUMENT, "Photo")), source)); + let app = Rc::new(RefCell::new(App { host, events: Vec::new() })); let shown = Rc::clone(&app); let mut fixture = Fixture::new(move |ui| { let mut app = shown.borrow_mut(); - let App { workspace, source, .. } = &mut *app; - let out = workspace.show(ui, source); - app.events.extend(out.events); + app.host.run(ui); + let taken = app.host.get_mut::>().map(HostedWorkspace::take_events).unwrap_or_default(); + app.events.extend(taken); }); fixture.room(by(1000.0, 900.0)); fixture.settle(); @@ -132,7 +140,7 @@ fn liquify_undo_mid_stroke_cancels_the_stroke_then_steps() { let (mut fixture, app) = open(); let left = canvas_point(&fixture, by(-40.0, 0.0)); drag(&mut fixture, primary, left, left + by(80.0, 10.0)); - assert_eq!(app.borrow().workspace.session().len(), 1); + assert_eq!(app.borrow().hosted().workspace().session().len(), 1); let below = canvas_point(&fixture, by(0.0, 40.0)); open_stroke(&mut fixture, below); app.borrow_mut().events.clear(); @@ -146,7 +154,7 @@ fn liquify_undo_mid_stroke_cancels_the_stroke_then_steps() { ), "{events:?}" ); - assert!(app.borrow().workspace.session().is_empty(), "the earlier stroke is undone"); + assert!(app.borrow().hosted().workspace().session().is_empty(), "the earlier stroke is undone"); } // A press, two drags and a release report Begin, Update, Update, Commit; each Update carries only its new point and @@ -185,4 +193,22 @@ fn liquify_stroke_events_begin_update_commit_and_short_strokes_are_recorded_whol // A closed Freeze Lasso records one stroke with amount 1 (0 with Alt at the press) and the first point again at its // end; fewer than 3 points record nothing. +// The P key and the footer's Preview box each toggle the preview and report one `Preview` event. +#[trial] +fn liquify_preview_key_and_box_each_toggle_the_preview_once() { + let (mut fixture, app) = open(); + assert!(app.borrow().hosted().workspace().preview(), "the preview is on at each opening"); + app.borrow_mut().events.clear(); + + fixture.frame(vec![key_press(Key::P, Modifiers::NONE)]); + assert!(!app.borrow().hosted().workspace().preview()); + assert!(matches!(app.borrow().events.as_slice(), [LiquifyEvent::Preview(false)]), "{:?}", app.borrow().events); + + app.borrow_mut().events.clear(); + let target = fixture.by_label("Preview").expect("the Preview box is in the footer"); + fixture.click(&target); + assert!(app.borrow().hosted().workspace().preview()); + assert!(matches!(app.borrow().events.as_slice(), [LiquifyEvent::Preview(true)]), "{:?}", app.borrow().events); +} + // Cmd+I and Cmd+D record the global step in the order pressed; Restore All empties the session. diff --git a/crates/imaging/tests/it/select_mask.rs b/crates/imaging/tests/it/select_mask.rs index e994a4f46..66fce98b3 100644 --- a/crates/imaging/tests/it/select_mask.rs +++ b/crates/imaging/tests/it/select_mask.rs @@ -11,10 +11,12 @@ use craft_host::{AppInfo, Host, InlineJobs}; use craft_imaging::trace::MaskSource; use craft_imaging::ui::mask_view::MaskViewMode; use craft_imaging::ui::select_mask::{ - SelectMaskEvent, SelectMaskLimits, SelectMaskOpen, SelectMaskPreviewRequest, SelectMaskSource, SelectMaskWorkspace, + EditMode, LimitRefused, RefineStroke, SelectMaskEdit, SelectMaskEvent, SelectMaskLimits, SelectMaskOp, SelectMaskOpen, SelectMaskPreviewRequest, + SelectMaskSession, SelectMaskSource, SelectMaskWorkspace, }; use craft_imaging::ui::wide_angle::PreviewDone; use craft_ui::canvas::{PixelRect, RasterSource}; +use craft_ui::dialog::{DialogHost, HostedWorkspace}; use craft_ui::primitives::Revision; use craft_ui::runtime::access::Role; use craft_ui::runtime::pending::Job; @@ -79,28 +81,34 @@ impl SelectMaskSource for Source { } } -/// What the app keeps of the workspace and what it saw. +/// What the app keeps: the dialog host that owns the workspace, and the events it took from it. struct App { - workspace: SelectMaskWorkspace, - source: Source, + host: DialogHost, events: Vec, } +impl App { + /// The hosted workspace. + fn hosted(&self) -> &HostedWorkspace { + self.host.get::>().expect("the workspace is open") + } +} + /// The workspace over a solid picture, settled. +// A pass's `WorkspaceCx` is built by the host only, so this runs the workspace on a `DialogHost`. fn open() -> (Fixture, Rc>, Arc) { let jobs = Arc::new(AtomicUsize::new(0)); let size = PixelSize::new(DOCUMENT[0], DOCUMENT[1]); - let app = Rc::new(RefCell::new(App { - workspace: SelectMaskWorkspace::new(SelectMaskOpen::new(DOCUMENT, "Photo", LIMITS)), - source: Source { image: Solid { size }, jobs: Arc::clone(&jobs) }, - events: Vec::new(), - })); + let source: Arc = Arc::new(Source { image: Solid { size }, jobs: Arc::clone(&jobs) }); + let mut host = DialogHost::new(); + host.open(HostedWorkspace::new(SelectMaskWorkspace::new(SelectMaskOpen::new(DOCUMENT, "Photo", LIMITS)), source)); + let app = Rc::new(RefCell::new(App { host, events: Vec::new() })); let shown = Rc::clone(&app); let mut fixture = Fixture::new(move |ui| { let mut app = shown.borrow_mut(); - let App { workspace, source, .. } = &mut *app; - let out = workspace.show(ui, source); - app.events.extend(out.events); + app.host.run(ui); + let taken = app.host.get_mut::>().map(HostedWorkspace::take_events).unwrap_or_default(); + app.events.extend(taken); }); fixture.host(Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).jobs(Arc::new(InlineJobs)).build())); fixture.room(Vec2::new(1200.0, 900.0)); @@ -138,12 +146,47 @@ fn select_mask_view_keys_pick_the_view_and_x_held_hides_it() { let (mut fixture, app, _) = open(); fixture.key(Key::Tab, Modifiers::NONE).settle(); fixture.key(Key::K, Modifiers::NONE).settle(); - assert_eq!(app.borrow().workspace.recipe().mode, MaskViewMode::BlackAndWhite); + assert_eq!(app.borrow().hosted().workspace().recipe().mode, MaskViewMode::BlackAndWhite); fixture.frame(vec![key_press(Key::X, Modifiers::NONE)]); fixture.settle(); - assert!(app.borrow().workspace.recipe().hidden, "X held hides the view"); + assert!(app.borrow().hosted().workspace().recipe().hidden, "X held hides the view"); fixture.frame(vec![key_release(Key::X, Modifiers::NONE)]); fixture.settle(); - assert!(!app.borrow().workspace.recipe().hidden, "the release shows it again"); + assert!(!app.borrow().hosted().workspace().recipe().hidden, "the release shows it again"); +} + +// The limits count edits and points over the whole session: a total equal to a limit passes, an edit past it is +// refused with the limit's number and records nothing, and `perform` gives the same refusal. +#[trial] +fn select_mask_limits_refuse_at_the_brush() { + let lasso = |points: usize| SelectMaskEdit::lasso(vec![[1.0, 2.0]; points], EditMode::Add); + let refine = |points: usize| RefineStroke::new(vec![[1.0, 2.0]; points], 20.0, EditMode::Add); + + let mut session = SelectMaskSession::default(); + for _ in 0..3 { + assert_eq!(session.add_edit(lasso(1), &LIMITS), Ok(())); + } + assert_eq!(session.add_edit(lasso(1), &LIMITS), Err(LimitRefused::Edits(3)), "three edits are the limit"); + assert_eq!(session.edits.len(), 3, "a refused edit records nothing"); + + let mut session = SelectMaskSession::default(); + assert_eq!(session.add_edit(lasso(6), &LIMITS), Ok(())); + assert_eq!(session.add_edit(lasso(5), &LIMITS), Err(LimitRefused::EditPoints(10)), "6 and 5 points pass the 10-point limit"); + assert_eq!(session.edits.len(), 1); + assert_eq!(session.add_edit(lasso(4), &LIMITS), Ok(()), "a total equal to the limit passes"); + + let mut session = SelectMaskSession::default(); + assert_eq!(session.add_stroke(refine(3), &LIMITS), Ok(())); + assert_eq!(session.add_stroke(refine(2), &LIMITS), Err(LimitRefused::StrokePoints(4))); + assert_eq!(session.strokes.len(), 1, "a refused stroke records nothing"); + assert_eq!(session.add_stroke(refine(1), &LIMITS), Ok(())); + assert_eq!(session.add_stroke(refine(0), &LIMITS), Err(LimitRefused::Strokes(2)), "two strokes are the limit"); + + let mut workspace = SelectMaskWorkspace::new(SelectMaskOpen::new(DOCUMENT, "Photo", LIMITS)); + for _ in 0..3 { + assert_eq!(workspace.perform(SelectMaskOp::Edit(lasso(1))), Ok(())); + } + assert_eq!(workspace.perform(SelectMaskOp::Edit(lasso(1))), Err(LimitRefused::Edits(3))); + assert_eq!(workspace.session().edits.len(), 3, "a refused request records nothing"); } diff --git a/migration/api-map/imaging-filter-gallery.toml b/migration/api-map/imaging-filter-gallery.toml index 35f86f147..672f4b0f1 100644 --- a/migration/api-map/imaging-filter-gallery.toml +++ b/migration/api-map/imaging-filter-gallery.toml @@ -25,9 +25,9 @@ status = "same" [[type]] name = "FilterGalleryOutput" old = "craft_imaging::ui::filter_gallery::FilterGalleryOutput" -new = "craft_imaging::ui::filter_gallery::FilterGalleryOutput" -status = "replaced" -note = "`preview_wanted`, `outcome` and `rect` are removed: the preview is requested through `FilterGallerySource::render`, and the dialog's result is `dialog: DialogOutput` (`accepted()` for OK)." +new = "" +status = "removed" +note = "Removed: a pass returns `WorkspacePass`; its `events`, `response` and `result` replace the output's fields, and the preview is requested through `FilterGallerySource::render`." [[type]] name = "FilterGallerySession" diff --git a/migration/api-map/imaging-liquify.toml b/migration/api-map/imaging-liquify.toml index 571b265b1..25842305f 100644 --- a/migration/api-map/imaging-liquify.toml +++ b/migration/api-map/imaging-liquify.toml @@ -75,9 +75,9 @@ note = "`Stroke` carries a `StrokeEvent` (`Begin`, `Update`, `Commit` with the s [[type]] name = "LiquifyOutput" old = "craft_imaging::ui::liquify::LiquifyOutput" -new = "craft_imaging::ui::liquify::LiquifyOutput" -status = "replaced" -note = "`closed: Option` replaces `outcome`, `response` replaces `rect`, and `cursor` is new." +new = "" +status = "removed" +note = "Removed: a pass returns `WorkspacePass`; its `events`, `response` and `result` replace the output's fields, and `LiquifyWorkspace::cursor` and `timing` give the cursor and the stroke timing." [[type]] name = "LiquifyOpen" diff --git a/migration/api-map/imaging-wide-angle.toml b/migration/api-map/imaging-wide-angle.toml index fdd37368c..787a8d4e5 100644 --- a/migration/api-map/imaging-wide-angle.toml +++ b/migration/api-map/imaging-wide-angle.toml @@ -13,9 +13,9 @@ note = "`show(ui, geometry, source)` takes the `Ui` and returns the output with [[type]] name = "WideAngleOutput" old = "craft_imaging::ui::wide_angle::WideAngleOutput" -new = "craft_imaging::ui::wide_angle::WideAngleOutput" -status = "replaced" -note = "`preview_wanted` and `outcome` are removed; `closed` and `accepted()` say how the dialog closed, `timing` is the finished job's." +new = "" +status = "removed" +note = "Removed: a pass returns `WorkspacePass`; its `events`, `response` and `result` replace the output's fields." [[type]] name = "WideAngleSource" diff --git a/migration/api-map/imaging-workspaces.toml b/migration/api-map/imaging-workspaces.toml index cff625e2e..dbb0bd657 100644 --- a/migration/api-map/imaging-workspaces.toml +++ b/migration/api-map/imaging-workspaces.toml @@ -136,9 +136,9 @@ note = "`Edit` and `Refine` carry an `EditPhase` (Begin, Update, Commit, Canc [[type]] name = "SelectMaskOutput" old = "craft_imaging::ui::select_mask::SelectMaskOutput" -new = "craft_imaging::ui::select_mask::SelectMaskOutput" -status = "replaced" -note = "`closed: Option` replaces `outcome`; `response` replaces `rect`; `preview_wanted` is gone (the workspace asks for the preview itself through `preview_job`)." +new = "" +status = "removed" +note = "Removed: a pass returns `WorkspacePass`; its `events`, `response` and `result` replace the output's fields, and the workspace asks for the preview itself through `preview_job`." [[type]] name = "SelectMaskWorkspace" @@ -388,8 +388,9 @@ status = "same" [[type]] name = "FillOutput" old = "craft_imaging::ui::fill::FillOutput" -new = "craft_imaging::ui::fill::FillOutput" -status = "same" +new = "" +status = "removed" +note = "Removed: a pass returns `WorkspacePass`; its `events` (`Apply`, `PickColor`, `SettingsChanged`), `response` and `result` replace the output's fields." [[type]] name = "FillLabels" @@ -498,9 +499,9 @@ note = "Loses `cursor_options`; `checkerboard` is a `craft_ui::primitives::Check [[type]] name = "VanishingPointOutput" old = "craft_imaging::ui::vanishing_point::VanishingPointOutput" -new = "craft_imaging::ui::vanishing_point::VanishingPointOutput" -status = "replaced" -note = "`closed` replaces `outcome`, `response` replaces `rect`; `preview_wanted` is gone (the workspace starts the preview job itself)." +new = "" +status = "removed" +note = "Removed: a pass returns `WorkspacePass`; its `events`, `response` and `result` replace the output's fields, and the workspace starts the preview job itself." [[type]] name = "VanishingPointStripTool" @@ -666,13 +667,13 @@ note = "Removed: a failed job shows through FullWindowStatus." type = "FillOutput" old = "preview_wanted" new = "" -note = "Replaced by FillSource::preview_job." +note = "Removed with `FillOutput` (`WorkspacePass`); the preview is `FillSource::preview_job`." [[setter]] type = "FillOutput" old = "outcome" -new = "closed, apply" -note = "closed: Option (Accept, Cancel) and apply: bool." +new = "" +note = "Removed with `FillOutput` (`WorkspacePass`): `result` is OK's or Cancel's answer, and Apply is `FillEvent::Apply`." [[setter]] type = "FillCanvas"