diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index ca77a9a2f8..787a271e31 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -110,6 +110,97 @@ pub enum LabelColor { Blue, Violet, Gray, + Seafoam, + Indigo, + Magenta, + Fuchsia, +} + +impl LabelColor { + /// Display order, independent of the PSD sheet-colour indices. + pub const ALL: [Self; 12] = [ + Self::None, + Self::Red, + Self::Orange, + Self::Yellow, + Self::Green, + Self::Seafoam, + Self::Blue, + Self::Indigo, + Self::Magenta, + Self::Fuchsia, + Self::Violet, + Self::Gray, + ]; + + /// Stable, language-independent command and inspection value. + pub fn id(self) -> &'static str { + match self { + Self::None => "none", + Self::Red => "red", + Self::Orange => "orange", + Self::Yellow => "yellow", + Self::Green => "green", + Self::Seafoam => "seafoam", + Self::Blue => "blue", + Self::Indigo => "indigo", + Self::Magenta => "magenta", + Self::Fuchsia => "fuchsia", + Self::Violet => "violet", + Self::Gray => "gray", + } + } + + pub fn label(self) -> &'static str { + match self { + Self::None => "No Color", + Self::Red => "Red", + Self::Orange => "Orange", + Self::Yellow => "Yellow", + Self::Green => "Green", + Self::Seafoam => "Seafoam", + Self::Blue => "Blue", + Self::Indigo => "Indigo", + Self::Magenta => "Magenta", + Self::Fuchsia => "Fuchsia", + Self::Violet => "Violet", + Self::Gray => "Gray", + } + } + + pub fn from_id(id: &str) -> Option { + Self::ALL.into_iter().find(|c| c.id() == id) + } +} + +#[cfg(test)] +mod label_color_tests { + use super::LabelColor; + + #[test] + fn layer_color_ids_and_existing_serialized_names_stay_stable() { + for (name, color) in [ + ("None", LabelColor::None), + ("Red", LabelColor::Red), + ("Orange", LabelColor::Orange), + ("Yellow", LabelColor::Yellow), + ("Green", LabelColor::Green), + ("Blue", LabelColor::Blue), + ("Violet", LabelColor::Violet), + ("Gray", LabelColor::Gray), + ] { + assert_eq!(serde_json::to_value(color).unwrap(), name); + assert_eq!(serde_json::from_value::(serde_json::json!(name)).unwrap(), color); + } + for c in LabelColor::ALL { + assert_eq!(LabelColor::from_id(c.id()), Some(c)); + assert_eq!(serde_json::from_value::(serde_json::to_value(c).unwrap()).unwrap(), c); + } + for id in ["", "Red", "0", "unknown", "🔴"] { + assert_eq!(LabelColor::from_id(id), None); + } + assert!(serde_json::from_value::(serde_json::json!("Unknown")).is_err()); + } } #[derive(Clone, Debug, PartialEq)] diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 2c7b577e0a..3722c57eca 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -1063,6 +1063,7 @@ fn build() -> Vec { v.extend(crate::channel_cmds::specs()); v.extend(crate::adjust_cmds::specs()); v.extend(crate::layer_menu_cmds::specs()); + v.extend(crate::layer_label_cmds::specs()); v.extend(crate::mode_cmds::specs()); v.extend(crate::multichannel_cmds::specs()); v.extend(crate::pattern_cmds::specs()); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 9ff5df29c9..ac4104300a 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -74,6 +74,7 @@ fn layer_sel(l: &Layer, selected: &[photocraft_doc::LayerId]) -> Value { "name": l.name, "kind": l.content.kind_name(), "visible": l.visible, + "labelColor": l.label.id(), "opacity": l.opacity, "fill": l.fill_opacity, "blend": l.blend.label(), diff --git a/crates/engine/src/layer_label_cmds.rs b/crates/engine/src/layer_label_cmds.rs new file mode 100644 index 0000000000..acb450cdbf --- /dev/null +++ b/crates/engine/src/layer_label_cmds.rs @@ -0,0 +1,80 @@ +//! Undoable layer colour labels. A group applies the label to its existing descendants, +//! without changing pixels, visibility, locks or the layer selection. + +use photocraft_doc::{LabelColor, LayerId}; +use serde_json::{Value, json}; + +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +const ID: &str = "layer.setLabelColor"; + +fn bad(message: impl Into) -> EngineError { + EngineError::BadParams { cmd: ID.into(), msg: message.into() } +} + +fn enabled(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + if st.selected_layers().is_empty() { Err("no layer selected".into()) } else { Ok(()) } +} + +fn set_label(s: &mut Session, p: &Value) -> Result { + let p = p.as_object().ok_or_else(|| bad("expected an object"))?; + let color = + p.get("color").and_then(Value::as_str).and_then(LabelColor::from_id).ok_or_else(|| { + bad("`color` must be a layer colour id (none, red, orange, yellow, green, seafoam, blue, indigo, magenta, fuchsia, violet, gray)") + })?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let roots = match p.get("layer") { + Some(v) => vec![LayerId(v.as_u64().ok_or_else(|| bad("`layer` must be an unsigned integer"))?)], + None => st.selected_layers(), + }; + if roots.is_empty() { + return Err(bad("no layer selected")); + } + let walk = st.doc.walk(); + let mut paths = Vec::with_capacity(roots.len()); + for id in roots { + let (path, _, _) = walk.iter().find(|(_, _, l)| l.id == id).ok_or(EngineError::NoLayer(id))?; + paths.push(path); + } + // A single walk also deduplicates a selected child whose parent is selected. + let mut changed = false; + let targets: Vec<_> = walk + .iter() + .filter(|(path, _, _)| paths.iter().any(|root| path.starts_with(root))) + .map(|(path, _, l)| { + changed |= l.label != color; + (path.clone(), l.id) + }) + .collect(); + if changed { + s.edit("Layer Color", |doc, _| { + for (path, id) in &targets { + doc.layer_at_mut(path).ok_or(EngineError::NoLayer(*id))?.label = color; + } + Ok(()) + })?; + if let Some(st) = s.active_mut() { + // This is saved document metadata; no canvas pixels need recompositing. + st.last_damage = Some(photocraft_geom::Rect::EMPTY); + } + } + Ok(json!({"color": color.id(), "layers": targets.iter().map(|(_, id)| id.0).collect::>(), "changed": changed})) +} + +pub fn specs() -> Vec { + vec![CommandSpec { + id: ID, + label: "Layer Color", + menu: &[], + shortcut: None, + params: r#"{"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray","layer":id?} (no layer: selected layers; groups include descendants)"#, + enabled, + run: set_label, + journal: true, + }] +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/layer_label_cmds/tests.rs b/crates/engine/src/layer_label_cmds/tests.rs new file mode 100644 index 0000000000..78fa018e7d --- /dev/null +++ b/crates/engine/src/layer_label_cmds/tests.rs @@ -0,0 +1,123 @@ +use super::*; +use photocraft_color::SampleType; +use photocraft_doc::{Layer, LayerContent}; + +fn fixture(depth: u8) -> (Session, [LayerId; 4]) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4, "depth": depth})).unwrap(); + let ids = s + .edit("Fixture", |doc, _| { + let mut leaf = Layer::raster("Hidden, locked", doc.pixel_format()); + leaf.visible = false; + leaf.locks.all = true; + leaf.label = LabelColor::Blue; + let leaf_id = leaf.id; + let mut inner = Layer::group("Inner", vec![leaf]); + if let LayerContent::Group(g) = &mut inner.content { + g.expanded = false; + } + let inner_id = inner.id; + let outer = Layer::group("Outer", vec![inner]); + let outer_id = outer.id; + let other = Layer::raster("Other", doc.pixel_format()); + let other_id = other.id; + doc.layers = vec![outer, other]; + Ok([outer_id, inner_id, leaf_id, other_id]) + }) + .unwrap(); + s.select_layer(ids[0]).unwrap(); + (s, ids) +} + +#[test] +fn layer_color_groups_and_overlapping_selection_are_one_undo_step() { + for depth in [8, 16, 32] { + let (mut s, [outer, inner, leaf, other]) = fixture(depth); + crate::layer_multi_cmds::set_selection(&mut s, vec![outer, leaf], Some(leaf), Some(outer)).unwrap(); + let before = s.active().unwrap().doc.clone(); + let selected = s.active().unwrap().selected_layers(); + let past = s.active().unwrap().history.past_len(); + let r = s.execute(ID, json!({"color": "seafoam"})).unwrap(); + assert_eq!(r["layers"], json!([outer.0, inner.0, leaf.0])); + assert_eq!(s.active().unwrap().history.past_len(), past + 1); + assert_eq!(s.active().unwrap().selected_layers(), selected); + assert_eq!(s.active().unwrap().last_damage, Some(photocraft_geom::Rect::EMPTY)); + let after = s.active().unwrap().doc.clone(); + for id in [outer, inner, leaf] { + assert_eq!(after.layer(id).unwrap().label, LabelColor::Seafoam); + } + assert_eq!(after.layer(other), before.layer(other)); + let mut expected = (*before).clone(); + for id in [outer, inner, leaf] { + expected.layer_mut(id).unwrap().label = LabelColor::Seafoam; + } + assert_eq!(*after, expected, "only labels change at depth {depth}"); + assert_eq!(crate::inspect::layer(after.layer(leaf).unwrap())["labelColor"], "seafoam"); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + assert!(s.redo()); + assert_eq!(s.active().unwrap().doc, after); + let past = s.active().unwrap().history.past_len(); + let revision = s.active().unwrap().revision; + assert_eq!(s.execute(ID, json!({"color": "seafoam"})).unwrap()["changed"], false); + assert_eq!(s.active().unwrap().history.past_len(), past); + assert_eq!(s.active().unwrap().revision, revision); + } +} + +#[test] +fn layer_color_every_color_and_reset_target_only_the_requested_layer() { + let (mut s, [outer, _, leaf, other]) = fixture(8); + for color in LabelColor::ALL { + s.execute(ID, json!({"color": color.id(), "layer": other.0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.layer(other).unwrap().label, color); + assert_eq!(d.layer(outer).unwrap().label, LabelColor::None); + assert_eq!(d.layer(leaf).unwrap().label, LabelColor::Blue); + } + s.execute(ID, json!({"color": "none", "layer": outer.0})).unwrap(); + assert!(s.active().unwrap().doc.walk().iter().all(|(_, _, l)| l.label == LabelColor::None || l.id == other)); + s.execute(ID, json!({"color": "green", "layer": outer.0})).unwrap(); + s.select_layer(leaf).unwrap(); + s.execute("layer.new.layer", json!({"name": "Created later"})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().label, LabelColor::None); + assert!(matches!(st.doc.layer(outer).unwrap().content, LayerContent::Group(_))); + assert_eq!(st.doc.depth, SampleType::U8); +} + +#[test] +fn layer_color_invalid_params_never_change_the_document_or_history() { + let (mut s, _) = fixture(8); + for params in [ + Value::Null, + json!([]), + json!({}), + json!({"color": "unknown"}), + json!({"color": 1}), + json!({"color": "red", "layer": "1"}), + json!({"color": "red", "layer": -1}), + json!({"color": "red", "layer": 1.5}), + json!({"color": "red", "layer": null}), + json!({"color": "red", "layer": u64::MAX}), + ] { + let st = s.active().unwrap(); + let before = (st.doc.clone(), st.revision, st.history.past_len()); + assert!(s.execute(ID, params).is_err()); + let st = s.active().unwrap(); + assert_eq!((st.doc.clone(), st.revision, st.history.past_len()), before); + } + let mut empty = Session::new(); + assert!(!empty.is_enabled(ID)); + assert!(empty.execute(ID, json!({"color": "red"})).is_err()); + empty.execute("file.new", json!({"width": 2, "height": 2})).unwrap(); + empty + .edit("Empty", |doc, active| { + doc.layers.clear(); + *active = None; + Ok(()) + }) + .unwrap(); + assert!(!empty.is_enabled(ID)); + assert!(empty.execute(ID, json!({"color": "red"})).is_err()); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 46cfd37f43..e739414210 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -46,6 +46,7 @@ pub mod image_cmds; pub mod inspect; pub mod jobs; pub mod layer_copy_cmds; +pub mod layer_label_cmds; pub mod layer_menu_cmds; pub mod layer_multi_cmds; pub mod layer_nav_cmds; diff --git a/crates/format/tests/layer_labels.rs b/crates/format/tests/layer_labels.rs new file mode 100644 index 0000000000..45707e8909 --- /dev/null +++ b/crates/format/tests/layer_labels.rs @@ -0,0 +1,19 @@ +use photocraft_color::{ColorMode, SampleType}; +use photocraft_doc::{Document, LabelColor, Layer, Size}; + +#[test] +fn layer_labels_pcraft_roundtrip_all_colors_and_depths() { + for depth in SampleType::ALL { + let mut doc = Document::new("Labels", Size::new(2, 2), ColorMode::Rgb, depth); + for color in LabelColor::ALL { + let mut child = Layer::raster("Child", doc.pixel_format()); + child.label = color; + let mut group = Layer::group(color.label(), vec![child]); + group.label = color; + doc.layers.push(group); + } + let bytes = photocraft_format::save_to_bytes(&doc, &Default::default()).unwrap(); + assert_eq!(photocraft_format::load_from_bytes(&bytes).unwrap(), doc, "{depth:?}"); + assert!(photocraft_format::load_from_bytes(&bytes[..bytes.len() / 2]).is_err()); + } +} diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rs index bb13932038..c398608965 100644 --- a/crates/io/src/blocks.rs +++ b/crates/io/src/blocks.rs @@ -68,6 +68,11 @@ pub fn label_from_index(v: u16) -> LabelColor { 5 => LabelColor::Blue, 6 => LabelColor::Violet, 7 => LabelColor::Gray, + // Photoshop 2024 added these without renumbering the original labels. + 8 => LabelColor::Seafoam, + 9 => LabelColor::Indigo, + 10 => LabelColor::Magenta, + 11 => LabelColor::Fuchsia, _ => LabelColor::None, } } @@ -83,6 +88,10 @@ pub fn label_index(l: LabelColor) -> u16 { LabelColor::Blue => 5, LabelColor::Violet => 6, LabelColor::Gray => 7, + LabelColor::Seafoam => 8, + LabelColor::Indigo => 9, + LabelColor::Magenta => 10, + LabelColor::Fuchsia => 11, } } diff --git a/crates/io/tests/layer_labels.rs b/crates/io/tests/layer_labels.rs new file mode 100644 index 0000000000..792d2d621f --- /dev/null +++ b/crates/io/tests/layer_labels.rs @@ -0,0 +1,53 @@ +use photocraft_color::{ColorMode, SampleType}; +use photocraft_doc::{Document, LabelColor, Layer, Size}; + +#[test] +fn layer_labels_keep_the_psd_indices() { + use photocraft_io::blocks::{label_from_index, label_index}; + let labels = [ + LabelColor::None, + LabelColor::Red, + LabelColor::Orange, + LabelColor::Yellow, + LabelColor::Green, + LabelColor::Blue, + LabelColor::Violet, + LabelColor::Gray, + LabelColor::Seafoam, + LabelColor::Indigo, + LabelColor::Magenta, + LabelColor::Fuchsia, + ]; + for (i, color) in labels.into_iter().enumerate() { + assert_eq!(label_index(color), i as u16); + assert_eq!(label_from_index(i as u16), color); + } + for i in [12, 255, u16::MAX] { + assert_eq!(label_from_index(i), LabelColor::None); + } +} + +#[test] +fn layer_labels_psd_roundtrip_all_colors_and_depths() { + for depth in SampleType::ALL { + let mut doc = Document::new("Labels", Size::new(2, 2), ColorMode::Rgb, depth); + for color in LabelColor::ALL { + let mut child = Layer::raster("Child", doc.pixel_format()); + child.label = color; + let mut group = Layer::group(color.label(), vec![child]); + group.label = color; + doc.layers.push(group); + } + let bytes = photocraft_io::export(&doc, "labels.psd", &Default::default()).unwrap().bytes; + let back = photocraft_io::import("labels.psd", &bytes).unwrap().document; + let labels = |d: &Document| d.walk().into_iter().map(|(_, _, l)| (l.name.clone(), l.label)).collect::>(); + assert_eq!(labels(&back), labels(&doc), "{depth:?}"); + assert_eq!(back.depth, depth); + } +} + +#[test] +fn layer_labels_truncated_sheet_color_is_not_a_label() { + let block = photocraft_psd::TaggedBlock::new(*b"lclr", vec![0]); + assert!(matches!(block.parsed(), Some(Err(_)))); +} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 8e1490eefa..343e9af088 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2135,4 +2135,10 @@ cameraRaw Color Barvy % of all commits % všech commitů Lines +/− Řádky +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: PR: {prs}, commity: {commits}, řádky +{added} / −{deleted} (Δ {delta}), binární soubory +{binAdded} / −{binDeleted}, {first} – {last} + +# Layer colour labels. + Seafoam Mořská pěna + Indigo Indigová + Fuchsia Fuchsiová + Violet Fialová Apply At Canvas Bounds Použít efekt na hranicích plátna diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 707d381c96..560f0557da 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2174,4 +2174,11 @@ % of all commits % aller Commits Lines +/− Zeilen +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: {prs} PRs, {commits} Commits, +{added} / −{deleted} Zeilen (Δ {delta}), +{binAdded} / −{binDeleted} Binärdateien, {first} – {last} + +# Layer colour labels. +layerLabel No Color Keine Farbe + Seafoam Meeresschaum + Indigo Indigo + Fuchsia Fuchsia + Violet Violett Apply At Canvas Bounds Effekt an Arbeitsflächenbegrenzungen anwenden diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 96d7a70619..ba73a9e9c1 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2206,4 +2206,10 @@ cameraRaw Amount Cantidad % of all commits % de todos los commits Lines +/− Líneas +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: {prs} PR, {commits} commits, +{added} / −{deleted} líneas (Δ {delta}), +{binAdded} / −{binDeleted} archivos binarios, {first} – {last} + +# Layer colour labels. + Seafoam Espuma de mar + Indigo Índigo + Fuchsia Fucsia + Violet Violeta Apply At Canvas Bounds Aplicar efecto en los límites del lienzo diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 142fa35cd8..43ea80e069 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2566,4 +2566,10 @@ cameraRaw Blending Fusion % of all commits % de tous les commits Lines +/− Lignes +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login} : {prs} PR, {commits} commits, +{added} / −{deleted} lignes (Δ {delta}), +{binAdded} / −{binDeleted} fichiers binaires, {first} – {last} + +# Layer colour labels. + Seafoam Écume de mer + Indigo Indigo + Fuchsia Fuchsia + Violet Violet Apply At Canvas Bounds Appliquer l’effet aux limites de la zone de travail diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 7b51bfd1d2..6ba9792420 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2553,4 +2553,10 @@ cameraRaw Blending Pembauran % of all commits % dari semua commit Lines +/− Baris +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: {prs} PR, {commits} commit, +{added} / −{deleted} baris (Δ {delta}), +{binAdded} / −{binDeleted} berkas biner, {first} – {last} + +# Layer colour labels. + Seafoam Busa Laut + Indigo Nila + Fuchsia Fuksia + Violet Ungu Apply At Canvas Bounds Terapkan efek di batas kanvas diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index e5af7eb236..fe208b6775 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2208,4 +2208,10 @@ cameraRaw Amount Quantità Lines +/− Righe +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: {prs} PR, {commits} commit, +{added} / −{deleted} righe (Δ {delta}), +{binAdded} / −{binDeleted} risorse binarie, {first} – {last} Convert to Layers Converti in livelli + +# Layer colour labels. + Seafoam Schiuma marina + Indigo Indaco + Fuchsia Fucsia + Violet Viola Apply At Canvas Bounds Applica effetto ai limiti dell’area di lavoro diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4f1bc752b6..2eaabf982f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2118,4 +2118,10 @@ cameraRaw Color カラー % of all commits 全コミットに占める割合 (%) Lines +/− 行数 +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: PR {prs} 件、コミット {commits} 件、行 +{added} / −{deleted} (Δ {delta})、バイナリ +{binAdded} / −{binDeleted}、{first} – {last} + +# Layer colour labels. + Seafoam シーフォーム + Indigo インディゴ + Fuchsia フクシア + Violet 紫 Apply At Canvas Bounds カンバスの境界に効果を適用 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e9901017f6..c0b8ca4782 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2719,4 +2719,9 @@ cameraRaw Color 색상 % of all commits 전체 커밋 대비 % Lines +/− 줄 +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: PR {prs}개, 커밋 {commits}개, 줄 +{added} / −{deleted} (Δ {delta}), 바이너리 +{binAdded} / −{binDeleted}, {first} – {last} + +# Layer colour labels. + Seafoam 바다 거품색 + Indigo 남색 + Fuchsia 자홍색 Apply At Canvas Bounds 캔버스 경계에 효과 적용 diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index c9cffeb0f1..6e6d4d0cc8 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -647,6 +647,25 @@ mod tests { } } + #[test] + fn layer_color_names_are_translated() { + for lang in Lang::all().filter(|l| l.complete_menus()) { + for color in photocraft_doc::LabelColor::ALL { + let cat = lang.0.catalog(); + assert!( + cat.contextual("layerLabel", color.label()).or_else(|| cat.plain(color.label())).is_some(), + "{} missing {}", + lang.code(), + color.label() + ); + } + } + let de = lang_from_tag("de").unwrap(); + assert_eq!(tr_ctx(de, "layerLabel", "No Color"), "Keine Farbe"); + assert_eq!(tr_ctx(de, "layerLabel", "Seafoam"), "Meeresschaum"); + assert_eq!(tr(Lang::EN, "Seafoam"), "Seafoam"); + } + /// Blend mode names come from the colour crate; each must be translated. #[test] fn blend_mode_names_are_translated() { diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 14ec627f64..6199d2ff01 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2573,4 +2573,10 @@ cameraRaw Whites Brancos % of all commits % de todos os commits Lines +/− Linhas +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} linhas (Δ {delta}), +{binAdded} / −{binDeleted} arquivos binários, {first} – {last} + +# Layer colour labels. + Seafoam Espuma do mar + Indigo Índigo + Fuchsia Fúcsia + Violet Violeta Apply At Canvas Bounds Aplicar efeito nos limites da tela diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 4e3d244ad3..9c6f8232a5 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2409,4 +2409,10 @@ cameraRaw Roughness Неровность % of all commits % от всех коммитов Lines +/− Строки +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: PR: {prs}, коммиты: {commits}, строки +{added} / −{deleted} (Δ {delta}), двоичные файлы +{binAdded} / −{binDeleted}, {first} – {last} + +# Layer colour labels. + Seafoam Морская пена + Indigo Индиго + Fuchsia Фуксия + Violet Фиолетовый Apply At Canvas Bounds Применить эффект на границах холста diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index bc468720bd..76827ae8aa 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2143,4 +2143,10 @@ cameraRaw Blending 混合 % of all commits 占全部提交的 % Lines +/− 行数 +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}:{prs} 个 PR,{commits} 次提交,行 +{added} / −{deleted}(Δ {delta}),二进制文件 +{binAdded} / −{binDeleted},{first} – {last} + +# Layer colour labels. + Seafoam 海沫色 + Indigo 靛蓝色 + Fuchsia 紫红色 + Violet 紫罗兰色 Apply At Canvas Bounds 应用画布边界的效果 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a09392f71a..bc73116d4b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2112,4 +2112,10 @@ cameraRaw Blending 混合 % of all commits 佔全部提交的 % Lines +/− 行數 +/− @{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}:{prs} 個 PR,{commits} 次提交,行 +{added} / −{deleted}(Δ {delta}),二進位檔 +{binAdded} / −{binDeleted},{first} – {last} + +# Layer colour labels. + Seafoam 海沫色 + Indigo 靛藍色 + Fuchsia 紫紅色 + Violet 紫羅蘭色 Apply At Canvas Bounds 套用效果至版面邊界 diff --git a/crates/ui-egui/src/layer_menu_ui.rs b/crates/ui-egui/src/layer_menu_ui.rs index 2c0d3d29a8..045641b59b 100644 --- a/crates/ui-egui/src/layer_menu_ui.rs +++ b/crates/ui-egui/src/layer_menu_ui.rs @@ -2,7 +2,7 @@ //! unavailable ones are greyed using the same enablement as the main menus. Items marked as menu //! invocations (`Value::Null` params) go through `menus::invoke`, so dialogs open like in the menu bar. -use photocraft_doc::{Layer, LayerContent}; +use photocraft_doc::{LabelColor, Layer, LayerContent}; use serde_json::{Value, json}; /// One entry: label, command id. `None` = separator. @@ -118,10 +118,80 @@ pub fn show(app: &crate::PhotocraftApp, ui: &mut egui::Ui, l: &Layer, on_set: bo rename = true; ui.close(); } + color_menu(app, ui, l, on_set, actions); rename }) } +fn color_name(color: LabelColor) -> &'static str { + crate::i18n::tr_ctx(crate::i18n::current(), "layerLabel", color.label()) +} + +fn common_color(app: &crate::PhotocraftApp, l: &Layer, on_set: bool) -> Option { + if !on_set { + return Some(l.label); + } + let st = app.session.active()?; + let ids = st.selected_layers(); + let mut labels = ids.iter().filter_map(|id| st.doc.layer(*id).map(|l| l.label)); + let first = labels.next()?; + labels.all(|c| c == first).then_some(first) +} + +fn color_menu(app: &crate::PhotocraftApp, ui: &mut egui::Ui, l: &Layer, on_set: bool, actions: &mut Vec<(String, Value)>) { + let current = common_color(app, l, on_set); + ui.menu_button(tl!("Color"), |ui| { + crate::widgets::menu_scroll(ui, |ui| { + ui.set_min_width(170.0); + for color in LabelColor::ALL { + if color == LabelColor::Red { + ui.separator(); + } + if color_button(ui, color, current == Some(color)).clicked() { + let params = if on_set { + json!({"color": color.id()}) + } else { + actions.push(("layer.select".into(), json!({"layer": l.id.0}))); + json!({"layer": l.id.0, "color": color.id()}) + }; + actions.push(("layer.setLabelColor".into(), params)); + ui.close(); + } + } + }); + }); +} + +fn color_button(ui: &mut egui::Ui, color: LabelColor, checked: bool) -> egui::Response { + use egui::{Atom, Rect, Stroke, StrokeKind, vec2}; + let t = crate::theme::Tokens::get(ui.ctx()); + let check_id = ui.id().with(("label-check", color.id())); + let swatch_id = ui.id().with(("label-swatch", color.id())); + let name = color_name(color); + let button = egui::Button::new((Atom::custom(check_id, vec2(14.0, 16.0)), Atom::custom(swatch_id, vec2(16.0, 16.0)), name, Atom::grow())).atom_ui(ui); + if checked && let Some(rect) = button.rect(check_id) { + crate::icons::paint(ui, rect, "check", 14.0, t.icon); + } + if let Some(rect) = button.rect(swatch_id) { + let rect = Rect::from_center_size(rect.center(), vec2(16.0, 16.0)); + let p = ui.painter(); + if let Some((swatch, _)) = t.layer_label_colors(color) { + p.rect_filled(rect, t.radius_sm, swatch); + } else { + let stroke = Stroke::new(1.0, t.text_dim); + p.rect_stroke(rect, t.radius_sm, stroke, StrokeKind::Inside); + let r = rect.shrink(4.0); + p.line_segment([r.left_top(), r.right_bottom()], stroke); + p.line_segment([r.right_top(), r.left_bottom()], stroke); + } + } + button.response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, ui.is_enabled(), checked, name)); + button.response +} + +#[cfg(test)] +mod color_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/layer_menu_ui/color_tests.rs b/crates/ui-egui/src/layer_menu_ui/color_tests.rs new file mode 100644 index 0000000000..a2a113a30a --- /dev/null +++ b/crates/ui-egui/src/layer_menu_ui/color_tests.rs @@ -0,0 +1,126 @@ +use super::*; +use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2}; +use egui_kittest::kittest::NodeT; +use egui_kittest::{Harness, kittest::Queryable}; +use photocraft_doc::LayerId; + +fn harness(kind: crate::theme::ThemeKind, ppp: f32) -> (Harness<'static, crate::PhotocraftApp>, LayerId, LayerId) { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let red = LayerId(s.execute("layer.new.layer", json!({"name": "Red layer"})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.setLabelColor", json!({"color": "red"})).unwrap(); + let other = LayerId(s.execute("layer.new.layer", json!({"name": "Other layer"})).unwrap()["layer"].as_u64().unwrap()); + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_pixels_per_point(ppp).with_max_steps(64).build_eframe(move |cc| { + crate::PhotocraftApp::setup_context(&cc.egui_ctx, kind); + let mut app = crate::PhotocraftApp::new(s, crate::Services::default()); + app.ui.theme = kind; + app + }); + h.run_steps(8); + (h, red, other) +} + +fn click(h: &mut Harness<'_, crate::PhotocraftApp>, at: Pos2, button: PointerButton, modifiers: Modifiers) { + h.event(Event::ModifiersChanged(modifiers)); + h.hover_at(at); + h.step(); + for pressed in [true, false] { + h.event(Event::PointerButton { pos: at, button, pressed, modifiers }); + h.step(); + } + h.run_steps(3); +} + +fn row(h: &Harness<'_, crate::PhotocraftApp>, id: LayerId) -> egui::Rect { + crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == id.0).unwrap().row +} + +#[test] +fn layer_color_context_menu_edits_the_clicked_layer_and_preserves_multi_selection() { + for ppp in [1.0, 2.0] { + let (mut h, red, other) = harness(crate::theme::ThemeKind::Pro, ppp); + let at = row(&h, red).center(); + click(&mut h, at, PointerButton::Secondary, Modifiers::NONE); + let at = h.get_by_label("Color ⏵").rect().center(); + click(&mut h, at, PointerButton::Primary, Modifiers::NONE); + let at = h.get_by_label("Seafoam").rect().center(); + click(&mut h, at, PointerButton::Primary, Modifiers::NONE); + let st = h.state().session.active().unwrap(); + assert_eq!(st.active_layer, Some(red)); + assert_eq!(st.doc.layer(red).unwrap().label, LabelColor::Seafoam); + assert_eq!(st.doc.layer(other).unwrap().label, LabelColor::None); + h.state_mut().run("layer.select", json!({"layer": other.0, "mode": "add"})).unwrap(); + h.run_steps(4); + let clicked = h.state().session.active().unwrap().doc.layer(red).unwrap(); + assert_eq!(common_color(h.state(), clicked, true), None); + let at = row(&h, red).center(); + click(&mut h, at, PointerButton::Secondary, Modifiers::NONE); + let at = h.get_by_label("Color ⏵").rect().center(); + click(&mut h, at, PointerButton::Primary, Modifiers::NONE); + let at = h.get_by_label("Indigo").rect().center(); + click(&mut h, at, PointerButton::Primary, Modifiers::NONE); + let st = h.state().session.active().unwrap(); + assert_eq!(st.selected_layers().len(), 2); + assert_eq!(st.doc.layer(red).unwrap().label, LabelColor::Indigo); + assert_eq!(st.doc.layer(other).unwrap().label, LabelColor::Indigo); + assert_eq!(common_color(h.state(), st.doc.layer(red).unwrap(), true), Some(LabelColor::Indigo)); + } +} + +#[test] +fn layer_color_background_is_confined_to_the_eye_column_in_every_theme() { + fn rects(shape: &egui::Shape, color: egui::Color32, out: &mut Vec) { + match shape { + egui::Shape::Rect(r) if r.fill == color => out.push(r.rect), + egui::Shape::Vec(shapes) => { + for s in shapes { + rects(s, color, out); + } + } + _ => {} + } + } + fn has_icon(shape: &egui::Shape, rect: egui::Rect) -> bool { + match shape { + egui::Shape::Rect(r) => r.brush.is_some() && r.rect == rect, + egui::Shape::Vec(shapes) => shapes.iter().any(|s| has_icon(s, rect)), + _ => false, + } + } + for kind in crate::theme::ThemeKind::ALL { + let (mut h, red, _) = harness(kind, 1.0); + for visible in [true, false] { + h.state_mut().run("layer.setProps", json!({"layer": red.0, "visible": visible})).unwrap(); + h.run_steps(4); + let r = row(&h, red); + let t = crate::theme::Tokens::for_kind(kind); + let (_, bg) = t.layer_label_colors(LabelColor::Red).unwrap(); + let mut fills = Vec::new(); + for s in &h.output().shapes { + rects(&s.shape, bg, &mut fills); + } + assert_eq!(fills, vec![egui::Rect::from_min_max(r.left_top(), pos2(r.left() + 30.0, r.bottom()))], "{kind:?}"); + use egui::emath::GuiRounding; + let icon = egui::Rect::from_center_size(pos2(r.left() + 15.0, r.center().y), vec2(15.0, 15.0)).round_to_pixels(h.ctx.pixels_per_point()); + assert_eq!(h.output().shapes.iter().any(|s| has_icon(&s.shape, icon)), visible, "centred eye in {kind:?}"); + } + let eye = pos2(row(&h, red).left() + 17.0, row(&h, red).center().y); + click(&mut h, eye, PointerButton::Primary, Modifiers::NONE); + assert!(h.state().session.active().unwrap().doc.layer(red).unwrap().visible); + assert_eq!(h.state().session.active().unwrap().doc.layer(red).unwrap().label, LabelColor::Red); + click(&mut h, eye, PointerButton::Primary, Modifiers::ALT); + assert!(h.state().session.active().unwrap().doc.layer(red).unwrap().visible); + } +} + +#[test] +fn layer_color_menu_marks_only_the_common_color() { + let mut h = Harness::new_ui(|ui| { + for c in LabelColor::ALL { + color_button(ui, c, c == LabelColor::Blue); + } + }); + h.run(); + assert_eq!(h.get_by_label("Blue").accesskit_node().toggled(), Some(egui::accesskit::Toggled::True)); + assert_eq!(h.get_by_label("Red").accesskit_node().toggled(), Some(egui::accesskit::Toggled::False)); +} diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index dc5ab7de64..f175494206 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1788,15 +1788,21 @@ fn layer_row( } else if resp.hovered() { painter.rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5)); } - // eye column divider + row divider, as in Photoshop - painter.line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator)); - painter.line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator)); } else if selected { painter.rect_filled(rect, t.radius, t.hover); painter.rect_stroke(rect, t.radius, Stroke::new(1.0, t.field_border), StrokeKind::Inside); } else if resp.hovered() { painter.rect_filled(rect, t.radius, t.hover.gamma_multiply(0.5)); } + let eye_cell = Rect::from_min_max(rect.left_top(), pos2((rect.left() + 30.0).min(rect.right()), rect.bottom())); + if let Some((_, background)) = t.layer_label_colors(l.label) { + painter.rect_filled(eye_cell, 0.0, background); + } + if t.pro { + // Paint dividers over the label so the eye column stays distinct. + painter.line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator)); + painter.line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator)); + } let mut x = rect.left() + 6.0; let eye = Rect::from_min_size(pos2(x, rect.center().y - 11.0), vec2(22.0, 22.0)); // The eye takes drags too (so a drag starting on it never reorders the row): dragging down @@ -1804,7 +1810,8 @@ fn layer_row( let eye_resp = ui.interact(eye, ui.id().with(("eye", l.id.0)), Sense::click_and_drag()); // A hidden layer's eye box is left empty (still clickable). if l.visible { - icons::paint(ui, eye, "eye", 15.0, t.icon); + // Centre the drawing in the column while preserving the visibility hit area. + icons::paint(ui, eye_cell, "eye", 15.0, t.layer_label_icon(l.label)); } eye_sweep(ctx, l, rect, &eye_resp, actions); if eye_resp.clicked() { diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index cf1cf80594..7ceb887dea 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -311,6 +311,31 @@ impl Tokens { self.histogram_color(mask).gamma_multiply(0.3) } + /// Semantic label hues stay recognisable across themes; None keeps the normal row surface. + pub fn layer_label_colors(&self, label: photocraft_doc::LabelColor) -> Option<(Color32, Color32)> { + use photocraft_doc::LabelColor; + let (swatch, eye) = match label { + LabelColor::None => return None, + LabelColor::Red => ([0xFC, 0x5D, 0x5B], [0x9F, 0x2F, 0x30]), + LabelColor::Orange => ([0xF7, 0x97, 0x44], [0x93, 0x4F, 0x0C]), + LabelColor::Yellow => ([0xDC, 0xD6, 0x4B], [0x99, 0x78, 0x0C]), + LabelColor::Green => ([0x85, 0xDC, 0x6A], [0x4E, 0x71, 0x2E]), + LabelColor::Seafoam => ([0x1C, 0x84, 0x88], [0x0B, 0x54, 0x4F]), + LabelColor::Blue => ([0x78, 0xAD, 0xF6], [0x41, 0x5B, 0x87]), + LabelColor::Indigo => ([0x54, 0x4B, 0xE7], [0x36, 0x34, 0x8E]), + LabelColor::Magenta => ([0xCC, 0x1A, 0x7E], [0x98, 0x1B, 0x51]), + LabelColor::Fuchsia => ([0xB0, 0x14, 0xC0], [0x71, 0x0F, 0x74]), + LabelColor::Violet => ([0x91, 0x76, 0xD5], [0x5D, 0x3F, 0x8E]), + LabelColor::Gray => ([0x9C, 0x9C, 0x9C], [0x57, 0x57, 0x57]), + }; + let rgb = |[r, g, b]: [u8; 3]| Color32::from_rgb(r, g, b); + Some((rgb(swatch), rgb(eye))) + } + + pub fn layer_label_icon(&self, label: photocraft_doc::LabelColor) -> Color32 { + if label == photocraft_doc::LabelColor::None { self.icon } else { Color32::from_gray(226) } + } + /// Analysis colours are semantic hues, independent of the application accent palette. pub fn scope_hue(&self, h: f32, s: f32) -> Color32 { let v = f32::from(self.histogram_level) / 255.0;