diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index f7a437a47b..cc69681032 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -462,6 +462,7 @@ fn command_uses_ambient_path(id: &str, params: &Value) -> bool { | "brush.presets.importAbr" | "brush.presets.importImage" | "gradient.presets.importGrd" + | "shape.presets.importCsh" | "plugin.install" | "swatches.import" | "style.presets.importAsl" diff --git a/crates/automation/src/workspace/tests.rs b/crates/automation/src/workspace/tests.rs index 10063ba9e6..411c145f12 100644 --- a/crates/automation/src/workspace/tests.rs +++ b/crates/automation/src/workspace/tests.rs @@ -875,3 +875,21 @@ fn absolute_paths_are_checked_against_the_authority_s_own_root() { let none = AuthorizedWorkspace::default(); assert!(none.read(&target.to_string_lossy()).is_err()); } + +#[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}"); +} diff --git a/crates/engine/src/cmd/preset_import_cmds.rs b/crates/engine/src/cmd/preset_import_cmds.rs index 417f5623a1..da1feb539f 100644 --- a/crates/engine/src/cmd/preset_import_cmds.rs +++ b/crates/engine/src/cmd/preset_import_cmds.rs @@ -34,26 +34,39 @@ pub const MAX_ABR_FILE_BYTES: u64 = photocraft_psd::abr::MAX_TOTAL_BYTES as u64; /// 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_within(p, cmd, what, MAX_FILE_BYTES) + file_bytes_limited(p, cmd, what, MAX_FILE_BYTES) } -/// [`file_bytes`] with a size cap of `max` bytes. -fn file_bytes_within(p: &Value, cmd: &str, what: &str, max: u64) -> Result<(Vec, String)> { +/// 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"))?; - if s.len() as u64 > max / 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 { + 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)) } @@ -101,7 +114,7 @@ fn import_abr(s: &mut Session, p: &Value) -> Result { move |ctx| { ctx.progress(0.0, "Importing brushes"); let p = ¶ms; - let (bytes, stem) = file_bytes_within(p, cmd, ".abr file", MAX_ABR_FILE_BYTES)?; + let (bytes, stem) = file_bytes_limited(p, cmd, ".abr file", MAX_ABR_FILE_BYTES)?; let group = match p.get("group") { Some(v) => v.as_str().map(str::trim).filter(|g| !g.is_empty()).ok_or_else(|| bad(cmd, "`group` must be a non-empty string"))?.to_string(), None if !stem.is_empty() => stem, @@ -372,6 +385,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}; @@ -617,16 +638,16 @@ mod tests { let path = dir.join("cap.abr"); std::fs::write(&path, [0u8; 10]).unwrap(); let p = json!({"path": path.to_string_lossy()}); - assert!(file_bytes_within(&p, "t", "f", 10).is_ok()); - assert!(file_bytes_within(&p, "t", "f", 9).is_err(), "a file over the cap is refused before reading"); + assert!(file_bytes_limited(&p, "t", "f", 10).is_ok()); + assert!(file_bytes_limited(&p, "t", "f", 9).is_err(), "a file over the cap is refused before reading"); // A sparse file between the two caps: refused as a .grd, which is checked before reading. let big = dir.join("big.grd"); std::fs::File::create(&big).unwrap().set_len(MAX_FILE_BYTES + 1).unwrap(); let err = Session::new().execute("gradient.presets.importGrd", json!({"path": big.to_string_lossy()})).unwrap_err(); assert!(err.to_string().contains("too large"), "{err}"); let data = json!({"data": "A".repeat(16)}); - assert!(file_bytes_within(&data, "t", "f", 12).is_ok()); - assert!(file_bytes_within(&data, "t", "f", 8).is_err()); + assert!(file_bytes_limited(&data, "t", "f", 12).is_ok()); + assert!(file_bytes_limited(&data, "t", "f", 8).is_err()); std::fs::remove_dir_all(&dir).ok(); } 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..119c548cc6 --- /dev/null +++ b/crates/engine/src/presets/shapes/csh.rs @@ -0,0 +1,87 @@ +//! 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, + } +} + +/// 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") + .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); + // 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 }); + 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..3c6e8779dd --- /dev/null +++ b/crates/engine/tests/csh_import.rs @@ -0,0 +1,133 @@ +//! 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_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(); + 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..2b6d545c2c --- /dev/null +++ b/crates/psd/src/csh.rs @@ -0,0 +1,126 @@ +//! 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(()) +} + +/// 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; + 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 f5ffbed8b7..3057596ef4 100644 --- a/crates/psd/src/lib.rs +++ b/crates/psd/src/lib.rs @@ -49,6 +49,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..aef1e31da4 --- /dev/null +++ b/crates/psd/tests/common/csh_fixture.rs @@ -0,0 +1,49 @@ +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 { + 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 = 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()); + } + 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/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4d945bddca..4ff30277c1 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4267,3 +4267,7 @@ cameraRaw Dehaze Odstranění oparu Refine Hair needs hair detection, which isn't available yet Upřesnit vlasy vyžaduje detekci vlasů, která zatím není k dispozici Select and Mask was closed: its document is no longer the active one Vybrat a maskovat bylo zavřeno: jeho dokument již není aktivní Select and Mask was closed: another layer was selected Vybrat a maskovat bylo zavřeno: byla vybrána jiná vrstva + 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 f37de4d0b7..aeb38ab56f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3542,3 +3542,7 @@ curves Smooth Glätten Refine Hair needs hair detection, which isn't available yet Haare verbessern benötigt eine Haarerkennung, die noch nicht verfügbar ist Select and Mask was closed: its document is no longer the active one Auswählen und maskieren wurde geschlossen: Das zugehörige Dokument ist nicht mehr aktiv Select and Mask was closed: another layer was selected Auswählen und maskieren wurde geschlossen: Es wurde eine andere Ebene ausgewählt + 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 e1671dd730..c7f6b6fe24 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4222,3 +4222,7 @@ curves Smooth Εξομάλυνση Select and Mask was closed: its document is no longer the active one Η Επιλογή και μάσκα έκλεισε: το έγγραφό της δεν είναι πλέον το ενεργό Select and Mask was closed: another layer was selected Η Επιλογή και μάσκα έκλεισε: επιλέχθηκε άλλο επίπεδο Select Layer Under Cursor Επιλογή επιπέδου κάτω από τον δρομέα + 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 7001561208..0b1fe128ff 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4479,3 +4479,7 @@ navigator Zoom Zoom Select and Mask was closed: its document is no longer the active one Se cerró Seleccionar y aplicar máscara: su documento ya no es el activo Select and Mask was closed: another layer was selected Se cerró Seleccionar y aplicar máscara: se seleccionó otra capa Select Layer Under Cursor Seleccionar capa bajo el cursor + 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 e360f8281e..3de84f3f90 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3335,6 +3335,14 @@ curves Smooth Lisser Could not write {name}: {error} Impossible d’écrire {name} : {error} Kept {name}: written by another application {name} conservé : écrit par une autre application Shadow Tint Teinte des ombres + +# 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} + +# PhotoCraft release checks. Check for Updates… Rechercher des mises à jour… PhotoCraft Updates Mises à jour de PhotoCraft Checking for updates… Recherche de mises à jour… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e0bbe74309..fc541b2193 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4430,3 +4430,7 @@ cameraRaw Yellow Sárga Refine Hair needs hair detection, which isn't available yet A Haj finomításához hajfelismerés kell, amely még nem érhető el Select and Mask was closed: its document is no longer the active one A Kijelölés és maszk bezárult: a dokumentuma már nem az aktív Select and Mask was closed: another layer was selected A Kijelölés és maszk bezárult: másik réteg lett kijelölve + 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 8ba824aa08..f20eac30ac 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3542,3 +3542,7 @@ curves Smooth Haluskan Select and Mask was closed: its document is no longer the active one Seleksi dan Mask ditutup: dokumennya tidak lagi aktif Select and Mask was closed: another layer was selected Seleksi dan Mask ditutup: layer lain dipilih Select Layer Under Cursor Pilih Lapisan di Bawah Kursor + 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 b54e247626..fe1b9c0314 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4633,3 +4633,7 @@ shape Appearance Aspetto Refine Hair needs hair detection, which isn't available yet Migliora capelli richiede il rilevamento dei capelli, non ancora disponibile Select and Mask was closed: its document is no longer the active one Seleziona e maschera è stato chiuso: il suo documento non è più quello attivo Select and Mask was closed: another layer was selected Seleziona e maschera è stato chiuso: è stato selezionato un altro livello + 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 fb4667b718..cf50109398 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4196,3 +4196,7 @@ curves Smooth スムーズ Refine Hair needs hair detection, which isn't available yet 髪の毛を調整には髪の毛の検出が必要ですが、まだ利用できません Select and Mask was closed: its document is no longer the active one 「選択とマスク」を閉じました: 対象のドキュメントがアクティブではなくなりました Select and Mask was closed: another layer was selected 「選択とマスク」を閉じました: 別のレイヤーが選択されました + 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 3cfc71bc3f..b1e332b398 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3740,3 +3740,7 @@ curves Smooth 매끄럽게 Select and Mask was closed: its document is no longer the active one 선택 및 마스크가 닫혔습니다: 해당 문서가 더 이상 활성 문서가 아닙니다 Select and Mask was closed: another layer was selected 선택 및 마스크가 닫혔습니다: 다른 레이어가 선택되었습니다 Select Layer Under Cursor 커서 아래 레이어 선택 + 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 7987682ad9..ef7be9641f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4279,3 +4279,7 @@ curves Smooth Vloeiend maken Select and Mask was closed: its document is no longer the active one Selecteren en maskeren is gesloten: het document is niet meer het actieve document Select and Mask was closed: another layer was selected Selecteren en maskeren is gesloten: er is een andere laag geselecteerd Select Layer Under Cursor Laag onder cursor selecteren + 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 2b11c69f3b..80ccbfcbe1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4140,3 +4140,7 @@ curves Smooth Wygładź Select and Mask was closed: its document is no longer the active one Zamknięto Zaznacz i maskuj: jego dokument nie jest już aktywny Select and Mask was closed: another layer was selected Zamknięto Zaznacz i maskuj: wybrano inną warstwę Select Layer Under Cursor Zaznacz warstwę pod kursorem + 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 5a61e53399..339c2a5ae3 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4276,7 +4276,6 @@ layerLabel No Color Sem cor Layer Mask Hides Effects A máscara de camada oculta os efeitos Vector Mask Hides Effects A máscara vetorial oculta os efeitos This Layer: Esta camada: - Underlying Layer: Camada subjacente: Dark Gray Cinza-escuro Medium Gray Cinza médio Select Custom Color… Selecionar cor personalizada… @@ -4448,3 +4447,7 @@ layerLabel No Color Sem cor Refine Hair needs hair detection, which isn't available yet Refinar cabelo requer detecção de cabelo, ainda não disponível Select and Mask was closed: its document is no longer the active one Selecionar e mascarar foi fechado: o documento dele não está mais ativo Select and Mask was closed: another layer was selected Selecionar e mascarar foi fechado: outra camada foi selecionada + 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 e4edcc493c..5427f4f200 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3310,6 +3310,14 @@ curves Smooth Сгладить Slab Serif С брусковыми засечками TrueType font Шрифт TrueType Variable font Вариативный шрифт + +# 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} + +# Bevel & Emboss shading controls. Highlight Mode Режим светлых тонов Highlight Color Цвет светлых тонов Highlight Opacity Непрозрачность светлых тонов diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index de3fd7bde5..a3fa24d139 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4589,3 +4589,7 @@ shape Appearance Izgled Select and Mask was closed: its document is no longer the active one Izaberi i maskiraj je zatvoren: njegov dokument više nije aktivan Select and Mask was closed: another layer was selected Izaberi i maskiraj je zatvoren: izabran je drugi sloj Select Layer Under Cursor Izaberi sloj ispod kursora + 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 cc24d48012..4a312f44dd 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4246,3 +4246,7 @@ cameraData Lens Lens Delete effect Efekti sil Current Layer: Geçerli Katman: Underlying Layer: Alttaki Katman: + 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 4c3fc17b5f..5c3975ba33 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4232,3 +4232,7 @@ curves Smooth Згладити Refine Hair needs hair detection, which isn't available yet Для уточнення волосся потрібне розпізнавання волосся, яке ще недоступне Select and Mask was closed: its document is no longer the active one Вікно «Виділити та маскувати» закрито: його документ більше не активний Select and Mask was closed: another layer was selected Вікно «Виділити та маскувати» закрито: вибрано інший шар + 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 5dc0e92048..219d527f73 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3796,6 +3796,13 @@ curves Smooth Làm mượt Could not write {name}: {error} Không thể ghi {name}: {error} Kept {name}: written by another application Đã giữ {name}: do ứng dụng khác ghi Shadow Tint Sắc độ bóng tối + +# 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} + Check for Updates… Kiểm tra bản cập nhật… PhotoCraft Updates Bản cập nhật PhotoCraft Checking for updates… Đang kiểm tra bản cập nhật… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57d852b405..3f035f5d30 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3203,3 +3203,7 @@ curves Smooth 平滑 Refine Hair needs hair detection, which isn't available yet 调整细线需要毛发检测,目前尚不可用 Select and Mask was closed: its document is no longer the active one 已关闭“选择与蒙版”:其文档不再是当前文档 Select and Mask was closed: another layer was selected 已关闭“选择与蒙版”:已选择另一个图层 + 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 1e14fda28a..1f7673b6fa 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3159,3 +3159,7 @@ curves Smooth 平滑 Refine Hair needs hair detection, which isn't available yet 調整毛髮需要毛髮偵測,目前尚無法使用 Select and Mask was closed: its document is no longer the active one 已關閉「選取並遮住」:其文件已不是使用中的文件 Select and Mask was closed: another layer was selected 已關閉「選取並遮住」:已選取另一個圖層 + 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/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index a4c30646e7..e9731f912f 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -510,6 +510,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/panels/preset_panels/panels.rs b/crates/ui-egui/src/panels/preset_panels/panels.rs index 4b0e05fbd6..c8c0f2734b 100644 --- a/crates/ui-egui/src/panels/preset_panels/panels.rs +++ b/crates/ui-egui/src/panels/preset_panels/panels.rs @@ -278,6 +278,9 @@ fn export_styles(app: &mut PhotocraftApp, params: Value, suggested: &str) -> Res // ------------------------------------------------------------------ Shapes pub fn shapes_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + if ui.button(tl!("Import Shapes…")).clicked() { + crate::preset_files_ui::import_shapes_dialog(app); + } let src = photocraft_engine::presets::shapes::all_groups(&app.session); let groups: Vec = src .iter() diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rs index 74be08360c..b147a6543d 100644 --- a/crates/ui-egui/src/preset_files_ui.rs +++ b/crates/ui-egui/src/preset_files_ui.rs @@ -16,7 +16,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", "asl", "pat", "aco", "act", "ase", "kys", "psp"]; +pub const PRESET_EXTS: &[&str] = &["abr", "grd", "asl", "pat", "aco", "act", "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() @@ -84,6 +84,23 @@ 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() { @@ -91,6 +108,7 @@ pub fn open(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Option ("gradient.presets.importGrd", "gradients"), "asl" => ("style.presets.importAsl", "styles"), "pat" => ("pattern.import", "patterns"), + "csh" => ("shape.presets.importCsh", "shapes"), "aco" | "act" | "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, @@ -112,13 +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}"), - _ => ("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})"; @@ -131,15 +157,23 @@ pub fn open(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Option