From 88efb46eb74a89e62b721483541e963f6a7b4ead Mon Sep 17 00:00:00 2001 From: jonathnwxh <258340642+jonathanwxh-cell@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:27:52 +0800 Subject: [PATCH 1/6] Import Photoshop custom shape sets into the Shapes library Add bounded CSH version 2 reading and a persistent engine import command, with Shapes-panel and File Open integration. Preserve the existing library on malformed sets and disambiguate imported names. Focused checks: 6 engine, 4 parser, 3 UI routing, 6 preset reader tests; explicit GPU rendering; strict affected-crate Clippy; panic_hunt; layering; parity generation (unchanged output). Original generated fixture cross-read with ag-psd. Photoshop-written CSH fixtures and export remain out of scope. Full repository CI is verified separately before upstream submission. Prepared with OpenAI Codex assistance for jonathnwxh. --- crates/engine/src/preset_import_cmds.rs | 28 +++++- crates/engine/src/presets/shapes.rs | 3 + crates/engine/src/presets/shapes/csh.rs | 80 +++++++++++++++ crates/engine/tests/csh_import.rs | 118 ++++++++++++++++++++++ crates/psd/src/csh.rs | 124 ++++++++++++++++++++++++ crates/psd/src/lib.rs | 1 + crates/psd/tests/common/csh_fixture.rs | 45 +++++++++ crates/psd/tests/csh.rs | 88 +++++++++++++++++ crates/ui-egui/src/jobs_ui.rs | 10 ++ crates/ui-egui/src/preset_files_ui.rs | 82 +++++++++++++++- crates/ui-egui/src/preset_panels.rs | 3 + docs/file-format-parity.md | 6 +- docs/gaps.md | 7 +- 13 files changed, 587 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/presets/shapes/csh.rs create mode 100644 crates/engine/tests/csh_import.rs create mode 100644 crates/psd/src/csh.rs create mode 100644 crates/psd/tests/common/csh_fixture.rs create mode 100644 crates/psd/tests/csh.rs diff --git a/crates/engine/src/preset_import_cmds.rs b/crates/engine/src/preset_import_cmds.rs index e6bff8eb6b..1fb439eb50 100644 --- a/crates/engine/src/preset_import_cmds.rs +++ b/crates/engine/src/preset_import_cmds.rs @@ -27,21 +27,35 @@ pub const MAX_FILE_BYTES: u64 = 512 << 20; /// File bytes from `data` (base64) or `path`, plus a default group name. pub(crate) fn file_bytes(p: &Value, cmd: &str, what: &str) -> Result<(Vec, String)> { + file_bytes_limited(p, cmd, what, MAX_FILE_BYTES) +} + +/// Read with the format's own input budget, before allocating file or decoded base64 bytes. +pub(crate) fn file_bytes_limited(p: &Value, cmd: &str, what: &str, max_bytes: u64) -> Result<(Vec, String)> { if let Some(d) = p.get("data") { let s = d.as_str().ok_or_else(|| bad(cmd, "`data` must be a base64 string"))?; - if s.len() as u64 > MAX_FILE_BYTES / 3 * 4 + 4 { + if s.len() as u64 > max_bytes / 3 * 4 + 4 { return Err(bad(cmd, "`data` is too large")); } let bytes = photocraft_paint::tile::b64_decode(s).ok_or_else(|| bad(cmd, "`data` is not valid base64"))?; + if bytes.len() as u64 > max_bytes { + return Err(bad(cmd, "`data` is too large")); + } return Ok((bytes, String::new())); } let path = p.get("path").and_then(Value::as_str).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, format!("give `path` ({what}) or `data` (base64)")))?; let len = std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.len(); - if len > MAX_FILE_BYTES { + if len > max_bytes { return Err(bad(cmd, format!("{path}: file too large ({len} bytes)"))); } - let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + use std::io::Read; + let file = std::fs::File::open(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + let mut bytes = Vec::new(); + file.take(max_bytes.saturating_add(1)).read_to_end(&mut bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + if bytes.len() as u64 > max_bytes { + return Err(bad(cmd, format!("{path}: file too large"))); + } let stem = std::path::Path::new(path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); Ok((bytes, stem)) } @@ -242,6 +256,14 @@ fn import_grd(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod tests { + #[test] + fn decoded_preset_data_cannot_exceed_its_format_budget() { + // Both payloads have four encoded characters: checking base64 length alone is insufficient. + let at_limit = serde_json::json!({"data": "AQI="}); + let over_limit = serde_json::json!({"data": "AQID"}); + assert_eq!(super::file_bytes_limited(&at_limit, "test", "preset", 2).unwrap().0, [1, 2]); + assert!(super::file_bytes_limited(&over_limit, "test", "preset", 2).is_err()); + } use super::*; use photocraft_psd::abr::{AbrSample, LegacyBrush, LegacyTip, write_v6, write_v12}; use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value as DV}; diff --git a/crates/engine/src/presets/shapes.rs b/crates/engine/src/presets/shapes.rs index e8a966e40d..abc534c681 100644 --- a/crates/engine/src/presets/shapes.rs +++ b/crates/engine/src/presets/shapes.rs @@ -16,6 +16,8 @@ use crate::commands::CommandSpec; use crate::vector_cmds::path_json; use crate::{EngineError, Result, Session}; +mod csh; + /// Group listing Edit › Define Custom Shape results (`EditState::custom_shapes`). pub const CUSTOM_GROUP: &str = "Custom Shapes"; @@ -428,6 +430,7 @@ fn reset(s: &mut Session, p: &Value) -> Result { pub fn specs() -> Vec { vec![ + csh::spec(), CommandSpec { id: "shape.presets.list", label: "Shape Presets", diff --git a/crates/engine/src/presets/shapes/csh.rs b/crates/engine/src/presets/shapes/csh.rs new file mode 100644 index 0000000000..e66b79653d --- /dev/null +++ b/crates/engine/src/presets/shapes/csh.rs @@ -0,0 +1,80 @@ +//! Import a complete custom-shape set before changing the persistent library. + +use std::collections::{HashMap, HashSet}; + +use serde_json::{Value, json}; + +use super::{CommandSpec, Group, Session, ShapePreset, always, bad, fit}; +use crate::Result; + +const CMD: &str = "shape.presets.importCsh"; + +pub(super) fn spec() -> CommandSpec { + CommandSpec { + id: CMD, + label: "Import Shapes", + menu: &[], + shortcut: None, + params: r#"{"path":str (.csh) | "data":str (base64),"group":str?} → {group,count,names}; appends a uniquely named group, never replaces existing presets"#, + enabled: always, + run: import, + journal: true, + } +} + +fn import(s: &mut Session, p: &Value) -> Result { + let group = p + .get("group") + .map(|v| v.as_str().map(str::trim).filter(|n| !n.is_empty()).map(str::to_owned).ok_or_else(|| bad(CMD, "`group` must be a non-empty string"))) + .transpose()?; + let params = p.clone(); + crate::jobs::run( + s, + "Import Shapes", + false, + move |ctx| { + ctx.check()?; + let (bytes, stem) = crate::preset_import_cmds::file_bytes_limited(¶ms, CMD, ".csh file", photocraft_psd::csh::MAX_FILE_BYTES as u64)?; + let shapes = photocraft_psd::csh::parse(&bytes).map_err(|e| bad(CMD, e.to_string()))?; + if shapes.is_empty() { + return Err(bad(CMD, "the CSH set contains no shapes")); + } + let mut items = Vec::with_capacity(shapes.len()); + for shape in shapes { + ctx.check()?; + let [top, left, bottom, right] = shape.bounds; + // The parser validates ordering; widen before subtraction for signed bounds. + let width = u32::try_from(i64::from(right) - i64::from(left)).map_err(|_| bad(CMD, "shape width exceeds supported bounds"))?; + let height = u32::try_from(i64::from(bottom) - i64::from(top)).map_err(|_| bad(CMD, "shape height exceeds supported bounds"))?; + let path = photocraft_io::vector_map::path_from_records(&shape.path, width, height); + if path.is_empty() { + return Err(bad(CMD, format!("shape {:?} has no path", shape.name))); + } + let path = fit(&path, [0.0, 0.0, 100.0, 100.0], true); + let name = if shape.name.trim().is_empty() { "Shape".to_owned() } else { shape.name }; + items.push(ShapePreset { name, path }); + } + let group = group.unwrap_or_else(|| if stem.is_empty() { "Imported Shapes".into() } else { stem }); + Ok((group, items)) + }, + |s, (group, mut items)| { + let group = super::super::gradients::unique_group(&s.presets.shapes, &group); + let mut taken: HashSet = s.presets.shapes.iter().flat_map(|g| g.items.iter().map(|i| i.name.clone())).collect(); + taken.extend(s.edit_state.custom_shapes.iter().map(|c| c.name.clone())); + let mut suffixes: HashMap = HashMap::new(); + for item in &mut items { + let base = item.name.clone(); + let suffix = suffixes.entry(base.clone()).or_insert(2); + while !taken.insert(item.name.clone()) { + item.name = format!("{base} {suffix}"); + *suffix += 1; + } + } + let names: Vec = items.iter().map(|i| i.name.clone()).collect(); + let result = json!({"group": group, "count": items.len(), "names": names}); + s.presets.shapes.push(Group::new(&group, items)); + s.presets_changed(); + Ok(result) + }, + ) +} diff --git a/crates/engine/tests/csh_import.rs b/crates/engine/tests/csh_import.rs new file mode 100644 index 0000000000..7af372995d --- /dev/null +++ b/crates/engine/tests/csh_import.rs @@ -0,0 +1,118 @@ +//! Original geometric CSH fixture, assembled from the public container/path layout. +//! No Adobe or third-party shape assets are embedded. + +use photocraft_engine::Session; +use serde_json::json; + +#[path = "../../psd/tests/common/csh_fixture.rs"] +mod fixture; +use fixture::{polygon_csh, triangle_csh}; + +#[test] +fn csh_import_makes_an_original_shape_available_without_a_document() { + let bytes = triangle_csh(); + if let Some(path) = std::env::var_os("PHOTOCRAFT_CSH_FIXTURE") { + std::fs::write(path, &bytes).unwrap(); + } + let mut session = Session::new(); + session + .execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&bytes), "group": "Original CSH"})) + .expect("CSH import must be available without an open document"); + let groups = photocraft_engine::presets::shapes::all_groups(&session); + let imported = groups.iter().find(|g| g.name == "Original CSH").expect("imported group"); + assert_eq!(imported.items.len(), 1); + assert_eq!(imported.items[0].name, "Triangle"); + let path = &imported.items[0].path; + assert_eq!(path.subpaths.len(), 1); + assert!(path.subpaths[0].closed); + assert_eq!(path.subpaths[0].knots.len(), 3); + // The reference bounds are twice as wide as tall; normalization must preserve that. + assert_eq!(path.control_bounds().unwrap(), (0.0, 25.0, 100.0, 75.0)); +} + +#[test] +fn csh_failed_import_preserves_existing_presets_and_revision() { + let mut session = Session::new(); + let before = session.presets.to_json(&session); + let revision = session.presets.rev; + let bytes = triangle_csh(); + for end in [0, 11, bytes.len() - 1] { + assert!(session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&bytes[..end])})).is_err()); + assert_eq!(session.presets.to_json(&session), before); + assert_eq!(session.presets.rev, revision); + } + assert!(session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&bytes), "group": 12})).is_err()); + assert_eq!(session.presets.to_json(&session), before); +} + +#[test] +fn csh_invalid_second_shape_does_not_partially_import_a_set() { + let triangle = triangle_csh(); + let mut set = triangle.clone(); + set[8..12].copy_from_slice(&2u32.to_be_bytes()); + set.extend_from_slice(&triangle[12..]); + // The first shape is complete; truncate the second shape's path/padding. + set.pop(); + let mut session = Session::new(); + session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&triangle)})).unwrap(); + let before = session.presets.to_json(&session); + let revision = session.presets.rev; + assert!(session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&set)})).is_err()); + assert_eq!(session.presets.to_json(&session), before); + assert_eq!(session.presets.rev, revision); +} + +#[test] +fn csh_multiple_shapes_with_matching_names_remain_individually_available() { + let triangle = triangle_csh(); + let mut set = triangle.clone(); + set[8..12].copy_from_slice(&2u32.to_be_bytes()); + set.extend_from_slice(&triangle[12..]); + let mut s = Session::new(); + let result = s.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&set), "group": "Pair"})).unwrap(); + assert_eq!(result["count"], 2); + assert_eq!(result["names"], json!(["Triangle", "Triangle 2"])); + let group = s.presets.shapes.iter().find(|g| g.name == "Pair").unwrap(); + assert_eq!(group.items.len(), 2); + assert_eq!(group.items[0].path, group.items[1].path); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + for name in ["Triangle", "Triangle 2"] { + s.execute("shape.presets.place", json!({"preset": name, "group": "Pair"})).unwrap(); + } +} + +#[test] +fn csh_repeat_import_names_are_unique_and_survive_preferences_reload() { + let mut session = Session::new(); + let params = json!({"data": photocraft_paint::tile::b64_encode(&triangle_csh()), "group": "Original CSH"}); + let first = session.execute("shape.presets.importCsh", params.clone()).unwrap(); + let second = session.execute("shape.presets.importCsh", params).unwrap(); + assert_eq!(first["count"], 1); + assert_eq!(second["count"], 1); + assert_ne!(first["group"], second["group"]); + assert_ne!(first["names"], second["names"]); + let persisted = session.presets.to_json(&session); + let mut restored = Session::new(); + restored.load_presets_json(persisted); + assert_eq!(restored.presets.shapes, session.presets.shapes); +} + +#[test] +fn csh_same_winding_inner_subpath_stays_a_hole_after_place_and_reload() { + // Same winding intentionally: a nonzero union would incorrectly fill the hole. + let bytes = + polygon_csh(&[&[(0.125, 0.125), (0.875, 0.125), (0.875, 0.875), (0.125, 0.875)], &[(0.375, 0.375), (0.625, 0.375), (0.625, 0.625), (0.375, 0.625)]]); + let mut imported = Session::new(); + let result = imported.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&bytes)})).unwrap(); + let mut s = Session::new(); + s.load_presets_json(imported.presets.to_json(&imported)); + s.execute("file.new", json!({"width": 96, "height": 96, "background": "transparent"})).unwrap(); + s.execute("shape.presets.place", json!({"preset": result["names"][0], "rect": [8, 8, 80, 80], "keepAspect": false, "fill": "#ff0000"})).unwrap(); + let image = photocraft_compose::flatten(&s.active().unwrap().doc); + assert!(image.px[48 * 96 + 16][0] > 0.99, "ring must remain red"); + assert!(image.px[48 * 96 + 16][3] > 0.99, "ring must remain opaque"); + assert!(image.px[48 * 96 + 48][3] < 0.01, "inner subpath must remain transparent"); + assert!(image.px[4 * 96 + 4][3] < 0.01, "outside shape must remain transparent"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(photocraft_compose::flatten(&s.active().unwrap().doc).px.iter().all(|pixel| pixel[3] < 0.01)); +} diff --git a/crates/psd/src/csh.rs b/crates/psd/src/csh.rs new file mode 100644 index 0000000000..674d79267c --- /dev/null +++ b/crates/psd/src/csh.rs @@ -0,0 +1,124 @@ +//! Photoshop custom shape sets (`.csh`, version 2). +//! +//! Container layout: Michel Mariani's public format research, +//! . +//! Geometry uses Adobe's path record format. No external implementation or shape assets copied. + +use crate::error::{PsdError, Result}; +use crate::io::Reader; +use crate::path::{PathData, RECORD_LEN}; + +/// Maximum encoded file size accepted by this reader. +pub const MAX_FILE_BYTES: usize = 64 << 20; +/// Maximum presets in a set. +pub const MAX_SHAPES: usize = 10_000; +/// Maximum path records across all presets, not per shape. +pub const MAX_RECORDS: usize = 1_000_000; +/// Maximum UTF-16 units in a preset name, including its optional trailing null. +pub const MAX_NAME_UNITS: usize = 32_768; + +/// A named shape with its reference bounds and normalized path records. +#[derive(Debug, Clone, PartialEq)] +pub struct CshShape { + /// Display name. + pub name: String, + /// Source shape identifier (usually a UUID). + pub id: String, + /// Reference rectangle: top, left, bottom, right. Coordinates may be negative. + pub bounds: [i32; 4], + /// Coordinates are fractions of the reference rectangle's width and height. + pub path: PathData, +} + +/// Read a complete set before callers modify their preset libraries. +/// Unsupported versions, truncated records and excessive aggregate sizes return errors. +pub fn parse(bytes: &[u8]) -> Result> { + if bytes.len() > MAX_FILE_BYTES { + return Err(PsdError::LimitExceeded("CSH file bytes")); + } + let mut r = Reader::new(bytes); + let signature = r.array()?; + if &signature != b"cush" { + return Err(PsdError::InvalidSignature { expected: "cush", found: signature }); + } + if r.u32()? != 2 { + return Err(PsdError::Unsupported("CSH file version (expected 2)".into())); + } + let count = r.u32()? as usize; + if count > MAX_SHAPES { + return Err(PsdError::LimitExceeded("CSH shape count")); + } + r.check_count(count as u64, 32)?; + let mut shapes = Vec::new(); + let mut remaining_records = MAX_RECORDS; + for _ in 0..count { + let units = r.u32()? as usize; + if units > MAX_NAME_UNITS { + return Err(PsdError::LimitExceeded("CSH name length")); + } + let raw = r.bytes(units * 2)?; + let mut name: Vec = raw.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect(); + if name.last() == Some(&0) { + name.pop(); + } + let name = String::from_utf16(&name).map_err(|_| PsdError::invalid("CSH name is not valid UTF-16"))?; + let padding = (4 - r.pos() % 4) % 4; + zero_padding(r.bytes(padding)?)?; + if r.u32()? != 1 { + return Err(PsdError::Unsupported("CSH shape version (expected 1)".into())); + } + let length = r.u32()?; + if !length.is_multiple_of(4) { + return Err(PsdError::invalid("CSH shape length must be aligned to four bytes")); + } + let mut shape = r.sub(u64::from(length))?; + let id_len = usize::from(shape.u8()?); + let id = std::str::from_utf8(shape.bytes(id_len)?).map_err(|_| PsdError::invalid("CSH identifier is not UTF-8"))?.to_owned(); + let bounds = [shape.i32()?, shape.i32()?, shape.i32()?, shape.i32()?]; + if bounds[2] <= bounds[0] || bounds[3] <= bounds[1] { + return Err(PsdError::invalid("CSH reference bounds are empty or reversed")); + } + let records = shape.remaining() / RECORD_LEN; + remaining_records = remaining_records.checked_sub(records).ok_or(PsdError::LimitExceeded("CSH aggregate path records"))?; + let path = PathData::from_bytes(shape.bytes(records * RECORD_LEN)?)?; + if shape.remaining() > 3 { + return Err(PsdError::invalid("CSH incomplete path record")); + } + zero_padding(shape.peek_rest())?; + validate_path(&path)?; + shapes.push(CshShape { name, id, bounds, path }); + } + if !r.is_empty() { + return Err(PsdError::invalid("CSH trailing data")); + } + Ok(shapes) +} + +fn zero_padding(bytes: &[u8]) -> Result<()> { + if bytes.iter().any(|&b| b != 0) { + return Err(PsdError::invalid("CSH nonzero padding")); + } + Ok(()) +} + +// The generic PSD reader is deliberately lenient; importing presets must not silently +// turn a truncated or miscounted shape into different geometry. +fn validate_path(path: &PathData) -> Result<()> { + let mut pending = 0u16; + let mut closed = false; + for record in &path.records { + match record.selector { + 0 | 3 if pending == 0 => { + pending = u16::from_be_bytes([record.data[0], record.data[1]]); + closed = record.selector == 0; + } + 1 | 2 | 4 | 5 if pending > 0 && closed == (record.selector <= 2) => pending -= 1, + 6..=8 if pending == 0 => {} + _ => return Err(PsdError::invalid("CSH path selectors or knot counts are inconsistent")), + } + } + if pending != 0 { + return Err(PsdError::invalid("CSH subpath is missing knots")); + } + Ok(()) +} diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs index 00d73c4003..c265aff0ff 100644 --- a/crates/psd/src/lib.rs +++ b/crates/psd/src/lib.rs @@ -47,6 +47,7 @@ pub mod atn; pub mod blend; pub mod builder; pub mod compression; +pub mod csh; pub mod descriptor; pub mod error; pub mod file; diff --git a/crates/psd/tests/common/csh_fixture.rs b/crates/psd/tests/common/csh_fixture.rs new file mode 100644 index 0000000000..176754327a --- /dev/null +++ b/crates/psd/tests/common/csh_fixture.rs @@ -0,0 +1,45 @@ +pub fn triangle_csh() -> Vec { + polygon_csh(&[&[(0.25, 0.25), (0.75, 0.25), (0.5, 0.75)]]) +} + +pub fn polygon_csh(polygons: &[&[(f64, f64)]]) -> Vec { + let mut out = b"cush".to_vec(); + out.extend_from_slice(&2u32.to_be_bytes()); + out.extend_from_slice(&1u32.to_be_bytes()); + let name: Vec = "Triangle".encode_utf16().chain(std::iter::once(0)).collect(); + out.extend_from_slice(&(name.len() as u32).to_be_bytes()); + for unit in &name { + out.extend_from_slice(&unit.to_be_bytes()); + } + if !name.len().is_multiple_of(2) { + out.extend_from_slice(&[0, 0]); + } + out.extend_from_slice(&1u32.to_be_bytes()); + let mut body = vec![36]; + body.extend_from_slice(b"00000000-0000-4000-8000-000000000001"); + for bound in [0i32, 0, 100, 200] { + body.extend_from_slice(&bound.to_be_bytes()); + } + for selector in [6u16, 8] { + body.extend_from_slice(&selector.to_be_bytes()); + body.extend_from_slice(&[0; 24]); + } + for polygon in polygons { + body.extend_from_slice(&0u16.to_be_bytes()); + body.extend_from_slice(&(polygon.len() as u16).to_be_bytes()); + body.extend_from_slice(&[0; 22]); + for &(x, y) in *polygon { + body.extend_from_slice(&2u16.to_be_bytes()); + for _ in 0..3 { + body.extend_from_slice(&((y * 16_777_216.0) as i32).to_be_bytes()); + body.extend_from_slice(&((x * 16_777_216.0) as i32).to_be_bytes()); + } + } + } + while !body.len().is_multiple_of(4) { + body.push(0); + } + out.extend_from_slice(&(body.len() as u32).to_be_bytes()); + out.extend_from_slice(&body); + out +} diff --git a/crates/psd/tests/csh.rs b/crates/psd/tests/csh.rs new file mode 100644 index 0000000000..d21cfb035e --- /dev/null +++ b/crates/psd/tests/csh.rs @@ -0,0 +1,88 @@ +use photocraft_psd::csh; +use photocraft_psd::path::{PathData, PsdKnot, PsdSubpath}; + +fn fixture(names: &[&str]) -> Vec { + let mut bytes = b"cush".to_vec(); + bytes.extend_from_slice(&2u32.to_be_bytes()); + bytes.extend_from_slice(&(names.len() as u32).to_be_bytes()); + for name in names { + let units: Vec = name.encode_utf16().chain(std::iter::once(0)).collect(); + bytes.extend_from_slice(&(units.len() as u32).to_be_bytes()); + for unit in units { + bytes.extend_from_slice(&unit.to_be_bytes()); + } + while !bytes.len().is_multiple_of(4) { + bytes.push(0); + } + bytes.extend_from_slice(&1u32.to_be_bytes()); + let mut body = vec![2, b'i', b'd']; + for bound in [-10i32, -20, 90, 180] { + body.extend_from_slice(&bound.to_be_bytes()); + } + let knot = PsdKnot { linked: true, pre: (0.125, 0.25), anchor: (0.5, 0.5), post: (0.75, 0.875) }; + let path = PathData::from_subpaths(&[PsdSubpath { closed: false, operation: 0, knots: vec![knot] }], false); + body.extend_from_slice(&path.to_bytes()); + while !body.len().is_multiple_of(4) { + body.push(0); + } + bytes.extend_from_slice(&(body.len() as u32).to_be_bytes()); + bytes.extend_from_slice(&body); + } + bytes +} + +#[test] +fn reads_multiple_names_padding_signed_bounds_and_cubic_controls() { + let bytes = fixture(&["Even", "Odd", "形😀"]); + let shapes = csh::parse(&bytes).unwrap(); + assert_eq!(shapes.iter().map(|s| s.name.as_str()).collect::>(), ["Even", "Odd", "形😀"]); + for shape in shapes { + assert_eq!(shape.bounds, [-10, -20, 90, 180]); + assert_eq!(shape.id, "id"); + let subpaths = shape.path.subpaths(); + assert_eq!(subpaths.len(), 1); + assert!(!subpaths[0].closed); + let knot = subpaths[0].knots[0]; + assert!(knot.linked); + assert_eq!(knot.pre, (0.125, 0.25)); + assert_eq!(knot.anchor, (0.5, 0.5)); + assert_eq!(knot.post, (0.75, 0.875)); + } +} + +#[test] +fn rejects_every_truncated_prefix_without_panicking() { + let bytes = fixture(&["One", "Two"]); + for end in 0..bytes.len() { + assert!(csh::parse(&bytes[..end]).is_err(), "accepted truncated prefix {end}"); + } +} + +#[test] +fn rejects_unsupported_headers_excessive_counts_and_invalid_unicode() { + let bytes = fixture(&["A"]); + for (offset, value) in [(4, 3u32), (8, u32::MAX), (12, u32::MAX), (24, u32::MAX)] { + let mut broken = bytes.clone(); + broken[offset..offset + 4].copy_from_slice(&value.to_be_bytes()); + assert!(csh::parse(&broken).is_err(), "offset {offset}"); + } + let mut broken = bytes.clone(); + broken[16..18].copy_from_slice(&0xd800u16.to_be_bytes()); + assert!(csh::parse(&broken).is_err()); + let mut trailing = bytes; + trailing.push(0); + assert!(csh::parse(&trailing).is_err()); +} + +#[test] +fn rejects_missing_knots_and_mismatched_open_closed_records() { + let bytes = fixture(&["A"]); + // Header/name/version/length = 28; id = 3; bounds = 16; two fill records = 52. + let length_record = 28 + 3 + 16 + 52; + let mut missing = bytes.clone(); + missing[length_record + 2..length_record + 4].copy_from_slice(&2u16.to_be_bytes()); + assert!(csh::parse(&missing).is_err()); + let mut mismatched = bytes; + mismatched[length_record..length_record + 2].copy_from_slice(&0u16.to_be_bytes()); + assert!(csh::parse(&mismatched).is_err()); +} diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index 29da41d481..429df45d79 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -490,6 +490,16 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { return; } match e.outcome { + JobOutcome::Done(v) if e.command == "shape.presets.importCsh" => { + let n = v.get("count").and_then(Value::as_u64).unwrap_or(0); + let group = v.get("group").and_then(Value::as_str).unwrap_or_default(); + app.ui.status = crate::i18n::fmt( + &crate::i18n::trn(crate::i18n::current(), n, "Imported {n} shape from {group}", "Imported {n} shapes from {group}"), + &[("group", group)], + ); + app.ui.status_error = false; + app.ui.presets_ui.shapes = true; + } JobOutcome::Done(v) if e.command == "brush.presets.importAbr" => { let n = v.get("count").and_then(Value::as_u64).unwrap_or(0); let group = v.get("group").and_then(Value::as_str).unwrap_or_default(); diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rs index 6138c08844..3615e87b6d 100644 --- a/crates/ui-egui/src/preset_files_ui.rs +++ b/crates/ui-egui/src/preset_files_ui.rs @@ -14,7 +14,7 @@ use crate::PhotocraftApp; /// the Swatches panel through [`crate::swatches_ui::import_bytes`]). /// `.psp` is Photoshop's live `Keyboard Shortcuts.psp` (the same XML as a `.kys`); other `.psp` /// settings files are refused with a clear message. -pub const PRESET_EXTS: &[&str] = &["abr", "grd", "pat", "aco", "ase", "kys", "psp"]; +pub const PRESET_EXTS: &[&str] = &["abr", "grd", "pat", "aco", "ase", "kys", "psp", "csh"]; fn ext(name: &str) -> String { std::path::Path::new(name).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default() @@ -52,12 +52,30 @@ fn source(name: &str, bytes: &[u8]) -> Value { json!({"data": photocraft_engine::paint::tile::b64_encode(bytes)}) } +/// Import a custom-shape set from the Shapes panel using the normal preset route. +pub(crate) fn import_shapes_dialog(app: &mut PhotocraftApp) { + let result = app.pick_file_bytes_filtered(&["csh"], |app, name, bytes| { + if ext(&name) != "csh" { + return Err(tl!("Choose a custom shape file (.csh).").into()); + } + open(app, &name, &bytes).ok_or_else(|| tl!("Choose a custom shape file (.csh).").to_string())??; + Ok(Value::Null) + }); + if let Err(error) = result + && error != crate::file_dialog::CANCELLED + { + app.ui.status = error; + app.ui.status_error = true; + } +} + /// Import a preset file; `None` when `name` isn't one. pub fn open(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Option> { let (cmd, what) = match ext(name).as_str() { "abr" => ("brush.presets.importAbr", "brushes"), "grd" => ("gradient.presets.importGrd", "gradients"), "pat" => ("pattern.import", "patterns"), + "csh" => ("shape.presets.importCsh", "shapes"), "aco" | "ase" => return Some(crate::swatches_ui::import_bytes(app, name, bytes, false).map(|_| ())), "kys" | "psp" => return Some(crate::kys_import::open_bytes(app, name, bytes).map(|_| ())), _ => return None, @@ -82,6 +100,7 @@ pub fn open(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Option ("Imported {n} brush from {file}", "Imported {n} brushes from {file}"), "patterns" => ("Imported {n} pattern from {file}", "Imported {n} patterns from {file}"), + "shapes" => ("Imported {n} shape from {file}", "Imported {n} shapes from {file}"), _ => ("Imported {n} gradient from {file}", "Imported {n} gradients from {file}"), }; let imported = crate::i18n::fmt(&crate::i18n::trn(crate::i18n::current(), n, one, other), &[("file", &stem)]); @@ -97,12 +116,20 @@ pub fn open(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Option = src .iter() diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 590b9febc5..44962eb31d 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-14 · **Change:** minor (CSH custom-shape import, #5359; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026 Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity and tests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write @@ -134,7 +134,8 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. | Actions `.atn` | R/W | R/W | `psd/src/atn.rs` (version 16 sets, exact round trip), `engine/src/atn_cmds.rs` (112 Photoshop events ↔ commands; other steps kept verbatim). Panel menu, CLI `batch --actions set.atn`, `actions.load`/`actions.save`. Photoshop 5-era version 12 files unsupported (AUTO-219-2) | | Styles `.asl` | R/W | no | #1693 | | Contours `.shc` | R/W | R/W | `psd/src/shc.rs`; Contour Editor Load…/Save… (FILE-215-15). No user contour library; not yet checked against a Photoshop-written file | -| Custom shapes `.csh`, tool presets `.tpl` | R/W | no | | +| Custom shapes `.csh` | R/W | R | Version 2 sets through Shapes → Import Shapes… or File → Open; persistent groups via `shape.presets.importCsh`. Original generated geometry cross-read with ag-psd; not yet checked against a Photoshop-written file. No export | +| Tool presets `.tpl` | R/W | no | | | Curves `.acv`, Levels `.alv`, other adjustment presets | R/W | not audited | | | C2PA Content Credentials | R/W | no | #1050 | @@ -142,6 +143,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. | Date | Change | Summary | |---|---|---| +| 2026-10-14 | minor | CSH custom-shape set import (#5359, FILE-215-15); export and Photoshop-written fixture verification remain open; no estimate changed | | 2026-10-13 | minor | PSD: a "Saving Merged Transparency" global block (`Mtrn`, `Mt16`, `Mt32`; Photoshop's 32-bit documents keep a positive layer count) marks the merged image's first extra channel as its transparency: opening such a file no longer adds a "Transparency" alpha channel, and the oracle compares psd-tools transparentbg.psd's alpha (83.7 % → 0.9 % of pixels off; its shape edges remain) | | 2026-10-13 | minor | Palette PNGs open in Indexed Color mode (#4804) | | 2026-10-12 | minor | `.atn`: 112 events mapped (Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, points, Bitmap) | diff --git a/docs/gaps.md b/docs/gaps.md index c952bac81b..9fa08b6f22 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (G10: CSH import, #5359; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -221,7 +221,9 @@ what an agent can't finish alone. (FILE-215-10, #2541), AVIF read (#463) and default-build AVIF write, JPEG XL, JPEG 2000 (#1047), Cineon (DPX landed, #1049), DICOM, EPS/DCS, PCX, Pixar, IFF, WBMP, MPO/JPS, PICT, Scitex CT, Photoshop Raw; layered TIFF extra alpha channels (FILE-215-7); spot plates (FILE-215-17); .atn, .asl, - .shc, .csh presets (FILE-215-15); C2PA (#1050). + .shc presets and .csh export (FILE-215-15); C2PA (#1050). +- **CSH import:** Version 2 custom-shape sets load into persistent Shapes groups (#5359). + Original synthetic geometry is independently cross-read; Photoshop-written fixture verification remains open. - **Detail:** [`file-format-parity.md`](file-format-parity.md). - **Estimate:** 120–220 h. @@ -262,6 +264,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-14 | minor | CSH custom-shape set import (#5359, FILE-215-15); export and Photoshop-written fixture verification remain open; no estimate changed | | 2026-10-13 | minor | G6: stale "missing tool" list corrected against `main` — Color Replacement (`paint.colorReplacement`), Red Eye (`paint.redEye`) and Add/Delete Anchor Point (P flyout, #4144) are live tools, so the toolbox is 67 of 68 and Art History Brush is the only one missing; no percentage or estimate changed | | 2026-10-13 | minor | G4: Hue Jitter amount-track appearance (#3825, partial); no readiness percentage or estimate changed | | 2026-10-13 | minor | G4: minimum inputs in Shape Dynamics and Transfer follow their Control (#3825, partial); no readiness percentage or estimate changed | From 2a02350cda10cec396651765fa52fabde6e45047 Mon Sep 17 00:00:00 2001 From: jonathnwxh <258340642+jonathanwxh-cell@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:47:42 +0800 Subject: [PATCH 2/6] Restrict CSH automation imports to inline data --- crates/automation/src/workspace.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index cde3a3a702..6644c84d00 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -363,7 +363,7 @@ fn preference_uses_ambient_filesystem(path: &str) -> bool { fn command_uses_ambient_path(id: &str, params: &Value) -> bool { match id { - "actions.load" | "brush.presets.importAbr" | "gradient.presets.importGrd" | "plugin.install" | "swatches.import" => { + "actions.load" | "brush.presets.importAbr" | "gradient.presets.importGrd" | "shape.presets.importCsh" | "plugin.install" | "swatches.import" => { // `data` wins over `path` in these commands; any `path` without it reads the filesystem. params.get("data").is_none() && params.get("path").is_some() } @@ -804,6 +804,24 @@ mod tests { assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "interface.language", "value": "fr"})).is_ok()); } + #[test] + fn csh_import_requires_inline_data_in_automation() { + let id = "shape.presets.importCsh"; + for path in ["/outside/set.csh", "set.csh", "../set.csh", ""] { + let params = serde_json::json!({"path": path}); + assert!(authorize_engine_command(id, ¶ms).is_err(), "{path}"); + assert!(authorize_desktop_engine_command(id, ¶ms).is_err(), "{path}"); + } + // The importer gives inline data precedence, even when a path is also supplied. + for params in [serde_json::json!({"data": "QUJD"}), serde_json::json!({"data": "QUJD", "path": "/outside/set.csh"})] { + assert!(authorize_engine_command(id, ¶ms).is_ok()); + assert!(authorize_desktop_engine_command(id, ¶ms).is_ok()); + } + let mut headless = crate::headless::Headless::new(); + let error = headless.command_run(id, serde_json::json!({"path": "/outside/set.csh"})).unwrap_err(); + assert!(error.to_string().contains("uses ambient filesystem paths and is disabled"), "{error}"); + } + #[test] fn registry_filesystem_path_params_are_classified() { let probe = serde_json::json!({ From 77d889850c1d523789171c07461120eca42187fe Mon Sep 17 00:00:00 2001 From: jonathnwxh <258340642+jonathanwxh-cell@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:28:46 +0800 Subject: [PATCH 3/6] Translate custom shape import labels and status messages --- crates/ui-egui/src/i18n/cs.tsv | 6 ++++++ crates/ui-egui/src/i18n/de.tsv | 6 ++++++ crates/ui-egui/src/i18n/el.tsv | 6 ++++++ crates/ui-egui/src/i18n/es.tsv | 6 ++++++ crates/ui-egui/src/i18n/fr.tsv | 6 ++++++ crates/ui-egui/src/i18n/hu.tsv | 6 ++++++ crates/ui-egui/src/i18n/id.tsv | 6 ++++++ crates/ui-egui/src/i18n/it.tsv | 6 ++++++ crates/ui-egui/src/i18n/ja.tsv | 6 ++++++ crates/ui-egui/src/i18n/ko.tsv | 6 ++++++ crates/ui-egui/src/i18n/nl.tsv | 6 ++++++ crates/ui-egui/src/i18n/pl.tsv | 6 ++++++ crates/ui-egui/src/i18n/pt-br.tsv | 6 ++++++ crates/ui-egui/src/i18n/ru.tsv | 6 ++++++ crates/ui-egui/src/i18n/sr.tsv | 6 ++++++ crates/ui-egui/src/i18n/tr.tsv | 6 ++++++ crates/ui-egui/src/i18n/uk.tsv | 6 ++++++ crates/ui-egui/src/i18n/vi.tsv | 6 ++++++ crates/ui-egui/src/i18n/zh-hans.tsv | 6 ++++++ crates/ui-egui/src/i18n/zh-hant.tsv | 6 ++++++ 20 files changed, 120 insertions(+) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 01a8b9e4d9..024bd7d415 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3752,3 +3752,9 @@ navigator Zoom Zvětšení Sent to {printer} Odesláno do {printer} set in Print Settings… nastavuje se v nastavení tisku… ICO is limited to 256 × 256 pixels ICO je omezen na 256 × 256 pixelů + +# Custom shape set import + Import Shapes… Importovat tvary… + Choose a custom shape file (.csh). Vyberte soubor vlastních tvarů (.csh). +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} Počet tvarů importovaných z {file}: {n}|Počet tvarů importovaných z {file}: {n}|Počet tvarů importovaných z {file}: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} Počet tvarů importovaných z {group}: {n}|Počet tvarů importovaných z {group}: {n}|Počet tvarů importovaných z {group}: {n} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 489647ed21..4eedb1056b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3142,3 +3142,9 @@ curves Smooth Glätten Sent to {printer} An {printer} gesendet set in Print Settings… in den Druckeinstellungen festlegen… ICO is limited to 256 × 256 pixels ICO ist auf 256 × 256 Pixel begrenzt + +# Custom shape set import + Import Shapes… Formen importieren… + Choose a custom shape file (.csh). Wählen Sie eine Datei mit eigenen Formen (.csh). +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} Anzahl der aus {file} importierten Formen: {n}|Anzahl der aus {file} importierten Formen: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} Anzahl der aus {group} importierten Formen: {n}|Anzahl der aus {group} importierten Formen: {n} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 410da1a188..8818e365c3 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3842,3 +3842,9 @@ curves Smooth Εξομάλυνση Sent to {printer} Στάλθηκε στον {printer} set in Print Settings… ορίζεται στις ρυθμίσεις εκτύπωσης… ICO is limited to 256 × 256 pixels Το ICO περιορίζεται σε 256 × 256 εικονοστοιχεία + +# Custom shape set import + Import Shapes… Εισαγωγή σχημάτων… + Choose a custom shape file (.csh). Επιλέξτε ένα αρχείο προσαρμοσμένων σχημάτων (.csh). +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} Αριθμός σχημάτων που εισήχθησαν από {file}: {n}|Αριθμός σχημάτων που εισήχθησαν από {file}: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} Αριθμός σχημάτων που εισήχθησαν από {group}: {n}|Αριθμός σχημάτων που εισήχθησαν από {group}: {n} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b5db4e9925..78dfe6453a 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2829,3 +2829,9 @@ curves Smooth Suavizar Sent to {printer} Enviado a {printer} set in Print Settings… se establece en Ajustes de impresión… ICO is limited to 256 × 256 pixels ICO está limitado a 256 × 256 píxeles + +# Custom shape set import + Import Shapes… Importar formas… + Choose a custom shape file (.csh). Selecciona un archivo de formas personalizadas (.csh). +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} Cantidad de formas importadas de {file}: {n}|Cantidad de formas importadas de {file}: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} Cantidad de formas importadas de {group}: {n}|Cantidad de formas importadas de {group}: {n} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index ab0cca6f40..7b044a5d31 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3146,3 +3146,9 @@ curves Smooth Lisser Sent to {printer} Envoyé à {printer} set in Print Settings… défini dans les paramètres d’impression… ICO is limited to 256 × 256 pixels Le format ICO est limité à 256 × 256 pixels + +# Custom shape set import + Import Shapes… Importer des formes… + Choose a custom shape file (.csh). Choisissez un fichier de formes personnalisées (.csh). +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} Nombre de formes importées depuis {file} : {n}|Nombre de formes importées depuis {file} : {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} Nombre de formes importées depuis {group} : {n}|Nombre de formes importées depuis {group} : {n} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9a7283a5a1..b5ba00e4fd 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4065,3 +4065,9 @@ cameraRaw Yellow Sárga Ink Characteristics Festék jellemzői Solidity: Fedőképesség: Redrawing Újrarajzolás + +# Custom shape set import + Import Shapes… Alakzatok importálása… + Choose a custom shape file (.csh). Válasszon egy egyéni alakzatfájlt (.csh). +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} A(z) {file} forrásból importált alakzatok száma: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} A(z) {group} forrásból importált alakzatok száma: {n} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 6924c45609..2ac208a3ed 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3133,3 +3133,9 @@ curves Smooth Haluskan Sent to {printer} Dikirim ke {printer} set in Print Settings… diatur di Pengaturan Cetak… ICO is limited to 256 × 256 pixels ICO dibatasi hingga 256 × 256 piksel + +# Custom shape set import + Import Shapes… Impor Bentuk… + Choose a custom shape file (.csh). Pilih berkas bentuk khusus (.csh). +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} Jumlah bentuk yang diimpor dari {file}: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} Jumlah bentuk yang diimpor dari {group}: {n} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2d42c550cc..c2de325c36 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4107,3 +4107,9 @@ navigator Zoom Zoom Sent to {printer} Inviato a {printer} set in Print Settings… impostato nelle impostazioni di stampa… ICO is limited to 256 × 256 pixels ICO è limitato a 256 × 256 pixel + +# Custom shape set import + Import Shapes… Importa forme… + Choose a custom shape file (.csh). Scegli un file di forme personalizzate (.csh). +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} Numero di forme importate da {file}: {n}|Numero di forme importate da {file}: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} Numero di forme importate da {group}: {n}|Numero di forme importate da {group}: {n} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index e05f27d718..cf5c89a58b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3821,3 +3821,9 @@ curves Smooth スムーズ Reset All Locked Settings ロックされた設定をすべて初期化 Copy Texture to Other Tools テクスチャを他のツールにコピー ICO is limited to 256 × 256 pixels ICO は 256 × 256 ピクセルまでです + +# Custom shape set import + Import Shapes… シェイプを読み込み… + Choose a custom shape file (.csh). カスタムシェイプファイル (.csh) を選択してください。 +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} {file} から読み込んだシェイプ数: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} {group} から読み込んだシェイプ数: {n} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 7de9f61f10..e58ba5aaa9 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3319,3 +3319,9 @@ curves Smooth 매끄럽게 Sent to {printer} {printer}(으)로 전송됨 set in Print Settings… 인쇄 설정에서 지정… ICO is limited to 256 × 256 pixels ICO는 256 × 256픽셀로 제한됩니다 + +# Custom shape set import + Import Shapes… 모양 가져오기… + Choose a custom shape file (.csh). 사용자 정의 모양 파일 (.csh)을 선택하세요. +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} {file}에서 가져온 모양 수: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} {group}에서 가져온 모양 수: {n} diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 4ed7d8a744..54aff52c29 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3904,3 +3904,9 @@ curves Smooth Vloeiend maken Sent to {printer} Verzonden naar {printer} set in Print Settings… instellen in de afdrukinstellingen… ICO is limited to 256 × 256 pixels ICO is beperkt tot 256 × 256 pixels + +# Custom shape set import + Import Shapes… Vormen importeren… + Choose a custom shape file (.csh). Kies een bestand met aangepaste vormen (.csh). +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} Aantal uit {file} geïmporteerde vormen: {n}|Aantal uit {file} geïmporteerde vormen: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} Aantal uit {group} geïmporteerde vormen: {n}|Aantal uit {group} geïmporteerde vormen: {n} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index a27cb4af8d..b75480583f 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3742,3 +3742,9 @@ curves Smooth Wygładź Sent to {printer} Wysłano do {printer} set in Print Settings… ustawiane w ustawieniach druku… ICO is limited to 256 × 256 pixels ICO jest ograniczony do 256 × 256 pikseli + +# Custom shape set import + Import Shapes… Importuj kształty… + Choose a custom shape file (.csh). Wybierz plik kształtów własnych (.csh). +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} Liczba kształtów zaimportowanych z {file}: {n}|Liczba kształtów zaimportowanych z {file}: {n}|Liczba kształtów zaimportowanych z {file}: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} Liczba kształtów zaimportowanych z {group}: {n}|Liczba kształtów zaimportowanych z {group}: {n}|Liczba kształtów zaimportowanych z {group}: {n} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0a64497704..6de97a3255 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3934,3 +3934,9 @@ layerLabel No Color Sem cor Sent to {printer} Enviado para {printer} set in Print Settings… definido nas configurações de impressão… ICO is limited to 256 × 256 pixels ICO é limitado a 256 × 256 pixels + +# Custom shape set import + Import Shapes… Importar formas… + Choose a custom shape file (.csh). Escolha um arquivo de formas personalizadas (.csh). +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} Quantidade de formas importadas de {file}: {n}|Quantidade de formas importadas de {file}: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} Quantidade de formas importadas de {group}: {n}|Quantidade de formas importadas de {group}: {n} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 2dbbf4003c..8b6442db06 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3110,3 +3110,9 @@ curves Smooth Сгладить Gray Value (Median) Уровень серого (медиана) Integrated Density Интегральная плотность Length Длина + +# Custom shape set import + Import Shapes… Импортировать фигуры… + Choose a custom shape file (.csh). Выберите файл произвольных фигур (.csh). +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} Количество фигур, импортированных из {file}: {n}|Количество фигур, импортированных из {file}: {n}|Количество фигур, импортированных из {file}: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} Количество фигур, импортированных из {group}: {n}|Количество фигур, импортированных из {group}: {n}|Количество фигур, импортированных из {group}: {n} diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 4a5f7459df..7c6e9415c8 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4219,3 +4219,9 @@ shape Appearance Izgled Ink Characteristics Karakteristike mastila Solidity: Punoća: Redrawing Ponovno iscrtavanje + +# Custom shape set import + Import Shapes… Uvezi oblike… + Choose a custom shape file (.csh). Izaberite datoteku prilagođenih oblika (.csh). +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} Broj oblika uvezenih iz {file}: {n}|Broj oblika uvezenih iz {file}: {n}|Broj oblika uvezenih iz {file}: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} Broj oblika uvezenih iz {group}: {n}|Broj oblika uvezenih iz {group}: {n}|Broj oblika uvezenih iz {group}: {n} diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 01c37a18b2..c13c9d385e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3876,3 +3876,9 @@ cameraData Lens Lens Ink Characteristics Mürekkep Özellikleri Solidity: Doluluk: Redrawing Yeniden çiziliyor + +# Custom shape set import + Import Shapes… Şekilleri İçe Aktar… + Choose a custom shape file (.csh). Özel şekil dosyası (.csh) seçin. +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} {file} kaynağından içe aktarılan şekil sayısı: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} {group} kaynağından içe aktarılan şekil sayısı: {n} diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 79ebc8df36..88a4cab307 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3843,3 +3843,9 @@ curves Smooth Згладити Sent to {printer} Надіслано на {printer} set in Print Settings… задається в параметрах друку… ICO is limited to 256 × 256 pixels ICO обмежено розміром 256 × 256 пікселів + +# Custom shape set import + Import Shapes… Імпортувати фігури… + Choose a custom shape file (.csh). Виберіть файл довільних фігур (.csh). +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} Кількість фігур, імпортованих із {file}: {n}|Кількість фігур, імпортованих із {file}: {n}|Кількість фігур, імпортованих із {file}: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} Кількість фігур, імпортованих із {group}: {n}|Кількість фігур, імпортованих із {group}: {n}|Кількість фігур, імпортованих із {group}: {n} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1fea5e6b38..9b8fb9e00a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3631,3 +3631,9 @@ curves Smooth Làm mượt Sent to {printer} Đã gửi tới {printer} set in Print Settings… đặt trong thiết lập in… ICO is limited to 256 × 256 pixels ICO giới hạn ở 256 × 256 pixel + +# Custom shape set import + Import Shapes… Nhập hình dạng… + Choose a custom shape file (.csh). Chọn tệp hình dạng tùy chỉnh (.csh). +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} Số hình dạng đã nhập từ {file}: {n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} Số hình dạng đã nhập từ {group}: {n} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 375b61c40b..149a511a22 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2754,3 +2754,9 @@ curves Smooth 平滑 Sent to {printer} 已发送到 {printer} set in Print Settings… 在打印设置中设置… ICO is limited to 256 × 256 pixels ICO 最大为 256 × 256 像素 + +# Custom shape set import + Import Shapes… 导入形状… + Choose a custom shape file (.csh). 请选择自定义形状文件 (.csh)。 +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} 从 {file} 导入的形状数量:{n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} 从 {group} 导入的形状数量:{n} diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index de931038db..4e32c26e16 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2739,3 +2739,9 @@ curves Smooth 平滑 Sent to {printer} 已傳送至 {printer} set in Print Settings… 在列印設定中設定… ICO is limited to 256 × 256 pixels ICO 最大為 256 × 256 像素 + +# Custom shape set import + Import Shapes… 匯入形狀… + Choose a custom shape file (.csh). 請選擇自訂形狀檔案 (.csh)。 +@plural Imported {n} shape from {file}|Imported {n} shapes from {file} 從 {file} 匯入的形狀數量:{n} +@plural Imported {n} shape from {group}|Imported {n} shapes from {group} 從 {group} 匯入的形狀數量:{n} From 7b4f2b26703d1b335d3b0c7d2c80600829bbd72d Mon Sep 17 00:00:00 2001 From: jonathnwxh <258340642+jonathanwxh-cell@users.noreply.github.com> Date: Mon, 19 Oct 2026 04:46:30 +0800 Subject: [PATCH 4/6] Remove obsolete ATN format gap while retaining contour preset gap --- docs/gaps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/gaps.md b/docs/gaps.md index acb238bc08..ca44ac48b9 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -226,7 +226,7 @@ what an agent can't finish alone. write (FILE-215-10, #2541; a single flattened page now saves via Save As / Save a Copy / CLI, 2026-10-11, #3401), AVIF read (#463) and default-build AVIF write, JPEG XL, JPEG 2000 (#1047), Cineon write (read landed), DICOM, EPS/DCS, Pixar, IFF, WBMP, MPO/JPS, PICT, Scitex CT, Photoshop - Raw; layered TIFF extra alpha channels (FILE-215-7); spot plates (FILE-215-17); .atn, .asl, + Raw; layered TIFF extra alpha channels (FILE-215-7); spot plates (FILE-215-17); .asl, .shc presets and .csh export (FILE-215-15); C2PA (#1050). - **CSH import:** Version 2 custom-shape sets load into persistent Shapes groups (#5359). Original synthetic geometry is independently cross-read; Photoshop-written fixture verification remains open. From 6506c5ce107413272be2686ae9cae1433a543ff9 Mon Sep 17 00:00:00 2001 From: jonathnwxh <258340642+jonathanwxh-cell@users.noreply.github.com> Date: Mon, 19 Oct 2026 04:53:20 +0800 Subject: [PATCH 5/6] Document CSH import atomicity and input validation contracts --- crates/engine/src/preset_import_cmds.rs | 6 +++++- crates/engine/src/presets/shapes/csh.rs | 4 ++++ crates/psd/src/csh.rs | 6 ++++-- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/preset_import_cmds.rs b/crates/engine/src/preset_import_cmds.rs index 972344da70..c9e876b0ec 100644 --- a/crates/engine/src/preset_import_cmds.rs +++ b/crates/engine/src/preset_import_cmds.rs @@ -33,7 +33,11 @@ pub(crate) fn file_bytes(p: &Value, cmd: &str, what: &str) -> Result<(Vec, S file_bytes_limited(p, cmd, what, MAX_FILE_BYTES) } -/// Read with the format's own input budget, before allocating file or decoded base64 bytes. +/// Load preset bytes with a format-specific limit; `data` takes precedence over `path`. +/// Inline base64 returns an empty group name; a file returns its filename stem. +/// The encoded-length check bounds base64 allocation, then decoded length is checked exactly. +/// File reads are capped at `max_bytes + 1` so growth after the metadata check is still rejected. +/// This helper does not authorize paths; automation callers must enforce their workspace policy. pub(crate) fn file_bytes_limited(p: &Value, cmd: &str, what: &str, max_bytes: u64) -> Result<(Vec, String)> { if let Some(d) = p.get("data") { let s = d.as_str().ok_or_else(|| bad(cmd, "`data` must be a base64 string"))?; diff --git a/crates/engine/src/presets/shapes/csh.rs b/crates/engine/src/presets/shapes/csh.rs index e66b79653d..d87f293a18 100644 --- a/crates/engine/src/presets/shapes/csh.rs +++ b/crates/engine/src/presets/shapes/csh.rs @@ -22,6 +22,10 @@ pub(super) fn spec() -> CommandSpec { } } +/// Parse and convert the complete set before applying any library changes. +/// Group and shape names are resolved against the live library on apply, not the worker's +/// snapshot, so edits made while the job runs do not introduce duplicate addressable names. +/// Conversion fits each path into a 100-by-100 reference box while preserving its aspect ratio. fn import(s: &mut Session, p: &Value) -> Result { let group = p .get("group") diff --git a/crates/psd/src/csh.rs b/crates/psd/src/csh.rs index 674d79267c..2b6d545c2c 100644 --- a/crates/psd/src/csh.rs +++ b/crates/psd/src/csh.rs @@ -101,8 +101,10 @@ fn zero_padding(bytes: &[u8]) -> Result<()> { Ok(()) } -// The generic PSD reader is deliberately lenient; importing presets must not silently -// turn a truncated or miscounted shape into different geometry. +/// Enforce subpath structure more strictly than the generic PSD path reader. +/// Each length record must be followed by exactly its declared number of knots, with matching +/// open/closed selectors. Fill and clipboard records are accepted only between subpaths. +/// Rejecting inconsistent records prevents a damaged preset from silently changing geometry. fn validate_path(path: &PathData) -> Result<()> { let mut pending = 0u16; let mut closed = false; From 9e81ec35766344f56f5796b631964245fc6f8f66 Mon Sep 17 00:00:00 2001 From: jonathanwxh-cell <258340642+jonathanwxh-cell@users.noreply.github.com> Date: Mon, 26 Oct 2026 09:50:13 +0000 Subject: [PATCH 6/6] fix(shapes): store CSH display names and report the group used MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Localization keys such as $$$/Presets/Shapes/Tiger=Tiger were kept raw, so the Shapes panel showed the key. File → Open now reports the group the importer stored, including a suffix when that name was already taken. --- crates/engine/src/presets/shapes/csh.rs | 5 ++++- crates/engine/tests/csh_import.rs | 15 +++++++++++++++ crates/psd/tests/common/csh_fixture.rs | 6 +++++- crates/ui-egui/src/preset_files_ui.rs | 25 ++++++++++++++++++------- 4 files changed, 42 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/presets/shapes/csh.rs b/crates/engine/src/presets/shapes/csh.rs index d87f293a18..119c548cc6 100644 --- a/crates/engine/src/presets/shapes/csh.rs +++ b/crates/engine/src/presets/shapes/csh.rs @@ -55,7 +55,10 @@ fn import(s: &mut Session, p: &Value) -> Result { return Err(bad(CMD, format!("shape {:?} has no path", shape.name))); } let path = fit(&path, [0.0, 0.0, 100.0, 100.0], true); - let name = if shape.name.trim().is_empty() { "Shape".to_owned() } else { shape.name }; + // Photoshop stores some preset names as `$$$/…/Key=Shown`. The Shapes panel + // renders the stored name, so keep the text after `=`. + let shown = photocraft_doc::pattern::display_name(&shape.name); + let name = if shown.trim().is_empty() { "Shape".to_owned() } else { shown.to_owned() }; items.push(ShapePreset { name, path }); } let group = group.unwrap_or_else(|| if stem.is_empty() { "Imported Shapes".into() } else { stem }); diff --git a/crates/engine/tests/csh_import.rs b/crates/engine/tests/csh_import.rs index 7af372995d..3c6e8779dd 100644 --- a/crates/engine/tests/csh_import.rs +++ b/crates/engine/tests/csh_import.rs @@ -8,6 +8,21 @@ use serde_json::json; mod fixture; use fixture::{polygon_csh, triangle_csh}; +#[test] +fn csh_import_stores_the_display_form_of_a_localization_key() { + let bytes = fixture::named_polygon_csh("$$$/Presets/Shapes/Tiger=Tiger", &[&[(0.25, 0.25), (0.75, 0.25), (0.5, 0.75)]]); + let blank = fixture::named_polygon_csh("$$$/Presets/Shapes/Blank= ", &[&[(0.25, 0.25), (0.75, 0.25), (0.5, 0.75)]]); + let mut session = Session::new(); + let result = session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&bytes), "group": "Localized CSH"})).unwrap(); + assert_eq!(result["group"], "Localized CSH"); + assert_eq!(result["names"], json!(["Tiger"])); + assert_eq!(session.presets.shapes.iter().find(|g| g.name == "Localized CSH").unwrap().items[0].name, "Tiger"); + let again = session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&bytes), "group": "Localized CSH"})).unwrap(); + assert_eq!(again["names"], json!(["Tiger 2"])); + let blanked = session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&blank)})).unwrap(); + assert_eq!(blanked["names"], json!(["Shape"])); +} + #[test] fn csh_import_makes_an_original_shape_available_without_a_document() { let bytes = triangle_csh(); diff --git a/crates/psd/tests/common/csh_fixture.rs b/crates/psd/tests/common/csh_fixture.rs index 176754327a..aef1e31da4 100644 --- a/crates/psd/tests/common/csh_fixture.rs +++ b/crates/psd/tests/common/csh_fixture.rs @@ -3,10 +3,14 @@ pub fn triangle_csh() -> Vec { } pub fn polygon_csh(polygons: &[&[(f64, f64)]]) -> Vec { + named_polygon_csh("Triangle", polygons) +} + +pub fn named_polygon_csh(label: &str, polygons: &[&[(f64, f64)]]) -> Vec { let mut out = b"cush".to_vec(); out.extend_from_slice(&2u32.to_be_bytes()); out.extend_from_slice(&1u32.to_be_bytes()); - let name: Vec = "Triangle".encode_utf16().chain(std::iter::once(0)).collect(); + let name: Vec = label.encode_utf16().chain(std::iter::once(0)).collect(); out.extend_from_slice(&(name.len() as u32).to_be_bytes()); for unit in &name { out.extend_from_slice(&unit.to_be_bytes()); diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rs index e29835c093..b147a6543d 100644 --- a/crates/ui-egui/src/preset_files_ui.rs +++ b/crates/ui-egui/src/preset_files_ui.rs @@ -130,14 +130,21 @@ pub fn open(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Option = r.get("warnings").and_then(|w| serde_json::from_value(w.clone()).ok()).unwrap_or_default(); app.ui.status_error = false; - let (one, other) = match what { - "brushes" => ("Imported {n} brush from {file}", "Imported {n} brushes from {file}"), - "styles" => ("Imported {n} style from {file}", "Imported {n} styles from {file}"), - "patterns" => ("Imported {n} pattern from {file}", "Imported {n} patterns from {file}"), - "shapes" => ("Imported {n} shape from {file}", "Imported {n} shapes from {file}"), - _ => ("Imported {n} gradient from {file}", "Imported {n} gradients from {file}"), + // Shape import may suffix the group when that name is taken. Report the group that + // was stored, which the background job path already does. + let reported_group = r.get("group").and_then(Value::as_str).filter(|g| !g.is_empty()); + let (one, other, slot, shown) = if what == "shapes" { + ("Imported {n} shape from {group}", "Imported {n} shapes from {group}", "group", reported_group.unwrap_or(stem.as_str())) + } else { + let (one, other) = match what { + "brushes" => ("Imported {n} brush from {file}", "Imported {n} brushes from {file}"), + "styles" => ("Imported {n} style from {file}", "Imported {n} styles from {file}"), + "patterns" => ("Imported {n} pattern from {file}", "Imported {n} patterns from {file}"), + _ => ("Imported {n} gradient from {file}", "Imported {n} gradients from {file}"), + }; + (one, other, "file", stem.as_str()) }; - let imported = crate::i18n::fmt(&crate::i18n::trn(crate::i18n::current(), n, one, other), &[("file", &stem)]); + let imported = crate::i18n::fmt(&crate::i18n::trn(crate::i18n::current(), n, one, other), &[(slot, shown)]); app.ui.status = match warnings.first() { Some(warning) => { let template = "{message} (notes: {n}; {warning})"; @@ -192,6 +199,10 @@ mod tests { let imported = app.session.presets.shapes.iter().find(|g| g.name == "Original").unwrap(); assert_eq!(imported.items.len(), 1); assert_eq!(imported.items[0].name, "Triangle"); + assert_eq!(app.ui.status, "Imported 1 shape from Original"); + open(&mut app, "Original.CSH", &csh_fixture::triangle_csh()).unwrap().unwrap(); + assert_eq!(app.ui.status, "Imported 1 shape from Original 1"); + assert!(app.session.presets.shapes.iter().any(|g| g.name == "Original 1")); } #[test]