diff --git a/crates/imaging/src/ui/filter_gallery/catalog.rs b/crates/imaging/src/ui/filter_gallery/catalog.rs index adeb95393..f52580225 100644 --- a/crates/imaging/src/ui/filter_gallery/catalog.rs +++ b/crates/imaging/src/ui/filter_gallery/catalog.rs @@ -4,6 +4,7 @@ use craft_ui::canvas::{PixelRect, RasterSource}; use craft_ui::contract::Entry; use craft_ui::patterns::form_dialogs::{DialogFields, Param, ParamKind}; +use craft_ui::primitives::textures::ThumbSource; use craft_ui::runtime::env::Label; use craft_ui::runtime::pending::Job; @@ -108,13 +109,11 @@ impl GalleryThumb { /// `preview` is the picture the canvas shows; its revision moves when a render lands. `render` starts the /// job that renders `effects` over `visible` (document pixels, widened by the filters' reach) at `zoom` /// (screen pixels per document pixel): the workspace asks again when the effects, the visible part or the -/// zoom change, and a newer request replaces the one running. +/// zoom change, and a newer request replaces the one running. `catalog` and `thumb_source` are what the +/// columns list and the automation surface checks keys against. pub trait FilterGallerySource: Send + Sync { /// The catalog the gallery lists and the effects name their filters in. - // P3(dialogs-w11): dl.K59 — default body until the app's sources implement it. - fn catalog(&self) -> &dyn FilterCatalog { - todo!("dl.K59") - } + fn catalog(&self) -> &dyn FilterCatalog; /// The rendered preview. fn preview(&self) -> &dyn RasterSource; @@ -122,11 +121,8 @@ pub trait FilterGallerySource: Send + Sync { /// The job that renders `effects` over `visible` at `zoom` into the preview. fn render(&self, effects: &[EffectLayer], visible: PixelRect, zoom: f64) -> Job; - /// The thumbnails the filter tree shows. - // P3(dialogs-w11): dl.K59 — default body until the app's sources implement it. - fn thumb_source(&self) -> &dyn craft_ui::primitives::textures::ThumbSource { - todo!("dl.K59") - } + /// The thumbnails the filter tree shows: each filter applied to a small crop of the layer. + fn thumb_source(&self) -> &dyn ThumbSource; } /// The catalog as one pass reads it: the folders and every filter in them, looked up by key. diff --git a/crates/imaging/src/ui/filter_gallery/mod.rs b/crates/imaging/src/ui/filter_gallery/mod.rs index 03a1d8c88..4ad13d448 100644 --- a/crates/imaging/src/ui/filter_gallery/mod.rs +++ b/crates/imaging/src/ui/filter_gallery/mod.rs @@ -7,11 +7,12 @@ //! effect-layer stack ([`EffectStack`]) and the preview's status. No tool strip and no options bar; a drag on //! the preview pans (the Hand tool is the canvas's only tool). //! -//! The session is the stack ([`FilterGallerySession`]) with [`EditHistory`] undo. The app's catalog -//! ([`FilterCatalog`]) names the filters and their parameters, its thumbnail source renders the folders' -//! pictures, and its [`FilterGallerySource`] renders the preview of the visible part -//! ([`FilterGalleryWorkspace::visible`]) as a job whenever the stack, the zoom or the visible part change. OK -//! runs `filter.filterGallery` with the effects; a smart filter opened again passes its recorded effects. +//! The session is the stack ([`FilterGallerySession`]) with [`EditHistory`] undo. The app's +//! [`FilterGallerySource`] holds its catalog ([`FilterCatalog`]), which names the filters and their parameters, +//! the thumbnail source that renders the folders' pictures, and the preview of the visible part +//! ([`FilterGalleryWorkspace::visible`]), rendered as a job whenever the stack, the zoom, the visible part or the +//! source change. The app hosts the workspace as a `HostedWorkspace`; OK runs `filter.filterGallery` with the +//! effects; a smart filter opened again passes its recorded effects. //! //! Files: `catalog` and `session`; `tree`, `stack`, `parameters` and this file's body. //! @@ -45,17 +46,18 @@ use craft_theme::Srgba; use craft_ui::canvas::{NavigationOptions, PixelRect, ViewCommands}; use craft_ui::contract::{Bind, Commands as _, Pattern, Pending, Remember as _, ShowContainer as _}; use craft_ui::dialog::{ - DialogOutput, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowZoomBar, - SideFooter, + FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowStatus, FullWindowTitle, FullWindowView, FullWindowWorkspace, + FullWindowZoomBar, SideFooter, WorkspaceCx, WorkspacePass, }; -use craft_ui::patterns::form_dialogs::FieldValue; +use craft_ui::patterns::form_dialogs::{FieldValue, set_param_field}; use craft_ui::primitives::Checker; -use craft_ui::primitives::textures::{ThumbSource, Thumbnails}; +use craft_ui::primitives::textures::{ThumbnailOptions, Thumbnails}; use craft_ui::runtime::env::{Env, Label}; use craft_ui::runtime::requests::ColorRequest; use craft_ui::runtime::words::CommonWords; use craft_ui::sections::{DialogRole, FooterButton}; -use egui::Ui; +use egui::{Context, Ui}; +use serde_json::{Value, json}; use crate::ui::wide_angle::PreviewDone; @@ -109,40 +111,22 @@ pub enum FilterGalleryEvent { PickColor(ColorRequest), } -/// What [`FilterGalleryWorkspace::show`] reports. -#[derive(Debug)] -#[non_exhaustive] -pub struct FilterGalleryOutput { - /// What happened this pass, in order. - pub events: Vec, - /// A color parameter's swatch pressed: the app opens its picker and answers into the selected - /// effect's fields ([`FilterGalleryWorkspace::set_color`]). - pub pick_color: Option, - /// The dialog: its response, why it closed and which footer button was picked (0 is OK, 1 is Cancel). - pub dialog: DialogOutput, +/// The undo step name of every stack change: the workspace's name. +fn history_name(words: &FilterGalleryWords) -> Arc { + words.name.clone().as_str().into() } -impl FilterGalleryOutput { - /// OK was chosen. - pub fn accepted(&self) -> bool { - self.dialog.picked == Some(OK) - } -} - -/// The footer button that accepts. -const OK: usize = 0; - -/// What one pass of the two closures shares. -struct Pass<'w> { - workspace: &'w mut FilterGalleryWorkspace, - events: Vec, - pick_color: Option, -} - -/// The Filter Gallery workspace. +/// The Filter Gallery workspace, hosted as a [`FullWindowWorkspace`] over the app's [`FilterGallerySource`]: its +/// pass reports [`FilterGalleryEvent`]s, and OK answers the session. /// /// Keys: the zoom commands zoom the preview, never the canvas behind; ⌘Z and ⇧⌘Z step the stack's history (a field /// being edited steps its own text first); Enter OK, Esc Cancel. +/// +/// Automation fields: `effects` (the stack as `[{filter, params, visible}]`), `select` (the selected layer's +/// index) and `zoom` (`"fit"` or the zoom, 1 = 100 %), which it lists and sets; and the actions `add` and `delete` +/// (`true`), `toggle` (a layer's index: its eye flips), `move` (`{from, to}`), `filter` (a filter key for the +/// selected layer) and `params` (values merged into the selected layer's parameters). Each change is one undo step +/// and is reported by the next pass. #[derive(Pattern)] pub struct FilterGalleryWorkspace { session: FilterGallerySession, @@ -194,122 +178,6 @@ impl FilterGalleryWorkspace { } } - /// Shows the workspace for this pass: the title (the selected effect's filter name as the subject's prefix, - /// PhotoCraft's "{effect} (layer, 66%)"), the side columns at the end edge (settings with the top footer - /// outermost, then the folders), the zoom bar (progress while the preview renders, else the render's time), - /// and the canvas over `source`'s preview with the Hand tool. Changes go through - /// [`FilterGallerySession::apply`] and are recorded in the history; a change, a zoom or a pan starts a new - /// preview job of `source`. - /// - /// `thumb_source` renders the pictures `thumbs` asks for (one per filter, the filter applied to a small - /// crop of the layer). - pub fn show( - &mut self, - ui: &mut Ui, - catalog: &dyn FilterCatalog, - thumbs: &Thumbnails, - thumb_source: &dyn ThumbSource, - source: &dyn FilterGallerySource, - ) -> FilterGalleryOutput { - let env = Env::of(ui); - let words = env.words::(); - let common = env.words::(); - let index = FilterIndex::of(catalog); - let events = std::mem::take(&mut self.queued); - self.selected = self.selected.min(self.session.effects.len().saturating_sub(1)); - let name = self.session.effects.get(self.selected).map_or_else(|| words.name.clone(), |effect| index.label(&effect.filter)); - let title = FullWindowTitle::new(name).subject(self.subject.clone()).zoom(self.percent).label(&env); - let buttons = [FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]; - let history_name: Arc = words.name.clone().as_str().into(); - let navigation = self.navigation; - let checkerboard = self.checkerboard; - let pass = RefCell::new(Pass { workspace: self, events, pick_color: None }); - - let mut dialog = FullWindowDialog::new(title) - .buttons(buttons) - .side_footer(SideFooter::top()) - .sides(|ui, _| { - let mut pass = pass.borrow_mut(); - let current = pass.workspace.selected; - let mut changes = Vec::new(); - let mut stack_pick = None; - let mut pick_color = None; - FullWindowSide::new(words.settings.clone()).headerless().show(ui, |ui, _| { - if let Some(effect) = pass.workspace.session.effects.get(current) { - let parameters = EffectParameters::new(current, effect, &index).show(ui); - changes.extend(parameters.change); - pick_color = parameters.pick_color; - } - let stack = EffectStack::new(&pass.workspace.session.effects, current, &index).show(ui); - stack_pick = stack.selected; - changes.extend(stack.change); - FullWindowStatus::of(&pass.workspace.status).show(ui); - }); - pass.pick_color = pick_color; - for change in changes { - pass.apply(change, catalog, &history_name); - } - if let Some(pick) = stack_pick { - pass.workspace.selected = pick.min(pass.workspace.session.effects.len().saturating_sub(1)); - } - let current_filter = - pass.workspace.session.effects.get(pass.workspace.selected).map(|effect| effect.filter.clone()).unwrap_or_default(); - let mut tree_pick = None; - FullWindowSide::new(words.filters.clone()).headerless().show(ui, |ui, _| { - tree_pick = FilterTree::new(&index, ¤t_filter, thumbs, thumb_source).show(ui).picked; - }); - if let Some(filter) = tree_pick { - let at = pass.workspace.selected; - pass.apply(EffectChange::set_filter(at, filter), catalog, &history_name); - } - }) - .show(ui, |ui, cx| { - let mut pass = pass.borrow_mut(); - let workspace = &mut *pass.workspace; - while let Some(step) = cx.take_step(workspace.history.can_undo(), workspace.history.can_redo()) { - workspace.step(step); - } - let mut view = workspace.view; - while let Some((command, _)) = cx.take_command::() { - view.apply(command); - } - let (visible, zoom) = workspace.visible(); - let key = (workspace.revision, visible, zoom.to_bits()); - let effects = &workspace.session.effects; - let status = cx.pending(key, || source.render(effects, visible, zoom)).clone(); - let mut bar = FullWindowZoomBar::new(Bind::bound(&mut view)).progress(FullWindowStatus::of(&status).progress()); - if let Pending::Ready(done) = &status { - let milliseconds = done.timing.as_millis().to_string(); - bar = bar.note(Label::from(words.preview_ms.fill(&[("n", milliseconds.as_str())]))); - } - bar.show(ui); - let mut canvas = FullWindowCanvas::new(Bind::bound(&mut view), source.preview()).navigation(navigation); - if let Some(checker) = checkerboard { - canvas = canvas.checkerboard(checker); - } - canvas.show(ui); - (view, status) - }); - // Once per pass, after the real run: the view it settled and the render status are stored. - dialog.settle(|_, (view, status)| { - let view = std::mem::take(view); - let workspace = &mut *pass.borrow_mut().workspace; - workspace.status = status.clone(); - workspace.shown = Some(view.view()); - workspace.percent = view.zoom_percent(); - workspace.zoom = view.device_zoom(); - workspace.view = view; - }); - - let Pass { workspace, mut events, pick_color } = pass.into_inner(); - events.append(&mut workspace.queued); - if workspace.selected != workspace.reported { - workspace.reported = workspace.selected; - events.push(FilterGalleryEvent::Select(workspace.selected)); - } - FilterGalleryOutput { events, pick_color, dialog: dialog.output } - } - /// The effect-layer stack as it is now. pub fn session(&self) -> &FilterGallerySession { &self.session @@ -328,7 +196,7 @@ impl FilterGalleryWorkspace { (PixelRect::new(part.x0 as i32, part.y0 as i32, part.x1 as i32, part.y1 as i32), self.zoom) } - /// The color the app picked for a [`FilterGalleryOutput::pick_color`] request: written into the request's + /// The color the app picked for a [`FilterGalleryEvent::PickColor`] request: written into the request's /// `key` of the selected effect (one undo step). pub fn set_color(&mut self, key: &str, color: Srgba) { let index = self.selected.min(self.session.effects.len().saturating_sub(1)); @@ -358,50 +226,228 @@ impl FilterGalleryWorkspace { self.revision += 1; self.history.record(&EditEvent::set(Mixed::Same(before), self.session.clone(), name.clone(), None)); } -} -impl Pass<'_> { - /// Applies `change` through the catalog, records it and reports it. - fn apply(&mut self, change: EffectChange, catalog: &dyn FilterCatalog, name: &Arc) { - let workspace = &mut *self.workspace; - let before = workspace.session.clone(); - let mut selected = workspace.selected; - if workspace.session.apply(change.clone(), catalog, &mut selected) { - workspace.selected = selected; - workspace.record(before, name); - self.events.push(FilterGalleryEvent::Stack(change)); + /// Applies `change` through `catalog`, records it as one undo step named `name` and queues its report for the + /// next pass to give: the one path of every stack change, from the columns and from automation. Returns whether + /// the stack changed. + fn change(&mut self, change: EffectChange, catalog: &dyn FilterCatalog, name: &Arc) -> bool { + let before = self.session.clone(); + let mut selected = self.selected; + if !self.session.apply(change.clone(), catalog, &mut selected) { + return false; } + self.selected = selected; + self.record(before, name); + self.queued.push(FilterGalleryEvent::Stack(change)); + true + } + + /// The selected layer's index, kept on a layer that exists. + fn clamped_selection(&self) -> usize { + self.selected.min(self.session.effects.len().saturating_sub(1)) + } + + /// Sets the automation field `field` to `value` over `catalog`; `Err` says why it refused. + fn set_field(&mut self, catalog: &dyn FilterCatalog, name: &Arc, field: &str, value: Value) -> Result<(), String> { + let rejects = |value: &Value| FieldRefusal::Rejects(value).message(field); + let index = |value: &Value| value.as_u64().and_then(|at| usize::try_from(at).ok()); + let selected = self.clamped_selection(); + let change = match field { + "effects" => { + let effects: Vec = serde_json::from_value(value.clone()).map_err(|_| rejects(&value))?; + if effects.is_empty() || effects.iter().any(|effect| catalog.filter(&effect.filter).is_none()) { + return Err(rejects(&value)); + } + EffectChange::Replace { effects } + } + "select" => { + let at = index(&value).ok_or_else(|| rejects(&value))?; + self.selected = at.min(self.session.effects.len().saturating_sub(1)); + return Ok(()); + } + "zoom" => { + match (value.as_str(), value.as_f64()) { + (Some("fit"), _) => self.view.apply(ViewCommands::FitOnScreen), + (_, Some(zoom)) if zoom.is_finite() && zoom > 0.0 => self.view.set_device_zoom(zoom), + _ => return Err(rejects(&value)), + }; + return Ok(()); + } + "add" | "delete" => match value.as_bool() { + Some(true) if field == "add" => EffectChange::Add, + Some(true) => EffectChange::Delete, + Some(false) => return Ok(()), + None => return Err(rejects(&value)), + }, + "toggle" => { + let at = index(&value).ok_or_else(|| rejects(&value))?; + let effect = self.session.effects.get(at).ok_or_else(|| rejects(&value))?; + EffectChange::set_visible(at, !effect.visible) + } + "move" => { + let count = self.session.effects.len(); + let (from, to) = (value.get("from").and_then(index), value.get("to").and_then(index)); + let (Some(from), Some(to)) = (from, to) else { return Err(rejects(&value)) }; + if from >= count || to >= count { + return Err(rejects(&value)); + } + EffectChange::move_to(from, to) + } + "filter" => { + let key = value.as_str().filter(|key| catalog.filter(key).is_some()).ok_or_else(|| rejects(&value))?; + EffectChange::set_filter(selected, key) + } + "params" => { + let (Some(effect), Some(entries)) = (self.session.effects.get(selected), value.as_object()) else { return Err(rejects(&value)) }; + let filter = catalog.filter(&effect.filter).ok_or_else(|| FieldRefusal::Inactive.message(field))?; + let mut fields = effect.fields.clone(); + for (key, entry) in entries { + set_param_field(&filter.params, &mut fields, key, entry.clone())?; + } + EffectChange::with_fields(selected, fields) + } + _ => return Err(FieldRefusal::Unknown.message(field)), + }; + self.change(change, catalog, name); + Ok(()) } } -// P3(dialogs-w11): dl.K59 — the workspace's trait surface; `show` and the automation fields are written in phase 3. -impl craft_ui::dialog::FullWindowWorkspace for FilterGalleryWorkspace { +impl FullWindowWorkspace for FilterGalleryWorkspace { type Source = dyn FilterGallerySource; type Event = FilterGalleryEvent; type Result = FilterGallerySession; const KEY: &'static str = "filter.filterGallery"; - fn show( - &mut self, - ui: &mut egui::Ui, - cx: craft_ui::dialog::WorkspaceCx<'_, Self::Source>, - ) -> craft_ui::dialog::WorkspacePass { - let _ = (ui, cx); - todo!("dl.K59") + /// Shows the workspace for this pass: the title (the selected effect's filter name as the subject's prefix, + /// PhotoCraft's "{effect} (layer, 66%)"), the side columns at the end edge (settings with the top footer + /// outermost, then the folders with the source's thumbnails), the zoom bar (progress while the preview renders, + /// else the render's time), and the canvas over the source's preview with the Hand tool. Changes go through + /// [`FilterGallerySession::apply`] and are recorded in the history; a change, a zoom, a pan or a new source + /// starts a new preview job. A swatch press reports [`FilterGalleryEvent::PickColor`]. + /// + /// OK closes at once: the gallery never holds its OK (`cx.hold_ok` is not read). + fn show(&mut self, ui: &mut Ui, cx: WorkspaceCx<'_, Self::Source>) -> WorkspacePass { + let WorkspaceCx { source, revision: source_revision, open, .. } = cx; + let (catalog, thumb_source) = (source.catalog(), source.thumb_source()); + let thumbs = Thumbnails::::in_context(ui.ctx(), "filterGallery.thumbs", ThumbnailOptions::default()); + let env = Env::of(ui); + let words = env.words::(); + let common = env.words::(); + let index = FilterIndex::of(catalog); + let mut events = std::mem::take(&mut self.queued); + self.selected = self.clamped_selection(); + let name = self.session.effects.get(self.selected).map_or_else(|| words.name.clone(), |effect| index.label(&effect.filter)); + let title = FullWindowTitle::new(name).subject(self.subject.clone()).zoom(self.percent).label(&env); + let buttons = [FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]; + let history_name = history_name(&words); + let navigation = self.navigation; + let checkerboard = self.checkerboard; + let shared = RefCell::new(&mut *self); + + let mut dialog = FullWindowDialog::new(title) + .opened(open) + .buttons(buttons) + .side_footer(SideFooter::top()) + .sides(|ui, _| { + let mut workspace = shared.borrow_mut(); + let current = workspace.selected; + let mut changes = Vec::new(); + let mut stack_pick = None; + let mut pick_color = None; + FullWindowSide::new(words.settings.clone()).headerless().show(ui, |ui, _| { + if let Some(effect) = workspace.session.effects.get(current) { + let parameters = EffectParameters::new(current, effect, &index).show(ui); + changes.extend(parameters.change); + pick_color = parameters.pick_color; + } + let stack = EffectStack::new(&workspace.session.effects, current, &index).show(ui); + stack_pick = stack.selected; + changes.extend(stack.change); + FullWindowStatus::of(&workspace.status).show(ui); + }); + if let Some(request) = pick_color { + workspace.queued.push(FilterGalleryEvent::PickColor(request)); + } + for change in changes { + workspace.change(change, catalog, &history_name); + } + if let Some(pick) = stack_pick { + workspace.selected = pick.min(workspace.session.effects.len().saturating_sub(1)); + } + let current_filter = workspace.session.effects.get(workspace.selected).map(|effect| effect.filter.clone()).unwrap_or_default(); + let mut tree_pick = None; + FullWindowSide::new(words.filters.clone()).headerless().show(ui, |ui, _| { + tree_pick = FilterTree::new(&index, ¤t_filter, &thumbs, thumb_source).show(ui).picked; + }); + if let Some(filter) = tree_pick { + let at = workspace.selected; + workspace.change(EffectChange::set_filter(at, filter), catalog, &history_name); + } + }) + .show(ui, |ui, cx| { + let mut workspace = shared.borrow_mut(); + let workspace = &mut **workspace; + while let Some(step) = cx.take_step(workspace.history.can_undo(), workspace.history.can_redo()) { + workspace.step(step); + } + let mut view = workspace.view; + while let Some((command, _)) = cx.take_command::() { + view.apply(command); + } + let (visible, zoom) = workspace.visible(); + // A new source (a document edit under the open gallery) previews again, and a late preview of the old + // pixels lands under a key no pass asks for. + let key = (workspace.revision, source_revision, visible, zoom.to_bits()); + let effects = &workspace.session.effects; + let status = cx.pending(key, || source.render(effects, visible, zoom)).clone(); + let mut bar = FullWindowZoomBar::new(Bind::bound(&mut view)).progress(FullWindowStatus::of(&status).progress()); + if let Pending::Ready(done) = &status { + let milliseconds = done.timing.as_millis().to_string(); + bar = bar.note(Label::from(words.preview_ms.fill(&[("n", milliseconds.as_str())]))); + } + bar.show(ui); + let mut canvas = FullWindowCanvas::new(Bind::bound(&mut view), source.preview()).navigation(navigation); + if let Some(checker) = checkerboard { + canvas = canvas.checkerboard(checker); + } + canvas.show(ui); + (view, status) + }); + // Once per pass, after the real run: the view it settled and the render status are stored. + dialog.settle(|_, (view, status)| { + let view = std::mem::take(view); + let mut workspace = shared.borrow_mut(); + workspace.status = status.clone(); + workspace.shown = Some(view.view()); + workspace.percent = view.zoom_percent(); + workspace.zoom = view.device_zoom(); + workspace.view = view; + }); + + let workspace = shared.into_inner(); + events.append(&mut workspace.queued); + if workspace.selected != workspace.reported { + workspace.reported = workspace.selected; + events.push(FilterGalleryEvent::Select(workspace.selected)); + } + let result = dialog.output.result(|| workspace.session.clone()); + WorkspacePass::new(dialog.output.response, events).result(result) } - fn json_fields(&self) -> Option { - todo!("dl.K59") + fn json_fields(&self) -> Option { + let zoom = if self.view.is_fit() { json!("fit") } else { json!(self.view.device_zoom()) }; + let effects = serde_json::to_value(&self.session.effects).unwrap_or_default(); + Some(json!({ "effects": effects, "select": self.clamped_selection(), "zoom": zoom })) } - 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.K59") + fn set_json_field(&mut self, ctx: &Context, source: &Self::Source, field: &str, value: Value) -> Result<(), String> { + let name = history_name(&Env::of_root(ctx).words::()); + self.set_field(source.catalog(), &name, field, value) } - fn confirm(&mut self, ctx: &egui::Context, source: &Self::Source) -> Option { - let _ = (ctx, source); - todo!("dl.K59") + fn confirm(&mut self, _: &Context, _: &Self::Source) -> Option { + Some(self.session.clone()) } } diff --git a/crates/imaging/src/ui/filter_gallery/session.rs b/crates/imaging/src/ui/filter_gallery/session.rs index 6b0e74b87..02cb2fac3 100644 --- a/crates/imaging/src/ui/filter_gallery/session.rs +++ b/crates/imaging/src/ui/filter_gallery/session.rs @@ -4,8 +4,10 @@ use craft_ui::patterns::form_dialogs::DialogFields; use super::catalog::FilterCatalog; -/// One effect layer: a filter, its fields (the catalog's parameters) and its eye. +/// One effect layer: a filter, its fields (the catalog's parameters) and its eye. It serialises as +/// `{filter, params, visible}`, with a choice by its option's name, as the engine's effects do. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct EffectLayer { /// The filter's key in the catalog. @@ -135,6 +137,11 @@ impl FilterGallerySession { } _ => false, }, + // The stack never empties: a gallery always has one layer to show. + EffectChange::Replace { effects } if !effects.is_empty() && effects != self.effects => { + self.effects = effects; + true + } EffectChange::Add => { let copy = self.effects[current].clone(); self.effects.insert(current + 1, copy); diff --git a/crates/imaging/src/ui/filter_gallery/stories.rs b/crates/imaging/src/ui/filter_gallery/stories.rs index c92f067b3..70925be2c 100644 --- a/crates/imaging/src/ui/filter_gallery/stories.rs +++ b/crates/imaging/src/ui/filter_gallery/stories.rs @@ -8,16 +8,17 @@ use std::time::Duration; use craft_theme::Srgba; use craft_ui::canvas::{PixelRect, RasterSource}; -use craft_ui::contract::Job; +use craft_ui::contract::{Bind, Job}; +use craft_ui::dialog::{FullWindowWorkspace as _, WorkspaceCx}; use craft_ui::patterns::form_dialogs::{Param, ParamKind}; -use craft_ui::primitives::textures::{FakeThumbSource, ThumbnailOptions, Thumbnails}; +use craft_ui::primitives::textures::{FakeThumbSource, ThumbSource, ThumbnailOptions, Thumbnails}; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use craft_ui::value_drag::SliderScale; use egui::Ui; use super::{ - EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGalleryOpen, FilterGallerySession, - FilterGallerySource, FilterGalleryWorkspace, FilterIndex, FilterTree, GalleryFilter, GalleryThumb, + EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGalleryEvent, FilterGalleryOpen, + FilterGallerySession, FilterGallerySource, FilterGalleryWorkspace, FilterIndex, FilterTree, GalleryFilter, GalleryThumb, }; use crate::ui::mock_image::MockImage; use crate::ui::wide_angle::PreviewDone; @@ -110,13 +111,23 @@ fn start() -> FilterGallerySession { session } -/// The picture under the effects, with a render that is done at once or never finishes. +/// The app's side of the workspace: the catalog, the thumbnails, and the picture under the effects, with a render +/// that is done at once or never finishes. struct MockSource { image: MockImage, rendering: bool, + thumbs: FakeThumbSource, } impl FilterGallerySource for MockSource { + fn catalog(&self) -> &dyn FilterCatalog { + &MockGallery + } + + fn thumb_source(&self) -> &dyn ThumbSource { + &self.thumbs + } + fn preview(&self) -> &dyn RasterSource { &self.image } @@ -136,19 +147,21 @@ impl FilterGallerySource for MockSource { } } -/// Shows the workspace over the session the story keeps. +/// Shows the workspace over the session the story keeps, its open state bound to the story's. fn workspace(ui: &mut Ui, data: &mut StoryData, rendering: bool) -> StoryOutput { let image = MockImage::default(); let session = data.value("session", start()).clone(); let mut workspace = FilterGalleryWorkspace::new(FilterGalleryOpen::new(image.size(), "Photo", session)); - let thumbs = Thumbnails::::in_context(ui.ctx(), "gallery-story-thumbs", ThumbnailOptions::default()); - let out = workspace.show(ui, &MockGallery, &thumbs, &FakeThumbSource::::new(), &MockSource { image, rendering }); + let source: &dyn FilterGallerySource = &MockSource { image, rendering, thumbs: FakeThumbSource::new() }; + let pass = workspace.show(ui, WorkspaceCx::new(source, Bind::bound(data.value("open", true)))); // A swatch press asks the app for a color; the story has no picker. - if let Some(request) = out.pick_color { - workspace.set_color(&request.key, Srgba::from_rgb_array([0.2, 0.7, 0.9])); + for event in &pass.events { + if let FilterGalleryEvent::PickColor(request) = event { + workspace.set_color(&request.key, Srgba::from_rgb_array([0.2, 0.7, 0.9])); + } } *data.value("session", start()) = workspace.session().clone(); - out.dialog.into() + StoryOutput::from(pass.response) } #[story(FilterGalleryWorkspace, covers = [Default], drive = Drive::Never)] diff --git a/crates/imaging/tests/it/filter_gallery.rs b/crates/imaging/tests/it/filter_gallery.rs index 7301e28c2..8c6b4a408 100644 --- a/crates/imaging/tests/it/filter_gallery.rs +++ b/crates/imaging/tests/it/filter_gallery.rs @@ -9,15 +9,16 @@ use std::time::Duration; use craft_behavior::PixelSize; use craft_host::{AppInfo, Host}; use craft_imaging::ui::filter_gallery::{ - EffectChange, EffectLayer, FilterCatalog, FilterCategory, FilterGalleryEvent, FilterGalleryOpen, FilterGalleryOutput, FilterGallerySession, - FilterGallerySource, FilterGalleryWorkspace, GalleryFilter, GalleryThumb, + EffectChange, EffectLayer, FilterCatalog, FilterCategory, FilterGalleryEvent, FilterGalleryOpen, FilterGallerySession, FilterGallerySource, + FilterGalleryWorkspace, GalleryFilter, GalleryThumb, }; use craft_imaging::ui::wide_angle::PreviewDone; use craft_ui::canvas::{PixelRect, RasterSource}; -use craft_ui::contract::Job; +use craft_ui::contract::{Bind, Job}; +use craft_ui::dialog::{FullWindowWorkspace as _, WorkspaceCx}; use craft_ui::patterns::form_dialogs::{Param, ParamKind}; use craft_ui::primitives::Revision; -use craft_ui::primitives::textures::{FakeThumbSource, ThumbnailOptions, Thumbnails}; +use craft_ui::primitives::textures::{FakeThumbSource, ThumbSource}; use craft_ui::testing::{Fixture, trial}; use craft_ui::value_drag::SliderScale; use egui::{Color32, ColorImage, Key, Modifiers, Vec2}; @@ -91,8 +92,11 @@ fn gallery_stack_new_delete_reorder_and_eye() { // Undo of a Delete gives the layer back and clamps the selection. -/// A flat picture the size of the layer, whose render finishes only when `done`. +/// The app's side: the catalog, the thumbnails, and a flat picture the size of the layer, whose render finishes only +/// when `done`. struct Flat { + catalog: Catalog, + thumbs: FakeThumbSource, done: bool, } @@ -115,6 +119,14 @@ impl RasterSource for Flat { } impl FilterGallerySource for Flat { + fn catalog(&self) -> &dyn FilterCatalog { + &self.catalog + } + + fn thumb_source(&self) -> &dyn ThumbSource { + &self.thumbs + } + fn preview(&self) -> &dyn RasterSource { self } @@ -133,31 +145,33 @@ impl FilterGallerySource for Flat { } } -/// A workspace in a fixture and what its passes reported. +/// A workspace in a fixture and the events its passes reported. struct Rig { fixture: Fixture, workspace: Rc>, - outputs: Rc>>, + events: Rc>>, } +/// Shows the workspace through its trait `show`, as a host does, with the open state kept across passes. fn rig(session: FilterGallerySession, done: bool) -> Rig { let workspace = Rc::new(RefCell::new(FilterGalleryWorkspace::new(FilterGalleryOpen::new(LAYER, "Layer 1", session)))); - let outputs = Rc::new(RefCell::new(Vec::new())); - let (shown, sink) = (workspace.clone(), outputs.clone()); - let source = Flat { done }; + let events = Rc::new(RefCell::new(Vec::new())); + let (shown, sink) = (workspace.clone(), events.clone()); + let source = Flat { catalog: Catalog, thumbs: FakeThumbSource::new(), done }; + let mut open = true; let mut fixture = Fixture::new(move |ui| { - let thumbs = Thumbnails::::in_context(ui.ctx(), "gallery-test-thumbs", ThumbnailOptions::default()); - let out = shown.borrow_mut().show(ui, &Catalog, &thumbs, &FakeThumbSource::::new(), &source); - sink.borrow_mut().push(out); + let source: &dyn FilterGallerySource = &source; + let pass = shown.borrow_mut().show(ui, WorkspaceCx::new(source, Bind::bound(&mut open))); + sink.borrow_mut().extend(pass.events); }); fixture.host(Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).build())); fixture.room(WINDOW).settle(); - Rig { fixture, workspace, outputs } + Rig { fixture, workspace, events } } impl Rig { fn events(&self) -> Vec { - self.outputs.borrow().iter().flat_map(|out| out.events.clone()).collect() + self.events.borrow().clone() } } diff --git a/crates/ui-canvas/src/canvas/full_window.rs b/crates/ui-canvas/src/canvas/full_window.rs index 3c9413ece..8634c82fc 100644 --- a/crates/ui-canvas/src/canvas/full_window.rs +++ b/crates/ui-canvas/src/canvas/full_window.rs @@ -125,25 +125,38 @@ impl<'a> FullWindowDialog<'a> { /// viewports are unavailable it fills the main window. The dialog's focus policy moves into the fallback overlay. #[must_use] pub fn own_window(mut self, spec: WindowSpec) -> Self { - self.props.mount = Mount::viewport_with(Overlay::full_window(self.props.focus), spec); - self.props.focus = FocusPolicy::NONE; + // A viewport mount takes its scope from the fallback overlay and holds `props.focus` at none. + let focus = std::mem::replace(self.focus_mut(), FocusPolicy::NONE); + self.props.mount = Mount::viewport_with(Overlay::full_window(focus), spec); self } /// Who gets Enter: the dialog's submit, or the body. #[must_use] pub fn enter(mut self, rule: EnterRule) -> Self { - self.props.focus = FocusPolicy { enter: rule, ..self.props.focus }; + let focus = self.focus_mut(); + *focus = FocusPolicy { enter: rule, ..*focus }; self } /// What takes the keyboard focus when the dialog opens. #[must_use] pub fn initial_focus(mut self, initial: Initial) -> Self { - self.props.focus = self.props.focus.initial(initial); + let focus = self.focus_mut(); + *focus = focus.initial(initial); self } + /// The dialog's focus policy, wherever its mount keeps it: the fallback overlay's in its own window, else the + /// container's. Every builder and the footer go through it, so the order of `own_window` and the others does not + /// matter. + fn focus_mut(&mut self) -> &mut FocusPolicy { + match &mut self.props.mount { + Mount::Viewport { fallback, .. } => &mut fallback.focus, + _ => &mut self.props.focus, + } + } + /// The dialog's own command scope, a child of [`ViewCommands::SCOPE`]: the dialog is an instance of `scope` and still /// of the view scope. Both scopes' chords act wherever the focus is inside the dialog, and the view commands still /// reach the zoom bar; `scope`'s commands reach the dialog's body by `take_command` on its context. @@ -275,7 +288,7 @@ impl Container for FullWindowDialog<'_> { } fn footer(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) { - let enter = self.props.focus.enter == EnterRule::Submit; + let enter = self.focus_mut().enter == EnterRule::Submit; let (content, buttons) = (&mut self.footer, &self.buttons); let (picked, guard, on_pick, settle) = (&mut self.picked, &mut self.guard, &mut self.on_pick, &mut self.settle); if self.sides.is_some() { diff --git a/crates/ui-canvas/src/canvas/full_window/hosted.rs b/crates/ui-canvas/src/canvas/full_window/hosted.rs index 7aa47824f..cfbe6c167 100644 --- a/crates/ui-canvas/src/canvas/full_window/hosted.rs +++ b/crates/ui-canvas/src/canvas/full_window/hosted.rs @@ -14,6 +14,15 @@ use crate::runtime::env::Label; /// /// The events of the pass that finishes the workspace go with it: a workspace whose app needs them folds them into /// its [`Result`](FullWindowWorkspace::Result). +/// +/// - Automation: [`json_fields`](FullWindowWorkspace::json_fields), [`set_json_field`](FullWindowWorkspace::set_json_field) +/// and [`confirm`](FullWindowWorkspace::confirm) are what the host's `ui.dialog` surface reaches. Each key applies or +/// is refused on its own; the events a set produces are queued by the workspace and reported by its next pass. +/// - Source revision: [`WorkspaceCx::revision`] moves with each new source; the workspace adds it to its pending key. +/// - Held OK: under [`WorkspaceCx::hold_ok`] the workspace makes its Accept button `stays_open`, disables it while +/// [`WorkspaceCx::ok_waits`], and reports the answer OK would give in [`WorkspacePass::held`]. The app takes it +/// ([`HostedWorkspace::take_ok`]) and answers ([`HostedWorkspace::answer_ok`]); a refusal reaches +/// [`ok_failed`](FullWindowWorkspace::ok_failed). pub trait FullWindowWorkspace: Send + 'static { /// What the workspace reads from the app each pass, usually a `dyn` trait of the workspace's crate. type Source: ?Sized + Send + Sync; @@ -69,6 +78,14 @@ pub struct WorkspaceCx<'a, S: ?Sized> { pub ok_waits: bool, } +impl<'a, S: ?Sized> WorkspaceCx<'a, S> { + /// A pass over `source` with the open state bound to `open`, at the first revision, with OK not held: what a + /// workspace shown outside a [`HostedWorkspace`] gets. The host's stories and trials build it. + pub fn new(source: &'a S, open: Bind<'a, bool>) -> Self { + WorkspaceCx { source, revision: 0, open, hold_ok: false, ok_waits: false } + } +} + /// What one pass of a [`FullWindowWorkspace`] reports. #[non_exhaustive] pub struct WorkspacePass { @@ -81,22 +98,20 @@ pub struct WorkspacePass { pub result: Option>, /// The result OK would give, reported in the pass the Accept button is picked under `cx.hold_ok`; `result` /// stays `None` then. - // P3(dialogs-w11): dl.K57 `WorkspacePass::held` pub held: Option, } impl WorkspacePass { /// A pass with `events` that leaves the workspace open. pub fn new(response: Response, events: Vec) -> Self { - WorkspacePass { response, events, result: None, held: None } // P3(dialogs-w11): dl.K57 + WorkspacePass { response, events, result: None, held: None } } /// The result a held OK gives this pass. - // P3(dialogs-w11): dl.K57 `WorkspacePass::held` #[must_use] - pub fn held(self, held: Option) -> Self { - let _ = (self, held); - todo!("dl.K57") + pub fn held(mut self, held: Option) -> Self { + self.held = held; + self } /// How the workspace finished this pass. @@ -109,6 +124,8 @@ impl WorkspacePass { /// A [`FullWindowWorkspace`] the [`DialogHost`](crate::dialog::DialogHost) owns, with the app's source. It keeps the /// events of each pass until the app takes them, and finishes as the workspace's pass says: OK's answer, or Cancel. +/// It forwards the host's automation calls (`json_fields`, `set_json_field`, `confirm`) to the workspace with its +/// source. /// /// ```ignore /// dialogs.open(HostedWorkspace::new(LiquifyWorkspace::new(open), Arc::new(source))); @@ -121,6 +138,19 @@ impl WorkspacePass { /// doc.run("filter.liquify", steps); /// } /// ``` +/// +/// A workspace whose OK the app checks first opens [`held_ok`](HostedWorkspace::held_ok): OK files its answer and +/// the workspace stays shown until the app answers. +/// +/// ```ignore +/// dialogs.open(HostedWorkspace::new(FillWorkspace::new(open), Arc::new(source)).held_ok()); +/// dialogs.run(ui); +/// if let Some(fill) = dialogs.get_mut::>() +/// && let Some(session) = fill.take_ok() +/// { +/// fill.answer_ok(doc.run("edit.contentAwareFill", session).map_err(|error| error.label())); +/// } +/// ``` pub struct HostedWorkspace { id: DialogId, workspace: W, @@ -129,7 +159,14 @@ pub struct HostedWorkspace { open: bool, revision: u64, hold_ok: bool, + /// From the filed OK until the app's answer: the workspace disables its OK. ok_waits: bool, + /// The held OK's answer, kept until the app answers it. + filed: Option, + /// `take_ok` has not handed out `filed` yet. + untaken: bool, + /// The app accepted the held OK: the next pass finishes with `filed`. + finish: bool, #[cfg(feature = "testing")] facts: crate::testing::StoryOutput, } @@ -146,6 +183,9 @@ impl HostedWorkspace { revision: 0, hold_ok: false, ok_waits: false, + filed: None, + untaken: false, + finish: false, #[cfg(feature = "testing")] facts: crate::testing::StoryOutput::default(), } @@ -175,27 +215,50 @@ impl HostedWorkspace { } /// The OK the workspace is holding for the app to act on, once; `None` when none is held. - pub fn take_ok(&mut self) -> Option { - todo!("dl.K57") + pub fn take_ok(&mut self) -> Option + where + W::Result: Clone, + { + if !std::mem::take(&mut self.untaken) { + return None; + } + self.filed.clone() } - /// The app's answer to a held OK: `Ok` closes the workspace with it, `Err(reason)` keeps it open and shows - /// `reason`. + /// The app's answer to a held OK: `Ok` closes the workspace with it in the next pass, `Err(reason)` keeps it + /// open with OK enabled again and hands `reason` to [`FullWindowWorkspace::ok_failed`]. Does nothing while no OK + /// is held. pub fn answer_ok(&mut self, answer: Result<(), Label>) { - let _ = answer; - todo!("dl.K57") + if self.filed.is_none() { + return; + } + match answer { + Ok(()) => self.finish = true, + Err(reason) => { + self.filed = None; + self.untaken = false; + self.ok_waits = false; + self.workspace.ok_failed(reason); + } + } } /// The app's source the workspace shows. - // P3(dialogs-w11): dl.K57 `HostedWorkspace::source` pub fn source(&self) -> &Arc { - todo!("dl.K57") + &self.source } /// The events of the passes since the last call, in order. pub fn take_events(&mut self) -> Vec { std::mem::take(&mut self.events) } + + /// Files a held OK's `result` for the app; OK waits for the answer. + fn file(&mut self, result: W::Result) { + self.filed = Some(result); + self.untaken = true; + self.ok_waits = true; + } } impl StackDialog for HostedWorkspace { @@ -206,6 +269,12 @@ impl StackDialog for HostedWorkspace { } fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + // The app accepted the held OK: the first pass after the answer finishes, whichever pass of a frame it is. + if std::mem::take(&mut self.finish) + && let Some(result) = self.filed.take() + { + return Some(DialogResult::Ok(result)); + } let cx = WorkspaceCx { source: &*self.source, revision: self.revision, @@ -219,6 +288,11 @@ impl StackDialog for HostedWorkspace { self.facts = crate::contract::Outcome::story_facts(&pass.response); } self.events.extend(pass.events); + // A pick reaches only the pass whose input held it; a later pass of the frame finds OK waiting and files + // nothing more. + if let Some(result) = pass.held.filter(|_| self.hold_ok && !self.ok_waits) { + self.file(result); + } pass.result } @@ -227,7 +301,15 @@ impl StackDialog for HostedWorkspace { } fn confirm(&mut self, ctx: &Context) -> Option { - self.workspace.confirm(ctx, &*self.source) + if self.ok_waits { + return None; + } + let result = self.workspace.confirm(ctx, &*self.source)?; + if self.hold_ok { + self.file(result); + return None; + } + Some(result) } fn json_fields(&self) -> Option { diff --git a/crates/ui-canvas/src/canvas/full_window/stories.rs b/crates/ui-canvas/src/canvas/full_window/stories.rs index 23247bca7..870604803 100644 --- a/crates/ui-canvas/src/canvas/full_window/stories.rs +++ b/crates/ui-canvas/src/canvas/full_window/stories.rs @@ -1,21 +1,23 @@ //! The story of the full-window dialog shell. +use std::ops::RangeInclusive; use std::sync::Arc; use super::{FullWindowDialog, FullWindowWorkspace, HostedWorkspace, WorkspaceCx, WorkspacePass}; use crate::canvas::{PixelRect, RasterSource}; use crate::contract::{Bind, Show as _, ShowContainer as _}; use crate::dialog::stories::hosted; -use crate::dialog::{DialogWords, FullWindowCanvas, FullWindowSide, FullWindowView, FullWindowZoomBar}; +use crate::dialog::{DialogWords, FieldRefusal, FullWindowCanvas, FullWindowSide, FullWindowView, FullWindowZoomBar}; use crate::display::Text; use crate::form::SliderField; use crate::primitives::Revision; -use crate::runtime::env::Env; +use crate::runtime::env::{Env, Label}; +use crate::runtime::windows::WindowSpec; use crate::runtime::words::CommonWords; use crate::sections::{DialogRole, FooterButton}; use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story}; use craft_behavior::PixelSize; -use egui::{Color32, ColorImage, Ui}; +use egui::{Color32, ColorImage, Context, Ui}; /// The drive of the workspace: a click on Cancel. fn cancel(fixture: &mut Fixture) { @@ -28,6 +30,18 @@ fn cancel(fixture: &mut Fixture) { /// the side columns, with Apply when the story asks for it. #[story(FullWindowDialog<'static>, covers = [Default], drive = Drive::Custom(cancel))] fn full_window_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + liquify_shell(ui, data, false) +} + +/// The same workspace in an OS window of its own, as RAW Develop opens; the story kit has no viewports, so it fills +/// the window. +#[story(FullWindowDialog<'static>, covers = [], drive = Drive::Custom(cancel))] +fn own_window_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + liquify_shell(ui, data, true) +} + +/// The Liquify shell of the stories above, in its own window when `own_window` says so. +fn liquify_shell(ui: &mut Ui, data: &mut StoryData, own_window: bool) -> StoryOutput { let apply = *data.value("apply", false); let mut brush = *data.value("brush size", 50.0_f64); let env = Env::of(ui); @@ -36,7 +50,11 @@ fn full_window_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { if apply { buttons.push(FooterButton::new(env.words::().apply.clone(), DialogRole::Other).stays_open(true)); } - let shown: StoryOutput = FullWindowDialog::new("Liquify") + let mut dialog = FullWindowDialog::new("Liquify"); + if own_window { + dialog = dialog.own_window(WindowSpec::dialog()); + } + let shown: StoryOutput = dialog .opened(Bind::bound(data.value("open", true))) .buttons(buttons) .sides(|ui, _| { @@ -77,12 +95,24 @@ impl RasterSource for Flat { #[derive(Clone, Copy, Debug, PartialEq)] pub(super) struct BrushChanged(pub(super) f64); +/// The brush sizes the sample workspace's slider and its `brush` field take. +const BRUSH_SIZES: RangeInclusive = 1.0..=100.0; + +/// The index of OK among the sample workspace's buttons. +const ACCEPT: usize = 0; + /// A workspace as Liquify shows one, for the hosted story and trials: the zoom bar over the canvas in the body, the -/// brush size in a side column, OK and Cancel. OK answers the brush size. +/// brush size in a side column, OK and Cancel. OK answers the brush size; automation reads and sets it as `brush`. #[derive(Default)] pub(super) struct BrushWorkspace { pub(super) view: FullWindowView, pub(super) brush: f64, + /// The source revision the last pass showed. + pub(super) revision: u64, + /// Why the app refused the last held OK. + pub(super) failed: Option