Merge approved PhotoCraft PR #5493: Import Photoshop custom shape sets into the Shapes panel

Port behavior and regression coverage into current modules; preserve current upstream behavior.
Integrated bounded atomic CSH set parsing, unique shape/group naming and native Shapes panel import with inline-data authorization guards; preserved duplicate-name, inner-hole, malformed-second-record and preferences-reload regressions. Combined independent catalog additions and retained current parity metadata.
This commit is contained in:
FredApps committed 2026-10-29 05:47:45 +01:00
commit c81347aaa8
35 files changed
+748 -21

No files matched your search

+1
View File
@@ -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"
+18
View File
@@ -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, &params).is_err(), "{path}");
assert!(authorize_desktop_engine_command(id, &params).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, &params).is_ok());
assert!(authorize_desktop_engine_command(id, &params).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}");
}
+32 -11
View File
@@ -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 = &params;
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<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};
@@ -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();
}
+3
View File
@@ -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<Value> {
pub fn specs() -> Vec<CommandSpec> {
vec![
csh::spec(),
CommandSpec {
id: "shape.presets.list",
label: "Shape Presets",
+87
View File
@@ -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<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(&params, 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<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)
},
)
}
+133
View File
@@ -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));
}
+126
View File
@@ -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(())
}
+1
View File
@@ -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;
+49
View 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
}
+88
View File
@@ -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());
}
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 6 and column 47.
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 6 and column 47.
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 47 and column 53.
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 4 and column 47.
+8
View File
@@ -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…
Can't render this file because it contains an unexpected character in line 6 and column 47.
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 6 and column 47.
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 4 and column 47.
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 79 and column 53.
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 6 and column 47.
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 63 and column 53.
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 8 and column 34.
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 6 and column 47.
+4 -1
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 6 and column 47.
+8
View File
@@ -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 Непрозрачность светлых тонов
Can't render this file because it contains an unexpected character in line 6 and column 47.
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 6 and column 47.
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 8 and column 34.
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 152 and column 53.
+7
View File
@@ -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…
Can't render this file because it contains an unexpected character in line 6 and column 47.
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 63 and column 53.
+4
View File
@@ -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}
Can't render this file because it contains an unexpected character in line 6 and column 47.
+10
View File
@@ -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();
@@ -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<GroupView> = src
.iter()
+99 -7
View File
@@ -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<Result<(), String>> {
let (cmd, what) = match ext(name).as_str() {
@@ -91,6 +108,7 @@ pub fn open(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Option<Result<
"grd" => ("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<Result<
let n = r.get("count").and_then(Value::as_u64).unwrap_or(0);
let warnings: Vec<String> = 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<Result<
app.ui.panels.brush_settings = true;
app.ui.brush_tab = 1;
}
if what == "shapes" {
app.ui.presets_ui.shapes = true;
}
if what == "styles" {
app.ui.presets_ui.styles = true;
}
}))
}
#[cfg(test)]
#[path = "../../psd/tests/common/csh_fixture.rs"]
mod csh_fixture;
#[cfg(test)]
mod tests {
use super::*;
use egui_kittest::kittest::Queryable;
#[test]
fn recognises_preset_files() {
@@ -147,12 +181,70 @@ mod tests {
assert!(is_preset_file("sunsets.grd"));
assert!(is_preset_file("Comic Styles.ASL"));
assert!(is_preset_file("Brand.ACO"));
assert!(is_preset_file("Palette.ACT"));
assert!(is_preset_file("exchange.ase"));
assert!(is_preset_file("Debaser-ColourLibrary-Part6.PAT"));
assert!(is_preset_file("Original.CSH"));
assert!(!is_preset_file("photo.psd"));
assert!(!is_preset_file("abr"));
}
#[test]
fn csh_open_imports_presets_and_shows_shapes_without_opening_a_document() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
open(&mut app, "Original.CSH", &csh_fixture::triangle_csh()).unwrap().unwrap();
assert!(app.session.active().is_none());
assert!(app.ui.presets_ui.shapes);
assert!(!app.ui.status_error);
let imported = app.session.presets.shapes.iter().find(|g| g.name == "Original").unwrap();
assert_eq!(imported.items.len(), 1);
assert_eq!(imported.items[0].name, "Triangle");
assert_eq!(app.ui.status, "Imported 1 shape from Original");
open(&mut app, "Original.CSH", &csh_fixture::triangle_csh()).unwrap().unwrap();
assert_eq!(app.ui.status, "Imported 1 shape from Original 1");
assert!(app.session.presets.shapes.iter().any(|g| g.name == "Original 1"));
}
#[test]
fn malformed_csh_open_preserves_the_library() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
let before = app.session.presets.to_json(&app.session);
assert!(open(&mut app, "broken.csh", b"cush").unwrap().is_err());
assert_eq!(app.session.presets.to_json(&app.session), before);
assert!(app.session.active().is_none());
}
#[test]
#[ignore = "requires a GPU adapter; renders the CSH import workflow for visual inspection"]
fn csh_panel_import_visual_evidence() {
let _guard = photocraft_testkit::gpu_lock();
let (dialog, requests) =
crate::file_dialog::fake(vec![Some(crate::file_dialog::FileDialogAnswer::Contents("Original.csh".into(), csh_fixture::triangle_csh()))]);
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_max_steps(64).wgpu().build_eframe(move |cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
let services = crate::Services { file_dialog: Some(dialog), ..Default::default() };
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
app.set_wgpu(cc.wgpu_render_state.as_ref().unwrap().clone());
app.run("file.new", json!({"width": 400, "height": 300, "background": "transparent"})).unwrap();
// A user-cleared library makes the one imported fixture visible without scrolling.
app.session.presets.shapes.clear();
app.ui.presets_ui.shapes = true;
app
});
h.run_steps(8);
let destination = std::env::var("PHOTOCRAFT_CSH_EVIDENCE").unwrap_or_else(|_| "csh-evidence".into());
std::fs::create_dir_all(&destination).unwrap();
h.render().unwrap().save(std::path::Path::new(&destination).join("before-import.png")).unwrap();
h.get_by_label("Import Shapes…").click();
h.run_steps(12);
assert!(matches!(requests.borrow().first(), Some(crate::file_dialog::FileDialogRequest::Open { extensions: Some(exts), .. }) if exts == &["csh"]));
assert_eq!(h.state().session.presets.shapes[0].items[0].name, "Triangle");
assert!(!h.state().ui.status_error);
h.state_mut().run("shape.presets.place", json!({"preset": "Triangle", "rect": [60, 60, 280, 180], "fill": "#d85a32"})).unwrap();
h.run_steps(8);
h.render().unwrap().save(std::path::Path::new(&destination).join("imported-triangle.png")).unwrap();
}
/// Import Brushes… with a PNG: the image becomes the current brush's tip (TOOL-213-12).
#[test]
fn import_brushes_turns_an_image_into_a_brush_tip() {
+3 -1
View File
@@ -136,7 +136,8 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.
| Actions `.atn` | R/W | R/W | `psd/src/atn.rs` (version 16 sets, exact round trip), `engine/src/atn_cmds.rs` (Photoshop events ↔ commands, including Apply Layer Comp by name, #7101; other steps kept verbatim; Save As maps to `file.saveAs`/`file.saveACopy` when its destination is a file, #7102). Panel menu, CLI `batch --actions set.atn`, `actions.load`/`actions.save`. Photoshop 5-era version 12 files unsupported (AUTO-219-2) |
| Styles `.asl` | R/W | R/W | `psd/src/asl.rs`, `io/src/asl_map.rs`; Styles panel Import/Export Styles…, `style.presets.importAsl`/`exportAsl` (#1051) |
| Contours `.shc` | R/W | R/W | `psd/src/shc.rs`; Contour Editor Load…/Save… (FILE-215-15). No user contour library; not yet checked against a Photoshop-written file |
| Custom shapes `.csh`, tool presets `.tpl` | R/W | no | |
| Custom shapes `.csh` | R/W | R | Version 2 sets through Shapes → Import Shapes… or File → Open; persistent groups via `shape.presets.importCsh`. Original generated geometry cross-read with ag-psd; not yet checked against a Photoshop-written file. No export |
| Tool presets `.tpl` | R/W | no | |
| Curves `.acv`, Levels `.alv`, other adjustment presets | R/W | not audited | |
| C2PA Content Credentials | R/W | no | #1050 |
@@ -177,6 +178,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.
| 2026-10-14 | minor | PSD smart objects warped with Transform Warp's Cylinder (`warpCylinder`, seven `warpValues`) are read and written: Replace Contents, Relink and Edit Contents re-render them wrapped instead of flat, and a regenerated `SoLd` no longer drops the warp (#4112). Vertical cylinders and ones with perspective are still unread |
| 2026-10-15 | minor | Bevel & Emboss Gloss Contour › Anti-aliased (`antialiasGloss`) is read and written, set by `glossAntiAlias` and shown in the Layer Style dialog; a PSD whose bevel is edited no longer loses it. Rendering still ignores contour anti-aliasing, as for the other effects' contours |
| 2026-10-15 | minor | Stroke › Overprint (`overprint`) is read and written, set by the stroke command's `overprint` and shown in the Layer Style dialog; an edited stroke no longer drops it. Rendering ignores it for now |
| 2026-10-14 | minor | CSH custom-shape set import (#5359, FILE-215-15); export and Photoshop-written fixture verification remain open; no estimate changed |
| 2026-10-14 | minor | Nikon NEF: the D4 profile's saturation level follows the sample depth (15520 at 14 bits, 3880 at 12), so 12-bit D4 files open as bright as their 14-bit twins instead of 2.6 stops darker (#5978) |
| 2026-10-14 | minor | Animated WebP: New Video Layer from File, Replace Footage, Reload Frame and Video Frames to Layers take every frame, composited, with the timeline rate from the durations (#1198) |
| 2026-10-14 | minor | PSD smart filter masks: Photoshop stores a smart object's filtered pixels without its filter mask and mixes the unfiltered ones (`FEid`) back in; import now mixes them and export writes them that way, so sf-filter-mask-hard, -gradient and sf-stack-blend-and-mask pass; Photoshop-oracle floor 185 → 188 of 258 |
+4 -1
View File
@@ -341,7 +341,9 @@ what an agent can't finish alone.
DICOM, EPS/DCS, Pixar, WBMP, MPO/JPS, PICT, Scitex CT, Photoshop
Raw; spot plates beyond PSD and TIFF: spot ink preview in RGB/CMYK documents and PDF Separation
(FILE-215-17); .atn,
.shc, .csh presets (.asl landed 2026-10-20) (FILE-215-15); C2PA (#1050).
.shc presets and .csh export (.asl landed 2026-10-20) (FILE-215-15); C2PA (#1050).
- **CSH import:** Version 2 custom-shape sets load into persistent Shapes groups (#5359).
Original synthetic geometry is independently cross-read; Photoshop-written fixture verification remains open.
- **Detail:** [`file-format-parity.md`](file-format-parity.md).
- **Progress (2026-10-23, #7415 split):** PSD stores and reads spot channels as Photoshop does (ink
0 = solid) and writes their identifiers (1053); PSDs from PhotoCraft 0.1.0–0.16.0, which stored
@@ -434,6 +436,7 @@ what an agent can't finish alone.
| 2026-10-15 | minor | G9: Animated Zoom preference takes effect (hold the Zoom tool to zoom continuously, #6210); prefs that do nothing 25 of 166; no estimate changed |
| 2026-10-16 | minor | G7: Content-Aware Move's live preview covers every selection the command takes (over 256 × 256: a coarse result solved scaled down, then the exact one); TOOL-213-4 done (#6680) |
| 2026-10-15 | minor | G9: Save in Background off saves in the foreground under a modal progress dialog (#6207); preferences that do nothing 25 → 24 of 169 |
| 2026-10-14 | minor | CSH custom-shape set import (#5359, FILE-215-15); export and Photoshop-written fixture verification remain open; no estimate changed |
| 2026-10-14 | minor | G1: PSD smart objects keep Transform Warp's Cylinder through Replace Contents, Relink, Edit Contents and re-saves (#4112) |
| 2026-10-15 | minor | G8: area type: Type tool click inside a closed path or shape wraps text inside it (TYPE-218-10); Type tool click on a path's outline (TYPE-218-1); Type scorecard 5 done, 4 partial, 1 missing |
| 2026-10-14 | minor | G14: the Nikon D4 profile's white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark (#5978); gap remains open |