diff --git a/crates/engine-core/src/cmd/channel_cmds.rs b/crates/engine-core/src/cmd/channel_cmds.rs index a595d6712d9..43c8965c4e8 100644 --- a/crates/engine-core/src/cmd/channel_cmds.rs +++ b/crates/engine-core/src/cmd/channel_cmds.rs @@ -79,12 +79,16 @@ fn operation<'a>(p: &'a Value, key: &str) -> &'a str { /// The Channels panel rows and view state of a document (also part of `inspect`). pub fn channels_json(st: &DocState) -> Value { let doc = &st.doc; - let mode = edit_mode(doc); + let mode = display_mode(doc); let v = &st.channel_view; let colors = color_count(doc); + let composite_visible = v.visible_colors(colors) == colors; json!({ "composite": composite_name(mode), - "colors": color_names(mode).iter().enumerate().map(|(k, n)| json!({ "name": n, "visible": v.color_visible(k) })).collect::>(), + "colors": color_names(mode).iter().enumerate().map(|(k, n)| { + let visible = if mode == ColorMode::Indexed { composite_visible } else { v.color_visible(k) }; + json!({ "name": n, "visible": visible }) + }).collect::>(), "alpha": doc.channels.iter().enumerate().map(|(i, c)| json!({ "index": i, "name": c.name, @@ -97,7 +101,7 @@ pub fn channels_json(st: &DocState) -> Value { "quickMask": doc.quick_mask.as_ref().map(|q| json!({ "visible": !v.quick_mask_hidden, "color": q.color.to_rgb(), "opacity": q.opacity, "indicates": q.indicates })), "target": v.target, "selectedColors": v.color_selection(colors).map(|c| c.indices().collect::>()), - "compositeVisible": v.visible_colors(colors) == colors, + "compositeVisible": composite_visible, "layerMaskView": crate::mask_view_cmds::view_json(st), }) } @@ -130,7 +134,6 @@ mod undo_channel_target_tests; use calc::{apply_image, calculations}; use manage::{delete_channel, duplicate_channel, move_channel, new_channel, new_spot, options, rename_channel, set_visible}; -use planes::edit_mode; pub(crate) use planes::tone; pub use planes::{ GraySurface, IsolatedCurveChannel, channel_format, color_count, curve_channel_for_colors, filter_mask_curve_channel, isolated_curve_channel, @@ -156,7 +159,7 @@ pub(crate) use targeting::{ targeted_channel, }; pub use tone_target::{ToneTarget, resolve_tone_target}; -pub use view::{ChannelTarget, ChannelView, QuickMaskOptions, color_names, composite_name}; +pub use view::{ChannelTarget, ChannelView, QuickMaskOptions, color_names, composite_name, display_mode}; pub(crate) use view::{fix_view, restore_view_after_undo}; pub fn specs() -> Vec { @@ -306,8 +309,7 @@ fn has_layer_mask(s: &Session) -> std::result::Result<(), String> { fn slot_ok(s: &Session) -> std::result::Result<(), String> { let d = s.active().ok_or("no document open")?; - let colors = color_count(&d.doc); - let shown = if colors > 1 { colors } else { 0 }; + let shown = targeting::shortcut_color_count(&d.doc); if N - 3 < shown + d.doc.channels.len() { Ok(()) } else { Err(format!("no channel for {SLOT_KEY}{N}")) } } diff --git a/crates/engine-core/src/cmd/channel_cmds/refs.rs b/crates/engine-core/src/cmd/channel_cmds/refs.rs index 329763f1092..f336f28e3a3 100644 --- a/crates/engine-core/src/cmd/channel_cmds/refs.rs +++ b/crates/engine-core/src/cmd/channel_cmds/refs.rs @@ -1,6 +1,6 @@ use super::planes::{color_count, edit_mode, luminosity, read_plane, tone}; use super::view::{color_names, composite_name}; -use super::{BlendMode, Document, EngineError, LayerContent, LayerId, Result, Session, Value, blend_channel, from_rgba, sel, to_rgba}; +use super::{BlendMode, ColorMode, Document, EngineError, LayerContent, LayerId, Result, Session, Value, blend_channel, from_rgba, sel, to_rgba}; // --------------------------------------------------------------------------------------------- // Channel references @@ -23,6 +23,7 @@ pub enum ChanRef { /// Resolve channel references; a color-name object cannot fall back to a named alpha channel. pub fn parse_ref(v: &Value, doc: &Document) -> Option { let mode = edit_mode(doc); + let is_index = |name: &str| doc.mode == ColorMode::Indexed && name.eq_ignore_ascii_case(composite_name(doc.mode)); match v { Value::Number(n) => n.as_u64().map(|i| ChanRef::Alpha(i as usize)), Value::Object(o) => { @@ -32,6 +33,9 @@ pub fn parse_ref(v: &Value, doc: &Document) -> Option { return doc.channels.iter().position(|c| c.name == name).map(ChanRef::Alpha); } if let Some(name) = o.get("color").and_then(Value::as_str) { + if is_index(name) { + return Some(ChanRef::Composite); + } let names = color_names(mode); let k = names.iter().position(|n| n.eq_ignore_ascii_case(name))?; Some(if names.len() == 1 { ChanRef::Composite } else { ChanRef::Color(k) }) @@ -58,7 +62,7 @@ pub fn parse_ref(v: &Value, doc: &Document) -> Option { if let Some(k) = color_names(mode).iter().position(|n| n.eq_ignore_ascii_case(&l)) { return Some(if color_names(mode).len() == 1 { ChanRef::Composite } else { ChanRef::Color(k) }); } - doc.channels.iter().position(|c| c.name == *s).map(ChanRef::Alpha) + doc.channels.iter().position(|c| c.name == *s).map(ChanRef::Alpha).or_else(|| is_index(s).then_some(ChanRef::Composite)) } _ => None, } diff --git a/crates/engine-core/src/cmd/channel_cmds/targeting.rs b/crates/engine-core/src/cmd/channel_cmds/targeting.rs index 071405c7d62..b0fdb72b427 100644 --- a/crates/engine-core/src/cmd/channel_cmds/targeting.rs +++ b/crates/engine-core/src/cmd/channel_cmds/targeting.rs @@ -1,7 +1,7 @@ use super::manage::fix_view_now; use super::planes::{GraySurface, color_count, materialize}; use super::refs::{ChanRef, bad, parse_ref}; -use super::view::{ChannelTarget, touch}; +use super::view::{ChannelTarget, color_names, display_mode, touch}; use super::{ColorMode, Document, EngineError, Layer, LayerId, Rect, Result, Session, Surface, Value, from_rgba, json, list}; // --------------------------------------------------------------------------------------------- @@ -518,11 +518,16 @@ pub(super) fn target_cmd(s: &mut Session, p: &Value) -> Result { /// The channel shortcuts' modifier as the platform writes it, for error messages (`⌘4`, `Ctrl+4`). pub(super) const SLOT_KEY: &str = if cfg!(target_os = "macos") { "⌘" } else { "Ctrl+" }; +/// Number of component shortcuts before the alpha shortcuts, matching the channel rows in Indexed mode. +pub(super) fn shortcut_color_count(doc: &Document) -> usize { + let count = color_names(display_mode(doc)).len(); + if count > 1 { count } else { 0 } +} + /// ⌘2 composite, ⌘3… colour channels then alpha channels (Photoshop CC defaults). pub(super) fn target_slot(s: &mut Session, slot: usize) -> Result { let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let colors = color_count(doc); - let shown_colors = if colors > 1 { colors } else { 0 }; + let shown_colors = shortcut_color_count(doc); let t = match slot { 2 => ChannelTarget::Composite, n if n - 3 < shown_colors => ChannelTarget::Color(n - 3), diff --git a/crates/engine-core/src/cmd/channel_cmds/view.rs b/crates/engine-core/src/cmd/channel_cmds/view.rs index fbd5157f4ba..6c80a3d7b8e 100644 --- a/crates/engine-core/src/cmd/channel_cmds/view.rs +++ b/crates/engine-core/src/cmd/channel_cmds/view.rs @@ -136,12 +136,19 @@ pub(super) fn touch(st: &mut DocState) { // --------------------------------------------------------------------------------------------- // Channel names and formats +/// The mode used to label channel rows. Indexed documents expose one palette index +/// channel even though their editable pixel surfaces are stored as RGB. +pub fn display_mode(doc: &Document) -> ColorMode { + if doc.mode == ColorMode::Indexed { ColorMode::Indexed } else { doc.pixel_format().mode } +} + /// Colour channel names of a document mode (the rows under the composite). pub fn color_names(mode: ColorMode) -> &'static [&'static str] { match mode { ColorMode::Cmyk => &["Cyan", "Magenta", "Yellow", "Black"], ColorMode::Lab => &["Lightness", "a", "b"], ColorMode::Grayscale => &["Gray"], + ColorMode::Indexed => &["Index"], _ => &["Red", "Green", "Blue"], } } @@ -152,6 +159,7 @@ pub fn composite_name(mode: ColorMode) -> &'static str { ColorMode::Cmyk => "CMYK", ColorMode::Lab => "Lab", ColorMode::Grayscale => "Gray", + ColorMode::Indexed => "Index", _ => "RGB", } } diff --git a/crates/ui-egui/src/panels/channels_indexed_rows_tests.rs b/crates/ui-egui/src/panels/channels_indexed_rows_tests.rs new file mode 100644 index 00000000000..9bf2d70a8c1 --- /dev/null +++ b/crates/ui-egui/src/panels/channels_indexed_rows_tests.rs @@ -0,0 +1,91 @@ +use serde_json::{Value, json}; + +use super::{Row, rows}; +use crate::PhotocraftApp; +use crate::panels::QUICK_MASK; + +fn app_with(mode: &str) -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100, "mode": mode})).unwrap(); + app +} + +fn indexed_app() -> Box { + let mut app = app_with("rgb"); + app.run("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none"})).unwrap(); + app +} + +fn row_names(app: &PhotocraftApp) -> Vec { + rows(app).into_iter().map(|row| row.name).collect() +} + +fn inspect(app: &mut PhotocraftApp) -> Value { + app.run("document.inspect", json!({})).unwrap() +} + +#[test] +fn indexed_quick_mask_adds_one_row_and_round_trips_the_selection() { + let mut app = indexed_app(); + assert_eq!(row_names(&app), ["Index"]); + assert!(!app.session.is_enabled("channel.target.slot3")); + app.run("select.rect", json!({"x": 50, "y": 25, "width": 100, "height": 50})).unwrap(); + let before = inspect(&mut app)["selectionBounds"].clone(); + assert_eq!(before, json!([50, 25, 100, 50])); + + app.run(QUICK_MASK, json!({})).unwrap(); + assert_eq!(row_names(&app), ["Index", "Quick Mask"]); + let targeted: Vec<_> = rows(&app).into_iter().filter(|row| row.targeted).map(|row| row.key).collect(); + assert_eq!(targeted, [Row::QuickMask]); + let document = inspect(&mut app); + assert_eq!(document["channels"]["composite"], "Index"); + assert_eq!(document["channels"]["colors"], json!([{"name": "Index", "visible": true}])); + + app.run(QUICK_MASK, json!({})).unwrap(); + assert_eq!(row_names(&app), ["Index"]); + assert_eq!(inspect(&mut app)["selectionBounds"], before); +} + +#[test] +fn indexed_saved_alpha_and_existing_channel_references_still_work() { + let mut app = indexed_app(); + let inspected_name = inspect(&mut app)["channels"]["composite"].clone(); + app.run("channel.target", json!({"channel": inspected_name})).unwrap(); + assert!(rows(&app)[0].targeted); + + app.run("channel.new", json!({"name": "Index"})).unwrap(); + let keys: Vec<_> = rows(&app).into_iter().map(|row| row.key).collect(); + assert_eq!(keys, [Row::Composite, Row::Alpha(0)]); + app.run("channel.target", json!({"channel": "RGB"})).unwrap(); + assert!(rows(&app)[0].targeted); + assert!(rows(&app)[0].visible); + + app.run("channel.setVisible", json!({"channel": "blue", "visible": false})).unwrap(); + let channel_view = inspect(&mut app)["channels"].clone(); + assert_eq!(channel_view["colors"], json!([{"name": "Index", "visible": false}])); + assert!(!rows(&app)[0].visible); + + app.run("channel.target.slot3", json!({})).unwrap(); + assert!(rows(&app)[1].targeted); + assert!(!app.session.is_enabled("channel.target.slot4")); + app.run("channel.target", json!({"channel": {"color": "Index"}})).unwrap(); + assert!(rows(&app)[0].targeted); + app.run("channel.target", json!({"channel": "Index"})).unwrap(); + assert!(rows(&app)[1].targeted, "an existing alpha name still resolves to that alpha"); +} + +#[test] +fn neighboring_document_modes_keep_their_channel_rows() { + for (mode, names) in [ + ("rgb", &["RGB", "Red", "Green", "Blue"][..]), + ("grayscale", &["Gray"][..]), + ("cmyk", &["CMYK", "Cyan", "Magenta", "Yellow", "Black"][..]), + ("lab", &["Lab", "Lightness", "a", "b"][..]), + ] { + assert_eq!(row_names(&app_with(mode)), names, "{mode}"); + } + + let mut app = app_with("rgb"); + app.run("image.mode.multichannel", json!({})).unwrap(); + assert_eq!(row_names(&app), ["Cyan", "Magenta", "Yellow"]); +} diff --git a/crates/ui-egui/src/panels/channels_panel.rs b/crates/ui-egui/src/panels/channels_panel.rs index ae1d2cbea34..9c1fdfd8da6 100644 --- a/crates/ui-egui/src/panels/channels_panel.rs +++ b/crates/ui-egui/src/panels/channels_panel.rs @@ -144,8 +144,8 @@ pub(crate) fn rows(app: &PhotocraftApp) -> Vec> { let doc = &st.doc; let view = &st.channel_view; let mask_view = photocraft_engine::mask_view_cmds::current(st).map(|v| v.mode); - let mode = doc.pixel_format().mode; - let colors = mode.color_channels(); + let mode = channel_cmds::display_mode(doc); + let colors = doc.pixel_format().mode.color_channels(); let quick = doc.quick_mask.is_some(); let masked = st.active_layer.and_then(|id| doc.layer(id)).filter(|l| l.mask.is_some()); let mask_targeted = mask_row_targeted(masked.is_some(), app.ui.mask_target, view.target, quick); @@ -153,8 +153,9 @@ pub(crate) fn rows(app: &PhotocraftApp) -> Vec> { // Multichannel images are their ink channels only (no composite or colour rows). let multichannel = doc.mode == photocraft_doc::ColorMode::Multichannel; let mut keys = if multichannel { Vec::new() } else { vec![Row::Composite] }; - if colors > 1 && !multichannel { - keys.extend((0..colors).map(Row::Color)); + let names = channel_cmds::color_names(mode); + if names.len() > 1 && !multichannel { + keys.extend((0..names.len()).map(Row::Color)); } if masked.is_some() { keys.push(Row::LayerMask); @@ -494,3 +495,7 @@ pub(crate) fn run_fired(app: &mut PhotocraftApp, ctx: &egui::Context, command: & #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "channels_indexed_rows_tests.rs"] +mod channels_indexed_rows_tests;