PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Channels: Multichannel conversion keeps the targeted channel (#7002)
David Mann361a1bf22e10
diff --git a/crates/engine/src/multichannel_cmds.rs b/crates/engine/src/multichannel_cmds.rsindex a6e74101b..b0d46c2e4 100644--- a/crates/engine/src/multichannel_cmds.rs+++ b/crates/engine/src/multichannel_cmds.rs@@ -19,6 +19,7 @@ use photocraft_doc::{AlphaChannel, Document, Layer, LayerContent};use photocraft_raster::Surface;use serde_json::{Value, json};+use crate::channel_cmds::ChannelTarget;use crate::commands::CommandSpec;use crate::{EngineError, Result, Session};@@ -119,6 +120,9 @@ fn inks_of(doc: &Document) -> Vec<(String, Color, Vec<f32>)> {}fn to_multichannel(s: &mut Session, _p: &Value) -> Result<Value> {+ let Some((old, view)) = s.active().map(|st| (st.doc.channels.len(), (st.channel_view.target, st.channel_view.alpha_visible.clone()))) else {+ return Err(EngineError::NoDocument);+ };let names = s.edit("Multichannel", |doc, active| {let inks = inks_of(doc);let mut channels: Vec<AlphaChannel> = inks@@ -143,15 +147,45 @@ fn to_multichannel(s: &mut Session, _p: &Value) -> Result<Value> {doc.icc_profile = None;Ok(inks.into_iter().map(|(n, _, _)| n).collect::<Vec<_>>())})?;+ // The alpha channels moved behind the inks.+ let map: Vec<Option<usize>> = (0..old).map(|i| Some(i + names.len())).collect();+ remap_view(s, view, &map);Ok(json!({ "mode": "multichannel", "channels": names }))}+/// Keep the Channels target and eyes on the same channels after a conversion moved them:+/// `view` is the target and alpha eyes before the conversion, `map[i]` the new index of old+/// channel `i`, `None` when it left (a targeted ink becomes the composite).+fn remap_view(s: &mut Session, (target, eyes): (ChannelTarget, Vec<bool>), map: &[Option<usize>]) {+ let Some(st) = s.active_mut() else { return };+ let mut visible = vec![false; st.doc.channels.len()];+ for (&on, to) in eyes.iter().zip(map) {+ if let (true, Some(slot)) = (on, to.and_then(|j| visible.get_mut(j))) {+ *slot = true;+ }+ }+ let v = &mut st.channel_view;+ v.alpha_visible = visible;+ if let ChannelTarget::Alpha(t) = target {+ v.target = map.get(t).copied().flatten().map_or(ChannelTarget::Composite, ChannelTarget::Alpha);+ }+ crate::channel_cmds::fix_view(st);+}+/// Image › Mode › RGB / CMYK / Lab / Grayscale from a Multichannel document (called by/// `color_cmds::convert_mode`). Profiles are not involved: Multichannel has none.pub(crate) fn convert_from(s: &mut Session, mode: ColorMode, _p: &Value) -> Result<Value> {if !matches!(mode, ColorMode::Rgb | ColorMode::Cmyk | ColorMode::Lab | ColorMode::Grayscale) {return Err(EngineError::Other(format!("a Multichannel document can't be converted to {mode:?}")));}+ // The inks leave; the other channels close up.+ let Some((spots, view)) = s+ .active()+ .map(|st| (st.doc.channels.iter().map(|c| c.spot.is_some()).collect::<Vec<_>>(), (st.channel_view.target, st.channel_view.alpha_visible.clone())))+ else {+ return Err(EngineError::NoDocument);+ };+ let map: Vec<Option<usize>> = spots.iter().enumerate().map(|(i, &spot)| (!spot).then(|| spots.iter().take(i).filter(|&&sp| !sp).count())).collect();let how = s.edit("Mode Change", |doc, active| {let (inks, others): (Vec<AlphaChannel>, Vec<AlphaChannel>) = std::mem::take(&mut doc.channels).into_iter().partition(|c| c.spot.is_some());let canvas = doc.bounds();@@ -195,6 +229,7 @@ pub(crate) fn convert_from(s: &mut Session, mode: ColorMode, _p: &Value) -> Resudoc.channels = others;Ok(if reinterpret { "channels" } else { "appearance" })})?;+ remap_view(s, view, &map);Ok(json!({ "mode": format!("{mode:?}").to_lowercase(), "from": "multichannel", "converted": how }))}diff --git a/crates/engine/src/multichannel_cmds/tests.rs b/crates/engine/src/multichannel_cmds/tests.rsindex e8df57498..f96ff48e9 100644--- a/crates/engine/src/multichannel_cmds/tests.rs+++ b/crates/engine/src/multichannel_cmds/tests.rs@@ -119,6 +119,33 @@ fn flattens_layers_and_keeps_alpha_channels() {assert!(doc(&s).layers[0].surface().unwrap().pixel(1, 1)[0] < 0.01);}+#[test]+fn targeted_alpha_channel_stays_targeted_across_conversions() {+ use crate::channel_cmds::ChannelTarget;+ let mut s = session("rgb", 8);+ s.execute("channel.new", json!({})).unwrap();+ let view = |s: &Session| s.active().unwrap().channel_view.clone();+ assert_eq!(view(&s).target, ChannelTarget::Alpha(0));+ assert_eq!(view(&s).alpha_visible, [true]);+ s.execute("image.mode.multichannel", json!({})).unwrap();+ // The alpha channel now follows the three inks.+ assert_eq!(view(&s).target, ChannelTarget::Alpha(3));+ assert_eq!(view(&s).alpha_visible, [false, false, false, true]);+ let cyan = doc(&s).channels[0].surface.pixel(4, 3)[0];+ s.execute("edit.fill", json!({"color": "#ffffff"})).unwrap();+ assert_eq!(doc(&s).channels[0].surface.pixel(4, 3)[0], cyan, "the fill must not touch the Cyan plate");+ assert_eq!(doc(&s).channels[3].name, "Alpha 1");+ // Back to RGB: the inks leave, the alpha channel is index 0 again.+ s.execute("image.mode.rgb", json!({})).unwrap();+ assert_eq!(view(&s).target, ChannelTarget::Alpha(0));+ assert_eq!(view(&s).alpha_visible, [true]);+ // A targeted ink becomes the composite.+ s.execute("image.mode.multichannel", json!({})).unwrap();+ s.active_mut().unwrap().channel_view.target = ChannelTarget::Alpha(1);+ s.execute("image.mode.rgb", json!({})).unwrap();+ assert_eq!(view(&s).target, ChannelTarget::Composite);+}+#[test]fn mismatched_channel_count_converts_the_printed_look() {let mut s = session("rgb", 8);