mirror of
https://github.com/storytold/photocraft.git
synced 2026-11-18 16:04:57 +00:00
Port CSH import backend while retaining recorded shape IDs
Port the ten backend, automation and test paths from #5493 by
@jonathanwxh-cell, pinned at 43920ab780.
Keep its original CSH codec, bounded preset reader and protection tests.
The prerequisite's UI, translation and parity-document changes are excluded.
Adapt ShapePreset construction to retain the exact source identifier. Empty
identifiers remain anonymous presets; repeated identifiers resolve when their
geometry is identical and refuse resolution when it conflicts. Add one
import-to-ATN Shape Blur regression and document the source attribution.
Original contribution: https://github.com/storytold/photocraft/pull/5493
Source-only integration; compilation and combined runtime validation remain.
This commit is contained in:
1 parent
609d839607
commit
c78b84a1cd
12 files changed
+593
-15
No files matched your search
@@ -468,6 +468,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"
|
||||
|
||||
@@ -1006,3 +1006,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}");
|
||||
}
|
||||
@@ -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<u8>, 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<u8>, 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<u8>, 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<Value> {
|
||||
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,
|
||||
@@ -392,6 +405,14 @@ fn import_grd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
#[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};
|
||||
@@ -675,16 +696,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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -300,8 +302,10 @@ pub(crate) fn filter_path(s: &Session, p: &Value) -> Result<Path> {
|
||||
let id = value.as_str().filter(|id| !id.is_empty()).ok_or_else(|| bad(CMD, "shapeId must be a nonempty string"))?;
|
||||
let mut matches = s.presets.shapes.iter().flat_map(|g| &g.items).filter(|shape| shape.id.as_deref() == Some(id));
|
||||
let found = matches.next().ok_or_else(|| bad(CMD, format!("no installed shape with id \"{id}\"")))?;
|
||||
if matches.next().is_some() {
|
||||
return Err(bad(CMD, format!("more than one installed shape has id \"{id}\"")));
|
||||
// Reimporting an unchanged library adds another display name for the same asset.
|
||||
// Different geometry under one ID is ambiguous and must not pick the first match.
|
||||
if matches.any(|shape| shape.path != found.path) {
|
||||
return Err(bad(CMD, format!("different installed shapes have id \"{id}\"")));
|
||||
}
|
||||
return Ok(found.path.clone());
|
||||
}
|
||||
@@ -465,6 +469,7 @@ fn reset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
csh::spec(),
|
||||
CommandSpec {
|
||||
id: "shape.presets.list",
|
||||
label: "Shape Presets",
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! 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<Value> {
|
||||
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() };
|
||||
// Keep opaque IDs unchanged. An anonymous preset remains usable by name;
|
||||
// repeated IDs are checked against geometry when a filter resolves them.
|
||||
let id = (!shape.id.is_empty()).then_some(shape.id);
|
||||
items.push(ShapePreset { name, path, id });
|
||||
}
|
||||
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<String> = 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<String, usize> = 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<String> = 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)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -4,6 +4,9 @@ use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem};
|
||||
use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D};
|
||||
use serde_json::json;
|
||||
|
||||
#[path = "../../../psd/tests/common/csh_fixture.rs"]
|
||||
mod csh_fixture;
|
||||
|
||||
const SHAPE_ID: &str = "original-fixture-square";
|
||||
|
||||
fn descriptor() -> Descriptor {
|
||||
@@ -100,6 +103,45 @@ fn custom_shape_smart_filter_keeps_geometry_across_save_without_preset_library()
|
||||
assert_eq!(pixels(&reopened), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_csh_id_resolves_in_an_action_after_reimport_and_preference_reload() {
|
||||
let mut s = fixture(16);
|
||||
let bytes = csh_fixture::triangle_csh();
|
||||
let id = photocraft_psd::csh::parse(&bytes).unwrap()[0].id.clone();
|
||||
let p = json!({"data":photocraft_paint::tile::b64_encode(&bytes)});
|
||||
s.execute("shape.presets.importCsh", p.clone()).unwrap();
|
||||
s.execute("shape.presets.importCsh", p).unwrap();
|
||||
let matches: Vec<_> = s.presets.shapes.iter().flat_map(|g| &g.items).filter(|shape| shape.id.as_deref() == Some(id.as_str())).collect();
|
||||
assert_eq!(matches.len(), 2, "both imports retain the source's opaque ID");
|
||||
let path = photocraft_engine::vector_cmds::path_json(&matches[0].path);
|
||||
let mut expected = fixture(16);
|
||||
expected.execute("filter.blur.shapeBlur", json!({"radius":5,"shapePath":path})).unwrap();
|
||||
let prefs = s.presets.to_json(&s);
|
||||
let mut s = fixture(16);
|
||||
s.load_presets_json(prefs);
|
||||
let shape =
|
||||
Descriptor::new("customShape").with("Nm ", D::Text(UnicodeString::new_nul("Old shape name"))).with("Idnt", D::Text(UnicodeString::new_nul(&id)));
|
||||
let d = Descriptor::new("null")
|
||||
.with("Rds ", D::UnitFloat { unit: *b"#Pxl", value: 5.0 })
|
||||
.with("customShape", D::Descriptor(shape))
|
||||
.with("keyOriginType", D::Integer(9));
|
||||
let imported = atn_cmds::import(&encoded(d)).unwrap();
|
||||
assert!(imported.unsupported.is_empty());
|
||||
s.actions.list = imported.actions;
|
||||
let before = saved(&s);
|
||||
assert_eq!(s.execute("actions.play", json!({"action":"Shape"})).unwrap()["ran"], 1);
|
||||
assert_eq!(pixels(&s), pixels(&expected));
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(saved(&s), before);
|
||||
// This original fixture has the same ID but a different path. Keep both presets
|
||||
// available by their unique names, while refusing ambiguous action playback.
|
||||
let other = csh_fixture::polygon_csh(&[&[(0.25, 0.25), (0.75, 0.25), (0.75, 0.75), (0.25, 0.75)]]);
|
||||
assert_eq!(photocraft_psd::csh::parse(&other).unwrap()[0].id, id);
|
||||
s.execute("shape.presets.importCsh", json!({"data":photocraft_paint::tile::b64_encode(&other)})).unwrap();
|
||||
assert!(s.execute("actions.play", json!({"action":"Shape"})).is_err());
|
||||
assert_eq!(saved(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_invalid_custom_shapes_refuse_before_document_or_history_changes() {
|
||||
let mut s = fixture(8);
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//! Photoshop custom shape sets (`.csh`, version 2).
|
||||
//!
|
||||
//! Container layout: Michel Mariani's public format research,
|
||||
//! <https://tonton-pixel.codeberg.page/photoshop-file-formats/custom-shapes-file-format.html>.
|
||||
//! 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<Vec<CshShape>> {
|
||||
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<u16> = 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(())
|
||||
}
|
||||
@@ -50,6 +50,7 @@ pub mod blend;
|
||||
pub mod builder;
|
||||
mod codepage;
|
||||
pub mod compression;
|
||||
pub mod csh;
|
||||
pub mod descriptor;
|
||||
pub mod error;
|
||||
pub mod file;
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
pub fn triangle_csh() -> Vec<u8> {
|
||||
polygon_csh(&[&[(0.25, 0.25), (0.75, 0.25), (0.5, 0.75)]])
|
||||
}
|
||||
|
||||
pub fn polygon_csh(polygons: &[&[(f64, f64)]]) -> Vec<u8> {
|
||||
named_polygon_csh("Triangle", polygons)
|
||||
}
|
||||
|
||||
pub fn named_polygon_csh(label: &str, polygons: &[&[(f64, f64)]]) -> Vec<u8> {
|
||||
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<u16> = 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
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
use photocraft_psd::csh;
|
||||
use photocraft_psd::path::{PathData, PsdKnot, PsdSubpath};
|
||||
|
||||
fn fixture(names: &[&str]) -> Vec<u8> {
|
||||
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<u16> = 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::<Vec<_>>(), ["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());
|
||||
}
|
||||
+6
-2
@@ -191,8 +191,12 @@ The nested object class is corroborated by
|
||||
[ag-psd's public descriptor definitions](https://github.com/Agamnentzar/ag-psd/blob/master/src/descriptor.ts).
|
||||
The ID selects the installed shape even after a rename. If that asset is absent,
|
||||
playback fails without applying a blur; it never substitutes a shape with
|
||||
the same name. The existing CSH-import contribution #5493 is the prerequisite
|
||||
for loading external shape libraries and must preserve their original IDs.
|
||||
the same name. CSH libraries use the backend of
|
||||
[@jonathanwxh-cell's #5493](https://github.com/storytold/photocraft/pull/5493),
|
||||
ported from revision `43920ab7804cd386b91b319b33a2a8d0832d4d91` with its bounded
|
||||
reader and import tests. Imported IDs retain their exact text. Empty IDs become
|
||||
anonymous presets usable by name; repeated IDs resolve only when all matching
|
||||
presets have identical geometry. Conflicting geometry fails ID lookup.
|
||||
|
||||
The native command rasterizes the selected vector shape as a normalized coverage
|
||||
kernel, retaining its aspect ratio and orientation. This follows the
|
||||
|
||||
Reference in new issue
Block a user