PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Filters on a type layer: ask to rasterize or convert to a Smart Object instead of greying out (#4333)
Marco Arnulfoa1fbfd9a6c1d
diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rsindex 40b51189e..32ae7fb3b 100644--- a/crates/engine/src/filters.rs+++ b/crates/engine/src/filters.rs@@ -413,7 +413,7 @@ pub fn specs() -> Vec<CommandSpec> {/// The most recent filter command in the session journal, retargeted at the active layer: dialogs/// such as the Filter Gallery record the layer they ran on, and Last Filter applies to the/// current layer, as in Photoshop (#1270).-pub(crate) fn last_filter(s: &Session) -> Option<(String, Value)> {+pub fn last_filter(s: &Session) -> Option<(String, Value)> {let (id, mut params) = s.journal.iter().rev().find(|(id, _)| params_for(id, &Value::Null).is_some() && id.starts_with("filter.")).cloned()?;if let Value::Object(m) = &mut params {m.remove("layer");diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 7d36f2975..b5e011378 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -335,6 +335,21 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {fields.insert("choice".into(), json!("apply"));}hit+ } else if crate::rasterize_prompt::is_filter(&fields) {+ // Photoshop: Convert to Smart Object / Rasterize / Cancel (#4303).+ let rasterize = DialogButton::new(ButtonRole::Default, tl!("Rasterize"), 84.0);+ let hit = if crate::rasterize_prompt::offers_smart_object(&fields) {+ let convert = DialogButton::new(ButtonRole::Alternate, tl!("Convert to Smart Object"), 160.0);+ dialog_buttons(ui, &[rasterize, cancel, convert])+ } else {+ dialog_buttons(ui, &[rasterize, cancel])+ };+ if hit == Some(ButtonRole::Alternate) {+ fields.insert("choice".into(), json!("smartObject"));+ } else if hit == Some(ButtonRole::Default) {+ fields.insert("choice".into(), json!("rasterize"));+ }+ hit} else {dialog_buttons(ui, &[ok, cancel])};diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex c9847d863..73cc9b61d 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -644,6 +644,9 @@ pub struct PhotocraftApp {pub(crate) raw_redevelop: Option<camera_raw_ui::Redevelop>,/// Filter › Adaptive Wide Angle dialog (wide_angle_ui).pub(crate) wide_angle: Option<wide_angle_ui::WideAngleDialog>,+ /// The filter a "Rasterize?" prompt answered for, run after the dialog closes, where the+ /// egui context is available again (rasterize_prompt).+ pub(crate) pending_after_prompt: Option<(String, serde_json::Value)>,/// Signature of the image we last put on the OS clipboard (to tell ours from other apps').os_clip_sig: Option<u64>,/// The session clipboard currently holds an image imported from the OS clipboard: it has no@@ -811,6 +814,7 @@ impl PhotocraftApp {pending_raw_open: None,raw_redevelop: None,wide_angle: None,+ pending_after_prompt: None,tone_hist: None,doc_hist: None,hist_job: None,@@ -1745,6 +1749,7 @@ impl eframe::App for PhotocraftApp {workspace_ui::windows(self, &ctx);palette::show(self, &ctx);dialogs::show(self, &ctx);+ rasterize_prompt::run_pending(self, &ctx);jobs_ui::dialog(self, &ctx);discard_ui::show(self, &ctx);tiff_options_ui::show(self, &ctx);diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 18f1d6afb..161c64c0c 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -167,6 +167,10 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:if let Some(r) = crate::tool_reset::invoke(app, id, ¶ms) {return r;}+ // A filter on a type layer asks to rasterize it first (#4303).+ if let Some(r) = crate::rasterize_prompt::intercept_filter(app, id, ¶ms) {+ return r;+ }// A pending Pen anchor is gesture state; Edit › Undo must match the keyboard.if id == "edit.undo" && crate::vector_ui::pen_undo_last_point(app) {return Ok(Value::Null);@@ -671,6 +675,10 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool {if crate::crop_ui::blocks(app, id) {return false;}+ // Filters stay live on a type layer: choosing one asks to rasterize it (#4303).+ if crate::rasterize_prompt::filter_needs(app, id).is_some() {+ return true;+ }if let Some(e) = crate::workspace_ui::is_enabled(app, id) {return e;}diff --git a/crates/ui-egui/src/rasterize_prompt.rs b/crates/ui-egui/src/rasterize_prompt.rsindex bb1a7570b..76de6a89a 100644--- a/crates/ui-egui/src/rasterize_prompt.rs+++ b/crates/ui-egui/src/rasterize_prompt.rs@@ -7,6 +7,11 @@//! and `ui.dialog.cancel` answer it). OK runs the matching `layer.rasterize.*` command, then paints//! where the click was, so rasterizing and painting are two history states, as in Photoshop.//! Cancel does nothing.+//!+//! A filter on a type layer asks the same question (#4303), with Photoshop's Convert to Smart+//! Object / Rasterize / Cancel: the layer is converted or rasterized, then the filter is chosen+//! again from the menu (its dialog, window or mode opens, or it runs), a smart filter on the Smart+//! Object. `ui.dialog.set` with `"choice": "smartObject"` picks the conversion.use serde_json::{Map, Value, json};@@ -120,6 +125,62 @@ pub fn open(app: &mut PhotocraftApp, kind: Kind, layer: photocraft_doc::LayerId,app.ui.open_dialog(DialogKind::Command, f)}+/// The active type layer when `id` is a filter that only needs it rasterized: the engine greys it+/// for not being a pixel layer, and the layer is not locked. The flag says whether the filter also+/// runs on a Smart Object, as a smart filter (Vanishing Point doesn't).+pub fn filter_needs(app: &PhotocraftApp, id: &str) -> Option<(photocraft_doc::LayerId, bool)> {+ if !id.starts_with("filter.") {+ return None;+ }+ let st = app.session.active()?;+ let layer = st.active_layer?;+ if !matches!(st.doc.layer(layer)?.content, photocraft_doc::LayerContent::Text(_)) {+ return None;+ }+ let locks = st.doc.effective_locks(layer);+ if locks.all || locks.pixels {+ return None;+ }+ // Last Filter checks the layer before the journal: with no filter to repeat it stays grey.+ if id == "filter.lastFilter" && photocraft_engine::filters::last_filter(&app.session).is_none() {+ return None;+ }+ // The engine's reason for a type layer: "filters need a pixel layer (active layer is a Type+ // layer)" from filters::has_filterable_layer, which also takes Smart Objects, or a filter's own+ // wording ("Vanishing Point needs a pixel layer (…)", "active layer is a Type layer, not a pixel+ // layer"). Any other reason (a job running) keeps the item grey.+ let reason = app.session.disabled_reason(id)?;+ (reason.contains("active layer is a Type layer") && reason.contains("pixel layer")).then(|| (layer, reason.starts_with("filters need a pixel layer")))+}++/// A filter chosen on a type layer: open the prompt instead and return its answer to the caller.+pub fn intercept_filter(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Value, String>> {+ let (layer, smart) = filter_needs(app, id)?;+ if let Some(d) = app.ui.dialogs.iter().find(|d| owns(&d.fields)) {+ return Some(Ok(json!({"dialog": d.id})));+ }+ let mut f = Map::new();+ f.insert(MARK.into(), json!(Kind::Type.key()));+ f.insert("__label".into(), json!("PhotoCraft"));+ f.insert("message".into(), json!(Kind::Type.message()));+ f.insert("layer".into(), json!(layer.0));+ f.insert("filter".into(), json!(id));+ f.insert("params".into(), params.clone());+ f.insert("choice".into(), json!("rasterize"));+ f.insert("smartObject".into(), json!(smart));+ Some(Ok(json!({"dialog": app.ui.open_dialog(DialogKind::Command, f)})))+}++/// Is this the filter prompt (Convert to Smart Object / Rasterize / Cancel)?+pub fn is_filter(fields: &Map<String, Value>) -> bool {+ owns(fields) && fields.contains_key("filter")+}++/// Does the filter prompt offer Convert to Smart Object?+pub fn offers_smart_object(fields: &Map<String, Value>) -> bool {+ fields.get("smartObject").and_then(Value::as_bool) == Some(true)+}+/// Is this dialog the prompt?pub fn owns(fields: &Map<String, Value>) -> bool {fields.contains_key(MARK)@@ -141,6 +202,9 @@ pub fn body(ui: &mut egui::Ui, f: &Map<String, Value>) {pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {let kind = f.get(MARK).and_then(Value::as_str).and_then(Kind::from_key).ok_or("not a rasterize prompt")?;let layer = f.get("layer").and_then(Value::as_u64).ok_or("the prompt has no layer")?;+ if let Some(filter) = f.get("filter").and_then(Value::as_str) {+ return confirm_filter(app, f, filter, layer);+ }let r = app.run(kind.command(), json!({ "layer": layer }))?;let tool = f.get("tool").and_then(Value::as_str).and_then(Tool::from_name);let at: Vec<f64> = f.get("at").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();@@ -159,6 +223,30 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,Ok(json!({ "rasterized": r, "painted": painted }))}+/// The filter prompt's answer: convert or rasterize the layer, then queue the filter for+/// [`run_pending`]. Liquify, Camera Raw and the other filters with their own window need the+/// egui context to open, which a dialog's answer doesn't have.+fn confirm_filter(app: &mut PhotocraftApp, f: &Map<String, Value>, filter: &str, layer: u64) -> Result<Value, String> {+ let smart = f.get("choice").and_then(Value::as_str) == Some("smartObject");+ if smart && !offers_smart_object(f) {+ return Err(format!("{filter} can't run as a smart filter"));+ }+ let command = if smart { "layer.smartObjects.convertToSmartObject" } else { Kind::Type.command() };+ let r = app.run(command, json!({ "layer": layer }))?;+ let params = f.get("params").cloned().unwrap_or(Value::Null);+ app.pending_after_prompt = Some((filter.to_string(), params));+ Ok(json!({ "converted": r, "filter": filter }))+}++/// Runs the filter a prompt was answered for, as the menu would, now that the layer can take it.+pub fn run_pending(app: &mut PhotocraftApp, ctx: &egui::Context) {+ let Some((filter, params)) = app.pending_after_prompt.take() else { return };+ if let Err(e) = crate::menus::invoke(app, ctx, &filter, params) {+ app.ui.status = e;+ app.ui.status_error = true;+ }+}+#[cfg(test)]#[path = "rasterize_prompt_tests.rs"]mod tests;diff --git a/crates/ui-egui/src/rasterize_prompt_tests.rs b/crates/ui-egui/src/rasterize_prompt_tests.rsindex 8eb2dfa58..510723beb 100644--- a/crates/ui-egui/src/rasterize_prompt_tests.rs+++ b/crates/ui-egui/src/rasterize_prompt_tests.rs@@ -169,3 +169,236 @@ fn the_control_channel_sees_and_confirms_the_prompt() {assert_eq!(r["ok"], json!(true), "{r}");assert_eq!(active_content(&app), "Pixel");}++const BLUR: &str = "filter.blur.gaussianBlur";++fn menu(app: &mut PhotocraftApp, id: &str) -> Result<serde_json::Value, String> {+ crate::menus::invoke(app, &egui::Context::default(), id, json!({}))+}++/// Answers the filter prompt, then the frame runs the queued filter.+fn answer(app: &mut PhotocraftApp, id: u64) {+ crate::dialogs::confirm(app, id).unwrap();+ run_pending(app, &egui::Context::default());+}++fn filter_dialog(app: &PhotocraftApp) -> Option<u64> {+ app.ui.dialogs.iter().find(|d| d.fields.get("__command") == Some(&json!(BLUR)) && !owns(&d.fields)).map(|d| d.id)+}++/// #4303: Filter › Gaussian Blur… on a type layer is live and asks to rasterize first.+#[test]+fn a_filter_on_a_type_layer_asks_then_opens_on_the_rasterized_layer() {+ let mut app = app_with(Kind::Type);+ assert!(!app.session.is_enabled(BLUR), "the engine itself still needs pixels");+ assert!(crate::menus::is_enabled(&app, BLUR));+ let before = past(&app);+ menu(&mut app, BLUR).unwrap();+ let d = prompt(&app).expect("the prompt");+ assert_eq!(d.fields["message"], json!(Kind::Type.message()));+ assert!(filter_dialog(&app).is_none(), "the filter waits for the answer");+ assert_eq!((past(&app), active_content(&app)), (before, "Type"));+ let id = d.id;+ answer(&mut app, id);+ assert_eq!(active_content(&app), "Pixel");+ assert_eq!(past(&app), before + 1);+ let blur = filter_dialog(&app).expect("Gaussian Blur opens on the rasterized layer");+ crate::dialogs::confirm(&mut app, blur).unwrap();+ assert_eq!(past(&app), before + 2, "rasterize, then blur");+ assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some(BLUR));+}++#[test]+fn cancelling_the_filter_prompt_keeps_the_type_layer() {+ let mut app = app_with(Kind::Type);+ let before = (past(&app), app.session.active().unwrap().doc.clone());+ menu(&mut app, BLUR).unwrap();+ // The menu again while it is up doesn't stack another prompt.+ menu(&mut app, BLUR).unwrap();+ assert_eq!(app.ui.dialogs.len(), 1);+ let id = prompt(&app).unwrap().id;+ crate::dialogs::cancel(&mut app, id).unwrap();+ assert!(app.ui.dialogs.is_empty());+ assert_eq!(past(&app), before.0);+ assert_eq!(*app.session.active().unwrap().doc, *before.1);+ assert_eq!(active_content(&app), "Type");+}++/// Convert to Smart Object keeps the text editable and applies the filter as a smart filter.+#[test]+fn convert_to_smart_object_applies_a_smart_filter() {+ let mut app = app_with(Kind::Type);+ menu(&mut app, BLUR).unwrap();+ let id = prompt(&app).unwrap().id;+ app.ui.dialog_mut(id).unwrap().fields.insert("choice".into(), json!("smartObject"));+ answer(&mut app, id);+ assert_eq!(active_content(&app), "Smart Object");+ let blur = filter_dialog(&app).expect("Gaussian Blur opens on the Smart Object");+ crate::dialogs::confirm(&mut app, blur).unwrap();+ let st = app.session.active().unwrap();+ let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("a Smart Object") };+ assert_eq!(sm.smart_filters.iter().map(|f| f.command.as_str()).collect::<Vec<_>>(), [BLUR]);+}++/// A filter without a dialog runs straight after rasterizing.+#[test]+fn a_filter_without_a_dialog_runs_after_rasterizing() {+ let mut app = app_with(Kind::Type);+ let before = past(&app);+ menu(&mut app, "filter.blur.blurMore").unwrap();+ let id = prompt(&app).unwrap().id;+ answer(&mut app, id);+ assert!(app.ui.dialogs.is_empty());+ assert_eq!(past(&app), before + 2);+ assert_eq!(active_content(&app), "Pixel");+}++#[test]+fn filters_stay_grey_where_rasterizing_would_not_help() {+ // A locked type layer can't be rasterized either.+ let mut app = app_with(Kind::Type);+ app.run("layer.lockLayers", json!({"pixels": true})).unwrap();+ assert!(!crate::menus::is_enabled(&app, BLUR));+ // Only type layers ask: a shape layer's filters stay grey, as before.+ let app = app_with(Kind::Shape);+ assert!(!crate::menus::is_enabled(&app, BLUR));+ // Non-filter commands a type layer greys are untouched.+ let app = app_with(Kind::Type);+ assert_eq!(crate::menus::is_enabled(&app, "edit.fill"), app.session.is_enabled("edit.fill"));+}++/// The dialogs, and the filter a prompt queued, frame by frame.+fn harness(app: PhotocraftApp) -> egui_kittest::Harness<'static, PhotocraftApp> {+ let h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state(+ |ui, app| {+ crate::dialogs::show(app, ui.ctx());+ run_pending(app, ui.ctx());+ },+ app,+ );+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);+ h+}++/// The prompt's buttons, clicked: Rasterize, then the filter.+#[test]+fn the_filter_prompt_offers_convert_rasterize_and_cancel() {+ use egui_kittest::kittest::Queryable;+ let app = app_with(Kind::Type);+ let mut h = harness(app);+ menu(h.state_mut(), BLUR).unwrap();+ h.run_steps(4);+ h.get_by_label("Convert to Smart Object");+ h.get_by_label("Cancel");+ h.get_by_label("Rasterize").click();+ h.run_steps(4);+ assert_eq!(active_content(h.state()), "Pixel");+ assert!(filter_dialog(h.state()).is_some());+}++#[test]+fn the_convert_button_converts_to_a_smart_object() {+ use egui_kittest::kittest::Queryable;+ let app = app_with(Kind::Type);+ let mut h = harness(app);+ menu(h.state_mut(), BLUR).unwrap();+ h.run_steps(4);+ h.get_by_label("Convert to Smart Object").click();+ h.run_steps(4);+ assert_eq!(active_content(h.state()), "Smart Object");+ assert!(filter_dialog(h.state()).is_some());+}++/// The filters with their own window or mode open on the rasterized layer, or on the Smart Object.+#[test]+fn filters_with_their_own_window_open_after_the_prompt() {+ type IsOpen = fn(&PhotocraftApp) -> bool;+ let open: [(&str, IsOpen); 4] = [+ ("filter.liquify", |a| a.distort.liquify.is_some()),+ ("filter.filterGallery", |a| a.distort.gallery.is_some()),+ ("filter.cameraRaw", |a| a.camera_raw.is_some()),+ ("filter.adaptiveWideAngle", |a| a.wide_angle.is_some()),+ ];+ for (filter, is_open) in open {+ for choice in ["rasterize", "smartObject"] {+ let mut app = app_with(Kind::Type);+ assert!(crate::menus::is_enabled(&app, filter), "{filter}");+ menu(&mut app, filter).unwrap();+ assert!(!is_open(&app), "{filter}: waits for the answer");+ let id = prompt(&app).unwrap_or_else(|| panic!("{filter}: no prompt")).id;+ app.ui.dialog_mut(id).unwrap().fields.insert("choice".into(), json!(choice));+ answer(&mut app, id);+ assert!(!app.ui.status_error, "{filter}/{choice}: {}", app.ui.status);+ assert_eq!(active_content(&app), if choice == "rasterize" { "Pixel" } else { "Smart Object" }, "{filter}");+ assert!(is_open(&app), "{filter}/{choice}: its window opens");+ }+ }+}++/// Last Filter asks only when there is a filter to repeat, then repeats it on the rasterized layer.+#[test]+fn last_filter_on_a_type_layer_needs_a_filter_to_repeat() {+ let mut app = app_with(Kind::Type);+ assert!(!crate::menus::is_enabled(&app, "filter.lastFilter"), "nothing to repeat yet");+ app.run("layer.new.layer", json!({})).unwrap();+ app.run("edit.fill", json!({"color": "#00ff00"})).unwrap();+ app.run("filter.blur.blurMore", json!({})).unwrap();+ let st = app.session.active().unwrap();+ let text = st.doc.layers.iter().find(|l| matches!(l.content, LayerContent::Text(_))).unwrap().id;+ app.run("layer.select", json!({"layer": text.0})).unwrap();+ assert!(crate::menus::is_enabled(&app, "filter.lastFilter"));+ let before = past(&app);+ menu(&mut app, "filter.lastFilter").unwrap();+ let id = prompt(&app).expect("the prompt").id;+ answer(&mut app, id);+ assert!(!app.ui.status_error, "{}", app.ui.status);+ assert_eq!(active_content(&app), "Pixel");+ assert_eq!(past(&app), before + 2, "rasterize, then Blur More again");+ assert_eq!(app.session.journal.iter().filter(|(id, _)| id == "filter.blur.blurMore").count(), 2);+}++/// Every Filter menu item live on a pixel layer is live on a type layer and gets there through the+/// prompt (Flame, Tree, Picture Frame already run on a type layer: they render on a new layer).+#[test]+fn every_filter_live_on_pixels_asks_on_a_type_layer() {+ let ids: Vec<&str> = crate::menu_catalog::CATALOG.iter().filter(|e| e.3.starts_with("filter.")).map(|e| e.3).collect();+ let mut pixels = app_with(Kind::Type);+ pixels.run("layer.rasterize.type", json!({})).unwrap();+ let mut asked = 0;+ for id in ids {+ let mut app = app_with(Kind::Type);+ if !crate::menus::is_enabled(&pixels, id) || app.session.is_enabled(id) {+ continue;+ }+ assert!(crate::menus::is_enabled(&app, id), "{id}");+ menu(&mut app, id).unwrap();+ let d = prompt(&app).unwrap_or_else(|| panic!("{id}: no prompt")).id;+ answer(&mut app, d);+ assert!(!app.ui.status_error, "{id}: {}", app.ui.status);+ assert_eq!(active_content(&app), "Pixel", "{id}");+ asked += 1;+ }+ assert!(asked > 40, "{asked} filters");+}++/// Vanishing Point edits pixels only: its prompt offers Rasterize, not Convert to Smart Object.+#[test]+fn vanishing_point_offers_only_rasterize() {+ use egui_kittest::kittest::Queryable;+ let app = app_with(Kind::Type);+ let mut h = harness(app);+ assert!(crate::menus::is_enabled(h.state(), "filter.vanishingPoint"));+ menu(h.state_mut(), "filter.vanishingPoint").unwrap();+ h.run_steps(4);+ assert!(h.query_by_label("Convert to Smart Object").is_none());+ let id = prompt(h.state()).unwrap().id;+ h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("choice".into(), json!("smartObject"));+ assert!(crate::dialogs::confirm(h.state_mut(), id).is_err(), "no conversion behind its back");+ assert_eq!(active_content(h.state()), "Type");+ menu(h.state_mut(), "filter.vanishingPoint").unwrap();+ h.run_steps(4);+ h.get_by_label("Rasterize").click();+ h.run_steps(4);+ assert_eq!(active_content(h.state()), "Pixel");+ assert!(h.state().distort.vanishing.is_some(), "Vanishing Point opens");+}