PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Add layer and group color labels (#1283) (#1289)
Shayan Horbankf5c3d37c5ab5
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rsindex ba0715962..82d0dd527 100644--- a/crates/doc/src/lib.rs+++ b/crates/doc/src/lib.rs@@ -112,6 +112,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> {+ 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::<LabelColor>(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::<LabelColor>(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::<LabelColor>(serde_json::json!("Unknown")).is_err());+ }}#[derive(Clone, Debug, PartialEq)]diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex d37e3157e..24d46558d 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -1037,6 +1037,7 @@ fn build() -> Vec<CommandSpec> {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.rsindex 022f5d218..a98851137 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.rsnew file mode 100644index 000000000..acb450cdb--- /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<String>) -> 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<Value> {+ 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::<Vec<_>>(), "changed": changed}))+}++pub fn specs() -> Vec<CommandSpec> {+ 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.rsnew file mode 100644index 000000000..78fa018e7--- /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.rsindex 18ef8bc84..df302590e 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.rsnew file mode 100644index 000000000..45707e890--- /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.rsindex 08dc493d2..967ad4207 100644--- a/crates/io/src/blocks.rs+++ b/crates/io/src/blocks.rs@@ -122,6 +122,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,}}@@ -137,6 +142,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.rsnew file mode 100644index 000000000..792d2d621--- /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::<Vec<_>>();+ 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.tsvindex 3b0940979..2dd0b92bb 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -2178,3 +2178,9 @@ cameraRaw Color BarvySet Neutral Gray Point Nastavit neutrální šedý bodSet White Point Nastavit bílý bodUnavailable in this color mode V tomto barevném režimu není k dispozici++# Layer colour labels.+ Seafoam Mořská pěna+ Indigo Indigová+ Fuchsia Fuchsiová+ Violet Fialovádiff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex a53d886e2..d443b190b 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2217,3 +2217,10 @@Set Neutral Gray Point Neutralen Graupunkt festlegenSet White Point Weißpunkt festlegenUnavailable in this color mode In diesem Farbmodus nicht verfügbar++# Layer colour labels.+layerLabel No Color Keine Farbe+ Seafoam Meeresschaum+ Indigo Indigo+ Fuchsia Fuchsia+ Violet Violettdiff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 9217a314f..929c6471a 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2248,3 +2248,9 @@ cameraRaw Amount CantidadSet Neutral Gray Point Definir punto gris neutroSet White Point Definir punto blancoUnavailable in this color mode No disponible en este modo de color++# Layer colour labels.+ Seafoam Espuma de mar+ Indigo Índigo+ Fuchsia Fucsia+ Violet Violetadiff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex 6b2d02605..fc567df53 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2607,3 +2607,9 @@ cameraRaw Blending FusionSet Neutral Gray Point Définir le point gris neutreSet White Point Définir le point blancUnavailable in this color mode Indisponible dans ce mode colorimétrique++# Layer colour labels.+ Seafoam Écume de mer+ Indigo Indigo+ Fuchsia Fuchsia+ Violet Violetdiff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex 162d85350..a9ddd31c4 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2594,3 +2594,9 @@ cameraRaw Blending PembauranSet Neutral Gray Point Atur Titik Abu-abu NetralSet White Point Atur Titik PutihUnavailable in this color mode Tidak tersedia dalam mode warna ini++# Layer colour labels.+ Seafoam Busa Laut+ Indigo Nila+ Fuchsia Fuksia+ Violet Ungudiff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex 828c7d38d..3bcba9f5c 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2250,3 +2250,9 @@ cameraRaw Amount QuantitàSet Neutral Gray Point Imposta il punto grigio neutroSet White Point Imposta punto biancoUnavailable in this color mode Non disponibile in questa modalità colore++# Layer colour labels.+ Seafoam Schiuma marina+ Indigo Indaco+ Fuchsia Fucsia+ Violet Violadiff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex 8dec6a4b7..2725faf79 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -2161,3 +2161,9 @@ cameraRaw Color カラーSet Neutral Gray Point 中間調のグレーポイントを設定Set White Point 白色点を設定Unavailable in this color mode このカラーモードでは使用できません++# Layer colour labels.+ Seafoam シーフォーム+ Indigo インディゴ+ Fuchsia フクシア+ Violet 紫diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex 47e89b719..570dbe579 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -2762,3 +2762,8 @@ cameraRaw Color 색상Click a red pupil to neutralize it 빨간 동공을 클릭하여 보정합니다open source 오픈 소스…and {n} more …외 {n}개++# Layer colour labels.+ Seafoam 바다 거품색+ Indigo 남색+ Fuchsia 자홍색diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rsindex 259bf0fa8..fbff4aef0 100644--- a/crates/ui-egui/src/i18n/mod.rs+++ b/crates/ui-egui/src/i18n/mod.rs@@ -667,6 +667,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/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 515b257d1..e4b73b484 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -3212,3 +3212,8 @@ cameraRaw Roughness ChropowatośćSet Neutral Gray Point Ustaw punkt neutralnej szarościSet White Point Ustaw punkt bieliUnavailable in this color mode Niedostępne w tym trybie koloru++# Layer colour labels.+ Seafoam Morski+ Indigo Indygo+ Fuchsia Fuksjadiff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex 5a1d38765..39c097642 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2615,3 +2615,9 @@ cameraRaw Whites BrancosSet Neutral Gray Point Definir ponto cinza neutroSet White Point Definir ponto brancoUnavailable in this color mode Indisponível neste modo de cor++# Layer colour labels.+ Seafoam Espuma do mar+ Indigo Índigo+ Fuchsia Fúcsia+ Violet Violetadiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 2cd334d70..b1f340d8c 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2454,3 +2454,9 @@ cameraRaw Roughness НеровностьSet Neutral Gray Point Задать нейтральную серую точкуSet White Point Задать точку белогоUnavailable in this color mode Недоступно в этом цветовом режиме++# Layer colour labels.+ Seafoam Морская пена+ Indigo Индиго+ Fuchsia Фуксия+ Violet Фиолетовыйdiff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex e3ce1fee9..a561de37d 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2186,3 +2186,9 @@ cameraRaw Blending 混合Set Neutral Gray Point 设置中性灰场Set White Point 设置白场Unavailable in this color mode 此颜色模式下不可用++# Layer colour labels.+ Seafoam 海沫色+ Indigo 靛蓝色+ Fuchsia 紫红色+ Violet 紫罗兰色diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex bbc2e6f5d..089d6e279 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2155,3 +2155,9 @@ cameraRaw Blending 混合Set Neutral Gray Point 設定中性灰點Set White Point 設定白點Unavailable in this color mode 此色彩模式無法使用++# Layer colour labels.+ Seafoam 海沫色+ Indigo 靛藍色+ Fuchsia 紫紅色+ Violet 紫羅蘭色diff --git a/crates/ui-egui/src/layer_menu_ui.rs b/crates/ui-egui/src/layer_menu_ui.rsindex 2c0d3d29a..045641b59 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: borename = 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<LabelColor> {+ 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.rsnew file mode 100644index 000000000..a2a113a30--- /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<egui::Rect>) {+ 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.rsindex 6dde57218..1d944a1db 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -1836,15 +1836,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@@ -1852,7 +1858,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.rsindex cf1cf8059..7ceb887de 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;