PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Lens Blur: an alpha channel as the depth map source, as in Photoshop (#7400) (#7508)
Korg1chf3fb5781ef43
diff --git a/crates/algo/src/blur2.rs b/crates/algo/src/blur2.rsindex e91740508..bb6b47656 100644--- a/crates/algo/src/blur2.rs+++ b/crates/algo/src/blur2.rs@@ -335,7 +335,7 @@ pub(crate) fn lens_blur(src: &Image, out: Rect, ctx: &Ctx, spec: &LensSpec) -> V}src.get(x, y, n - 1)}- DepthSource::LayerMask => spec.depth_map?.get(x, y, 0),+ DepthSource::LayerMask | DepthSource::Channel => spec.depth_map?.get(x, y, 0),};Some(if spec.invert { 1.0 - d } else { d })};diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rsindex 5a034e456..ac4b3b1fc 100644--- a/crates/algo/src/lib.rs+++ b/crates/algo/src/lib.rs@@ -482,7 +482,8 @@ pub enum FilterParams {distribution: Distribution,monochromatic: bool,seed: u32,- /// Depth for [`DepthSource::LayerMask`] (channel 0, document coordinates), supplied by the caller.+ /// Depth for [`DepthSource::LayerMask`] and [`DepthSource::Channel`] (channel 0, document+ /// coordinates), supplied by the caller.#[serde(skip)]depth_map: Option<std::sync::Arc<Image>>,},diff --git a/crates/algo/src/params_ext.rs b/crates/algo/src/params_ext.rsindex 3a9572fb4..234960419 100644--- a/crates/algo/src/params_ext.rs+++ b/crates/algo/src/params_ext.rs@@ -182,6 +182,9 @@ pub enum DepthSource {None,Transparency,LayerMask,+ /// An alpha channel of the document (Photoshop lists them after Layer Mask), supplied by the+ /// caller like the layer mask.+ Channel,}/// Built-in Shape Blur kernels.diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rsindex 6f86413d1..f9fab33e3 100644--- a/crates/engine/src/edit_menu_cmds.rs+++ b/crates/engine/src/edit_menu_cmds.rs@@ -331,7 +331,7 @@ fn can_caf(s: &Session) -> std::result::Result<(), String> {}/// Mask surface (gray) of an alpha channel by index or name.-fn channel_mask<'a>(doc: &'a Document, v: &Value) -> Option<&'a Surface> {+pub(crate) fn channel_mask<'a>(doc: &'a Document, v: &Value) -> Option<&'a Surface> {match v {Value::Number(n) => doc.channels.get(n.as_u64()? as usize).map(|c| &c.surface),Value::String(name) => doc.channels.iter().find(|c| c.name == *name).map(|c| &c.surface),diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rsindex 221709080..dd0ff8c80 100644--- a/crates/engine/src/filters.rs+++ b/crates/engine/src/filters.rs@@ -292,6 +292,11 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result<Value>let surf = match &mut l.content {LayerContent::Raster(surf) => surf,LayerContent::Smart(_) => {+ // A smart filter re-renders from its params alone, without the document's+ // channels, so Lens Blur's alpha-channel depth would be lost (#7400).+ if matches!(fp, FilterParams::LensBlur { depth: algo::DepthSource::Channel, .. }) {+ return Err(EngineError::Other("Lens Blur can't read an alpha channel as depth on a Smart Object: rasterize the layer first".into()));+ }// Non-destructive: record the filter and re-render the smart object from its source.let sf =SmartFilter { command: id.clone(), params: params.clone(), blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true };diff --git a/crates/engine/src/filters/validation.rs b/crates/engine/src/filters/validation.rsindex 068d37e9d..b2359ffa5 100644--- a/crates/engine/src/filters/validation.rs+++ b/crates/engine/src/filters/validation.rs@@ -123,9 +123,11 @@ fn choices(id: &str) -> Option<&'static [(&'static str, &'static str)]> {"filter.distort.zigZag" => &[("style", "pondRipples|outFromCenter|aroundCenter")],"filter.render.lensFlare" => &[("lens", "zoom|prime35|prime105|moviePrime")],"filter.render.lightingEffects" => &[("lightType", "spot|point|infinite"), ("texture", "none|red|green|blue|alpha|luminance")],- "filter.blur.lensBlur" => {- &[("shape", "hexagon|triangle|square|pentagon|heptagon|octagon"), ("depthMap", "none|transparency|layerMask"), ("distribution", "uniform|gaussian")]- }+ "filter.blur.lensBlur" => &[+ ("shape", "hexagon|triangle|square|pentagon|heptagon|octagon"),+ ("depthMap", "none|transparency|layerMask|channel"),+ ("distribution", "uniform|gaussian"),+ ],"filter.other.hsbHsl" => &[("inputMode", "rgb|hsb|hsl"), ("rowOrder", "hsb|hsl|rgb")],"filter.video.deInterlace" => &[("eliminate", "oddFields|evenFields"), ("createBy", "interpolation|duplication")],_ => return None,diff --git a/crates/engine/src/filters_ext.rs b/crates/engine/src/filters_ext.rsindex e4f6523a1..0425e1932 100644--- a/crates/engine/src/filters_ext.rs+++ b/crates/engine/src/filters_ext.rs@@ -277,6 +277,7 @@ pub fn params_for(id: &str, p: &Value) -> Option<FilterParams> {depth: match s(p, "depthMap", "none") {"transparency" => DepthSource::Transparency,"layerMask" => DepthSource::LayerMask,+ "channel" => DepthSource::Channel,_ => DepthSource::None,},focal_distance: f(p, "focalDistance", 0.0).clamp(0.0, 255.0),@@ -429,8 +430,19 @@ fn map_from_document(doc: &Document, layer: Option<u64>) -> Option<algo::Image>}/// Resolves inputs that live outside the target layer: Displace's map (`mapPath`, or-/// `mapDocument` index with optional `mapLayer` id).+/// `mapDocument` index with optional `mapLayer` id), and the alpha channel Lens Blur reads its+/// depth from (`depthChannel`, an index or a name).pub(crate) fn resolve(s: &Session, fp: &mut FilterParams, p: &Value) -> Result<()> {+ if let FilterParams::LensBlur { depth: DepthSource::Channel, depth_map, .. } = fp {+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;+ let channel = p+ .get("depthChannel")+ .ok_or_else(|| EngineError::Other("Lens Blur: `depthMap` channel needs `depthChannel` (an alpha channel's index or name)".into()))?;+ let surface = crate::edit_menu_cmds::channel_mask(doc, channel)+ .ok_or_else(|| EngineError::Other(format!("Lens Blur: the document has no alpha channel {channel}")))?;+ *depth_map = Some(Arc::new(algo::Image::read(surface, doc.bounds())));+ return Ok(());+ }let FilterParams::Displace { map, .. } = fp else { return Ok(()) };if map.is_some() {return Ok(());@@ -662,7 +674,7 @@ pub fn specs() -> Vec<CommandSpec> {"filter.blur.lensBlur","Lens Blur…",["Filter", "Blur"],- r##"{"radius":0..100=15,"shape":"hexagon|triangle|square|pentagon|heptagon|octagon","bladeCurvature":0..100=0,"rotation":0..360=0,"depthMap":"none|transparency|layerMask","focalDistance":0..255=0,"invert":bool,"brightness":0..100=0,"threshold":0..255=255,"noise":0..100=0,"distribution":"uniform|gaussian","monochromatic":bool,"seed":u32=0}"##+ r##"{"radius":0..100=15,"shape":"hexagon|triangle|square|pentagon|heptagon|octagon","bladeCurvature":0..100=0,"rotation":0..360=0,"depthMap":"none|transparency|layerMask|channel","depthChannel":index|name?,"focalDistance":0..255=0,"invert":bool,"brightness":0..100=0,"threshold":0..255=255,"noise":0..100=0,"distribution":"uniform|gaussian","monochromatic":bool,"seed":u32=0}"##),cmd!("filter.blur.shapeBlur",diff --git a/crates/engine/src/filters_ext/tests.rs b/crates/engine/src/filters_ext/tests.rsindex 0f32c5367..490568e87 100644--- a/crates/engine/src/filters_ext/tests.rs+++ b/crates/engine/src/filters_ext/tests.rs@@ -220,6 +220,51 @@ fn lens_blur_uses_the_layer_mask_as_depth() {assert_ne!(pixels(&s), before);}+/// #7400: an alpha channel is a Lens Blur depth source, by name or index, as Photoshop lists+/// the document's channels in Depth Map › Source. A missing channel is an error that changes+/// nothing, and on a Smart Object (whose smart filters re-render without the channels) it is+/// refused instead of silently blurring without depth.+#[test]+fn lens_blur_reads_an_alpha_channel_as_depth() {+ let mut s = session();+ // A white channel: depth 1 everywhere. Creating it targets it; the filter is for the layer.+ s.execute("channel.new", json!({"name": "Depth Map", "fill": "white"})).unwrap();+ s.execute("channel.target", json!({"channel": "composite"})).unwrap();+ let before = pixels(&s);+ for channel in [json!("Depth Map"), json!(0)] {+ let p = |focal: f64| json!({"radius": 6, "depthMap": "channel", "depthChannel": channel, "focalDistance": focal});+ // Focal distance 255 puts depth 1 in focus: nothing blurs.+ s.execute("filter.blur.lensBlur", p(255.0)).unwrap();+ assert_eq!(pixels(&s), before, "{channel}: in focus");+ s.execute("filter.blur.lensBlur", p(0.0)).unwrap();+ assert_ne!(pixels(&s), before, "{channel}: out of focus blurs");+ s.execute("edit.undo", json!({})).unwrap();+ assert_eq!(pixels(&s), before);+ }+ for bad in [+ json!({"radius": 6, "depthMap": "channel"}),+ json!({"radius": 6, "depthMap": "channel", "depthChannel": "Nope"}),+ json!({"radius": 6, "depthMap": "channel", "depthChannel": 7}),+ ] {+ let doc = s.active().unwrap().doc.clone();+ let past = s.active().unwrap().history.past_len();+ let e = s.execute("filter.blur.lensBlur", bad.clone()).unwrap_err().to_string();+ assert!(e.contains("Lens Blur"), "{bad}: {e}");+ assert_eq!(pixels(&s), before, "{bad}: nothing changed");+ let st = s.active().unwrap();+ assert!(std::sync::Arc::ptr_eq(&doc, &st.doc), "{bad}: the document was replaced");+ assert_eq!(st.history.past_len(), past, "{bad}: a history step was recorded");+ }+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();+ let doc = s.active().unwrap().doc.clone();+ let past = s.active().unwrap().history.past_len();+ let e = s.execute("filter.blur.lensBlur", json!({"radius": 6, "depthMap": "channel", "depthChannel": "Depth Map"})).unwrap_err().to_string();+ assert!(e.contains("Smart Object"), "{e}");+ let st = s.active().unwrap();+ assert!(std::sync::Arc::ptr_eq(&doc, &st.doc), "no smart filter was added");+ assert_eq!(st.history.past_len(), past, "no history step");+}+#[test]fn params_map_to_algorithm_units() {assert_eq!(params_for("filter.pixelate.crystallize", &json!({"cellSize": 1})), Some(FilterParams::Crystallize { cell_size: 3.0, seed: 0 }));diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rsindex 72126a69c..d09caf495 100644--- a/crates/ui-egui/src/filter_dialog.rs+++ b/crates/ui-egui/src/filter_dialog.rs@@ -111,7 +111,8 @@ pub fn parse_spec(spec: &str) -> Vec<Param> {Kind::Color(crate::color_picker_ui::parse_hex(default))} else if v == "doc" {Kind::Document- } else if v == "json" || v.starts_with("layer id") || v.starts_with('[') || v.starts_with('{') {+ } else if v == "json" || v.starts_with("layer id") || v.starts_with('[') || v.starts_with('{') || v.trim_end_matches('?') == "index|name" {+ // `index|name`: a reference (an alpha channel…) the dialog sets through another control.Kind::Json} else if let Some(n) = v.strip_prefix("int[").and_then(|r| r.strip_suffix(']')).and_then(|n| n.parse().ok()) {Kind::Grid(n)@@ -468,6 +469,9 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {if crate::blur_pins::handles(command) {crate::blur_pins::init(app, &mut fields);}+ if command == LENS_BLUR {+ lens_blur_channels(app, &mut fields);+ }if parse_spec(spec.params).iter().any(|p| p.kind == Kind::Document) {// The document picker lists every open document (params refer to them by index).let names: Vec<String> = app.session.documents().iter().map(|d| d.doc.name.clone()).collect();@@ -594,6 +598,37 @@ fn uses_logarithmic_slider(min: f32, max: f32) -> bool {min > 0.0 && max / min > 500.0}+const LENS_BLUR: &str = "filter.blur.lensBlur";++/// Lens Blur's Depth Map Source lists the document's alpha channels after None, Transparency+/// and Layer Mask, as in Photoshop (#7400): their names go to `__channels`. A `channel` source+/// without a channel this document has (references aren't remembered) opens as None.+fn lens_blur_channels(app: &PhotocraftApp, f: &mut Map<String, Value>) {+ let names: Vec<String> = app.session.active().map(|d| d.doc.channels.iter().map(|c| c.name.clone()).collect()).unwrap_or_default();+ let known = f.get("depthChannel").and_then(|v| channel_index(v, &names)).is_some();+ if f.get("depthMap").and_then(Value::as_str) == Some("channel") && !known {+ f.insert("depthMap".into(), json!("none"));+ f.remove("depthChannel");+ }+ f.insert("__channels".into(), json!(names));+}++/// Lens Blur's Source menu entry for the alpha channel at `index`. By index, not name: two+/// channels may share a name, and each must be choosable.+fn channel_choice(index: usize) -> String {+ format!("channel:{index}")+}++/// The alpha channel `v` names (an index, or a name: the first channel so named), as the+/// engine reads `depthChannel`.+fn channel_index(v: &Value, names: &[String]) -> Option<usize> {+ match v {+ Value::Number(n) => n.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < names.len()),+ Value::String(name) => names.iter().position(|n| n == name),+ _ => None,+ }+}+/// Schema dialogs whose `profile` menu lists the installed profiles after the built-ins.const PROFILE_DIALOGS: &[&str] = &["edit.assignProfile", "edit.convertToProfile", "view.proofSetup"];@@ -767,6 +802,23 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {let mut cur = f.get(&p.key).and_then(Value::as_str).unwrap_or(initial).to_string();let labels: Vec<String> = options.iter().map(|o| choice_label(o)).collect();let mut opts: Vec<(String, &str)> = options.iter().cloned().zip(labels.iter().map(String::as_str)).collect();+ // Lens Blur's Source: each alpha channel by its name, in place of `channel`.+ let depth = cmd == LENS_BLUR && p.key == "depthMap";+ let names: Vec<String> = if depth {+ f.get("__channels").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect()+ } else {+ Vec::new()+ };+ let channels: Vec<String> = (0..names.len()).map(channel_choice).collect();+ if depth {+ opts.retain(|(v, _)| v != "channel");+ opts.extend(channels.iter().cloned().zip(names.iter().map(String::as_str)));+ if cur == "channel"+ && let Some(i) = f.get("depthChannel").and_then(|v| channel_index(v, &names))+ {+ cur = channel_choice(i);+ }+ }// Like Photoshop, the profile menus also list every profile installed in// the system (printer and paper profiles), by description.let installed = if p.key == "profile" && PROFILE_DIALOGS.contains(&cmd.as_str()) {@@ -788,6 +840,12 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {opts.push((cur.clone(), stem.as_str()));}crate::widgets::dropdown(ui, &format!("flt-{cmd}-{}", p.key), &mut cur, &opts, 170.0);+ if let Some(i) = cur.strip_prefix("channel:").filter(|_| depth).and_then(|i| i.parse::<usize>().ok()) {+ f.insert("depthChannel".into(), json!(i));+ cur = "channel".into();+ } else if depth {+ f.remove("depthChannel");+ }f.insert(p.key.clone(), json!(cur));});}@@ -1468,6 +1526,38 @@ mod tests {assert_eq!(params["amount"].as_f64(), Some(37.5));}+ /// #7400: Lens Blur's Source lists the document's alpha channels, by name, each choosable even+ /// when two share a name; `depthChannel` is set through that menu, not shown as a field, and+ /// like the other references it isn't remembered, so a remembered `channel` source opens as None.+ #[test]+ fn lens_blur_source_lists_the_alpha_channels() {+ let spec = photocraft_engine::commands::find(LENS_BLUR).unwrap().params;+ let params = parse_spec(spec);+ assert!(params.iter().any(|p| p.key == "depthChannel" && p.kind == Kind::Json), "depthChannel is no dialog field");+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 20, "height": 10})).unwrap();+ app.run("channel.new", json!({"name": "Depth Map", "fill": "white"})).unwrap();+ let id = open(&mut app, LENS_BLUR).unwrap();+ assert_eq!(app.ui.dialog_mut(id).unwrap().fields["__channels"], json!(["Depth Map"]));+ // The menu's values are channel indices, so two channels with one name are both choosable.+ app.run("channel.new", json!({"name": "Depth Map", "fill": "black"})).unwrap();+ let id = open(&mut app, LENS_BLUR).unwrap();+ let names: Vec<String> = serde_json::from_value(app.ui.dialog_mut(id).unwrap().fields["__channels"].clone()).unwrap();+ assert_eq!(names, ["Depth Map", "Depth Map"]);+ assert_eq!((channel_choice(0), channel_choice(1)), ("channel:0".to_string(), "channel:1".to_string()));+ assert_eq!(channel_index(&json!(1), &names), Some(1), "the second one by its index");+ assert_eq!(channel_index(&json!("Depth Map"), &names), Some(0), "a name is the first so named, as the engine reads it");+ assert_eq!(channel_index(&json!(2), &names), None);++ app.session.prefs.edit(|p| {+ p.dialogs.insert(LENS_BLUR.into(), json!({"depthMap": "channel", "depthChannel": "Depth Map"}));+ });+ let id = open(&mut app, LENS_BLUR).unwrap();+ let f = &app.ui.dialog_mut(id).unwrap().fields;+ assert_eq!(f["depthMap"], "none", "no channel was remembered with it");+ assert!(f.get("depthChannel").is_none());+ }+#[test]fn wide_positive_ranges_use_the_logarithmic_slider_path() {assert!(uses_logarithmic_slider(0.1, 1000.0), "Gaussian Blur radius");diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex a170c9663..d5d58b2ff 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -743,6 +743,7 @@Brush Settings 브러시 설정Brushes 브러시Channels 채널+ Channel 채널Character 문자Character Styles 문자 스타일Clone Source 복제 원본diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 8928778e4..0f242f8f6 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -772,6 +772,7 @@Brush Settings 画笔设置Brushes 画笔Channels 通道+ Channel 通道Character 字符Character Styles 字符样式Clone Source 仿制源diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex 0d6818057..621bee551 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -777,6 +777,7 @@Brush Settings 筆刷設定Brushes 筆刷Channels 色版+ Channel 色版Character 字元Character Styles 字元樣式Clone Source 仿製來源